opencode-claude-code-acpbridge 0.10.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.
- package/CHANGELOG.md +301 -261
- package/LICENSE +21 -0
- package/README.md +597 -321
- package/dist/plugin/compat.d.ts +14 -0
- package/dist/plugin/compat.d.ts.map +1 -0
- package/dist/plugin/compat.js +45 -0
- package/dist/plugin/compat.js.map +1 -0
- package/dist/plugin/index.d.ts.map +1 -1
- package/dist/plugin/index.js +9 -3
- package/dist/plugin/index.js.map +1 -1
- package/dist/provider/model.d.ts +2 -1
- package/dist/provider/model.d.ts.map +1 -1
- package/dist/provider/model.js +20 -9
- package/dist/provider/model.js.map +1 -1
- package/docs/DEVELOPMENT.md +413 -136
- package/examples/01-minimal.jsonc +12 -9
- package/examples/02-per-agent-permissions.jsonc +39 -0
- package/examples/03-opencode-fidelity.jsonc +21 -0
- package/examples/04-model-and-effort.jsonc +35 -0
- package/examples/05-custom-agents.jsonc +32 -0
- package/examples/06-claude-ecosystem.jsonc +28 -0
- package/examples/07-manual-provider.jsonc +55 -0
- package/examples/08-permission-bridge.jsonc +42 -0
- package/examples/README.md +35 -17
- package/package.json +35 -30
- package/examples/02-permisos-por-agente.jsonc +0 -34
- package/examples/03-fidelidad-opencode.jsonc +0 -21
- package/examples/04-modelo-y-esfuerzo.jsonc +0 -36
- package/examples/05-agentes-personalizados.jsonc +0 -29
- package/examples/06-ecosistema-claude.jsonc +0 -24
- package/examples/07-provider-manual.jsonc +0 -42
- package/examples/08-puente-permisos.jsonc +0 -50
package/docs/DEVELOPMENT.md
CHANGED
|
@@ -1,193 +1,470 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Development — `opencode-claude-code-acpbridge`
|
|
2
2
|
|
|
3
|
-
|
|
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.
|
|
11
|
+
## 1. Overview
|
|
12
|
+
|
|
13
|
+
One npm package that OpenCode loads as **two things at once**:
|
|
8
14
|
|
|
9
|
-
|
|
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
|
-
|
|
12
|
-
|
|
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
|
-
|
|
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.
|
|
35
|
+
## 2. Architecture
|
|
19
36
|
|
|
20
37
|
```
|
|
21
|
-
┌─────────────────────────
|
|
22
|
-
│
|
|
23
|
-
OpenCode ──────┼─► Plugin (V2)
|
|
24
|
-
(TUI/run) │ • provider.transform:
|
|
25
|
-
│ •
|
|
26
|
-
│ • agent.transform:
|
|
27
|
-
│ claude-code +
|
|
28
|
-
│ • session.hook("context"):
|
|
29
|
-
│
|
|
30
|
-
│ • event: session.revert.* → clearLink
|
|
31
|
-
│
|
|
32
|
-
│
|
|
33
|
-
│
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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
|
-
- **
|
|
45
|
-
-
|
|
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.
|
|
69
|
+
## 3. Components (`src/`)
|
|
50
70
|
|
|
51
71
|
### `provider/model.ts` — `ACPOrchestratorModel`
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
- **
|
|
56
|
-
|
|
57
|
-
- `
|
|
58
|
-
- `
|
|
59
|
-
-
|
|
60
|
-
-
|
|
61
|
-
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
- **
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
-
|
|
70
|
-
|
|
71
|
-
|
|
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).
|
|
72
144
|
|
|
73
145
|
### `acp/mcp-host.ts` — `McpHost`
|
|
74
|
-
TCP server
|
|
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`).
|
|
75
150
|
|
|
76
151
|
### `acp/mcp-runtime.ts`
|
|
77
|
-
|
|
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.
|
|
78
160
|
|
|
79
161
|
### `acp/claude-config.ts`
|
|
80
|
-
`ClaudeCodeControl` (
|
|
81
|
-
|
|
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.
|
|
82
180
|
|
|
83
181
|
### `plugin/index.ts` · `bridge-rules.ts`
|
|
84
|
-
- **`provider.transform
|
|
85
|
-
-
|
|
86
|
-
-
|
|
87
|
-
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
-
|
|
92
|
-
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
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.
|
|
98
243
|
|
|
99
244
|
---
|
|
100
245
|
|
|
101
|
-
## 4.
|
|
102
|
-
|
|
103
|
-
###
|
|
104
|
-
1. `doStream`
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
- **
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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.
|
|
135
352
|
|
|
136
353
|
---
|
|
137
354
|
|
|
138
|
-
## 5. Build
|
|
139
|
-
|
|
140
|
-
**Antes de tocar la sincronía de historial**: `npm test`. El agente falso (`test/fake-agent.mjs`) habla ACP real y conduce el `mcp-runtime` real; `test/characterization.test.mjs` fija los comportamientos (KEEP) y cada fallo corregido; `test/fixtures/v2/*.jsonl` son prompts **reales** de OpenCode V2 (grabados con `ACP_RECORD`, anonimizados con `scripts/sanitize-recording.mjs`). Un cambio en `history.ts` sin una fixture real que lo respalde no entra — esta lógica ya se rompió varias veces (0.8.0, 9299af9).
|
|
355
|
+
## 5. Build and tests
|
|
141
356
|
|
|
142
357
|
```bash
|
|
143
358
|
npm install
|
|
144
359
|
npm run build # tsc → dist/
|
|
145
|
-
|
|
360
|
+
npm test # tsc + node --test "test/*.test.mjs"
|
|
361
|
+
npm run check:install # installs the packed package like OpenCode does and loads it
|
|
146
362
|
```
|
|
147
363
|
|
|
148
|
-
**
|
|
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`.
|
|
149
371
|
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
--agent claude-code -m acp/default "responde solo: ok"
|
|
153
|
-
```
|
|
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).
|
|
154
374
|
|
|
155
|
-
|
|
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`).
|
|
156
381
|
|
|
157
|
-
**
|
|
382
|
+
**Smoke test in OpenCode V2** (a test project whose `opencode.json` loads the plugin by its
|
|
383
|
+
absolute directory path):
|
|
158
384
|
|
|
159
|
-
|
|
160
|
-
|
|
385
|
+
```bash
|
|
386
|
+
cd <project> && ACP_DEBUG=1 opencode run --standalone --agent claude-code -m acp/default "reply only: ok"
|
|
387
|
+
```
|
|
161
388
|
|
|
162
|
-
|
|
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:
|
|
163
415
|
|
|
164
416
|
```js
|
|
165
417
|
import { streamText } from "ai";
|
|
166
418
|
import { createACPModelProvider } from "../dist/index.js";
|
|
167
|
-
const model = createACPModelProvider({ command:"claude-agent-acp", claudeExecutable:"…"
|
|
168
|
-
for await (const p of streamText({ model, prompt:"
|
|
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) { /* … */ }
|
|
169
421
|
```
|
|
170
422
|
|
|
171
|
-
|
|
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.
|
|
172
428
|
|
|
173
|
-
|
|
429
|
+
Cost note: a real prompt counts against your subscription. Inspection spikes (discovery,
|
|
430
|
+
building config, `setSessionMode`) spend no tokens.
|
|
174
431
|
|
|
175
432
|
---
|
|
176
433
|
|
|
177
|
-
## 6.
|
|
178
|
-
|
|
179
|
-
- **
|
|
180
|
-
-
|
|
181
|
-
-
|
|
182
|
-
|
|
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`.
|
|
183
449
|
|
|
184
450
|
---
|
|
185
451
|
|
|
186
|
-
## 7.
|
|
187
|
-
|
|
188
|
-
-
|
|
189
|
-
-
|
|
190
|
-
|
|
191
|
-
-
|
|
192
|
-
|
|
193
|
-
-
|
|
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*.
|