opencode-claude-code-acpbridge 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +139 -68
  3. package/dist/acp/claude-config.d.ts +52 -0
  4. package/dist/acp/claude-config.d.ts.map +1 -1
  5. package/dist/acp/claude-config.js +23 -7
  6. package/dist/acp/claude-config.js.map +1 -1
  7. package/dist/acp/mcp-host.d.ts +10 -0
  8. package/dist/acp/mcp-host.d.ts.map +1 -1
  9. package/dist/acp/mcp-host.js +17 -4
  10. package/dist/acp/mcp-host.js.map +1 -1
  11. package/dist/acp/mcp-runtime.js +112 -11
  12. package/dist/acp/mcp-runtime.js.map +1 -1
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +3 -2
  15. package/dist/index.js.map +1 -1
  16. package/dist/log.d.ts +11 -0
  17. package/dist/log.d.ts.map +1 -0
  18. package/dist/log.js +50 -0
  19. package/dist/log.js.map +1 -0
  20. package/dist/plugin/bridge-rules.d.ts +22 -0
  21. package/dist/plugin/bridge-rules.d.ts.map +1 -0
  22. package/dist/plugin/bridge-rules.js +104 -0
  23. package/dist/plugin/bridge-rules.js.map +1 -0
  24. package/dist/plugin/catalog.d.ts +7 -0
  25. package/dist/plugin/catalog.d.ts.map +1 -1
  26. package/dist/plugin/catalog.js +38 -0
  27. package/dist/plugin/catalog.js.map +1 -1
  28. package/dist/plugin/index.d.ts +6 -13
  29. package/dist/plugin/index.d.ts.map +1 -1
  30. package/dist/plugin/index.js +305 -241
  31. package/dist/plugin/index.js.map +1 -1
  32. package/dist/plugin/sessions.d.ts +11 -8
  33. package/dist/plugin/sessions.d.ts.map +1 -1
  34. package/dist/plugin/sessions.js +47 -7
  35. package/dist/plugin/sessions.js.map +1 -1
  36. package/dist/provider/factory.d.ts.map +1 -1
  37. package/dist/provider/factory.js +5 -3
  38. package/dist/provider/factory.js.map +1 -1
  39. package/dist/provider/history.d.ts +44 -0
  40. package/dist/provider/history.d.ts.map +1 -0
  41. package/dist/provider/history.js +145 -0
  42. package/dist/provider/history.js.map +1 -0
  43. package/dist/provider/model.d.ts +193 -32
  44. package/dist/provider/model.d.ts.map +1 -1
  45. package/dist/provider/model.js +1521 -500
  46. package/dist/provider/model.js.map +1 -1
  47. package/dist/provider/recorder.d.ts +5 -0
  48. package/dist/provider/recorder.d.ts.map +1 -0
  49. package/dist/provider/recorder.js +63 -0
  50. package/dist/provider/recorder.js.map +1 -0
  51. package/docs/DEVELOPMENT.md +56 -27
  52. package/examples/01-minimal.jsonc +9 -6
  53. package/examples/02-permisos-por-agente.jsonc +22 -17
  54. package/examples/03-fidelidad-opencode.jsonc +8 -7
  55. package/examples/04-modelo-y-esfuerzo.jsonc +29 -23
  56. package/examples/05-agentes-personalizados.jsonc +24 -14
  57. package/examples/06-ecosistema-claude.jsonc +12 -11
  58. package/examples/07-provider-manual.jsonc +12 -8
  59. package/examples/08-puente-permisos.jsonc +43 -25
  60. package/examples/README.md +10 -9
  61. package/package.json +6 -5
@@ -1,18 +1,18 @@
1
- import { tool } from "@opencode-ai/plugin";
1
+ import { Agent, Model, Plugin, Provider } from "@opencode/plugin";
2
2
  import { fileURLToPath } from "node:url";
3
3
  import { dirname, join } from "node:path";
4
4
  import { discoverAgent } from "./discover.js";
5
- import { loadAnthropicCatalog, buildModels } from "./catalog.js";
5
+ import { loadAnthropicCatalog, buildModelsInfo } from "./catalog.js";
6
6
  import { readCacheKeyed, writeCache } from "./cache.js";
7
7
  import { getLink, clearLink } from "./sessions.js";
8
+ import { publishAgentRules } from "./bridge-rules.js";
8
9
  import { detectClaudeExecutable } from "../provider/factory.js";
9
- const DEBUG = !!process.env.ACP_DEBUG;
10
- const dbg = (m) => { if (DEBUG)
11
- process.stderr.write(`[acp-plugin] ${m}\n`); };
10
+ import { logger } from "../log.js";
11
+ const dbg = logger("acp-plugin").dbg;
12
12
  const DISCOVERY_TTL = 60 * 60 * 1000; // 1h
13
- /** Last seen revert marker per OpenCode session, so the `session.updated` firehose
14
- * only acts when the rewind point actually moved. */
15
- const revertMarks = new Map();
13
+ /** Registro del provider en vuelo por providerId: si la config recarga dos veces
14
+ * en paralelo, la segunda reutiliza la promesa en vez de correr check+add en carrera. */
15
+ const providerRegisterInflight = new Map();
16
16
  function hash(s) {
17
17
  let h = 5381;
18
18
  for (let i = 0; i < s.length; i++)
@@ -22,156 +22,160 @@ function hash(s) {
22
22
  function isPlainObject(v) {
23
23
  return v != null && typeof v === "object" && !Array.isArray(v);
24
24
  }
25
- /** Deep merge where `override` wins (arrays/scalars replace; plain objects recurse). */
25
+ /** Clon profundo de valores (arrays / plain objects recursivos; escalares tal cual). */
26
+ function cloneValue(v) {
27
+ if (Array.isArray(v))
28
+ return v.map(cloneValue);
29
+ if (isPlainObject(v)) {
30
+ const o = {};
31
+ for (const k of Object.keys(v))
32
+ o[k] = cloneValue(v[k]);
33
+ return o;
34
+ }
35
+ return v;
36
+ }
37
+ /** Deep merge where `override` wins (arrays/scalars replace; plain objects recurse).
38
+ * Clona la estructura fusionada para no compartir referencias anidadas con `base`. */
26
39
  function deepMerge(base, override) {
27
40
  if (!isPlainObject(base) || !isPlainObject(override))
28
- return override;
29
- const out = { ...base };
41
+ return cloneValue(override);
42
+ const out = cloneValue(base);
30
43
  for (const k of Object.keys(override)) {
31
- out[k] = k in base ? deepMerge(base[k], override[k]) : override[k];
44
+ out[k] = k in base ? deepMerge(base[k], override[k]) : cloneValue(override[k]);
32
45
  }
33
46
  return out;
34
47
  }
35
- /** Resolve the npm spec OpenCode should load the provider factory from. */
48
+ /** Resolve the module spec OpenCode should load the provider factory from. */
36
49
  function resolveNpmSpec(override) {
37
50
  if (override)
38
51
  return override;
39
52
  const here = fileURLToPath(import.meta.url); // <root>/dist/plugin/index.js
40
53
  if (here.includes("/node_modules/opencode-claude-code-acpbridge/"))
41
54
  return "opencode-claude-code-acpbridge";
42
- return `file://${join(dirname(here), "..", "..")}`; // dev / file install → package root
55
+ // dev / local install → the built entrypoint (importable from both Bun and Node,
56
+ // unlike the package directory which only Bun resolves)
57
+ return `file://${join(dirname(here), "..", "index.js")}`;
43
58
  }
44
59
  /** Strip plugin-only keys; the rest are the provider/agent options passed to the factory. */
45
60
  function providerOptions(opts) {
46
- const { name: _n, npm: _npm, providerId: _p, models: _m, ...rest } = opts;
61
+ const { name: _n, npm: _npm, providerId: _p, models: _m, agents: _a, agentModel: _am, ...rest } = opts;
47
62
  return rest;
48
63
  }
64
+ /** Native feature set shared by the Claude Code agents ("clean brain" + the reactivated
65
+ * native capabilities, all permission-bridged to OpenCode). Two ways to delegate:
66
+ * Claude Code's own `Task` (`nativeSubagents`; also exposes the user's ~/.claude/agents,
67
+ * loaded through `settingSources: user`) and OpenCode's `subagent` tool, whose child
68
+ * sessions stay visible and continuable by ANY model — the preferred one for real work,
69
+ * since the user switches between this provider and others mid-session (descriptions
70
+ * steer the agent). IDENTICAL for both agents on purpose: they differ ONLY in the initial
71
+ * session mode, so a plan session can never end up half-restricted. */
72
+ const NATIVE_BASE = {
73
+ allowedTools: ["mcp__opencode"], // OpenCode's tools don't double-prompt (it owns them)
74
+ // Common native tools are covered by OpenCode → disable them so the agent doesn't try
75
+ // (and "approve") a native Bash/Write/… it can't actually run; it uses mcp__opencode__* instead.
76
+ // Native Read too: what it reads never reaches OpenCode's history, so after a switch to
77
+ // another model that content is gone. OpenCode V2's `read` handles images/PDF itself.
78
+ disallowedTools: ["Bash", "Read", "Write", "Edit", "MultiEdit", "Glob", "Grep", "WebFetch", "TodoWrite"],
79
+ resourceSearch: true, // ListMcpResources / ReadMcpResource (superior to OpenCode)
80
+ nativeSubagents: true, // Task: native subagents that delegate to OpenCode's tools
81
+ // Gap tools OpenCode doesn't cover, plus the two that make plan mode work at all:
82
+ // ExitPlanMode (without it a plan-mode session has NO way out) and WebSearch.
83
+ nativeTools: ["NotebookEdit", "ExitPlanMode", "WebSearch"],
84
+ projectMemory: true, // CLAUDE.md/AGENTS.md (verified: keeps subscription)
85
+ nativeSkills: true, // ~/.claude/skills, hooks disabled (verified: keeps subscription)
86
+ };
87
+ /** Agent profiles: Claude session mode (the only difference between the two) + Claude
88
+ * native options. V2's `Agent.Info` has no `options` field, so these travel to the
89
+ * provider per call through the `context` hook (merged with `options.agents.<name>.options`). */
90
+ function agentDefs(opts) {
91
+ if (opts.agents && opts.agents !== true && isPlainObject(opts.agents))
92
+ return opts.agents;
93
+ if (opts.agents && opts.agents !== true && !isPlainObject(opts.agents)) {
94
+ dbg("agents config inválida — usando defaults");
95
+ }
96
+ return {
97
+ "claude-code": {
98
+ name: "Claude Code",
99
+ description: "Claude Code (subscription) — native capabilities with permissions bridged to OpenCode",
100
+ model: opts.agentModel ?? "default",
101
+ options: { mode: "default", ...NATIVE_BASE },
102
+ },
103
+ "claude-code-plan": {
104
+ name: "Claude Code (plan)",
105
+ description: "Claude Code — plan mode (research & plan, no destructive edits)",
106
+ model: opts.agentModel ?? "default",
107
+ variant: "high",
108
+ options: { mode: "plan", ...NATIVE_BASE },
109
+ },
110
+ };
111
+ }
112
+ /** `Model.Ref` for an agent: `"default"` → `<provider>/default`, a full ref passes through. */
113
+ function modelRef(value, providerID, variant) {
114
+ const ref = typeof value === "string"
115
+ ? Model.Ref.parse(value.includes("/") || value.includes("#") ? value : `${providerID}/${value}`)
116
+ : value;
117
+ return { ...ref, ...(variant && !ref.variant ? { variant: Model.VariantID.make(variant) } : {}) };
118
+ }
49
119
  /**
50
- * Permission-bridge meta-tool. The provider emits a `claude_permission` tool-call
51
- * when the Claude agent asks (via ACP `requestPermission`) to run a NATIVE tool;
52
- * this surfaces OpenCode's own `ask` prompt with the native tool's details, and
53
- * the verdict (approved / rejected) is the tool-result the provider maps back to
54
- * allow/deny. Granularity per native tool comes from the `patterns` below, e.g.
55
- * `permission: { claude_permission: { "Read*": "allow", "*": "ask" } }`.
56
- */
57
- const claudePermissionTool = tool({
58
- description: "Permission gate for a native Claude Code tool. Approve to let the agent run that native tool; reject to block it.",
59
- args: {
60
- tool: tool.schema.string().optional().describe("native tool requested (e.g. Write, Bash, NotebookEdit, Skill)"),
61
- kind: tool.schema.string().optional().describe("execute|edit|read|delete|fetch|think|…"),
62
- title: tool.schema.string().optional().describe("human label of the action"),
63
- input: tool.schema.any().optional().describe("the native tool input"),
64
- },
65
- async execute(args, ctx) {
66
- // Permission = the NATIVE tool name → the prompt reads "Call tool Skill /
67
- // NotebookEdit / Bash …" and rules/"Allow always" are PER native tool.
68
- const native = String(args.tool ?? args.title ?? "native tool").trim() || "native tool";
69
- // Pattern = the action target (command / skill / path) so GLOB rules match,
70
- // e.g. `permission: { Bash: { "git *": "allow" }, Skill: { "review*": "allow" }, "*": "ask" }`.
71
- const inp = args.input && typeof args.input === "object" ? args.input : {};
72
- const rawTarget = String((inp.command ?? inp.skill ?? inp.name ?? inp.notebook_path ?? inp.file_path ?? inp.path) ||
73
- (typeof args.input === "string" ? args.input : "") || args.title || "").trim();
74
- const target = rawTarget || "*";
75
- // "Allow always" glob: ONLY collapse shell commands (kind=execute) to the first
76
- // token (`git status` → `git *`); otherwise the exact target. With no real target
77
- // offer NO always-glob — avoids persisting a broad "*" rule that would auto-approve
78
- // everything for this native tool.
79
- const always = args.kind === "execute" && rawTarget.includes(" ") ? `${rawTarget.split(/\s+/)[0]} *`
80
- : rawTarget || undefined;
81
- // ctx.ask surfaces OpenCode's prompt (default "ask" when no rule matches); throws
82
- // PermissionRejectedError on reject → the provider denies the native tool.
83
- await ctx.ask({
84
- permission: native,
85
- patterns: [target],
86
- always: always ? [always] : [],
87
- metadata: { kind: args.kind, title: args.title, input: args.input },
88
- });
89
- return `approved: ${native}`;
90
- },
91
- });
92
- /**
93
- * OpenCode plugin half. With the auto-register hook below, a minimal config is enough:
120
+ * OpenCode plugin half. Minimal config is enough:
94
121
  *
95
- * "plugin": [["opencode-claude-code-acpbridge", { "command": "claude-agent-acp" }]]
122
+ * "plugins": [{ "package": "opencode-claude-code-acpbridge",
123
+ * "options": { "command": "claude-agent-acp" } }]
96
124
  *
97
- * The plugin discovers the agent's models (cached), pulls their metadata from
98
- * models.dev, and injects `provider.acp` with the populated models — while the
99
- * user keeps full control of every agent option via these plugin options.
125
+ * It discovers the agent's models (cached), pulls their metadata from models.dev,
126
+ * registers the `acp` provider with the populated `Model.Info[]`, injects the
127
+ * `claude-code` / `claude-code-plan` agents, and bridges every per-request value
128
+ * (session link, agent options) through the `context` hook.
100
129
  */
101
- export const ACPPlugin = async (_input, options) => {
102
- const opts = (options ?? {});
103
- const providerId = opts.providerId ?? "acp";
104
- return {
105
- // Register the permission-bridge meta-tool so OpenCode can execute it and show
106
- // its `ask` prompt when the Claude agent requests a native tool.
107
- tool: { claude_permission: claudePermissionTool },
108
- // Bridge OpenCode's sessionID → providerOptions.acp so the provider can map it
109
- // to a Claude Code session and resume instead of replaying the whole history.
110
- "chat.params": async (input, output) => {
111
- try {
112
- if (input?.model?.providerID !== providerId)
113
- return;
114
- const oc = input?.sessionID;
115
- if (!oc)
116
- return;
117
- output.options = output.options ?? {};
118
- output.options.ocSession = oc; // registry key — always
119
- // Which OpenCode agent is driving this turn. The provider keeps it for its
120
- // logs and for the notice it prints when the Claude agent leaves plan mode
121
- // on its own (OpenCode still shows the agent the user picked).
122
- if (input?.agent)
123
- output.options.ocAgent = String(input.agent);
124
- const link = getLink(oc);
125
- if (link?.acpSessionId) { // only if registered (resumable)
126
- output.options.resumeId = link.acpSessionId;
127
- output.options.resumeLen = link.sentHistoryLen;
128
- // Seed the model's cumulative usage snapshot so per-turn deltas stay
129
- // correct after a process restart (ACP usage is cumulative per session).
130
- if (link.lastUsage)
131
- output.options.resumeLastUsage = link.lastUsage;
132
- // Conversation identity, for the model to notice if this OpenCode
133
- // sessionID were ever reused for an unrelated conversation.
134
- if (link.convKey)
135
- output.options.resumeConvKey = link.convKey;
136
- }
137
- }
138
- catch { /* ignore */ }
139
- },
140
- // Rewinding a conversation (revert / unrevert) truncates OpenCode's history,
141
- // but the Claude Code session on the other side still remembers every turn that
142
- // was undone. Drop the registry link so the next turn starts a clean agent
143
- // session from the truncated history instead of resuming one that would
144
- // resurrect it. The provider ALSO detects this from the prompt itself (history
145
- // fingerprint), so programmatic use without the plugin stays correct.
146
- event: async ({ event }) => {
147
- try {
148
- if (event?.type !== "session.updated")
149
- return;
150
- const info = event?.properties?.info;
151
- const id = info?.id;
152
- if (!id)
153
- return;
154
- const mark = info?.revert ? `${info.revert.messageID}:${info.revert.partID ?? ""}` : "";
155
- if (revertMarks.get(id) === mark)
156
- return;
157
- revertMarks.set(id, mark);
158
- if (clearLink(id))
159
- dbg(`session ${id} rewound (revert=${mark || "cleared"}) — link dropped, next turn starts fresh`);
160
- }
161
- catch { /* never break the event bus */ }
162
- },
163
- config: async (cfg) => {
130
+ /** ¿Está la tool `question` en el set de tools del agente? Soporta array / Set /
131
+ * Record (según cómo OpenCode lo haya convertido); sin info se asume que sí
132
+ * para conservar el comportamiento actual. */
133
+ function hasQuestionTool(item) {
134
+ const t = item?.tools;
135
+ if (t == null)
136
+ return true;
137
+ if (Array.isArray(t))
138
+ return t.includes("question");
139
+ if (t instanceof Set)
140
+ return t.has("question");
141
+ if (typeof t === "object") {
142
+ if ("question" in t)
143
+ return !!t.question;
144
+ return true;
145
+ }
146
+ return true;
147
+ }
148
+ /** A session title from the first user message: first meaningful line, quotes and
149
+ * markup stripped, cut on a word boundary. */
150
+ export function titleFrom(messages) {
151
+ const first = messages.find((m) => m?.role === "user");
152
+ if (!first)
153
+ return undefined;
154
+ const parts = typeof first.content === "string" ? [first.content] : (first.content ?? []).filter((p) => p?.type === "text").map((p) => p.text);
155
+ const line = String(parts.join("\n"))
156
+ .replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g, " ")
157
+ .split("\n")
158
+ .map((l) => l.replace(/^["'`\s#>*-]+|["'`\s]+$/g, "").trim())
159
+ .find((l) => l.length > 2);
160
+ if (!line)
161
+ return undefined;
162
+ if (line.length <= 60)
163
+ return line;
164
+ const cut = line.slice(0, 60);
165
+ return `${cut.slice(0, cut.lastIndexOf(" ") > 30 ? cut.lastIndexOf(" ") : 60)}…`;
166
+ }
167
+ export const ACPPlugin = Plugin.define({
168
+ id: "opencode-claude-code-acpbridge",
169
+ async setup(ctx) {
170
+ const opts = (ctx.options ?? {});
171
+ const providerId = opts.providerId ?? "acp";
172
+ const agentOptions = new Map();
173
+ if (!opts.command && !process.env.ACP_COMMAND) {
174
+ dbg("no `command` in plugin options — skipping auto-register (declare the provider manually)");
175
+ }
176
+ else {
164
177
  try {
165
- if (!opts.command && !process.env.ACP_COMMAND) {
166
- dbg("no `command` in plugin options — skipping auto-register (declare the provider manually)");
167
- return;
168
- }
169
178
  const command = opts.command ?? process.env.ACP_COMMAND;
170
- cfg.provider ??= {};
171
- if (cfg.provider[providerId]) {
172
- dbg(`provider '${providerId}' already declared in config — leaving it untouched`);
173
- return;
174
- }
175
179
  // Resolve the native Claude binary the same way the provider factory does,
176
180
  // so the ephemeral discovery agent can find it under a minimal config.
177
181
  const claudeExecutable = opts.claudeExecutable ?? process.env.CLAUDE_CODE_EXECUTABLE ?? detectClaudeExecutable();
@@ -184,117 +188,177 @@ export const ACPPlugin = async (_input, options) => {
184
188
  discovered = await discoverAgent(discOpts);
185
189
  writeCache("discovery.json", discovered, key);
186
190
  }
187
- const agentModels = discovered?.models?.length
188
- ? discovered.models
189
- : [{ id: "default", name: "Claude Code (ACP)" }];
191
+ const agentModels = discovered?.models?.length ? discovered.models : [{ id: "default", name: "Claude Code (ACP)" }];
190
192
  const catalog = await loadAnthropicCatalog();
191
- const models = buildModels(agentModels, discovered?.promptCaps ?? {}, catalog);
192
- cfg.provider[providerId] = {
193
- npm: resolveNpmSpec(opts.npm),
194
- name: opts.name ?? "Claude Code (ACP)",
195
- options: { ...discOpts },
196
- models,
197
- };
198
- dbg(`auto-registered provider '${providerId}' (npm ${resolveNpmSpec(opts.npm)}) — models: ${Object.keys(models).join(", ")}`);
199
- // Inject "claude-code" agents (unless disabled or already declared). Default
200
- // model is the agent's recommended one ("default" = Opus 4.7). Per-agent ACP
201
- // options (mode/effort) travel to the provider as `providerOptions.acp`.
202
- if (opts.agents !== false) {
203
- const defaultModel = opts.agentModel ?? "default";
204
- const toRef = (m) => (m.includes("/") ? m : `${providerId}/${m}`);
205
- // Native feature set shared by the Claude Code agents ("clean brain" + the
206
- // reactivated native capabilities, all permission-bridged to OpenCode). CRUCIAL:
207
- // `nativeSubagents` gives the agent Claude Code's OWN `Task` tool, so delegated
208
- // work runs as a native subagent on the subscription. Without it the agent falls
209
- // back to OpenCode's forwarded `task` tool, which spawns OpenCode subagents routed
210
- // to OTHER providers (opencode-go/…) — those fail when they're down/out-of-balance.
211
- // IDENTICAL for both agents on purpose. `claude-code-plan` and `claude-code`
212
- // differ ONLY in the initial session mode. The Claude agent can leave plan
213
- // mode by itself (ExitPlanMode), and nothing tells OpenCode to switch agent —
214
- // so if the two profiles differed, the agent would believe it may edit while
215
- // OpenCode kept handing it the restricted plan profile. Making the mode the
216
- // only difference removes that half-restricted state entirely.
217
- const nativeBase = {
218
- allowedTools: ["mcp__opencode"], // OpenCode's tools don't double-prompt (it owns them)
219
- // Common native tools are covered by OpenCode → disable them so the agent
220
- // doesn't try (and "approve") a native Bash/Write/… it can't actually run;
221
- // it uses mcp__opencode__* instead. Native gap tools stay (see `nativeTools`).
222
- disallowedTools: ["Bash", "Write", "Edit", "MultiEdit", "Glob", "Grep", "WebFetch", "TodoWrite"],
223
- resourceSearch: true, // ListMcpResources / ReadMcpResource (superior to OpenCode)
224
- nativeSubagents: true, // Task: native subagents that delegate to OpenCode's tools
225
- // Gap tools OpenCode doesn't cover, plus the two that make plan mode work
226
- // at all: ExitPlanMode (without it a plan-mode session has NO way out and
227
- // the mode is re-forced every turn) and WebSearch (OpenCode only registers
228
- // its own `websearch` for providerID "opencode" or with exa/parallel on).
229
- nativeTools: ["NotebookEdit", "Read", "ExitPlanMode", "WebSearch"],
230
- projectMemory: true, // CLAUDE.md/AGENTS.md (verified: keeps subscription)
231
- nativeSkills: true, // ~/.claude/skills, hooks disabled (verified: keeps subscription)
232
- };
233
- const defs = opts.agents ?? {
234
- "claude-code": {
235
- description: "Claude Code (subscription) — native capabilities with permissions bridged to OpenCode",
236
- model: defaultModel,
237
- // The bridge meta-tool itself is auto-allowed; the REAL prompt is raised
238
- // inside it via ctx.ask under the NATIVE tool's name (Skill/NotebookEdit/…),
239
- // so users see and rule on the actual action. Override per tool, e.g.
240
- // `permission: { Skill: "allow", NotebookEdit: "ask" }`.
241
- permission: { claude_permission: "allow" },
242
- options: {
243
- mode: "default", // not bypass → the agent asks → permission bridge
244
- ...nativeBase,
245
- },
246
- },
247
- "claude-code-plan": {
248
- description: "Claude Code — plan mode (research & plan, no destructive edits)",
249
- model: defaultModel, variant: "high",
250
- // Same permission bridge as claude-code: native tool requests surface as
251
- // OpenCode `ask` prompts under the real tool name.
252
- permission: { claude_permission: "allow" },
253
- options: {
254
- ...nativeBase,
255
- // The ONLY difference from `claude-code`. Read-only research & planning
256
- // is enforced by the session mode (and OpenCode's own plan gating), not
257
- // by a narrower tool profile — see the note on `nativeBase`. Approving
258
- // the plan moves the session to `default`, and from that moment this
259
- // agent behaves exactly like `claude-code`.
260
- mode: "plan",
193
+ const models = buildModelsInfo(agentModels, discovered?.promptCaps ?? {}, catalog, providerId);
194
+ const npmSpec = resolveNpmSpec(opts.npm);
195
+ // The provider no longer comes from `provider.<id>` in config (V2 resolves
196
+ // packages through `aisdk:<spec>`): the plugin registers it directly.
197
+ // Guard contra reloads paralelos: el check `get` + `add` no es atómico,
198
+ // así que se memoiza la promesa en vuelo por providerId y se reutiliza.
199
+ let registering = providerRegisterInflight.get(providerId);
200
+ if (!registering) {
201
+ const fresh = ctx.provider.transform((editor) => {
202
+ if (editor.get(providerId)) {
203
+ dbg(`provider '${providerId}' already declared — keeping the existing definition`);
204
+ return;
205
+ }
206
+ editor.add({
207
+ info: {
208
+ ...Provider.Info.empty(Provider.ID.make(providerId)),
209
+ name: opts.name ?? "Claude Code (ACP)",
210
+ activation: "enabled",
211
+ package: `aisdk:${npmSpec}`,
212
+ settings: { ...discOpts },
261
213
  },
262
- },
214
+ models,
215
+ });
216
+ });
217
+ providerRegisterInflight.set(providerId, fresh);
218
+ // Solo se memoiza mientras está en vuelo: al asentarse se libera para
219
+ // que la próxima recarga (secuencial) use su propio `ctx`.
220
+ const done = () => {
221
+ if (providerRegisterInflight.get(providerId) === fresh)
222
+ providerRegisterInflight.delete(providerId);
263
223
  };
264
- cfg.agent ??= {};
265
- const injected = [];
266
- for (const [name, raw] of Object.entries(defs)) {
267
- const def = raw;
268
- const pluginBase = {
269
- description: def.description,
270
- model: toRef(def.model ?? defaultModel),
271
- mode: def.mode ?? "primary",
272
- ...(def.variant ? { variant: def.variant } : {}),
273
- ...(def.permission ? { permission: def.permission } : {}),
274
- options: def.options ?? {},
275
- };
276
- // The user's `agent.<name>` in opencode.json wins over the plugin defaults
277
- // (merge): declare only what you want to change (e.g. `permission`) and
278
- // inherit the rest; `disable:true` turns the agent off.
279
- cfg.agent[name] = cfg.agent[name] ? deepMerge(pluginBase, cfg.agent[name]) : pluginBase;
280
- injected.push(name);
281
- }
282
- if (injected.length)
283
- dbg(`agents (plugin defaults ⊕ user config): ${injected.join(", ")}`);
224
+ fresh.then(done, done);
225
+ registering = fresh;
226
+ }
227
+ await registering;
228
+ dbg(`auto-registered provider '${providerId}' (aisdk:${npmSpec}) — models: ${models.map((m) => m.id).join(", ")}`);
229
+ if (opts.agents !== false) {
230
+ const defs = agentDefs(opts);
231
+ await ctx.agent.transform((editor) => {
232
+ for (const [name, raw] of Object.entries(defs)) {
233
+ const def = raw;
234
+ const user = isPlainObject(opts.agents) ? opts.agents[name] : undefined;
235
+ // V1-style per-agent Claude options, overridden by the user's copy.
236
+ agentOptions.set(name, deepMerge(def.options ?? {}, isPlainObject(user) ? user.options ?? {} : {}));
237
+ // A `model` the user already declared (config/other plugin) wins: only
238
+ // fill the field when it is missing, so the transform stays idempotent.
239
+ const model = modelRef((isPlainObject(user) && user.model) || def.model || "default", providerId, def.variant);
240
+ const description = (isPlainObject(user) && user.description) || def.description;
241
+ const questionRule = { action: "question", resource: "*", effect: "allow" };
242
+ editor.update(name, (item) => {
243
+ if (def.name)
244
+ item.name = Agent.Name.make(def.name);
245
+ if (description && !item.description)
246
+ item.description = description;
247
+ if (!item.model)
248
+ item.model = model;
249
+ // Solo tiene sentido permitir `question` si la tool existe en el agente.
250
+ if (hasQuestionTool(item) &&
251
+ !item.permissions.some((r) => r.action === "question" && r.resource === "*")) {
252
+ item.permissions.push(questionRule);
253
+ }
254
+ // Context-pruning plugins (opencode-dcp) rewrite OpenCode's copy of the
255
+ // history: `compress` swaps ranges for summaries and the plugin tags every
256
+ // message. The Claude Code session keeps its own context, so that saves
257
+ // nothing — it only makes the history diverge and forces a cold replay.
258
+ // Denying the action removes the tool and, in DCP, the tagging with it.
259
+ if (!item.permissions.some((r) => r.action === "compress")) {
260
+ item.permissions.push({ action: "compress", resource: "*", effect: "deny" });
261
+ }
262
+ // Publish the rules the permission bridge evaluates against (the
263
+ // user's `permissions` included). `action:"*"` defaults are ignored
264
+ // at evaluation time — see bridge-rules.ts.
265
+ publishAgentRules(name, item.permissions);
266
+ });
267
+ }
268
+ // Any agent can run on this provider (a subagent inherits its parent's
269
+ // model), so the bridge needs every agent's rules — not just ours.
270
+ for (const item of editor.list()) {
271
+ if (!(String(item.id) in defs))
272
+ publishAgentRules(String(item.id), item.permissions);
273
+ }
274
+ });
275
+ dbg(`agents registered: ${Object.keys(defs).join(", ")}`);
284
276
  }
285
277
  }
286
278
  catch (e) {
287
- // Never break OpenCode boot: log and continue (user can declare provider manually).
288
- const detail = e instanceof Error ? (e.stack || e.message) : typeof e === "object" ? JSON.stringify(e) : String(e);
289
- dbg(`auto-register failed: ${detail}`);
279
+ // Never break OpenCode boot: log and continue (the user can still declare
280
+ // the provider manually, and the hooks below stay registered).
281
+ dbg(`auto-register failed: ${e instanceof Error ? e.stack || e.message : String(e)}`);
290
282
  }
291
- },
292
- dispose: async () => { },
293
- };
294
- };
295
- const acpPluginModule = {
296
- id: "opencode-claude-code-acpbridge",
297
- server: ACPPlugin,
298
- };
299
- export default acpPluginModule;
283
+ }
284
+ // Session link + agent options → the provider. V2 passes NO provider options
285
+ // from config, so everything the model needs per call is injected here
286
+ // (`SessionRequestOptions`: generation keys stay typed, the rest becomes
287
+ // `providerOptions.<providerID>`).
288
+ // The same per-call options go with the auxiliary calls too: without them a
289
+ // compaction request reached the provider anonymous and was served by a cold,
290
+ // throwaway session replaying the whole history.
291
+ const inject = (kind) => (event) => {
292
+ if (event.model.providerID !== providerId)
293
+ return;
294
+ event.options.ocSession = event.sessionID;
295
+ event.options.ocAgent = String(event.agent);
296
+ event.options.requestKind = kind;
297
+ // Whether the agent can ask the user: the permission bridge needs `question`.
298
+ event.options.hasQuestion = !!event.tools && "question" in event.tools;
299
+ const link = getLink(event.sessionID);
300
+ if (link?.acpSessionId) {
301
+ event.options.resumeId = link.acpSessionId;
302
+ event.options.resumeLen = link.sentHistoryLen;
303
+ // Seed the cumulative usage snapshot so per-turn deltas stay correct
304
+ // after a restart (ACP usage is cumulative per session).
305
+ if (link.lastUsage)
306
+ event.options.resumeLastUsage = link.lastUsage;
307
+ if (link.convKey)
308
+ event.options.resumeConvKey = link.convKey;
309
+ if (link.idPrefixes?.length)
310
+ event.options.resumeIdPrefixes = link.idPrefixes;
311
+ }
312
+ const extra = agentOptions.get(String(event.agent));
313
+ if (extra)
314
+ for (const [k, v] of Object.entries(extra))
315
+ event.options[k] = v;
316
+ };
317
+ const context = await ctx.session.hook("context", inject("primary"), { providerID: providerId });
318
+ const compaction = await ctx.session.hook("compaction", inject("compaction"), { providerID: providerId });
319
+ const generate = await ctx.session.hook("generate", inject("generate"), { providerID: providerId });
320
+ // Titles: OpenCode's title instructions live in the system prompt, which `preset`
321
+ // never forwards — Claude received the bare first message, answered it, and the
322
+ // session got titled with a fragment of that answer (`<invoke name="Read">`). A
323
+ // title derived from the first message costs nothing and is never wrong that way.
324
+ const title = await ctx.session.hook("title", (event) => {
325
+ if (event.model.providerID !== providerId || opts.titleFromModel)
326
+ return;
327
+ const t = titleFrom(event.messages);
328
+ if (t)
329
+ event.result = t;
330
+ }, { providerID: providerId });
331
+ // Rewinding a conversation truncates OpenCode's history, but the Claude Code
332
+ // session on the other side still remembers every undone turn. Drop the
333
+ // registry link so the next turn starts a clean agent session instead of
334
+ // resuming one that would resurrect it. The provider ALSO detects this from
335
+ // the prompt itself (history fingerprint), so programmatic use without the
336
+ // plugin stays correct.
337
+ const closed = new AbortController();
338
+ const events = (async () => {
339
+ try {
340
+ for await (const event of ctx.event.subscribe({ signal: closed.signal })) {
341
+ if (event.type !== "session.revert.committed" && event.type !== "session.revert.cleared")
342
+ continue;
343
+ const sessionID = event.data?.sessionID;
344
+ if (sessionID && clearLink(sessionID)) {
345
+ dbg(`session ${sessionID} rewound — link dropped, next turn starts fresh`);
346
+ }
347
+ }
348
+ }
349
+ catch {
350
+ /* aborted on cleanup */
351
+ }
352
+ })();
353
+ return async () => {
354
+ closed.abort();
355
+ await context.dispose();
356
+ await compaction.dispose();
357
+ await generate.dispose();
358
+ await title.dispose();
359
+ await events;
360
+ };
361
+ },
362
+ });
363
+ export default ACPPlugin;
300
364
  //# sourceMappingURL=index.js.map