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
@@ -1,184 +1,470 @@
1
- # Desarrollo — `opencode-claude-code-acpbridge`
1
+ # Development — `opencode-claude-code-acpbridge`
2
2
 
3
- Guía de arquitectura interna, flujos y cómo extender el paquete. Para uso, ver el [README](../README.md); para configuraciones de ejemplo, [examples/](../examples/).
3
+ How the package works inside, its key flows, and how to extend it. For usage see the
4
+ [README](../README.md); for ready-made configs see [examples/](../examples/).
5
+
6
+ > **OpenCode V2 only.** The plugin half uses the V2 plugin runtime (`Plugin.define`, promise
7
+ > API) and the V2 config format. It does not load in OpenCode V1.
4
8
 
5
9
  ---
6
10
 
7
- ## 1. Visión general
11
+ ## 1. Overview
12
+
13
+ One npm package that OpenCode loads as **two things at once**:
8
14
 
9
- Un único paquete npm que OpenCode carga como **dos cosas a la vez**:
15
+ - **Provider** (`createACPModelProvider`): implements `LanguageModelV3` from the Vercel AI
16
+ SDK. Underneath it is an **ACP client** (Agent Client Protocol) that spawns
17
+ `claude-agent-acp`, the ACP adapter for Claude Code.
18
+ - **Plugin** (`export default Plugin.define({ id, setup })`, V2 promise API):
19
+ - registers the provider and the agents through transforms;
20
+ - injects the session id and the per-call options through the `context` hook;
21
+ - names sessions without a model call (`title` hook);
22
+ - drops the stored session link on `session.revert.*` events.
10
23
 
11
- - **Provider** (`createACPModelProvider`) — implementa `LanguageModelV3` (Vercel AI SDK). Por debajo es un **cliente ACP** que spawnea `claude-agent-acp` (Claude Code).
12
- - **Plugin** (`export default Plugin.define({ id, setup })`, API V2 promise) — registra el provider y los agentes por transform, inyecta el `sessionID` y las opciones por llamada por el hook `context`, y limpia el enlace de sesión en los eventos `session.revert.*`. El entrypoint de desarrollo local es `index.js` (raíz): `Host.resolve` de OpenCode busca `<dir>/index.*` cuando el destino del plugin es un directorio.
24
+ For local development the entry point is the root `index.js`: when the plugin target is a
25
+ directory, OpenCode's `Host.resolve` looks for `<dir>/index.*`.
13
26
 
14
- El principio rector es **"OpenCode orquesta"**: el agente Claude solo **razona y propone** llamadas a herramientas; **OpenCode las ejecuta** (con sus permisos y TUI) y reinyecta el resultado. Para lograrlo, al agente se le **desactivan sus herramientas nativas** (`tools: []`) y se le exponen **las de OpenCode** mediante un MCP server sintético.
27
+ The guiding principle is **"OpenCode orchestrates"**. Claude only **reasons and proposes**
28
+ tool calls; **OpenCode runs them** (with its permissions and TUI) and feeds the result back.
29
+ To get there, Claude Code's common native tools are **disabled**, and **OpenCode's tools** are
30
+ exposed to it through a synthetic MCP server. The native tools that stay enabled are the ones
31
+ with no OpenCode equivalent, and they go through the **permission bridge** (§4).
15
32
 
16
33
  ---
17
34
 
18
- ## 2. Arquitectura
35
+ ## 2. Architecture
19
36
 
20
37
  ```
21
- ┌───────────────────────── proceso OpenCode ─────────────────────────┐
22
- │ │
23
- OpenCode ──────┼─► Plugin (V2) Provider (LanguageModelV3) │
24
- (TUI/run) │ • provider.transform: • doStream(prompt, tools) │
25
- │ • registra provider acp • ACPOrchestratorModel │
26
- │ • agent.transform: sesión ACP persistente │
27
- │ claude-code + reglas ─────► providerOptions.acp │
28
- │ • session.hook("context"): ◄── ocSession/ocAgent/resume* │
29
- │ sessionID + opciones ─────► + mode/effort por agente │
30
- │ • event: session.revert.* → clearLink (replay si diverge) │
31
- │ │ │
32
- │ McpHost (TCP) ◄── tools de OpenCode │
33
- │ │ getServerConfig() │
34
- └────────────────────────────────────────┼────────────────────────────┘
35
- │ spawn (stdio JSON-RPC ACP)
36
- ▼
37
- claude-agent-acp (proceso aparte)
38
- │ spawnea por stdio
39
- ▼
40
- mcp-runtime.js (node) ──TCP──► McpHost
41
- (MCP server "opencode", difiere tools/call)
38
+ ┌───────────────────────── OpenCode process ──────────────────────────┐
39
+ │ │
40
+ OpenCode ──────┼─► Plugin (V2) Provider (LanguageModelV3) │
41
+ (TUI/run) │ • provider.transform: • doStream(prompt, tools) │
42
+ │ • registers the acp provider • ACPOrchestratorModel │
43
+ │ • agent.transform: persistent ACP session │
44
+ │ claude-code + rules ──────► providerOptions.acp │
45
+ │ • session.hook("context"): ◄─── ocSession/ocAgent/resume* │
46
+ │ session id + options ─────► + per-agent mode/effort │
47
+ │ • event: session.revert.* → clearLink │
48
+ │ │ │
49
+ │ McpHost (TCP) ◄── OpenCode's tools │
50
+ │ │ getServerConfig() │
51
+ └─────────────────────────────────────────┼────────────────────────────┘
52
+ │ spawn (stdio JSON-RPC, ACP)
53
+ ▼
54
+ claude-agent-acp (separate process)
55
+ │ spawns over stdio
56
+ ▼
57
+ mcp-runtime.js (node) ──TCP──► McpHost
58
+ (MCP server "opencode", defers tools/call)
42
59
  ```
43
60
 
44
- - **Canal ACP**: stdio entre el provider y `claude-agent-acp` (JSON-RPC ndjson, `@agentclientprotocol/sdk`).
45
- - **Canal de tools**: el agente arranca `mcp-runtime.js` como MCP server (stdio); este reenvía cada `tools/call` por **TCP** al `McpHost` (dentro del provider), que lo **difiere** hasta que OpenCode ejecuta la tool.
61
+ - **ACP channel:** stdio between the provider and `claude-agent-acp` (newline-delimited
62
+ JSON-RPC, `@agentclientprotocol/sdk`).
63
+ - **Tool channel:** the agent starts `mcp-runtime.js` as an MCP server over stdio. The runtime
64
+ forwards each `tools/call` over **TCP** to the `McpHost` inside the provider, which
65
+ **defers** it until OpenCode has run the tool.
46
66
 
47
67
  ---
48
68
 
49
- ## 3. Componentes (`src/`)
69
+ ## 3. Components (`src/`)
50
70
 
51
71
  ### `provider/model.ts` — `ACPOrchestratorModel`
52
- El corazón. Implementa `doStream`/`doGenerate` y mantiene una **sesión ACP persistente por conversación**.
53
-
54
- - **Conexión** (`connect`): spawnea el agente con el env correcto (`CLAUDE_CODE_EXECUTABLE`, `CLAUDE_CONFIG_DIR`, `CLAUDE_CODE_STREAM_CLOSE_TIMEOUT`, `ANTHROPIC_MODEL`), abre `ClientSideConnection`, `initialize`. El cliente auto-aprueba `requestPermission` (OpenCode ya gobierna los permisos).
55
- - **Identidad de sesión**: una `TurnState` por conversación (`Map` indexado por el sessionID de OpenCode), más un índice por `sessionId` ACP para enrutar los callbacks del agente. Recrear la sesión tira el prompt cache de Claude (vive y muere con ella), así que se recrea lo mínimo posible:
56
- - `systemKey` solo cuenta **si el system de verdad viaja** — con `systemPromptMode: "preset"` (default) no viaja, así que cambiar de agente en OpenCode **no** recrea nada.
57
- - `toolsKey` ya **no** recrea: un set de tools distinto se aplica en caliente con `notifications/tools/list_changed` por el canal MCP.
58
- - `cfgKey` (thinking/systemPromptMode) sí recrea: son parámetros de creación.
59
- - La llamada del small model (títulos/resúmenes, `tools=0`) va a una sesión efímera aparte.
60
- - **Sincronía de historial**: `sentKeys` guarda una huella por mensaje no-system ya enviado. Comparando con el prompt entrante se distingue *append* (envía solo la cola), *revert* (el prompt es prefijo estricto → sesión nueva) y *divergencia* por compactación (→ sesión nueva). En el catch-up se **omiten** los `tool-call`/`tool-result` propios (prefijo nonce del host: el agente ya los tiene) y se truncan los ajenos.
61
- - **Buffer de stream** (`emit`/`flushPending`): texto y thinking llegan por stdio ACP mientras las tool-calls llegan por el socket TCP del host, sin orden garantizado. Cuando una tool-call cierra el stream, lo que sigue llegando se **bufferiza** y se vuelca en el stream de continuación en vez de perderse.
62
- - **Contexto factual** (`contextBlocks`): con `preset` el system de OpenCode no llega al agente, así que su bloque `<env>` (y `<available_references>`) se reenvía como contenido de **usuario** — completo la primera vez, luego solo el delta.
63
- - **`effectiveCtrl(options)`**: fusiona `config.claudeCode` con `providerOptions.acp` (mode/effort/thinking/systemPromptMode por agente/llamada).
64
- - **`applySessionConfig`**: aplica `mode` (`setSessionMode`) y `effort` (`setSessionConfigOption`) **en caliente** (sin recrear).
65
- - **Flujo de tools diferidas** (ver §4).
66
- - **Usage**: `mapUsage`/`subtractUsage` → emite el consumo de tokens por turno en el `finish`.
72
+ The core. Implements `doStream`/`doGenerate` and keeps **one persistent ACP session per
73
+ conversation**.
74
+
75
+ - **Connection** (`connect`): spawns the agent with its environment and opens a
76
+ `ClientSideConnection`, then `initialize`. The environment it sets:
77
+ - `CLAUDE_CODE_EXECUTABLE`;
78
+ - `CLAUDE_CONFIG_DIR`, only with `configDir: "isolated"` or a path;
79
+ - `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` (`autoCompactPct`, default 75);
80
+ - `ANTHROPIC_MODEL`, only when `claudeCode.model` is set;
81
+ - `CLAUDE_CODE_STREAM_CLOSE_TIMEOUT`, only with `streamCloseTimeoutMs`. claude-agent-acp
82
+ 0.31 doesn't read it.
83
+
84
+ `requestPermission` is **not** auto-approved: it goes through the permission bridge (§4).
85
+ - **Session identity:** one `TurnState` per conversation, in a `Map` keyed by the OpenCode
86
+ session id, plus an index by ACP `sessionId` to route the agent's callbacks. Recreating a
87
+ session throws away Claude's prompt cache, which lives and dies with it, so it is recreated
88
+ as rarely as possible:
89
+ - `systemKey` only counts **if the system prompt actually travels**. With
90
+ `systemPromptMode: "preset"` (the default) it doesn't, so switching agents in OpenCode
91
+ recreates nothing.
92
+ - `toolsKey` doesn't recreate either: a different tool set is applied live with an MCP
93
+ `notifications/tools/list_changed`.
94
+ - `cfgKey` is the full **creation profile**: `buildClaudeCodeOptions` without model and
95
+ effort, plus `systemPromptMode`. When it changes (an agent with other native tools), the
96
+ session is **forked** (`unstable_forkSession` with the new `_meta`, `forkInPlace`) instead
97
+ of recreated.
98
+ - A different acp model is applied with `unstable_setSessionModel`. There is **one**
99
+ orchestrator (one agent process) for every model of the provider; each model id is an
100
+ `ACPModelView` over it (`factory.ts`).
101
+ - A call without tools (titles or summaries in programmatic use) goes to a separate
102
+ `:notools` session that closes after answering. Inside OpenCode the plugin sets titles
103
+ without a model.
104
+ - A per-conversation lock (`withLock`) guards creating and reusing a session.
105
+ - **History sync** (`history.ts`): two fingerprints of what the agent already knows.
106
+ - `sentKeys`: the legacy per-message keys.
107
+ - `sentAnchors`: the user's messages plus tool-call ids.
108
+ - `historyMode` decides which one acts; `shadow` logs every disagreement.
109
+ - The incoming prompt is classified as *append* (send only the tail), *revert* or
110
+ *divergence*.
111
+ - The tail is cleaned of the agent's **own output** (`dropOwnLead`: emitted texts in
112
+ `ownTexts`, ids with its own prefix in `ownPrefixes`).
113
+ - Another model's turns travel as `<other_model_turn>`. A full replay is a bounded
114
+ `<conversation_history>` (about 400,000 characters, newest kept).
115
+ - **Turns and generations:** each `session/prompt` carries a generation (`sendPrompt`). The
116
+ completion of an old one, cancelled or merged by the agent's prompt queue, is ignored.
117
+ `abortTurn` cancels, rejects the deferred MCP calls and drains pending permissions; `settle`
118
+ waits for the old prompt to finish.
119
+ - **Stream buffer** (`emit`/`flushPending`): text and thinking arrive over the ACP stdio,
120
+ while tool calls arrive over the host's TCP socket, with no guaranteed order. When a tool
121
+ call closes the stream, whatever keeps arriving is **buffered** and flushed into the
122
+ continuation stream instead of being lost.
123
+ - **Factual context** (`contextBlocks`): with `preset`, OpenCode's system prompt never reaches
124
+ the agent. So its `<env>` block (and `<available_references>`) is forwarded as **user**
125
+ content: in full the first time, then only the changes.
126
+ - **`effectiveCtrl(options)`**: merges `config.claudeCode` with `providerOptions.acp`
127
+ (per-agent or per-call mode, effort, thinking, systemPromptMode and the native toggles).
128
+ - **`applySessionConfig`**: applies the model (`unstable_setSessionModel`), the `mode`
129
+ (`setSessionMode`) and the `effort` (`setSessionConfigOption`) **live**, without
130
+ recreating the session.
131
+ - **Deferred tool flow:** see §4.
132
+ - **Usage** (`usageNow`): the context size comes from `usage_update.used`, the last request.
133
+ `PromptResponse.usage` is the SUM over the turn and only provides the cache proportions.
134
+ - **Compaction:**
135
+ - `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` makes Claude Code compact its own session first.
136
+ - A compaction request from OpenCode (`requestKind`) is served in the live session
137
+ (`serveCompaction`).
138
+ - With `historyMode: "v2"`, a hidden native `/compact` follows (`nativeCompact`) and the
139
+ checkpoint is adopted with no new session.
140
+ - **Resources:**
141
+ - `session/close` (through `extMethod`) when a session is dropped;
142
+ - idle sweep (`sweepIdle`) with per-session and per-subagent TTLs;
143
+ - an LRU cap of `maxLiveSessions` (default 6).
67
144
 
68
145
  ### `acp/mcp-host.ts` — `McpHost`
69
- TCP server dentro del provider. `setTools()` recibe las tools de OpenCode; cuando el runtime pide `getTools`/`callTool`, responde. **Difiere** los `callTool`: guarda `{socket, runtimeId}` por `toolCallId` y resuelve cuando OpenCode entrega el resultado (`resolveToolCall`).
146
+ TCP server inside the provider. `setTools()` receives OpenCode's tools; it answers the
147
+ runtime's `getTools`/`callTool`. It **defers** each `callTool`: it keeps
148
+ `{socket, runtimeId}` per `toolCallId` and answers when OpenCode delivers the result
149
+ (`resolveToolCall`), or fails it (`rejectToolCall`).
70
150
 
71
151
  ### `acp/mcp-runtime.ts`
72
- MCP server **stdio sin dependencias** (solo `node:net`/`node:readline`) que el agente spawnea. Reenvía `tools/list`/`tools/call` por TCP al host (puerto en `ACP_TOOL_HOST_PORT`). No impone timeout cliente → el `tools/call` puede esperar a OpenCode tanto como `CLAUDE_CODE_STREAM_CLOSE_TIMEOUT`. Blindado contra `EPIPE`/`ECONNRESET` (el agente lo mata al cerrar).
152
+ **Dependency-free** stdio MCP server (only `node:net`/`node:readline`) that the agent spawns.
153
+ It forwards `tools/list`/`tools/call` over TCP to the host (port in `ACP_TOOL_HOST_PORT`).
154
+ - **No client-side timeout:** a `tools/call` can wait for OpenCode as long as the agent allows
155
+ (`MCP_TOOL_TIMEOUT`, about 27 h in claude-agent-acp 0.31).
156
+ - **Forwarding:** `_meta["claudecode/toolUseId"]` and the agent's `notifications/cancelled` go
157
+ on to the host.
158
+ - **Shutdown:** it is hardened against `EPIPE`/`ECONNRESET`, which happen when the agent kills
159
+ it on close.
73
160
 
74
161
  ### `acp/claude-config.ts`
75
- `ClaudeCodeControl` (tipo) + `buildClaudeCodeOptions` (→ `_meta.claudeCode.options`) + `resolveConfigDir`/`prepareIsolatedConfigDir`. El **"cerebro limpio"** por defecto: `tools:[]`, `settingSources:[]`, `strictMcpConfig:true` (sin connectors claude.ai), y un `CLAUDE_CONFIG_DIR` aislado con `~/.claude/.credentials.json` **symlinkeado** (auth sin heredar el ecosistema). `prepareIsolatedConfigDir` **re-enlaza el symlink en cada arranque**: el agente puede reemplazarlo con un archivo obsoleto al refrescar el token → 401; re-linkear lo mantiene sincronizado con `~/.claude`.
76
- **Toggles de features nativos** (componen `tools`/`settingSources`/`agents`/`settings`; con todos off = cerebro limpio, cero regresión): `nativeTools`, `resourceSearch`, `nativeSubagents` (→ `DEFAULT_SUBAGENT` que delega a OpenCode), `nativeSkills`, `projectMemory`, `skillShell`, `allowedTools`. Un override crudo (`ctrl.tools`/`ctrl.settingSources`) **gana** sobre la composición.
162
+ `ClaudeCodeControl` (the options type), `buildClaudeCodeOptions` (builds
163
+ `_meta.claudeCode.options`) and `resolveConfigDir`/`prepareIsolatedConfigDir`.
164
+
165
+ - **"Clean brain" by default:**
166
+ - `tools: []`, `settingSources: []`;
167
+ - `strictMcpConfig: true`, so no claude.ai connectors;
168
+ - `allowedTools: ["mcp__opencode"]`, so OpenCode's own tools never trigger a second prompt.
169
+ - **Config dir:** the default is `configDir: false`. The agent keeps its state in your
170
+ `~/.claude`, so sessions can be resumed with `claude --resume <id>`. That doesn't pull in
171
+ your ecosystem: `settingSources`/`tools`/`strictMcpConfig` still decide what loads.
172
+ `"isolated"` uses `~/.acp-model-provider/claude-config` with `~/.claude/.credentials.json`
173
+ **symlinked** in, re-linked on every start: the agent may replace the link with a stale
174
+ copy when it refreshes the token, which ends in 401s.
175
+ - **Native feature toggles** (they compose `tools`/`settingSources`/`agents`/`settings`; all
176
+ off = clean brain): `nativeTools`, `resourceSearch`, `nativeSubagents` (adds
177
+ `DEFAULT_SUBAGENT`, which delegates to OpenCode's tools), `nativeSkills`, `projectMemory`,
178
+ `skillShell`, `allowedTools`. A raw override (`ctrl.tools`/`ctrl.settingSources`) **wins**
179
+ over the composition.
77
180
 
78
181
  ### `plugin/index.ts` · `bridge-rules.ts`
79
- - **`provider.transform`**: descubre modelos (con caché TTL), construye `Model.Info[]` (`buildModelsInfo`) y **registra** el provider `acp` (`package: aisdk:<spec>`, `settings` = config del agente ACP). Sin `command` (ni `ACP_COMMAND`) no registra nada y deja declarar el provider a mano.
80
- - **`agent.transform`**: inyecta `claude-code`/`claude-code-plan`. Solo rellena campos vacíos (`description`, `model`) → idempotente ante replays y respeta la config del usuario; añade `{action:"question", resource:"*", effect:"allow"}` (la tool `question` nativa no duplique diálogo) y **publica** las reglas del puente (`publishAgentRules`).
81
- - **`session.hook("context")`** (scoped `providerID: acp`): inyecta por llamada `ocSession`/`ocAgent` + `resumeId`/`resumeLen`/`resumeLastUsage`/`resumeConvKey` desde el registro, y las opciones Claude del agente (`plugins[].options.agents.<n>.options`: mode/native*). V2 no pasa provider options desde config: todo lo necesita el hook.
82
- - **`event.subscribe`**: `session.revert.committed|cleared` → `clearLink` — la sesión ACP recordaría turnos deshechos, así que el siguiente turno arranca en fresco con replay completo.
83
- - **`bridge-rules.ts`** (módulo compartido plugin↔provider, igual que `sessions.ts`): store de reglas por agente + `always.json` persistente (`~/.acp-model-provider/always.json`). `evaluate()` replica `Permission.evaluate` de V2 con **una diferencia deliberada**: ignora reglas `action:"*"` (los defaults de V2 son `*: allow` y aprobarían toda tool nativa) → default `ask`.
84
-
85
- ### `plugin/discover.ts` · `catalog.ts` · `cache.ts` · `sessions.ts`
86
- - `discover`: conexión ACP **efímera** → `availableModels`/`modes`/`promptCapabilities`.
87
- - `catalog`: metadata desde `~/.cache/opencode/models.json` (o `models.dev`), `variants` de effort, `default`→opus. `buildModels` (CLI/diagnóstico) y `buildModelsInfo` (→ `Model.Info[]` para `provider.transform`).
88
- - `cache`: cachés TTL en `~/.acp-model-provider/`.
89
- - `sessions`: registro `sessions.json` (sessionID OpenCode ↔ sessionId ACP + usage/convKey).
90
-
91
- ### `provider/factory.ts` · `env.ts` · `bin/cli.ts`
92
- Factory del provider (una instancia por `modelId`), config por env vars, y el comando `sync`.
182
+ - **`provider.transform`:**
183
+ - discovers the models, with a 1 h cache;
184
+ - builds `Model.Info[]` (`buildModelsInfo`);
185
+ - **registers** the `acp` provider (`package: aisdk:<spec>`; `settings` = the agent config).
186
+
187
+ Without `command` (or `ACP_COMMAND`) it registers nothing, so you can declare the provider
188
+ by hand. An `acp` provider that already exists is kept as it is.
189
+ - **`agent.transform`:**
190
+ - **Injection.** Adds `claude-code`/`claude-code-plan`, or the plugin's `options.agents`,
191
+ which **replaces** that list; `agents: false` injects none. It only fills empty fields
192
+ (`description`, `model`), so it stays idempotent across config reloads and respects your
193
+ config.
194
+ - **Rules it adds.** `{action:"question", resource:"*", effect:"allow"}` when the agent has
195
+ the `question` tool, because the bridge's dialog runs through it. `compress: deny`, for
196
+ the DCP plugin: rewriting OpenCode's copy of the history would only force cold replays.
197
+ - **Publishing.** It **publishes** every agent's rules to the bridge (`publishAgentRules`),
198
+ not only its own: a subagent inherits its parent's model and may run on this provider.
199
+ - **`session.hook("context")`**, also for the `compaction` and `generate` calls (only for the
200
+ `acp` provider), injects per call:
201
+ - `ocSession`/`ocAgent`/`requestKind`;
202
+ - the registry's `resumeId`/`resumeLen`/`resumeLastUsage`/`resumeConvKey`/`resumeIdPrefixes`;
203
+ - the agent's Claude options (`mode`, native toggles…).
204
+
205
+ V2 passes no provider options from config: everything the model needs comes through this
206
+ hook.
207
+ - **`session.hook("title")`:** names the session from the first user message with no model
208
+ call (`titleFrom`), unless the `titleFromModel` option is set.
209
+ - **`event.subscribe`:** `session.revert.committed|cleared` → `clearLink`, so a restart never
210
+ resumes a session that remembers undone turns. The live session handles the revert itself
211
+ (`smartRevert`, §4).
212
+ - **`bridge-rules.ts`** (shared by plugin and provider, like `sessions.ts`):
213
+ - a per-agent rule store plus the persistent `~/.acp-model-provider/always.json`;
214
+ - `evaluate()` mirrors V2's `Permission.evaluate` with **one deliberate difference**: it
215
+ ignores `action:"*"` rules, because V2's defaults are `*: allow` and would approve every
216
+ native tool. The default is `ask`.
217
+
218
+ ### `plugin/discover.ts` · `catalog.ts` · `cache.ts` · `sessions.ts` · `compat.ts`
219
+ - `discover`: a **short-lived** ACP connection → `availableModels`, `modes`,
220
+ `promptCapabilities`, agent version.
221
+ - `catalog`:
222
+ - model metadata from `~/.cache/opencode/models.json` (or models.dev);
223
+ - effort `variants` (low, medium, high, xhigh, max);
224
+ - the agent's `default` maps to the Opus family.
225
+
226
+ `buildModels` serves the CLI and diagnostics; `buildModelsInfo` produces the `Model.Info[]`
227
+ for `provider.transform`.
228
+ - `cache`: TTL caches in `~/.acp-model-provider/`.
229
+ - `sessions`: the `sessions.json` registry (OpenCode session id ↔ ACP sessionId, plus
230
+ usage, conversation key and id prefixes). It is pruned to 30 days / 500 entries.
231
+ - `compat`: load-time warnings when OpenCode or `claude-agent-acp` is outside the tested range.
232
+
233
+ ### `provider/factory.ts` · `env.ts` · `history.ts` · `recorder.ts` · `bin/cli.ts` · `log.ts`
234
+ - `factory.ts`: the provider factory. One shared `ACPOrchestratorModel`, plus an
235
+ `ACPModelView` per model id.
236
+ - `env.ts`: config from environment variables.
237
+ - `recorder.ts`: the `ACP_RECORD` recorder (§5).
238
+ - `bin/cli.ts`: the `sync` command (`npx opencode-claude-code-acpbridge sync claude-agent-acp`).
239
+ - `log.ts`: the shared logger.
240
+ - Daily file log in `~/.acp-model-provider/logs/acp-YYYYMMDD.log`. `ACP_LOG=0` turns it off;
241
+ `ACP_LOG_DIR` moves it.
242
+ - `ACP_DEBUG=1` adds the debug lines on stderr.
93
243
 
94
244
  ---
95
245
 
96
- ## 4. Flujos clave
97
-
98
- ### Tool-call diferido (el núcleo de "OpenCode orquesta")
99
- 1. `doStream` recibe el prompt + tools. El provider las expone vía `McpHost` y manda el prompt al agente.
100
- 2. El agente decide usar una tool → llama al MCP `mcp-runtime` → este reenvía `callTool` por TCP al `McpHost`.
101
- 3. `McpHost.onToolCall` → el provider **emite a OpenCode** `tool-input-start/delta/end` → `tool-call` (con el nombre **real**) → `finish("tool-calls")`, y **deja el `callTool` MCP pendiente**.
102
- 4. OpenCode ejecuta la tool (permisos/TUI) y en el **siguiente `doStream`** trae el `tool-result`.
103
- 5. El provider detecta la continuación, hace `McpHost.resolveToolCall(id, result)` → el `callTool` MCP por fin responde → el agente continúa el mismo turno.
104
-
105
- ### Sesión: reuse / reset / resume — mensajes incrementales (requisito central)
106
- ACP es una sesión viva: el agente recuerda todo lo que ya le enviaste, así que **reenviar la historia entera cada turno quema tokens y rompe el prompt cache** (commit `4a7d7be`, v0.8.0). OpenCode, en cambio, siempre construye el prompt completo; el provider decide qué viaja de verdad:
107
-
108
- - **Reuse** (mismo proceso, misma conversación): `sentKeys` guarda una huella por mensaje ya enviado; comparando con el prompt entrante se detecta *append* → se envía **solo la cola** (`hist.slice(fromIndex)`), omitiendo los `tool-call`/`tool-result` propios (prefijo nonce del host: el agente ya los tiene). Cero reenvío, cache intacta.
109
- - **Resume** (proceso nuevo): el `context` hook aporta `resumeId`/`resumeLen` desde el registro `sessions.json`; si el historial creció sin divergir, `unstable_resumeSession(acpSessionId)` reanuda y `sentKeys = keys.slice(0, resumeLen)` → **sin replay** de lo ya enviado.
110
- - **Reset**: cambia system/cfg de creación → cierra la vieja y `newSession` con replay completo (necesario: es otra conversación).
111
- - **Divergencia** (revert/compactación): el prompt ya no es prefijo estricto de `sentKeys`, o el plugin recibe `session.revert.*` → `clearLink` → sesión fresca + replay completo (la sesión ACP recordaría turnos deshechos).
112
- - **Catch-up** (sesión viva + historia reescrita): se reenvía solo lo no visto, con los ajenos truncados según el rol del mensaje.
113
-
114
- ### Modo y esfuerzo por agente
115
- `plugins[].options.agents.<n>.options` (V2: `Agent.Info` no tiene `options`, viven en las opciones del plugin) → el `context` hook las vuelca en `event.options` por llamada → V2 las anida como `providerOptions.<providerID>` (key = providerID) → `doStream` las lee (`effectiveCtrl`) → `setSessionMode`/`setSessionConfigOption` en caliente. El esfuerzo elegido como **variante del modelo** (`acp/default#high`) también aterriza ahí (variant.settings); un `effort` explícito del agente gana (request > model defaults). `effort` solo aplica si el modelo expone niveles en `session/configOptions`; si no, warning no fatal.
116
-
117
- ### Puente de permisos (tools nativas)
118
- Cuando el agente usa una tool **nativa** (Skill/Read/NotebookEdit/ExitPlanMode/…), Claude Code llama `requestPermission` (ACP). El provider **no auto-aprueba**; enruta la decisión en dos pasos:
119
-
120
- 1. **Reglas primero** (`evaluate` en `bridge-rules.ts`): con `ocAgent` + tool nativa + target (p. ej. `Bash` + `git *`) busca en las reglas publicadas por `agent.transform` + `always.json` → `allow`/`deny` resuelven **sin diálogo**. Ignora `action:"*"` y default `ask` (fail-safe).
121
- 2. **`ask` → diálogo `question`**: `onRequestPermission` devuelve una Promise pendiente y **emite a OpenCode** un tool-call de la tool nativa **`question`** (`{questions:[{question, header, options:[Allow once, Always allow?, Deny]}]}`), `finish` y cierra el controller (mismo patrón que `onToolCall`). OpenCode ejecuta `question` (por eso los agentes inyectados llevan `{action:"question",resource:"*",effect:"allow"}`) y el diálogo aparece en la TUI.
122
- 3. El siguiente `doStream` trae el tool-result de `question`; `detectContinuation` lo distingue (`pendingPermissions` vs `pendingTools`) y `questionVerdict` lo parsea: etiquetas exactas de output tipado (`{answers:[["Always allow"]]}`) o texto renderizado (`"q"="Always allow"`) → `Always allow` persiste la regla en `always.json` (`addAlwaysRule`); **cualquier cosa ambigua falla CERRADA** (deny), incluido el free-form "type your own answer".
123
-
124
- Robustez (heredada de V1): `onCancel` **no derriba** la sesión con permiso diferido en vuelo (OpenCode pausa para el diálogo) pero arma un **watchdog** que libera si la continuación nunca llega; `endTurn`/reuse **drenan** `pendingPermissions` como deny para que el agente nunca cuelgue; sin turno vivo se aprueba (el agent-blocking es peor). Las tools comunes van en `allowedTools: ["mcp__opencode"]` (no piden `requestPermission`; OpenCode las orquesta).
125
-
126
- ### Facturación (suscripción vs extra usage)
127
- Anthropic clasifica la sesión por el **system prompt**: si reenvías el de OpenCode (`append`/`replace`), la trata como app de terceros → *extra usage*; con `preset` (default) usa el preset oficial `claude_code` → **suscripción**. Decidido empíricamente; ver [acp-subscription-billing](../README.md#system-prompt-y-facturación-suscripción-vs-extra-usage).
246
+ ## 4. Key flows
247
+
248
+ ### Deferred tool call (the core of "OpenCode orchestrates")
249
+ 1. `doStream` receives the prompt and the tools. The provider exposes the tools through
250
+ `McpHost` and sends the prompt to the agent.
251
+ 2. The agent decides to use a tool and calls the `mcp-runtime` MCP server, which forwards
252
+ `callTool` over TCP to the `McpHost`.
253
+ 3. `McpHost.onToolCall` → the provider **emits to OpenCode**
254
+ `tool-input-start/delta/end` → `tool-call` (with the **real** tool name) →
255
+ `finish("tool-calls")`, and **leaves the MCP `callTool` pending**.
256
+ 4. OpenCode runs the tool (permissions, TUI) and brings the `tool-result` in the **next**
257
+ `doStream`.
258
+ 5. The provider detects the continuation (`detectContinuation`) and calls
259
+ `McpHost.resolveToolCall(id, result)`. The MCP `callTool` finally answers and the agent
260
+ continues the same turn.
261
+
262
+ Details:
263
+ - **Grouping by step.** Tool calls are grouped per step (`addStepItem`/`closeStep`). Read-only
264
+ ones wait `toolBatchMs` for their siblings, and all of them leave with a **single** `finish`.
265
+ - **Late calls.** Calls that arrive once the stream has closed are queued (`queuedItems`) and
266
+ leave at the start of the next continuation.
267
+ - **Messages after the results.** If the continuation brings messages after the tool results
268
+ (a steer, a `<system-update>`, a subagent result, the max-steps prefill), they go into the
269
+ running turn: as a queued prompt, or appended to the last result when the agent doesn't
270
+ support `promptQueueing`.
271
+ - **Aborts.** If a result is `aborted` and a new message follows, the old turn is cancelled and
272
+ the message goes as a new turn.
273
+ - **Cancelled calls.** An agent `notifications/cancelled` withdraws a call that hasn't been
274
+ emitted yet.
275
+
276
+ ### Sessions: incremental messages (the central requirement)
277
+ ACP is a live session: the agent remembers everything already sent. So **re-sending the
278
+ whole history every turn burns tokens and breaks the prompt cache** (commit `4a7d7be`, 0.8.0).
279
+ OpenCode, on the other hand, always builds the full prompt. The provider decides what actually
280
+ travels:
281
+
282
+ - **Reuse** (same process, same conversation): the fingerprints detect an *append* and only
283
+ the **tail** is sent, without the agent's own output. Nothing is re-sent and the cache stays
284
+ warm. Turns by another model (after a model switch) travel as `<other_model_turn>`.
285
+ - **Resume** (new process): the `context` hook brings `resumeId`/`resumeLen` from the
286
+ `sessions.json` registry. If the history grew without diverging and the conversation key
287
+ matches, `unstable_resumeSession(acpSessionId)` resumes it and only the unseen part travels.
288
+ - **Profile change** (`cfgKey`): fork of the live session with the new options, no replay.
289
+ - **System prompt change** (only when it travels: `append`/`replace`): a new session with a
290
+ bounded replay.
291
+ - **Revert:**
292
+ - with `smartRevert` (default on), the session is forked back to the point before the
293
+ reverted message (`resumeSessionAt`, from the transcript checkpoint), with no replay;
294
+ - if that isn't possible, a new session with a bounded replay.
295
+ - **Compaction:** served in the live session (see `serveCompaction`). With `historyMode: "v2"`
296
+ the resulting `<conversation-checkpoint>` is adopted without a new session.
297
+ - **Any other divergence:** a new session with a bounded replay.
298
+
299
+ ### Mode and effort per agent
300
+ Per-agent options travel like this:
301
+ 1. They live in `plugins[].options.agents.<name>.options`, because V2's `Agent.Info` has no
302
+ `options` field.
303
+ 2. The `context` hook puts them in `event.options` on every call.
304
+ 3. V2 nests them as `providerOptions.<providerID>`.
305
+ 4. `doStream` reads them (`effectiveCtrl`).
306
+ 5. `setSessionMode`/`setSessionConfigOption` apply them live.
307
+
308
+ The effort chosen as a **model variant** (`acp/default#high`) lands in the same place, through
309
+ the variant's `settings`. An explicit `effort` of the agent wins (request > model defaults).
310
+ `effort` only applies when the model exposes levels in `session/configOptions`; otherwise
311
+ it's a non-fatal warning.
312
+
313
+ ### Permission bridge (native tools)
314
+ When the agent uses a **native** Claude Code tool that OpenCode can't run for it (Skill,
315
+ NotebookEdit, WebSearch, native subagents, ExitPlanMode…), Claude Code calls
316
+ `requestPermission` (ACP). The provider routes the decision:
317
+
318
+ 1. **Rules first** (`evaluate` in `bridge-rules.ts`). With `ocAgent`, the native tool name
319
+ (the first word of the ACP tool title) and its target (the skill name, the notebook path,
320
+ the command…), it looks at the published rules and `always.json`.
321
+ - `allow`/`deny` decide with **no dialog**.
322
+ - `action:"*"` rules are ignored, and the default is `ask` (fail-safe).
323
+ 2. **`ask` → a `question` dialog.** `onRequestPermission` returns a pending Promise and
324
+ **emits to OpenCode** a tool call of OpenCode's own **`question`** tool
325
+ (`{questions:[{question, header:"Permission", options:[Allow once, Always allow, Deny]}]}`),
326
+ then `finish` (same pattern as a tool call). OpenCode runs `question` and the dialog shows
327
+ up in the TUI.
328
+ 3. **The answer.** The next `doStream` carries the `question` result.
329
+ - `detectContinuation` tells it apart from tool results (`pendingPermissions` vs
330
+ `pendingTools`), and `questionVerdict` parses it: the exact label of the typed output
331
+ (`{answers:[["Always allow"]]}`), or the rendered text (`"q"="Always allow"`).
332
+ - `Always allow` stores the rule in `always.json` (`addAlwaysRule`).
333
+ - **Anything ambiguous fails CLOSED** (deny), including a free-form typed answer.
334
+
335
+ Robustness:
336
+ - **Cancel.** In V2, OpenCode reads each stream to the end, so a cancel is a **real abort**
337
+ (`onCancel` → `abortTurn`).
338
+ - **Draining.** Ending a turn drains `pendingPermissions` as deny, so the agent never hangs.
339
+ A request that arrives with the stream closed is **queued** for the next continuation.
340
+ - **Ids.** Question ids carry the session's own prefix (`<idPrefix>perm_N`).
341
+ - **No `question` tool.** If the agent lacks `question` (`hasQuestion` from the hook), the
342
+ request is denied with a reason.
343
+ - **ExitPlanMode.** It shows the agent's real options (`askPlanApproval`); a typed answer
344
+ rejects the plan and reaches Claude as feedback.
345
+
346
+ ### Billing (subscription vs extra usage)
347
+ Anthropic classifies the session by its **system prompt**. Forwarding OpenCode's
348
+ (`append`/`replace`) makes it a third-party app, billed as *extra usage*. With `preset` (the
349
+ default) it's the official `claude_code` preset, so it counts against the **subscription**.
350
+ This was established empirically (`scripts/verify-billing.mjs`); see the billing section of
351
+ the README.
128
352
 
129
353
  ---
130
354
 
131
- ## 5. Build y pruebas
355
+ ## 5. Build and tests
132
356
 
133
357
  ```bash
134
358
  npm install
135
359
  npm run build # tsc → dist/
136
- ACP_DEBUG=1 … # logs [acp-orchestrator] / [acp-mcp-host] / [acp-plugin] en stderr
360
+ npm test # tsc + node --test "test/*.test.mjs"
361
+ npm run check:install # installs the packed package like OpenCode does and loads it
137
362
  ```
138
363
 
139
- **Smoke test en OpenCode V2** (proyecto de prueba con `.opencode/opencode.json` registrando el plugin por ruta absoluta):
364
+ **Before touching history sync**, run `npm test`. What the suite contains:
365
+ - **Fake agent.** `test/fake-agent.mjs` speaks real ACP and drives the real `mcp-runtime`.
366
+ - **Characterization.** `test/characterization.test.mjs` pins the behaviours that must stay
367
+ (KEEP) and every bug fixed so far.
368
+ - **Real fixtures.** `test/fixtures/v2/*.jsonl` are **real** OpenCode V2 prompts, recorded with
369
+ `ACP_RECORD=<dir>` and anonymized with `scripts/sanitize-recording.mjs`.
370
+ - **Other suites.** `plugin`, `sessions`, `fixtures` and `compat`.
140
371
 
141
- ```bash
142
- cd <proyecto> && ACP_DEBUG=1 opencode --standalone run \
143
- --agent claude-code -m acp/default "responde solo: ok"
144
- ```
372
+ A change to `history.ts` without a real fixture behind it doesn't go in: this logic has
373
+ broken several times (0.8.0, 9299af9).
145
374
 
146
- Verificar en el log: `loading plugin` → `[acp-plugin] auto-registered provider 'acp' … models: …` → `agents registered: claude-code, claude-code-plan` → `> claude-code · default` → `[acp-orchestrator] connected to agent`. Notas: `opencode run` **sin `-m` ignora `agent.model`** (usa el model global de config — comportamiento V2 del CLI); el diálogo `question` del puente requiere TUI interactiva (`opencode --standalone`).
375
+ **Switching `historyMode` from `shadow` to `v2`:**
376
+ 1. Use OpenCode normally for a while in `shadow` (the default).
377
+ 2. Look for `shadow-diff` lines in `~/.acp-model-provider/logs/acp-YYYYMMDD.log`. Each one is
378
+ a turn where the anchor fingerprint would have decided differently.
379
+ 3. If they only show cases where `v2` avoids a needless reset, set
380
+ `claudeCode.historyMode: "v2"` (or `ACP_HISTORY_MODE=v2`).
147
381
 
148
- **Scripts de verificación** (`scripts/`, no se publican a npm, requieren `dist/`):
382
+ **Smoke test in OpenCode V2** (a test project whose `opencode.json` loads the plugin by its
383
+ absolute directory path):
149
384
 
150
- - `node scripts/verify-billing.mjs` — comprueba que cada feature nativo mantiene la **suscripción** (0 extra usage).
151
- - `node scripts/spike-permission-bridge.mjs` — valida el **puente de permisos** e2e (approved crea el archivo; denied no).
385
+ ```bash
386
+ cd <project> && ACP_DEBUG=1 opencode run --standalone --agent claude-code -m acp/default "reply only: ok"
387
+ ```
152
388
 
153
- **Spikes** (sin OpenCode): scripts `.mjs` dentro del repo que importan `../dist/...` y usan `streamText` del AI SDK o el SDK ACP directamente. Patrón típico:
389
+ Check the log, in this order:
390
+ 1. `loading plugin`;
391
+ 2. `[acp-plugin] auto-registered provider 'acp' … models: …`;
392
+ 3. `agents registered: claude-code, claude-code-plan`;
393
+ 4. `[acp-orchestrator] connected to agent`.
394
+
395
+ Notes:
396
+ - `opencode run` **without `-m` ignores the agent's `model`** and uses the global model from
397
+ config: that's how the V2 CLI behaves.
398
+ - The bridge's `question` dialog needs the interactive TUI.
399
+
400
+ **Verification scripts** (`scripts/`, not published to npm; they need `dist/`). They run
401
+ against the real `claude-agent-acp`; `VERIFY_MODEL=haiku` makes them cheaper.
402
+
403
+ | Script | What it checks |
404
+ | --- | --- |
405
+ | `verify-session-continuity.mjs` | session reuse across turns, revert without memory of undone turns |
406
+ | `verify-interleave-fix.mjs` | another model's turns in between are caught up |
407
+ | `verify-stream-integrity.mjs` | tool calls, reasoning block, text not cut |
408
+ | `verify-smart-revert.mjs` | a revert forks the session instead of replaying (`ACP_RECORD` decisions) |
409
+ | `verify-billing.mjs` | every native feature keeps usage on the **subscription** |
410
+ | `spike-permission-bridge.mjs` | the permission bridge end to end (approved creates the file, denied doesn't) |
411
+ | `check-install.mjs` | `npm pack` + install like OpenCode, then load the plugin and provider |
412
+
413
+ **Spikes** (without OpenCode): `.mjs` scripts inside the repo that import `../dist/...` and use
414
+ the AI SDK's `streamText` or the ACP SDK directly:
154
415
 
155
416
  ```js
156
417
  import { streamText } from "ai";
157
418
  import { createACPModelProvider } from "../dist/index.js";
158
- const model = createACPModelProvider({ command:"claude-agent-acp", claudeExecutable:"…", claudeCode:{configDir:"isolated"} }).languageModel("sonnet");
159
- for await (const p of streamText({ model, prompt:"di ok", providerOptions:{ acp:{ mode:"bypassPermissions", effort:"low" } } }).fullStream) { /* … */ }
419
+ const model = createACPModelProvider({ command: "claude-agent-acp", claudeExecutable: "…" }).languageModel("sonnet");
420
+ for await (const p of streamText({ model, prompt: "say ok", providerOptions: { acp: { mode: "bypassPermissions", effort: "low" } } }).fullStream) { /* … */ }
160
421
  ```
161
422
 
162
- Para inspeccionar lo que el provider envía, hay un volcado opt-in: setea `ACP_DUMP=<archivo>` para escribir `{modelId,ctrl,meta,prompt}` del primer turno con tools (úsalo solo en depuración).
423
+ **Inspecting what the provider sends:** set `ACP_RECORD=<dir>`. Each conversation gets a JSONL
424
+ file with:
425
+ - the prompt OpenCode sent, with large payloads cut;
426
+ - the decision taken (`new` / `reuse` / `continuation` / `smart-revert` / `shadow-diff`…);
427
+ - the blocks that actually went to the agent.
163
428
 
164
- Nota de coste: un prompt real consume de tu suscripción; los spikes de inspección (discovery, construir config, `setSessionMode`) no gastan tokens.
429
+ Cost note: a real prompt counts against your subscription. Inspection spikes (discovery,
430
+ building config, `setSessionMode`) spend no tokens.
165
431
 
166
432
  ---
167
433
 
168
- ## 6. Extender
169
-
170
- - **Nuevos agentes por defecto**: edita `agentDefs()` en `plugin/index.ts`. Cada entrada `{ name, description, model, variant, options }`. El usuario puede sobreescribir con `plugins[].options.agents.<n>` (options con `deepMerge`; description/model solo se rellenan si el usuario no los declaró en `agents.<n>` de config) o declarar el agente completo en `agents:` de config.
171
- - **Nuevos parámetros por-llamada**: añádelos a `ClaudeCodeControl` y léelos en `effectiveCtrl`; si son runtime, aplícalos en `applySessionConfig` (hay `setSessionMode`, `setSessionConfigOption`, `unstable_setSessionModel`).
172
- - **Más metadata de modelos**: `catalog.ts` (`buildModels`/`matchCatalog`).
173
- - **Otro agente ACP** (no Claude Code): el provider es genérico ACP; el comando/exe y el "cerebro limpio" se controlan por `options`. Las partes específicas de Claude están en `claude-config.ts`.
434
+ ## 6. Extending
435
+
436
+ - **New built-in agents:** edit `agentDefs()` in `plugin/index.ts`.
437
+ - Each entry is `{ name, description, model, variant, options }`.
438
+ - Users replace the whole list with a plain-object `plugins[].options.agents` (no merge
439
+ with the built-in profile), or turn it off with `agents: false`.
440
+ - `model` and `description` are only filled when the user hasn't set them in OpenCode's
441
+ `agents` section.
442
+ - **New per-call parameters:** add them to `ClaudeCodeControl`.
443
+ - Read them in `effectiveCtrl`, adding the key to its allow-list so it can come per agent.
444
+ - If they apply at runtime, apply them in `applySessionConfig`. The available calls are
445
+ `setSessionMode`, `setSessionConfigOption` and `unstable_setSessionModel`.
446
+ - **More model metadata:** `catalog.ts` (`buildModels`/`matchCatalog`).
447
+ - **Another ACP agent (not Claude Code):** the provider is generic ACP; the command and binary
448
+ come from the options. The Claude-specific parts live in `claude-config.ts`.
174
449
 
175
450
  ---
176
451
 
177
- ## 7. Decisiones de diseño no obvias
178
-
179
- - **`tools: []`** desactiva las tools nativas del agente — sin esto habría dos ejecutores y el modelo "OpenCode orquesta" se rompe.
180
- - **El runtime MCP corre con `node`, no `process.execPath`** — dentro de OpenCode `process.execPath` es el binario `opencode`, que no ejecuta un script JS arbitrario. Override con `ACP_RUNTIME_NODE`.
181
- - **Auth con config dir aislado** — un dir vacío rompe la auth; se **enlaza** `~/.claude/.credentials.json`.
182
- - **`systemPromptMode: "preset"` por defecto** — cualquier otro modo reenvía el system de OpenCode y dispara *extra usage*.
183
- - **Robustez EPIPE** — al cerrar el agente (p. ej. tras un error de API), sockets/pipes emiten EPIPE; blindado en `model.ts`/`discover.ts`/`mcp-host.ts`/`mcp-runtime.ts`.
184
- - **`default` = Opus 4.7** — el alias `default` del agente es Opus con 1M ctx; `sonnet[1m]` se factura como *extra usage*.
452
+ ## 7. Non-obvious design decisions
453
+
454
+ - **Common native tools disabled.**
455
+ - What: `disallowedTools` on the built-in agents covers Bash, Read, Write, Edit, MultiEdit,
456
+ Glob, Grep, WebFetch and TodoWrite, plus `tools: []` in the clean brain.
457
+ - Why: two executors would break "OpenCode orchestrates", and what a native tool reads never
458
+ reaches OpenCode's history. After a switch to another model that content would be gone.
459
+ - **The MCP runtime runs with `node`, not `process.execPath`.** Inside OpenCode,
460
+ `process.execPath` is the `opencode` binary, which doesn't run an arbitrary JS script.
461
+ Override with `ACP_RUNTIME_NODE`.
462
+ - **Isolated config dir needs the credentials link.** An empty dir breaks auth, so
463
+ `~/.claude/.credentials.json` is **linked** in.
464
+ - **`systemPromptMode: "preset"` by default.** Any other mode forwards OpenCode's system prompt
465
+ and triggers *extra usage*.
466
+ - **EPIPE hardening.** When the agent closes (e.g. after an API error), sockets and pipes raise
467
+ EPIPE. This is handled in `model.ts`, `discover.ts`, `mcp-host.ts` and `mcp-runtime.ts`.
468
+ - **The `default` model.**
469
+ - What: `default` is Claude Code's recommended model, an Opus with a 1M context.
470
+ - Observed: `sonnet[1m]` is billed as *extra usage*.