opencode-claude-code-acpbridge 0.10.1 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,40 @@ All notable changes to `opencode-claude-code-acpbridge`. The format is based on
6
6
  > **OpenCode V2 only since 0.9.0.** Versions 0.9.0 and later load only in OpenCode V2. If you
7
7
  > are still on OpenCode V1, stay on 0.8.x. See [MIGRATION_V2.md](MIGRATION_V2.md).
8
8
 
9
+ ## [0.11.0] — 2026-10-26
10
+
11
+ ### Changed — breaking
12
+
13
+ - **One agent per Claude Code mode.** The plugin injects a `claude-<mode>` agent for every
14
+ session mode the agent reports: `claude-default`, `claude-plan`, `claude-acceptedits`,
15
+ `claude-auto`, `claude-dontask`, `claude-bypasspermissions` (the six known modes when
16
+ discovery has none). They replace `claude-code` and `claude-code-plan`, with no aliases:
17
+ rename those agents in your `agents` section (`claude-code` → `claude-default`,
18
+ `claude-code-plan` → `claude-plan`). The mode only governs Claude's native tools; OpenCode's
19
+ tools keep the agent's OpenCode permissions. Effort stays a model variant; `claude-plan`
20
+ keeps `high`.
21
+ - **The `acp` models are paired with the Claude Code agents** (`pairModels`, default `true`).
22
+ OpenCode V2 offers every model to every agent, so the plugin enforces it:
23
+ - selecting an agent or model that breaks the pair moves the session back to a valid model
24
+ (the agent's own, the session's last non-`acp` model, or OpenCode's default `model`);
25
+ - an `acp` request from any other agent fails at once (HTTP 400, `x-should-retry: false`);
26
+ - OpenCode subagents launched from a `claude-*` agent get their own model or the default one
27
+ instead of inheriting `acp`.
28
+
29
+ Agents you declare with an `acp/…` model count as Claude Code agents. `pairModels: false`
30
+ restores the old behaviour.
31
+ - The usage-limit error now says to switch agent rather than model.
32
+
33
+ ### Fixed
34
+
35
+ - **Each effort variant started its own agent process.** OpenCode V2 builds a new SDK instance
36
+ for every distinct model `settings`, and the effort variants are settings, so `#high`,
37
+ `#low` and the plain model each spawned a `claude-agent-acp` that resumed the same Claude
38
+ session apart from the others (cache partly cold; going back to a variant found a process
39
+ that had missed the turns in between). Provider instances built from the same agent config
40
+ now share one orchestrator: effort switches live with `setSessionConfigOption`, and the
41
+ model without a variant restores the session's own effort.
42
+
9
43
  ## [0.10.1] — 2026-10-23
10
44
 
11
45
  ### Fixed
package/README.md CHANGED
@@ -52,7 +52,7 @@ and as a **model provider** (`createACPModelProvider`).
52
52
  | **OpenCode** | An open-source coding agent with a TUI, a desktop app and a CLI. They all talk to a local OpenCode **server**. |
53
53
  | **Plugin** | A package the OpenCode server loads to add features. You list plugins in `opencode.json`, and OpenCode installs them from npm. |
54
54
  | **Provider / model** | Where OpenCode sends prompts, e.g. `anthropic/claude-…`. This package adds a provider, `acp`, whose models (`acp/default`, `acp/sonnet`, …) are served by Claude Code. |
55
- | **Agent** | A configured assistant in OpenCode (`build`, `plan`, …). This package adds two: `claude-code` and `claude-code-plan`. |
55
+ | **Agent** | A configured assistant in OpenCode (`build`, `plan`, …). This package adds one per Claude Code mode: `claude-default`, `claude-plan`, `claude-acceptedits`, `claude-auto`, `claude-dontask`, `claude-bypasspermissions`. |
56
56
  | **Tool** | Something the model can call: `read`, `edit`, `bash`, MCP tools… |
57
57
  | **Claude Code** | Anthropic's coding agent (the `claude` CLI). Running through it keeps usage on your Pro/Max **subscription**. |
58
58
  | **ACP** | The [Agent Client Protocol](https://agentclientprotocol.com), a standard way for an editor or client to drive a coding agent. |
@@ -134,8 +134,8 @@ claude
134
134
  On start, the plugin **asks the agent which models it offers**, using a short-lived ACP
135
135
  connection. It fills in their metadata (context, cost, modalities) from
136
136
  [models.dev](https://models.dev) and **registers the `acp` provider** at runtime. You'll see
137
- `acp/default`, `acp/sonnet`, `acp/haiku`… in the model picker, and the agents `claude-code` and
138
- `claude-code-plan` in the agent picker. Check from a terminal with `opencode models | grep acp/`.
137
+ `acp/default`, `acp/sonnet`, `acp/haiku`… in the model picker, and one `claude-<mode>` agent per
138
+ Claude Code mode (`claude-default`, `claude-plan`…) in the agent picker. Check from a terminal with `opencode models | grep acp/`.
139
139
 
140
140
  - **Discovery is cached for 1 hour** in `~/.acp-model-provider/`. Only the first start (or the
141
141
  first after the cache expires) pays the 3–5 s it takes to start the agent. Force a refresh
@@ -162,8 +162,8 @@ The first request after that can take a few extra seconds while the package inst
162
162
 
163
163
  ## First use: agents, models and effort
164
164
 
165
- Pick the **`claude-code`** agent (or `claude-code-plan`) in OpenCode, or choose an `acp/…` model
166
- for any agent.
165
+ Pick a **`claude-<mode>`** agent in OpenCode (`claude-default` to start). The `acp/…` models
166
+ belong to those agents only: see [Models are paired with the Claude Code agents](#models-are-paired-with-the-claude-code-agents).
167
167
 
168
168
  **Models.** The list comes from **your account**, not from this package: it's whatever the
169
169
  agent reports. At the time of writing, on a Max account:
@@ -178,13 +178,14 @@ agent reports. At the time of writing, on a Max account:
178
178
  - `opus` works through `claudeCode.model` even though discovery doesn't list it.
179
179
  - You can also use full ids such as `claude-sonnet-4-6`.
180
180
 
181
- **All models share one agent process.** The model is applied per session with
182
- `session/set_model`, so switching `opus` → `sonnet` mid-conversation keeps the session: no
183
- replay, no new process.
181
+ **All models and effort levels share one agent process.** The model is applied per session
182
+ with `session/set_model`, so switching `opus` → `sonnet` mid-conversation keeps the session: no
183
+ replay, no new process. The same goes for the agent's mode (`session/set_mode`) and effort.
184
184
 
185
185
  **Effort** (how hard Claude thinks) is exposed as model **variants**: `acp/sonnet#low` …
186
- `#medium`, `#high`, `#xhigh`, `#max` (V2 syntax `provider/model#variant`). Pick one in the TUI,
187
- or set it per agent (see [Agents and subagents](#agents-and-subagents)) or for the whole
186
+ `#medium`, `#high`, `#xhigh`, `#max` (V2 syntax `provider/model#variant`). It is applied live
187
+ (`setSessionConfigOption`); the model **without** a variant goes back to the session's own
188
+ effort. Pick one in the TUI, or set it per agent (see [Agents and subagents](#agents-and-subagents)) or for the whole
188
189
  provider:
189
190
 
190
191
  ```jsonc
@@ -247,8 +248,9 @@ the provider.
247
248
  | `streamCloseTimeoutMs` | `number` | `ACP_STREAM_CLOSE_TIMEOUT_MS` | `600000` | Sets `CLAUDE_CODE_STREAM_CLOSE_TIMEOUT` for older agents. `claude-agent-acp` ≥ 0.31 doesn't read it: a pending tool call is bounded by `MCP_TOOL_TIMEOUT` (~27 h by default), so waiting for you to approve a permission never cuts the turn. |
248
249
  | `providerId` | `string` | — | `"acp"` | Provider id the models are registered under (see [below](#changing-the-provider-id)). |
249
250
  | `name` | `string` | — | `"Claude Code (ACP)"` | Provider display name. |
250
- | `agents` | `false \| Record` | — | two agents | `false` injects no agents. A `Record` **replaces** the default `claude-code` / `claude-code-plan` definitions entirely, including their native toolset ([details](#agents-and-subagents)). |
251
+ | `agents` | `false \| Record` | — | one per mode | `false` injects no agents. A `Record` **replaces** the default `claude-<mode>` definitions entirely, including their native toolset ([details](#agents-and-subagents)). |
251
252
  | `agentModel` | `string` | — | `"default"` | Model of the injected agents. |
253
+ | `pairModels` | `boolean` | — | `true` | Reserve the provider's models for the injected agents, and those agents for the provider's models ([details](#models-are-paired-with-the-claude-code-agents)). `false` lets any agent use any model. |
252
254
  | `titleFromModel` | `boolean` | — | `false` | Let the model title sessions. By default the plugin titles them from the first user message, with no model call. |
253
255
  | `npm` | `string` | — | auto | Package spec the provider is loaded from. Only needed in unusual setups. |
254
256
  | `claudeCode` | `object` | — | "clean brain" | How Claude Code runs: the table below. |
@@ -348,7 +350,7 @@ hand, so there is only one backend:
348
350
  ]
349
351
  ```
350
352
 
351
- Auto-registration, resume, the permission bridge and the agents (`claude-code` →
353
+ Auto-registration, resume, the permission bridge and the agents (`claude-default` →
352
354
  `anthropic/default`) then all use that id.
353
355
 
354
356
  > [!WARNING]
@@ -361,15 +363,23 @@ Auto-registration, resume, the permission bridge and the agents (`claude-code`
361
363
 
362
364
  ## Agents and subagents
363
365
 
364
- The plugin **injects two agents** into OpenCode:
366
+ The plugin **injects one agent per Claude Code session mode**, as the agent reports them on
367
+ start (model `acp/default`; `claude-default` comes first):
365
368
 
366
- - **`claude-code`**: native Claude Code (model `acp/default`), ACP mode **`default`**. Every
367
- native tool goes through the [permission bridge](#tools-and-the-permission-bridge), so
368
- **OpenCode stays the only authority**.
369
- - **`claude-code-plan`**: mode **`plan`**. Claude **plans** (researches, reads, writes the
370
- plan) without making destructive changes. Effort variant `high`.
371
-
372
- Both have the same native toolset and differ only in their starting mode.
369
+ | Agent | Mode | Native tools (Skill, Task, WebSearch, NotebookEdit…) |
370
+ | --- | --- | --- |
371
+ | `claude-default` | `default` | Every one goes through the [permission bridge](#tools-and-the-permission-bridge): **OpenCode stays the only authority**. |
372
+ | `claude-plan` | `plan` | Claude **plans** (researches, reads, writes the plan) without making changes until you approve it. Effort variant `high`. |
373
+ | `claude-acceptedits` | `acceptEdits` | Native edits are accepted without asking. |
374
+ | `claude-auto` | `auto` | Claude Code's classifier approves or denies each native action. |
375
+ | `claude-dontask` | `dontAsk` | Native actions not pre-approved are denied, never asked. |
376
+ | `claude-bypasspermissions` | `bypassPermissions` | Never asks: the permission bridge is skipped. |
377
+
378
+ They share the same native toolset and differ only in their starting mode. **The mode only
379
+ governs Claude's native tools.** OpenCode's own tools (`bash`, `edit`, `write`, MCP…) always
380
+ run with the OpenCode permissions of the agent, whatever its mode: restrict or open those in
381
+ the `agents` section of your config (below). **Effort** is picked as usual, as a variant of the
382
+ `acp/…` model.
373
383
 
374
384
  To **adjust** them (permissions, model, description), use the `agents` section of your
375
385
  OpenCode config, shown just below. To **replace** them with your own agents, use the plugin's
@@ -379,15 +389,16 @@ OpenCode config, shown just below. To **replace** them with your own agents, use
379
389
  "plugins": [{ "package": "opencode-claude-code-acpbridge",
380
390
  "options": { "command": "claude-agent-acp",
381
391
  "agents": { // or "agents": false to inject none
382
- "claude-code": { "model": "default", "options": { "mode": "default" } },
383
- "claude-code-plan": { "model": "default", "variant": "high", "options": { "mode": "plan" } }
392
+ "claude-default": { "model": "default", "options": { "mode": "default" } },
393
+ "claude-plan": { "model": "default", "variant": "high", "options": { "mode": "plan" } }
384
394
  }
385
395
  }
386
396
  }]
387
397
  ```
388
398
 
389
399
  > [!WARNING]
390
- > A plugin-level `agents` record **replaces** the built-in definitions. Your `options` are all
400
+ > A plugin-level `agents` record **replaces** the built-in definitions (and the pairing then
401
+ > covers exactly the agents you list). Your `options` are all
391
402
  > those agents get, so the native toolset of the defaults is gone unless you list it:
392
403
  > - `disallowedTools`;
393
404
  > - `resourceSearch`, `nativeSubagents`;
@@ -407,7 +418,7 @@ through the plugin's `context` hook. They are applied **live** (`setSessionMode`
407
418
  > plugin:
408
419
  > ```jsonc
409
420
  > "agents": {
410
- > "claude-code": {
421
+ > "claude-default": {
411
422
  > "permissions": [
412
423
  > { "action": "edit", "resource": "*", "effect": "deny" },
413
424
  > { "action": "bash", "resource": "*", "effect": "ask" }
@@ -417,11 +428,11 @@ through the plugin's `context` hook. They are applied **live** (`setSessionMode`
417
428
  > ```
418
429
  > `"disabled": true` turns an injected agent off.
419
430
 
420
- - **Modes.** OpenCode runs the tools with its own permissions, so Claude Code's permission
421
- modes don't change *who* authorises:
422
- - `bypassPermissions` only skips the `requestPermission` round trip;
431
+ - **Modes.** OpenCode runs its tools with its own permissions, so Claude Code's permission
432
+ modes don't change *who* authorises them:
433
+ - `bypassPermissions` only skips the `requestPermission` round trip for native tools;
423
434
  - `plan` is the one with a real effect of its own;
424
- - avoid `dontAsk`, which can block tools.
435
+ - `dontAsk` denies the native tools outright (skills, native subagents, web search).
425
436
  - **Two ways to delegate.**
426
437
  - **OpenCode's `subagent` tool** is preferred for real work. The child session is visible in
427
438
  OpenCode, **any model** can continue it, and its result stays in the shared history.
@@ -430,8 +441,12 @@ through the plugin's `context` hook. They are applied **live** (`setSessionMode`
430
441
  `nativeActivity`).
431
442
  - Both tools' descriptions steer Claude. If one of your agents relies on native
432
443
  `Bash`/`Edit`, it uses OpenCode's tools instead.
433
- - **OpenCode subagents on this provider.** A child session inherits its parent's model (`acp`).
434
- Child sessions:
444
+ - **OpenCode subagents run on another model.** OpenCode gives a child session its parent's model
445
+ unless the subagent has its own, and the `acp` models are reserved for the `claude-*` agents.
446
+ So when a `claude-*` agent launches `general`, `explore`…, the plugin passes the subagent its
447
+ own model, or OpenCode's default `model` when it has none. Without either (or with
448
+ `model: "acp/…"` in the call), the call fails with a message saying what to set. With
449
+ `pairModels: false`, child sessions inherit `acp` as before and:
435
450
  - get the base profile (`allowedTools: ["mcp__opencode"]`);
436
451
  - get a native permission request denied with a reason if their agent can't use `question`
437
452
  (OpenCode's `general` denies it), instead of hanging;
@@ -446,7 +461,7 @@ through the plugin's `context` hook. They are applied **live** (`setSessionMode`
446
461
  - keep planning.
447
462
 
448
463
  If you **type** an answer instead, the plan is rejected and your text reaches Claude as
449
- feedback. The mode you chose survives switching from the plan agent to `claude-code`.
464
+ feedback. The mode you chose survives switching from `claude-plan` to `claude-default`.
450
465
  - **Resuming without resending history.** `~/.acp-model-provider/sessions.json` maps each
451
466
  OpenCode session to its Claude Code session. On reopening, the provider resumes it
452
467
  (`resumeSession`) instead of replaying the whole history. Entries older than 30 days are
@@ -455,11 +470,27 @@ through the plugin's `context` hook. They are applied **live** (`setSessionMode`
455
470
  Claude, which would answer the message instead. So the plugin titles sessions from their
456
471
  first message, with no model call. `titleFromModel: true` restores the model call.
457
472
 
473
+
474
+ ### Models are paired with the Claude Code agents
475
+
476
+ The `acp/…` models are **only for the `claude-*` agents**, and those agents **only use `acp/…`
477
+ models** (`pairModels`, on by default):
478
+
479
+ - **Switching agent switches the model.** Picking a `claude-*` agent puts the session on that
480
+ agent's `acp` model; going back to `build` (or any other agent) puts it back on that agent's
481
+ model, or the last non-`acp` model the session used, or OpenCode's default `model`.
482
+ - **OpenCode's model picker still lists every model for every agent**: V2 has no per-agent model
483
+ list. If you pick a model that breaks the pair, the plugin moves the session back to a valid
484
+ one, and an `acp` request from another agent fails at once with
485
+ `Claude Code: the model … is reserved for the Claude Code agents (claude-*)…`.
486
+ - **Subagents** never inherit an `acp` model (see above).
487
+ - `pairModels: false` turns all of this off.
488
+
458
489
  ---
459
490
 
460
491
  ## Tools and the permission bridge
461
492
 
462
- The `claude-code` agent gets Claude Code's native power without bypassing OpenCode:
493
+ The `claude-*` agents get Claude Code's native power without bypassing OpenCode:
463
494
 
464
495
  - **Common tools → OpenCode runs them.** Claude reaches every tool OpenCode exposes through
465
496
  MCP: OpenCode's own (`read`, `write`, `bash`, `edit`, `grep`…) and those of your MCP servers.
@@ -482,7 +513,7 @@ The `claude-code` agent gets Claude Code's native power without bypassing OpenCo
482
513
  arrive while OpenCode is still running the previous step are queued for the next one, never
483
514
  dropped; native subagents working in parallel do this, for example.
484
515
  - **Context-pruning plugins** ([opencode-dcp](https://www.npmjs.com/package/@p4r4d0xb0x/opencode-dcp)).
485
- The plugin denies `compress` to the `claude-code*` agents. DCP rewrites OpenCode's copy of
516
+ The plugin denies `compress` to the `claude-*` agents. DCP rewrites OpenCode's copy of
486
517
  the history, but the Claude Code session keeps its own context, so pruning only caused
487
518
  divergences and replays. DCP keeps working for your other agents.
488
519
  - **The permission bridge.** When Claude (or a native subagent) wants a **native** tool,
@@ -493,8 +524,8 @@ The `claude-code` agent gets Claude Code's native power without bypassing OpenCo
493
524
  `agents.<name>.permissions`; `action: "*"` defaults are ignored.
494
525
  - Anything not covered opens the dialog: the bridge **fails closed**.
495
526
  - `Always allow` answers are stored in `~/.acp-model-provider/always.json`.
496
- - The bridge needs the agent **not** to be in `bypassPermissions`, which is why `claude-code`
497
- uses `mode: "default"`.
527
+ - The bridge needs the agent **not** to be in `bypassPermissions`: `claude-bypasspermissions`
528
+ runs native tools without asking anyone.
498
529
  - **The classic "clean brain"**, where OpenCode runs everything and there are no native tools:
499
530
  use `mode: "bypassPermissions"` with no native toggles, or a manual provider with
500
531
  `claudeCode.tools: []`.
@@ -506,8 +537,8 @@ The `claude-code` agent gets Claude Code's native power without bypassing OpenCo
506
537
  OpenCode sends the **full** history on every call, while an ACP session keeps **state**. The
507
538
  provider keeps one Claude Code session per conversation and sends it **only what it hasn't
508
539
  seen**. Claude's prompt cache lives with that session, so the session is recreated as rarely
509
- as possible. You can switch between `acp` and any other OpenCode model in the same
510
- conversation, in both directions, and carry on.
540
+ as possible. You can switch between a `claude-*` agent (on `acp`) and any other agent and
541
+ model in the same conversation, in both directions, and carry on.
511
542
 
512
543
  - **Claude's own answer isn't sent back.** OpenCode stores Claude's reply and resends it on the
513
544
  next turn. The provider recognises it (by the text it emitted and its own tool ids) and
@@ -520,14 +551,14 @@ conversation, in both directions, and carry on.
520
551
  (`nativeActivity`), so the other model sees it.
521
552
  - **Usage limit.** If your Claude quota runs out, the error says so plainly and isn't retried
522
553
  in a loop:
523
- `Claude Code: usage limit reached (resets: <when>). Switch to another model in OpenCode to
524
- continue; the Claude Code session is kept for when you come back.`
554
+ `Claude Code: usage limit reached (resets: <when>). Switch to another agent in OpenCode (not
555
+ claude-*) to continue with its model; the Claude Code session is kept for when you come back.`
525
556
  - **Typing while Claude works** (*steer*), or **interrupting and typing something else**, both
526
557
  work:
527
558
  - your message reaches Claude, through Claude Code's own queue or together with the pending
528
559
  tool result;
529
560
  - an interrupted turn is cancelled on the agent before the new one starts.
530
- - **Changing agent** (`claude-code` ↔ `claude-code-plan`) or **toolset** keeps the session,
561
+ - **Changing agent** (`claude-default` ↔ `claude-plan` …) or **toolset** keeps the session,
531
562
  live. Moving to an agent with **another native profile** forks the session.
532
563
  - **Changing `acp` model** (opus ↔ sonnet) keeps the session (`session/set_model`).
533
564
  - **Compaction.** Claude compacts its own session before OpenCode would (`autoCompactPct`). If
@@ -603,10 +634,11 @@ per turn decision.
603
634
  | --- | --- |
604
635
  | `Model not found: acp/…` | OpenCode didn't load your config, or auto-registration failed. Run `opencode debug config`: it must list your document with `plugins`. With `ACP_DEBUG=1`, look for `[acp-plugin] auto-registered provider 'acp' … — models: …` at startup. For a local directory plugin with no `loading plugin` line, the root `index.js` is missing: run `npm run build`. |
605
636
  | Auto-registration adds no models | Run `npx opencode-claude-code-acpbridge sync claude-agent-acp` to see what the agent reports and to refresh the cache. If the agent can't find the `claude` binary, set `claudeExecutable`. |
606
- | `API Error: 400 … extra usage` | The system prompt triggered Anthropic's classifier. Use `systemPromptMode: "preset"` (the default) or the `claude-code` agent. Typical causes: `append`/`replace`, or an agent from another plugin with an aggressive system prompt. See [Billing](#billing-subscription-vs-extra-usage). |
637
+ | `API Error: 400 … extra usage` | The system prompt triggered Anthropic's classifier. Use `systemPromptMode: "preset"` (the default) or a `claude-*` agent. Typical causes: `append`/`replace`, or an agent from another plugin with an aggressive system prompt. See [Billing](#billing-subscription-vs-extra-usage). |
607
638
  | `Authentication required` | Claude Code isn't logged in, or the isolated config dir has no credentials. Run `claude` and log in; with `configDir: "isolated"` the provider links `~/.claude/.credentials.json` automatically. |
608
639
  | Claude says it has no `read` / doesn't use the tools | The internal MCP server must run with `node` (on the `PATH`). Override with `ACP_RUNTIME_NODE`. |
609
- | `Claude Code: usage limit reached …` | Your subscription limit. Switch to another model in OpenCode and come back later: the session is kept. |
640
+ | `Claude Code: usage limit reached …` | Your subscription limit. Switch to another agent (not `claude-*`) and come back later: the session is kept. |
641
+ | `Claude Code: the model … is reserved for the Claude Code agents` | An `acp` model was used by another agent. Pick a `claude-*` agent, or another model for that agent. See [pairing](#models-are-paired-with-the-claude-code-agents). |
610
642
  | Many `shadow-diff` lines in the log | With `historyMode: "shadow"`, each one is a turn where the new fingerprint would have decided differently. If they're all `legacy: diverged` → `anchors: append`, `"v2"` would save those replays. |
611
643
  | Token usage out of control / `cacheR` at 0 | With `ACP_DEBUG=1`, look for `dropping session … —` on every turn, which names the reason. See [Switching models](#switching-models-mid-session-and-token-cost). |
612
644
  | Context keeps growing and OpenCode doesn't compact | Only the `[1m]` models advertise a 1M window, and OpenCode won't compact until close to it. Use the regular model for earlier compaction. |
@@ -684,7 +716,7 @@ npm test # tsc + node --test
684
716
  - **Run your checkout in OpenCode**: point the plugin at the repository directory,
685
717
  `"plugins": [{ "package": "/path/to/opencode-claude-code-acpbridge", "options": { "command": "claude-agent-acp" } }]`.
686
718
  OpenCode loads `<dir>/index.*`, and the root `index.js` re-exports `dist/`, so build first.
687
- - **Smoke test**: `opencode run --standalone --agent claude-code -m acp/default "…"` in a test
719
+ - **Smoke test**: `opencode run --standalone --agent claude-default -m acp/default "…"` in a test
688
720
  project. The bridge's `question` dialog needs the interactive TUI.
689
721
  - The package also exports `createACPProviderFromEnv`. It is the upstream
690
722
  `@mcpc-tech/acp-ai-provider` without tool orchestration, if you only want plain chat.
@@ -720,8 +752,9 @@ src/
720
752
  mcp-runtime.ts # stdio runtime the agent spawns (hand-written MCP, no deps) → TCP to the host
721
753
  claude-config.ts # clean brain + isolated CLAUDE_CONFIG_DIR with credentials; mode/effort/system prompt
722
754
  plugin/
723
- index.ts # Plugin.define: provider.transform (acp), agent.transform (claude-code + rules),
755
+ index.ts # Plugin.define: provider.transform (acp), agent.transform (claude-<mode> + rules),
724
756
  # context/compaction/generate hooks, title (no model), session.revert.* → clearLink
757
+ pairing.ts # one agent per mode; acp models ↔ claude-* agents (pairTarget, subagentDecision)
725
758
  bridge-rules.ts # per-agent rule store + always.json; fail-closed evaluate() (ignores action:"*")
726
759
  discover.ts # short-lived ACP connection → models / modes / capabilities
727
760
  catalog.ts # models.dev metadata + effort variants → Model.Info[]
@@ -88,7 +88,7 @@ export interface ClaudeCodeControl {
88
88
  * ACP session mode, applied at runtime via `setSessionMode` (e.g. `"plan"`,
89
89
  * `"bypassPermissions"`). Unlike `permissionMode` (which the ACP agent ignores
90
90
  * for the session mode), this actually switches the mode. Can be set per-call
91
- * through `providerOptions.acp.mode` (e.g. a `claude-code-plan` agent).
91
+ * through `providerOptions.acp.mode` (e.g. the `claude-plan` agent).
92
92
  */
93
93
  mode?: ClaudePermissionMode;
94
94
  /**
@@ -1,4 +1,12 @@
1
1
  import { Plugin } from "@opencode/plugin";
2
+ /** Agent profiles: one per Claude Code session mode the agent reports (`claude-default`,
3
+ * `claude-plan`, …; the mode is the only difference) + Claude native options. V2's
4
+ * `Agent.Info` has no `options` field, so these travel to the provider per call through
5
+ * the `context` hook (merged with `options.agents.<name>.options`). */
6
+ export declare function agentDefs(opts: Record<string, any>, modes?: ReadonlyArray<{
7
+ id: string;
8
+ name?: string;
9
+ }>): Record<string, any>;
2
10
  /** A session title from the first user message: first meaningful line, quotes and
3
11
  * markup stripped, cut on a word boundary. */
4
12
  export declare function titleFrom(messages: readonly any[]): string | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/plugin/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAY,MAAM,kBAAkB,CAAC;AAyJlE;+CAC+C;AAC/C,wBAAgB,SAAS,CAAC,QAAQ,EAAE,SAAS,GAAG,EAAE,GAAG,MAAM,GAAG,SAAS,CAatE;AAED,eAAO,MAAM,SAAS,eAsMpB,CAAC;AAEH,eAAe,SAAS,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/plugin/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAgB,MAAM,EAAY,MAAM,kBAAkB,CAAC;AA8FlE;;;wEAGwE;AACxE,wBAAgB,SAAS,CAAC,IAAI,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,EAAE,KAAK,GAAE,aAAa,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,MAAM,CAAA;CAAE,CAAkB,GAAG,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAM9I;AAsCD;+CAC+C;AAC/C,wBAAgB,SAAS,CAAC,QAAQ,EAAE,SAAS,GAAG,EAAE,GAAG,MAAM,GAAG,SAAS,CAatE;AAED,eAAO,MAAM,SAAS,eAiSpB,CAAC;AAEH,eAAe,SAAS,CAAC"}
@@ -6,6 +6,7 @@ import { loadAnthropicCatalog, buildModelsInfo } from "./catalog.js";
6
6
  import { readCacheKeyed, writeCache } from "./cache.js";
7
7
  import { getLink, clearLink } from "./sessions.js";
8
8
  import { publishAgentRules } from "./bridge-rules.js";
9
+ import { FALLBACK_MODES, modeAgentDefs, pairTarget, subagentDecision, isProviderModel, refString } from "./pairing.js";
9
10
  import { detectClaudeExecutable } from "../provider/factory.js";
10
11
  import { logger } from "../log.js";
11
12
  import { compatibilityWarnings } from "./compat.js";
@@ -60,7 +61,7 @@ function resolveNpmSpec(override) {
60
61
  }
61
62
  /** Strip plugin-only keys; the rest are the provider/agent options passed to the factory. */
62
63
  function providerOptions(opts) {
63
- const { name: _n, npm: _npm, providerId: _p, models: _m, agents: _a, agentModel: _am, ...rest } = opts;
64
+ const { name: _n, npm: _npm, providerId: _p, models: _m, agents: _a, agentModel: _am, pairModels: _pm, ...rest } = opts;
64
65
  return rest;
65
66
  }
66
67
  /** Native feature set shared by the Claude Code agents ("clean brain" + the reactivated
@@ -69,7 +70,7 @@ function providerOptions(opts) {
69
70
  * loaded through `settingSources: user`) and OpenCode's `subagent` tool, whose child
70
71
  * sessions stay visible and continuable by ANY model — the preferred one for real work,
71
72
  * since the user switches between this provider and others mid-session (descriptions
72
- * steer the agent). IDENTICAL for both agents on purpose: they differ ONLY in the initial
73
+ * steer the agent). IDENTICAL for every agent on purpose: they differ ONLY in the initial
73
74
  * session mode, so a plan session can never end up half-restricted. */
74
75
  const NATIVE_BASE = {
75
76
  allowedTools: ["mcp__opencode"], // OpenCode's tools don't double-prompt (it owns them)
@@ -86,30 +87,17 @@ const NATIVE_BASE = {
86
87
  projectMemory: true, // CLAUDE.md/AGENTS.md (verified: keeps subscription)
87
88
  nativeSkills: true, // ~/.claude/skills, hooks disabled (verified: keeps subscription)
88
89
  };
89
- /** Agent profiles: Claude session mode (the only difference between the two) + Claude
90
- * native options. V2's `Agent.Info` has no `options` field, so these travel to the
91
- * provider per call through the `context` hook (merged with `options.agents.<name>.options`). */
92
- function agentDefs(opts) {
90
+ /** Agent profiles: one per Claude Code session mode the agent reports (`claude-default`,
91
+ * `claude-plan`, …; the mode is the only difference) + Claude native options. V2's
92
+ * `Agent.Info` has no `options` field, so these travel to the provider per call through
93
+ * the `context` hook (merged with `options.agents.<name>.options`). */
94
+ export function agentDefs(opts, modes = FALLBACK_MODES) {
93
95
  if (opts.agents && opts.agents !== true && isPlainObject(opts.agents))
94
96
  return opts.agents;
95
97
  if (opts.agents && opts.agents !== true && !isPlainObject(opts.agents)) {
96
98
  dbg("invalid agents config — using defaults");
97
99
  }
98
- return {
99
- "claude-code": {
100
- name: "Claude Code",
101
- description: "Claude Code (subscription) — native capabilities with permissions bridged to OpenCode",
102
- model: opts.agentModel ?? "default",
103
- options: { mode: "default", ...NATIVE_BASE },
104
- },
105
- "claude-code-plan": {
106
- name: "Claude Code (plan)",
107
- description: "Claude Code — plan mode (research & plan, no destructive edits)",
108
- model: opts.agentModel ?? "default",
109
- variant: "high",
110
- options: { mode: "plan", ...NATIVE_BASE },
111
- },
112
- };
100
+ return modeAgentDefs(modes, opts.agentModel ?? "default", NATIVE_BASE);
113
101
  }
114
102
  /** `Model.Ref` for an agent: `"default"` → `<provider>/default`, a full ref passes through. */
115
103
  function modelRef(value, providerID, variant) {
@@ -125,9 +113,10 @@ function modelRef(value, providerID, variant) {
125
113
  * "options": { "command": "claude-agent-acp" } }]
126
114
  *
127
115
  * It discovers the agent's models (cached), pulls their metadata from models.dev,
128
- * registers the `acp` provider with the populated `Model.Info[]`, injects the
129
- * `claude-code` / `claude-code-plan` agents, and bridges every per-request value
130
- * (session link, agent options) through the `context` hook.
116
+ * registers the `acp` provider with the populated `Model.Info[]`, injects one
117
+ * `claude-<mode>` agent per Claude Code session mode, pairs the provider's models
118
+ * with those agents, and bridges every per-request value (session link, agent
119
+ * options) through the `context` hook.
131
120
  */
132
121
  /** ¿Está la tool `question` en el set de tools del agente? Soporta array / Set /
133
122
  * Record (según cómo OpenCode lo haya convertido); sin info se asume que sí
@@ -172,6 +161,10 @@ export const ACPPlugin = Plugin.define({
172
161
  const opts = (ctx.options ?? {});
173
162
  const providerId = opts.providerId ?? "acp";
174
163
  const agentOptions = new Map();
164
+ // Model ↔ agent pairing (see pairing.ts). Off with `pairModels: false`, and inert
165
+ // until our agents are registered (a manually declared provider has none).
166
+ const pairing = { providerID: providerId, agentModels: new Map(), acpAgents: new Set() };
167
+ const pairingOn = () => opts.pairModels !== false && pairing.acpAgents.size > 0;
175
168
  if (!opts.command && !process.env.ACP_COMMAND) {
176
169
  dbg("no `command` in plugin options — skipping auto-register (declare the provider manually)");
177
170
  }
@@ -231,7 +224,7 @@ export const ACPPlugin = Plugin.define({
231
224
  await registering;
232
225
  dbg(`auto-registered provider '${providerId}' (aisdk:${npmSpec}) — models: ${models.map((m) => m.id).join(", ")}`);
233
226
  if (opts.agents !== false) {
234
- const defs = agentDefs(opts);
227
+ const defs = agentDefs(opts, discovered?.modes ?? []);
235
228
  await ctx.agent.transform((editor) => {
236
229
  for (const [name, raw] of Object.entries(defs)) {
237
230
  const def = raw;
@@ -273,10 +266,18 @@ export const ACPPlugin = Plugin.define({
273
266
  }
274
267
  // Any agent can run on this provider (a subagent inherits its parent's
275
268
  // model), so the bridge needs every agent's rules — not just ours.
269
+ const agentModels = new Map();
276
270
  for (const item of editor.list()) {
277
271
  if (!(String(item.id) in defs))
278
272
  publishAgentRules(String(item.id), item.permissions);
273
+ agentModels.set(String(item.id), item.model ? { ...item.model, providerID: String(item.model.providerID), id: String(item.model.id) } : undefined);
279
274
  }
275
+ pairing.agentModels = agentModels;
276
+ // Ours, plus any agent the user configured with one of the provider's models.
277
+ pairing.acpAgents = new Set([
278
+ ...Object.keys(defs),
279
+ ...[...agentModels].filter(([, m]) => isProviderModel(m, providerId)).map(([id]) => id),
280
+ ]);
280
281
  });
281
282
  dbg(`agents registered: ${Object.keys(defs).join(", ")}`);
282
283
  }
@@ -302,6 +303,9 @@ export const ACPPlugin = Plugin.define({
302
303
  event.options.requestKind = kind;
303
304
  // Whether the agent can ask the user: the permission bridge needs `question`.
304
305
  event.options.hasQuestion = !!event.tools && "question" in event.tools;
306
+ // Only the Claude Code agents may use this provider: the provider refuses the rest.
307
+ if (pairingOn())
308
+ event.options.pairedAgent = pairing.acpAgents.has(String(event.agent));
305
309
  const link = getLink(event.sessionID);
306
310
  if (link?.acpSessionId) {
307
311
  event.options.resumeId = link.acpSessionId;
@@ -341,13 +345,70 @@ export const ACPPlugin = Plugin.define({
341
345
  // the prompt itself (history fingerprint), so programmatic use without the
342
346
  // plugin stays correct.
343
347
  const closed = new AbortController();
348
+ // Pairing watcher. The TUI commits a turn's agent and model as two separate calls
349
+ // (switchAgent, then switchModel), so a session is checked once both have landed —
350
+ // a short per-session debounce — and only a pair still broken then is fixed.
351
+ const lastOther = new Map(); // last non-acp model seen per session
352
+ const pending = new Map();
353
+ const remember = (sessionID, model) => {
354
+ if (model?.providerID && !isProviderModel(model, providerId))
355
+ lastOther.set(sessionID, { providerID: String(model.providerID), id: String(model.id), ...(model.variant ? { variant: String(model.variant) } : {}) });
356
+ };
357
+ const defaultModel = async () => {
358
+ try {
359
+ const m = (await ctx.model.default())?.data;
360
+ return m ? { providerID: String(m.providerID), id: String(m.id) } : undefined;
361
+ }
362
+ catch {
363
+ return undefined;
364
+ }
365
+ };
366
+ const checkPair = async (sessionID) => {
367
+ if (closed.signal.aborted || !pairingOn())
368
+ return;
369
+ try {
370
+ const session = await ctx.session.get({ sessionID: sessionID });
371
+ const current = session?.model ? { ...session.model, providerID: String(session.model.providerID), id: String(session.model.id) } : undefined;
372
+ remember(sessionID, current);
373
+ const fallback = lastOther.get(sessionID) ?? (await defaultModel());
374
+ const target = pairTarget(pairing, { agent: session?.agent ? String(session.agent) : undefined, model: current }, fallback);
375
+ if (!target) {
376
+ if (current && session?.agent && isProviderModel(current, providerId) && !pairing.acpAgents.has(String(session.agent)))
377
+ log.note(`pairing: session ${sessionID} (agent ${session.agent}) is on ${refString(current)} and no non-acp model is known — set a default \`model\` in OpenCode`);
378
+ return;
379
+ }
380
+ dbg(`pairing: session ${sessionID} agent ${session?.agent} on ${current ? refString(current) : "?"} → ${refString(target)}`);
381
+ await ctx.session.switchModel({ sessionID: sessionID, model: Model.Ref.parse(refString(target)) });
382
+ }
383
+ catch (e) {
384
+ dbg(`pairing check failed for ${sessionID}: ${e instanceof Error ? e.message : String(e)}`);
385
+ }
386
+ };
387
+ const schedulePair = (sessionID) => {
388
+ clearTimeout(pending.get(sessionID));
389
+ pending.set(sessionID, setTimeout(() => {
390
+ pending.delete(sessionID);
391
+ void checkPair(sessionID);
392
+ }, 150));
393
+ };
344
394
  const events = (async () => {
345
395
  try {
346
396
  for await (const event of ctx.event.subscribe({ signal: closed.signal })) {
397
+ const data = event.data;
398
+ const sessionID = data?.sessionID;
399
+ if (!sessionID)
400
+ continue;
401
+ if (event.type === "session.created" || event.type === "session.agent.selected" || event.type === "session.model.selected") {
402
+ if (!pairingOn())
403
+ continue;
404
+ remember(sessionID, data?.previous && event.type === "session.model.selected" ? data.previous : undefined);
405
+ remember(sessionID, data?.model);
406
+ schedulePair(sessionID);
407
+ continue;
408
+ }
347
409
  if (event.type !== "session.revert.committed" && event.type !== "session.revert.cleared")
348
410
  continue;
349
- const sessionID = event.data?.sessionID;
350
- if (sessionID && clearLink(sessionID)) {
411
+ if (clearLink(sessionID)) {
351
412
  dbg(`session ${sessionID} rewound — link dropped, next turn starts fresh`);
352
413
  }
353
414
  }
@@ -356,8 +417,35 @@ export const ACPPlugin = Plugin.define({
356
417
  /* aborted on cleanup */
357
418
  }
358
419
  })();
420
+ // OpenCode subagents never run on this provider: a child would inherit its Claude
421
+ // Code parent's model, so it gets its own configured model or the default one.
422
+ const subagent = await ctx.tool.hook("execute.before", async (event) => {
423
+ if (event.tool !== "subagent" || !pairingOn() || !isPlainObject(event.input))
424
+ return;
425
+ const input = event.input;
426
+ let parentModel;
427
+ try {
428
+ const parent = await ctx.session.get({ sessionID: event.sessionID });
429
+ if (parent?.model)
430
+ parentModel = { providerID: String(parent.model.providerID), id: String(parent.model.id) };
431
+ }
432
+ catch { /* unknown parent: judged on the agent's own model */ }
433
+ const decision = subagentDecision(pairing, input, parentModel, await defaultModel());
434
+ if (!decision)
435
+ return;
436
+ if (decision.kind === "reject")
437
+ throw new Error(`The model ${decision.model} is reserved for the Claude Code agents (claude-*); subagent "${input.agent}" cannot use it. Omit \`model\` or pass a model of another provider.`);
438
+ if (decision.kind === "missing")
439
+ throw new Error(`Subagent "${input.agent}" would inherit a Claude Code (${providerId}) model, which is reserved for the claude-* agents. Give that agent a model in OpenCode's config, set a default \`model\`, or pass \`model\` explicitly.`);
440
+ dbg(`pairing: subagent ${input.agent} from ${event.sessionID} → ${decision.model}`);
441
+ event.input = { ...input, model: decision.model };
442
+ });
359
443
  return async () => {
360
444
  closed.abort();
445
+ for (const timer of pending.values())
446
+ clearTimeout(timer);
447
+ pending.clear();
448
+ await subagent.dispose();
361
449
  await context.dispose();
362
450
  await compaction.dispose();
363
451
  await generate.dispose();