opencode-claude-code-acpbridge 0.7.0 → 0.9.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 (46) hide show
  1. package/CHANGELOG.md +183 -0
  2. package/README.md +135 -40
  3. package/dist/acp/claude-config.d.ts +23 -4
  4. package/dist/acp/claude-config.d.ts.map +1 -1
  5. package/dist/acp/claude-config.js +25 -10
  6. package/dist/acp/claude-config.js.map +1 -1
  7. package/dist/acp/mcp-host.d.ts +12 -1
  8. package/dist/acp/mcp-host.d.ts.map +1 -1
  9. package/dist/acp/mcp-host.js +18 -2
  10. package/dist/acp/mcp-host.js.map +1 -1
  11. package/dist/acp/mcp-runtime.js +98 -9
  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/plugin/bridge-rules.d.ts +22 -0
  17. package/dist/plugin/bridge-rules.d.ts.map +1 -0
  18. package/dist/plugin/bridge-rules.js +104 -0
  19. package/dist/plugin/bridge-rules.js.map +1 -0
  20. package/dist/plugin/catalog.d.ts +7 -0
  21. package/dist/plugin/catalog.d.ts.map +1 -1
  22. package/dist/plugin/catalog.js +42 -2
  23. package/dist/plugin/catalog.js.map +1 -1
  24. package/dist/plugin/index.d.ts +3 -13
  25. package/dist/plugin/index.d.ts.map +1 -1
  26. package/dist/plugin/index.js +243 -174
  27. package/dist/plugin/index.js.map +1 -1
  28. package/dist/plugin/sessions.d.ts +11 -1
  29. package/dist/plugin/sessions.d.ts.map +1 -1
  30. package/dist/plugin/sessions.js +36 -5
  31. package/dist/plugin/sessions.js.map +1 -1
  32. package/dist/provider/model.d.ts +93 -14
  33. package/dist/provider/model.d.ts.map +1 -1
  34. package/dist/provider/model.js +698 -213
  35. package/dist/provider/model.js.map +1 -1
  36. package/docs/DEVELOPMENT.md +50 -23
  37. package/examples/01-minimal.jsonc +9 -6
  38. package/examples/02-permisos-por-agente.jsonc +22 -17
  39. package/examples/03-fidelidad-opencode.jsonc +8 -7
  40. package/examples/04-modelo-y-esfuerzo.jsonc +29 -23
  41. package/examples/05-agentes-personalizados.jsonc +24 -14
  42. package/examples/06-ecosistema-claude.jsonc +12 -11
  43. package/examples/07-provider-manual.jsonc +12 -8
  44. package/examples/08-puente-permisos.jsonc +43 -25
  45. package/examples/README.md +10 -9
  46. package/package.json +6 -4
@@ -3,27 +3,47 @@
3
3
  //
4
4
  // Session strategy (efficiency + prompt caching):
5
5
  // - The AI SDK is stateless: OpenCode resends the FULL prompt every doStream.
6
- // - We keep a PERSISTENT ACP session per conversation. On the first turn of a
7
- // conversation we send the whole history; on later turns we send only the
8
- // DELTA (the last user message) — the agent already holds its side (its
9
- // answers + tool-results) in the session and reuses Claude's prompt cache.
10
- // - We reset to a fresh session only when the conversation changes (different
11
- // first user message) or the tool set changes — this isolates OpenCode's
12
- // title/small-model call (tools=0) from the real call (tools=N).
6
+ // - We keep a PERSISTENT ACP session PER CONVERSATION and send only what the
7
+ // agent hasn't seen yet. The agent holds its own side (its answers + the
8
+ // tool-results it received over MCP) and reuses Claude's prompt cache, which
9
+ // lives and dies with the session — so NOT recreating the session is exactly
10
+ // the same thing as preserving the cache.
11
+ // - A session is recreated only when the history genuinely diverges (revert,
12
+ // compaction) or when a creation-time parameter changes. A different agent,
13
+ // a changed tool set or a new system prompt do NOT reset it.
13
14
  //
14
15
  // Tool flow: when the agent calls an MCP tool, the host fires onToolCall → we
15
16
  // emit a `tool-call` with the REAL OpenCode tool name, finish `tool-calls`, and
16
17
  // leave the MCP tools/call DEFERRED; the next doStream brings OpenCode's
17
- // tool-result → we resolve it and the same agent turn continues.
18
+ // tool-result → we resolve it and the same agent turn continues. Text/thinking
19
+ // arriving while that stream is closed is BUFFERED, never dropped.
18
20
  import { spawn } from "node:child_process";
19
21
  import { Writable, Readable } from "node:stream";
22
+ import { randomBytes } from "node:crypto";
20
23
  import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
21
24
  import { McpHost } from "../acp/mcp-host.js";
22
25
  import { buildClaudeCodeOptions, resolveConfigDir, } from "../acp/claude-config.js";
23
26
  import { setLink, updateUsage } from "../plugin/sessions.js";
27
+ import { addAlwaysRule, evaluate as evaluateBridge } from "../plugin/bridge-rules.js";
24
28
  const DEBUG = !!process.env.ACP_DEBUG;
25
29
  const dbg = (m) => { if (DEBUG)
26
30
  process.stderr.write(`[acp-orchestrator] ${m}\n`); };
31
+ /** Always-on notices (session lifecycle) — the user needs these without ACP_DEBUG. */
32
+ const note = (m) => process.stderr.write(`[acp] ${m}\n`);
33
+ /** Max live conversations kept per model instance (LRU); older idle ones are torn down. */
34
+ const MAX_LIVE_SESSIONS = 8;
35
+ /** Cap on a foreign tool-result replayed as text during catch-up. */
36
+ const CATCHUP_RESULT_CHARS = 2000;
37
+ /** Tope del buffer `pending` (chunks emitidos sin controller vivo): sin cap un turno
38
+ * largo con el stream cerrado lo haría crecer sin límite (OOM). */
39
+ const MAX_PENDING_PARTS = 1000;
40
+ /** System-prompt blocks worth forwarding to the agent as FACTUAL context (never as
41
+ * a system prompt — that would make Anthropic bill the session as extra usage). */
42
+ const CONTEXT_TAGS = ["env", "available_references"];
43
+ /** Dialog labels — also the strings the verdict parser looks for (see `questionVerdict`). */
44
+ const ALLOW_ONCE = "Allow once";
45
+ const ALWAYS_ALLOW = "Always allow";
46
+ const DENY = "Deny";
27
47
  function emptyUsage() {
28
48
  return {
29
49
  inputTokens: { total: undefined, noCache: undefined, cacheRead: undefined, cacheWrite: undefined },
@@ -73,20 +93,25 @@ export class ACPOrchestratorModel {
73
93
  agent = null;
74
94
  connection = null;
75
95
  connecting = null;
76
- current = null;
96
+ /** Live conversations, keyed by OpenCode sessionID (or the conversation hash).
97
+ * ONE state per conversation: a single shared state made two open chats — or a
98
+ * subagent — tear each other's session down and replay the history every turn. */
99
+ sessions = new Map();
100
+ /** Same states indexed by ACP sessionId, to route agent-initiated callbacks. */
101
+ byAcpSession = new Map();
77
102
  idSeq = 0;
78
103
  promptCaps = {};
79
- cancelWatchdog = null;
80
104
  constructor(config) {
81
105
  this.config = config;
82
106
  this.modelId = config.modelId ?? "claude-code";
83
107
  }
84
108
  // ---- LanguageModelV3 ------------------------------------------------------
85
109
  async doStream(options) {
86
- const continuation = this.detectContinuation(options.prompt);
110
+ const continuation = this.detectContinuation(options.prompt, options);
111
+ const ref = { t: continuation?.t ?? null };
87
112
  const stream = new ReadableStream({
88
- start: (controller) => void this.onStart(controller, options, continuation),
89
- cancel: () => this.onCancel(),
113
+ start: (controller) => void this.onStart(controller, options, continuation, ref),
114
+ cancel: () => this.onCancel(ref),
90
115
  });
91
116
  return { stream, warnings: [] };
92
117
  }
@@ -115,24 +140,31 @@ export class ACPOrchestratorModel {
115
140
  return { content, finishReason, usage, warnings: [] };
116
141
  }
117
142
  // ---- turn lifecycle -------------------------------------------------------
118
- async onStart(controller, options, continuation) {
143
+ async onStart(controller, options, continuation, ref) {
119
144
  try {
120
145
  controller.enqueue({ type: "stream-start", warnings: [] });
121
146
  // (1) Continuation of a deferred tool-call OR a bridged permission — resume
122
147
  // the same agent turn.
123
- if (continuation && this.current) {
124
- const t = this.current;
125
- this.clearCancelWatchdog(); // the turn DID continue — disarm the abort timer
148
+ if (continuation) {
149
+ const t = continuation.t;
150
+ ref.t = t;
151
+ this.clearCancelWatchdog(t); // the turn DID continue — disarm the abort timer
126
152
  t.controller = controller;
127
- t.textId = null;
128
- t.reasoningId = null;
129
- for (const { toolCallId, result, output } of continuation) {
153
+ t.lastActive = Date.now();
154
+ // Everything in this prompt is already known to the agent: its own tool-calls
155
+ // and the results it will receive right now. Recording them here is what stops
156
+ // the next turn from replaying whole file/shell outputs it already has.
157
+ t.sentKeys = this.history(options.prompt).map((m) => this.msgKey(m));
158
+ // Text/thinking that arrived while the stream was closed goes out FIRST, in
159
+ // order, so nothing the agent said before calling the tool is lost.
160
+ this.flushPending(t);
161
+ for (const { toolCallId, result, output } of continuation.results) {
130
162
  const permResolve = t.pendingPermissions.get(toolCallId);
131
163
  if (permResolve) {
132
- // Permission bridge: OpenCode's `ask` verdict came back as the
133
- // claude_permission tool-result → resolve the deferred requestPermission.
164
+ // Permission bridge: the user's `question` answer came back as the
165
+ // tool-result → resolve the deferred requestPermission.
134
166
  t.pendingPermissions.delete(toolCallId);
135
- permResolve(this.isApprovedOutput(output));
167
+ permResolve(this.questionVerdict(output));
136
168
  }
137
169
  else {
138
170
  t.pendingTools.delete(toolCallId);
@@ -144,59 +176,100 @@ export class ACPOrchestratorModel {
144
176
  await this.ensureConnected();
145
177
  const tools = this.convertTools(options.tools);
146
178
  const ctrl = this.effectiveCtrl(options);
179
+ const po = this.providerOptions(options);
180
+ const ocSession = po.ocSession;
147
181
  const convKey = hashText(this.firstUserText(options.prompt));
148
- const toolsKey = tools.map((t) => t.name).sort().join(",");
149
- // System prompt is part of the identity: OpenCode can switch agents within a
150
- // session (same history, different system prompt). The agent can't change its
151
- // system prompt mid-session, so a system change forces a fresh session that
152
- // replays the full history under the new system prompt.
153
- const systemKey = hashText(this.systemText(options.prompt));
182
+ const toolsKey = tools.map((x) => x.name).sort().join(",");
183
+ // The system prompt is part of the session identity ONLY when it actually
184
+ // travels. Under the default `preset` mode OpenCode's system is never sent
185
+ // (see buildSystemPromptMeta), so hashing it would tear the session down —
186
+ // and replay the whole history — every time OpenCode swaps agents or its
187
+ // dynamic blocks (date, AGENTS.md, skills) shift. The factual part of that
188
+ // system is forwarded separately as user context (see contextBlocks).
189
+ const systemMode = ctrl.systemPromptMode ?? "preset";
190
+ const systemKey = systemMode === "preset" ? "preset" : hashText(this.systemText(options.prompt));
154
191
  // Params baked into newSession's _meta (thinking/systemPromptMode) can't change
155
192
  // mid-session → a change forces a fresh session. mode/effort are applied at
156
193
  // runtime via set_mode/set_config_option instead (no reset needed).
157
- const cfgKey = hashText(JSON.stringify({ t: ctrl.thinking, s: ctrl.systemPromptMode ?? "preset" }));
158
- // Session registry plumbing (chat.params → providerOptions.acp): `ocSession`
159
- // is the OpenCode key; `resumeId`/`resumeLen` come from the persistent registry.
160
- const po = options.providerOptions?.[this.provider] ?? {};
161
- const ocSession = po.ocSession;
162
- const histLen = options.prompt.length;
163
- // (2) Same conversation + tools + system + creation-cfg → reuse session, send only the delta.
164
- if (this.current &&
165
- this.current.convKey === convKey &&
166
- this.current.toolsKey === toolsKey &&
167
- this.current.systemKey === systemKey &&
168
- this.current.cfgKey === cfgKey) {
169
- dbg(`reuse session ${this.current.sessionId} — delta only (cache-friendly)`);
170
- // A fresh user turn: drop any deferred state left by a prior turn that was
171
- // abandoned (continuation never arrived) so it can't hang or leak.
172
- this.clearCancelWatchdog();
173
- this.drainPermissions(this.current);
174
- this.current.pendingTools.clear();
175
- this.current.controller = controller;
176
- this.current.textId = null;
177
- this.current.reasoningId = null;
178
- if (ocSession)
179
- this.current.ocSession = ocSession;
180
- await this.applySessionConfig(this.current, ctrl); // runtime mode/effort change
181
- if (ocSession)
182
- setLink(ocSession, this.current.sessionId, histLen);
183
- const blocks = this.lastUserBlocks(options.prompt);
184
- this.connection
185
- .prompt({ sessionId: this.current.sessionId, prompt: blocks })
186
- .then((resp) => this.onPromptDone(resp))
187
- .catch((err) => this.onPromptError(err));
188
- return;
194
+ const cfgKey = hashText(JSON.stringify({ t: ctrl.thinking, s: systemMode }));
195
+ const hist = this.history(options.prompt);
196
+ const keys = hist.map((m) => this.msgKey(m));
197
+ // OpenCode's title/summary call arrives on the same model and session but with
198
+ // NO tools. Give it a throwaway session instead of letting it evict the real
199
+ // conversation. Only when the live conversation DOES have tools — a genuinely
200
+ // tool-less conversation (programmatic use) must keep reusing its own session.
201
+ const baseKey = ocSession ?? convKey;
202
+ const live = this.sessions.get(baseKey);
203
+ const key = tools.length === 0 && live && live.toolsKey !== "" ? `${baseKey}:notools` : baseKey;
204
+ let t = this.sessions.get(key);
205
+ if (t && t.convKey !== convKey) {
206
+ this.endTurn(t);
207
+ t = undefined;
208
+ } // key reused for another conversation
209
+ // (2) Reuse the live session whenever we can — this is what keeps the cache warm.
210
+ if (t) {
211
+ let drop = null;
212
+ if (t.systemKey !== systemKey)
213
+ drop = "system prompt changed";
214
+ else if (t.cfgKey !== cfgKey)
215
+ drop = "creation config changed";
216
+ if (!drop) {
217
+ // A changed tool set is applied to the LIVE session (MCP list_changed)
218
+ // rather than forcing a new one.
219
+ if (t.toolsKey !== toolsKey) {
220
+ t.host.setTools(tools);
221
+ t.host.notifyToolsChanged();
222
+ t.toolsKey = toolsKey;
223
+ dbg(`tools changed (${tools.length}) — refreshed in place, session kept`);
224
+ }
225
+ const cls = this.classifyHistory(t, keys);
226
+ if (cls.kind !== "append") {
227
+ drop = cls.kind === "revert" ? "history reverted" : "history diverged (compaction/rollback)";
228
+ }
229
+ else {
230
+ const live = t;
231
+ ref.t = live;
232
+ dbg(`reuse session ${live.sessionId} — ${keys.length - cls.fromIndex} new msg(s) (cache-friendly)`);
233
+ // A fresh user turn: drop any deferred state left by a prior turn that was
234
+ // abandoned (continuation never arrived) so it can't hang or leak.
235
+ this.clearCancelWatchdog(live);
236
+ this.drainPermissions(live);
237
+ live.pendingTools.clear();
238
+ live.controller = controller;
239
+ live.lastActive = Date.now();
240
+ if (ocSession)
241
+ live.ocSession = ocSession;
242
+ if (po.ocAgent)
243
+ live.ocAgent = String(po.ocAgent);
244
+ this.flushPending(live);
245
+ await this.applySessionConfig(live, ctrl);
246
+ const tail = hist.slice(cls.fromIndex);
247
+ const blocks = [
248
+ ...this.contextBlocks(live, options.prompt, ctrl),
249
+ ...(tail.length ? this.blocksFor(tail, live) : this.lastUserBlocks(options.prompt)),
250
+ ];
251
+ live.sentKeys = keys;
252
+ if (ocSession)
253
+ setLink(ocSession, live.sessionId, hist.length, convKey);
254
+ this.connection
255
+ .prompt({ sessionId: live.sessionId, prompt: blocks })
256
+ .then((resp) => this.onPromptDone(live, resp))
257
+ .catch((err) => this.onPromptError(live, err));
258
+ return;
259
+ }
260
+ }
261
+ dbg(`dropping session ${t.sessionId} — ${drop}`);
262
+ this.endTurn(t);
263
+ t = undefined;
189
264
  }
190
- // (3) Need a session: new conversation / tools / system / cfg changed, OR a
265
+ // (3) Need a session: new conversation, or the history diverged, or a
191
266
  // resumable session from a new process. Set up the MCP host once.
192
- const reason = !this.current ? "new conversation"
193
- : this.current.convKey !== convKey ? "new conversation"
194
- : this.current.toolsKey !== toolsKey ? "tools changed"
195
- : this.current.systemKey !== systemKey ? "system prompt changed"
196
- : "config changed";
197
- this.endTurn();
198
- const host = new McpHost("opencode");
199
- host.onToolCall((c) => this.onToolCall(c));
267
+ // Unique per-host prefix so minted toolCallIds NEVER collide with ids from a
268
+ // previous session still present in OpenCode's replayed history (a fresh host is
269
+ // created on every session reset). A random nonce is robust across resets, process
270
+ // restarts and resume — unlike a per-host counter, which restarts at 0.
271
+ const idPrefix = `acp_${randomBytes(5).toString("hex")}_`;
272
+ const host = new McpHost("opencode", idPrefix);
200
273
  await host.start();
201
274
  host.setTools(tools);
202
275
  const serverConfig = host.getServerConfig();
@@ -204,9 +277,13 @@ export class ACPOrchestratorModel {
204
277
  // history grew rather than diverged) → no history replay (saves tokens). Else
205
278
  // create a fresh session and replay the full history.
206
279
  const resumeId = po.resumeId;
280
+ const resumeLen = typeof po.resumeLen === "number" ? po.resumeLen : 0;
207
281
  let sessionId;
208
282
  let replayFull = true;
209
- if (!this.current && resumeId && histLen > (po.resumeLen ?? 0)) {
283
+ if (DEBUG && po.resumeConvKey && po.resumeConvKey !== convKey) {
284
+ dbg(`resumeConvKey mismatch (registry=${po.resumeConvKey} current=${convKey}) — resuming anyway`);
285
+ }
286
+ if (resumeId && resumeLen > 0 && hist.length > resumeLen) {
210
287
  try {
211
288
  await this.connection.unstable_resumeSession({
212
289
  sessionId: resumeId,
@@ -215,8 +292,7 @@ export class ACPOrchestratorModel {
215
292
  // Re-apply the clean-brain options on resume too. Without this the agent
216
293
  // falls back to its defaults (--tools default, --setting-sources=user,
217
294
  // project,local, no --strict-mcp-config) and the resumed session regains
218
- // native tools + the claude.ai connectors. getOrCreateSession forwards
219
- // this _meta to createSession when the session isn't live in-process.
295
+ // native tools + the claude.ai connectors.
220
296
  _meta: { claudeCode: { options: buildClaudeCodeOptions(ctrl) } },
221
297
  });
222
298
  sessionId = resumeId;
@@ -230,7 +306,7 @@ export class ACPOrchestratorModel {
230
306
  if (!sessionId) {
231
307
  // OpenCode's system prompt → _meta.systemPrompt (preset/append/replace).
232
308
  const meta = { claudeCode: { options: buildClaudeCodeOptions(ctrl) } };
233
- const sysMeta = this.buildSystemPromptMeta(options.prompt, ctrl.systemPromptMode ?? "preset");
309
+ const sysMeta = this.buildSystemPromptMeta(options.prompt, systemMode);
234
310
  if (sysMeta !== undefined)
235
311
  meta.systemPrompt = sysMeta;
236
312
  const session = await this.connection.newSession({
@@ -239,51 +315,112 @@ export class ACPOrchestratorModel {
239
315
  _meta: meta,
240
316
  });
241
317
  sessionId = session.sessionId;
242
- dbg(`new session ${sessionId} (${reason}) model=${session.models?.currentModelId ?? "?"} (requested: ${ctrl.model ?? "default"}, mode: ${ctrl.mode ?? "default"}, effort: ${ctrl.effort ?? "default"}) — tools(${tools.length})`);
318
+ dbg(`model=${session.models?.currentModelId ?? "?"} (requested: ${ctrl.model ?? "default"}, mode: ${ctrl.mode ?? "default"}, effort: ${ctrl.effort ?? "default"}) — tools(${tools.length})`);
243
319
  }
244
320
  if (!sessionId)
245
321
  throw new Error("failed to create or resume an ACP session");
246
- const t = {
322
+ // The ACP sessionId IS the Claude Code session id: surfacing it lets the user
323
+ // pick the conversation back up natively.
324
+ note(`session ${sessionId}${replayFull ? "" : " (resumed)"} — retomable con: claude --resume ${sessionId}`);
325
+ t = {
326
+ key,
247
327
  host,
328
+ idPrefix,
248
329
  sessionId,
249
330
  convKey,
250
331
  toolsKey,
251
332
  systemKey,
252
333
  cfgKey,
253
334
  ocSession,
335
+ ocAgent: po.ocAgent ? String(po.ocAgent) : undefined,
254
336
  // Resume path: seed the cumulative usage snapshot from the persisted
255
337
  // registry so the first post-resume `subtractUsage` produces a real
256
338
  // turn delta instead of the full cumulative.
257
339
  lastUsage: replayFull ? undefined : po.resumeLastUsage,
340
+ // Full replay covers the whole history; a bare resume only covers up to what
341
+ // the registry last recorded — the rest still needs sending below.
342
+ sentKeys: replayFull ? [] : keys.slice(0, resumeLen),
258
343
  controller,
344
+ pending: [],
259
345
  pendingTools: new Set(),
260
346
  pendingPermissions: new Map(),
261
347
  textId: null,
262
348
  reasoningId: null,
349
+ cancelWatchdogs: new Set(),
350
+ lastActive: Date.now(),
263
351
  };
264
- this.current = t;
265
- await this.applySessionConfig(t, ctrl); // mode/effort at runtime
352
+ ref.t = t;
353
+ host.onToolCall((c) => this.onToolCall(t, c));
354
+ this.sessions.set(key, t);
355
+ this.byAcpSession.set(sessionId, t);
356
+ this.evictIdleSessions();
357
+ await this.applySessionConfig(t, ctrl);
266
358
  if (ocSession)
267
- setLink(ocSession, sessionId, histLen);
359
+ setLink(ocSession, sessionId, hist.length, convKey);
360
+ const tail = replayFull ? hist : hist.slice(resumeLen);
361
+ if (DEBUG && !replayFull)
362
+ dbg(`resume — catch-up ${tail.length} msg(s)`);
363
+ const promptBlocks = [
364
+ ...this.contextBlocks(t, options.prompt, ctrl),
365
+ ...(tail.length ? this.blocksFor(tail, t) : [{ type: "text", text: "" }]),
366
+ ];
367
+ t.sentKeys = keys;
368
+ const started = t;
268
369
  this.connection
269
- .prompt({ sessionId, prompt: replayFull ? this.convertMessages(options.prompt) : this.lastUserBlocks(options.prompt) })
270
- .then((resp) => this.onPromptDone(resp))
271
- .catch((err) => this.onPromptError(err));
370
+ .prompt({ sessionId, prompt: promptBlocks })
371
+ .then((resp) => this.onPromptDone(started, resp))
372
+ .catch((err) => this.onPromptError(started, err));
272
373
  }
273
374
  catch (err) {
274
375
  dbg(`onStart error: ${err instanceof Error ? err.message : String(err)}`);
275
- controller.enqueue({ type: "error", error: err });
376
+ try {
377
+ controller.enqueue({ type: "error", error: err });
378
+ }
379
+ catch { /* ignore */ }
276
380
  try {
277
381
  controller.close();
278
382
  }
279
383
  catch { /* ignore */ }
280
384
  }
281
385
  }
282
- onPromptDone(resp) {
283
- const t = this.current;
284
- if (!t || !t.controller)
386
+ /** Enqueue if a stream is attached; otherwise BUFFER. The stream is closed between
387
+ * a tool-call and its continuation, and text/thought chunks keep arriving on the
388
+ * (independent) ACP stdio channel meanwhile — dropping them truncated answers and
389
+ * hid the reasoning block entirely. */
390
+ emit(t, part) {
391
+ if (t.controller) {
392
+ try {
393
+ t.controller.enqueue(part);
394
+ return;
395
+ }
396
+ catch { /* closed underneath us */ }
397
+ }
398
+ t.pending.push(part);
399
+ // Cap anti-OOM: con el controller cerrado mucho rato `pending` crecería sin
400
+ // límite — se descartan los chunks más antiguos.
401
+ if (t.pending.length > MAX_PENDING_PARTS) {
402
+ t.pending.splice(0, t.pending.length - MAX_PENDING_PARTS);
403
+ dbg(`pending desbordado (>${MAX_PENDING_PARTS}) — descartados los más antiguos`);
404
+ }
405
+ }
406
+ flushPending(t) {
407
+ if (!t.controller || t.pending.length === 0)
408
+ return;
409
+ const parts = t.pending;
410
+ t.pending = [];
411
+ dbg(`flushing ${parts.length} buffered chunk(s) into the continuation stream`);
412
+ for (const p of parts) {
413
+ try {
414
+ t.controller.enqueue(p);
415
+ }
416
+ catch { /* ignore */ }
417
+ }
418
+ }
419
+ onPromptDone(t, resp) {
420
+ if (!t.controller)
285
421
  return; // cut for a pending tool-call
286
422
  this.closeBlocks(t);
423
+ this.flushPending(t);
287
424
  const turn = subtractUsage(resp?.usage, t.lastUsage); // ACP usage is cumulative per session
288
425
  if (resp?.usage) {
289
426
  t.lastUsage = resp.usage;
@@ -292,45 +429,52 @@ export class ACPOrchestratorModel {
292
429
  }
293
430
  if (DEBUG && turn)
294
431
  dbg(`usage(turn): in=${turn.inputTokens} out=${turn.outputTokens} cacheR=${turn.cachedReadTokens} cacheW=${turn.cachedWriteTokens}`);
295
- t.controller.enqueue({
296
- type: "finish",
297
- usage: mapUsage(turn),
298
- finishReason: { unified: resp?.stopReason === "max_tokens" ? "length" : "stop", raw: resp?.stopReason },
299
- });
300
432
  try {
433
+ t.controller.enqueue({
434
+ type: "finish",
435
+ usage: mapUsage(turn),
436
+ finishReason: { unified: resp?.stopReason === "max_tokens" ? "length" : "stop", raw: resp?.stopReason },
437
+ });
301
438
  t.controller.close();
302
439
  }
303
440
  catch { /* ignore */ }
304
441
  t.controller = null; // keep the session for the next turn (delta)
305
442
  }
306
- onPromptError(err) {
307
- const t = this.current;
308
- if (!t || !t.controller)
443
+ onPromptError(t, err) {
444
+ if (!t.controller)
309
445
  return;
310
446
  dbg(`prompt error: ${err instanceof Error ? err.message : String(err)}`);
311
- t.controller.enqueue({ type: "error", error: err });
312
447
  try {
448
+ t.controller.enqueue({ type: "error", error: err });
313
449
  t.controller.close();
314
450
  }
315
451
  catch { /* ignore */ }
316
452
  t.controller = null;
317
453
  }
318
454
  /** Fired by the MCP host when the agent calls an OpenCode tool. */
319
- onToolCall(call) {
320
- const t = this.current;
321
- if (!t || !t.controller)
455
+ onToolCall(t, call) {
456
+ if (!t.controller)
322
457
  return;
323
458
  dbg(`agent → tool-call ${call.name} (${call.toolCallId}) → emit to OpenCode`);
324
459
  this.closeBlocks(t);
325
460
  t.pendingTools.add(call.toolCallId);
326
- const inputJson = JSON.stringify(call.args ?? {});
327
- t.controller.enqueue({ type: "tool-input-start", id: call.toolCallId, toolName: call.name });
328
- t.controller.enqueue({ type: "tool-input-delta", id: call.toolCallId, delta: inputJson });
329
- t.controller.enqueue({ type: "tool-input-end", id: call.toolCallId });
330
- t.controller.enqueue({ type: "tool-call", toolCallId: call.toolCallId, toolName: call.name, input: inputJson });
331
- t.controller.enqueue({ type: "finish", usage: emptyUsage(), finishReason: { unified: "tool-calls", raw: "tool_use" } });
461
+ // `call.args` puede traer refs circulares/BigInt → JSON.stringify lanzaría y
462
+ // tumbaría el turno: degradar a marcador en vez de crashear.
463
+ let inputJson;
332
464
  try {
333
- t.controller.close();
465
+ inputJson = JSON.stringify(call.args ?? {});
466
+ }
467
+ catch (e) {
468
+ dbg(`tool-call ${call.name}: args no serializables (${e instanceof Error ? e.message : String(e)}) — input="<serialization error>"`);
469
+ inputJson = '"<serialization error>"';
470
+ }
471
+ this.emit(t, { type: "tool-input-start", id: call.toolCallId, toolName: call.name });
472
+ this.emit(t, { type: "tool-input-delta", id: call.toolCallId, delta: inputJson });
473
+ this.emit(t, { type: "tool-input-end", id: call.toolCallId });
474
+ this.emit(t, { type: "tool-call", toolCallId: call.toolCallId, toolName: call.name, input: inputJson });
475
+ this.emit(t, { type: "finish", usage: emptyUsage(), finishReason: { unified: "tool-calls", raw: "tool_use" } });
476
+ try {
477
+ t.controller?.close();
334
478
  }
335
479
  catch { /* ignore */ }
336
480
  t.controller = null; // DO NOT resolve yet — wait for the continuation doStream
@@ -339,83 +483,182 @@ export class ACPOrchestratorModel {
339
483
  /** Map approve/reject to one of the options the agent offered (by kind/optionId). */
340
484
  permOutcome(params, approved) {
341
485
  const opts = params?.options ?? [];
342
- const want = approved
343
- ? (o) => o.kind === "allow_once" || o.kind === "allow_always" || o.optionId === "allow"
344
- : (o) => o.kind === "reject_once" || o.kind === "reject_always" || o.optionId === "reject";
345
- const opt = opts.find(want) ?? (approved ? opts[0] : undefined);
346
- if (!opt)
486
+ if (!opts.length)
347
487
  return { outcome: { outcome: "cancelled" } };
348
- return { outcome: { outcome: "selected", optionId: opt.optionId } };
488
+ if (!approved) {
489
+ const rej = opts.find((o) => o.kind === "reject_once" || o.kind === "reject_always" || o.optionId === "reject");
490
+ return rej ? { outcome: { outcome: "selected", optionId: rej.optionId } } : { outcome: { outcome: "cancelled" } };
491
+ }
492
+ // Approving an ExitPlanMode must NOT silently hand out bypass/auto. The agent
493
+ // offers, in order, `bypassPermissions`, `auto`, `acceptEdits`, `default` — and
494
+ // picking the first `allow_*` would grant the broadest one. Approving a plan means
495
+ // "go ahead, still asking me about edits" → prefer `default`.
496
+ if (params?.toolCall?.kind === "switch_mode") {
497
+ const safe = opts.find((o) => o.optionId === "default") ?? opts.find((o) => o.optionId === "acceptEdits");
498
+ if (safe)
499
+ return { outcome: { outcome: "selected", optionId: safe.optionId } };
500
+ }
501
+ const opt = opts.find((o) => o.kind === "allow_once" || o.kind === "allow_always" || o.optionId === "allow") ?? opts[0];
502
+ return opt ? { outcome: { outcome: "selected", optionId: opt.optionId } } : { outcome: { outcome: "cancelled" } };
349
503
  }
350
504
  /** Tool name the agent wants permission for. The ACP toolCall carries NO bare
351
505
  * name — `title` is a human label like "Read /path", "Write /path", "Skill" — so
352
506
  * we take the first token. This becomes the permission key, so per-tool rules
353
507
  * (`permission: { Read: … }`) match. The full title travels separately as metadata. */
354
508
  permToolName(toolCall) {
509
+ // ExitPlanMode surfaces as a `switch_mode` permission — give it a stable, rule-able
510
+ // name so the prompt reads clearly and `permission: { ExitPlanMode: … }` matches.
511
+ if (toolCall?.kind === "switch_mode")
512
+ return "ExitPlanMode";
355
513
  const title = String(toolCall?.title ?? "").trim();
356
514
  return title.split(/\s+/)[0] || String(toolCall?.kind ?? "") || "tool";
357
515
  }
358
- /** ACP requestPermission → OpenCode `ask`, via the claude_permission meta-tool.
359
- * Deferred: returns a Promise the agent awaits until OpenCode's verdict comes
360
- * back as the meta-tool's result (resolved in onStart's continuation branch). */
516
+ /** Extract the markdown plan from an ExitPlanMode (`switch_mode`) tool call: it rides
517
+ * in `rawInput.plan`, with the tool-call text content as a fallback. */
518
+ planText(toolCall) {
519
+ const raw = toolCall?.rawInput;
520
+ if (raw && typeof raw === "object" && typeof raw.plan === "string")
521
+ return raw.plan;
522
+ const content = Array.isArray(toolCall?.content) ? toolCall.content : [];
523
+ return content
524
+ .map((c) => (c?.type === "content" && c.content?.type === "text" ? c.content.text : typeof c?.text === "string" ? c.text : ""))
525
+ .filter(Boolean)
526
+ .join("\n");
527
+ }
528
+ /** ACP requestPermission → the agent's own rules first, then the `question` dialog.
529
+ * Deferred: returns a Promise the agent awaits until the verdict comes back as
530
+ * the `question` tool-result (resolved in onStart's continuation branch). */
361
531
  onRequestPermission(params) {
362
- const t = this.current;
363
- // No live turn/controller → approve so the agent never hangs.
532
+ const t = this.byAcpSession.get(String(params?.sessionId ?? ""));
533
+ // Sin turno vivo (crash/reinicio) — denegar es más seguro que aprobar a ciegas.
364
534
  if (!t || !t.controller)
535
+ return Promise.resolve(this.permOutcome(params, false));
536
+ const toolCall = params?.toolCall;
537
+ const native = this.permToolName(toolCall);
538
+ const target = this.bridgeTarget(toolCall);
539
+ const agent = t.ocAgent ?? "default";
540
+ // (1) allow/deny rules answer outright — no dialog, same as a native tool
541
+ // OpenCode would resolve itself.
542
+ const rules = evaluateBridge(agent, native, target.pattern);
543
+ dbg(`requestPermission(${native} → ${target.pattern}) agent=${agent} rules=${rules}`);
544
+ if (rules === "allow")
365
545
  return Promise.resolve(this.permOutcome(params, true));
546
+ if (rules === "deny")
547
+ return Promise.resolve(this.permOutcome(params, false));
548
+ // (2) "ask": raise a `question` dialog and wait for its tool-result.
366
549
  const callId = `perm_${++this.idSeq}`;
367
- dbg(`requestPermission(${this.permToolName(params?.toolCall)}) → bridge as claude_permission (${callId})`);
550
+ dbg(`requestPermission(${native}) → bridge as question (${callId})`);
368
551
  return new Promise((resolve) => {
369
- t.pendingPermissions.set(callId, (approved) => resolve(this.permOutcome(params, approved)));
370
- this.emitPermissionCall(t, callId, params?.toolCall);
552
+ t.pendingPermissions.set(callId, (verdict) => {
553
+ if (verdict.approved && verdict.always && target.always)
554
+ addAlwaysRule(agent, native, target.always);
555
+ resolve(this.permOutcome(params, verdict.approved));
556
+ });
557
+ this.emitPermissionCall(t, callId, toolCall, native, target);
371
558
  });
372
559
  }
373
- /** Emit a claude_permission tool-call to OpenCode (same deferred pattern as a
374
- * real tool-call): OpenCode applies its `ask` permission and returns the
375
- * verdict as the tool-result on the next doStream. */
376
- emitPermissionCall(t, callId, toolCall) {
560
+ /** Action target of a native request (command / skill / path), plus the glob an
561
+ * "Always allow" would persist. Shell commands collapse to their first token
562
+ * (`git status` → `git *`); a request with no real target persists nothing, so
563
+ * the dialog never offers a broad rule that would auto-approve everything. */
564
+ bridgeTarget(toolCall) {
565
+ const raw = toolCall?.rawInput;
566
+ const inp = raw && typeof raw === "object" ? raw : {};
567
+ const text = String((inp.command ?? inp.skill ?? inp.name ?? inp.notebook_path ?? inp.file_path ?? inp.path) ||
568
+ (typeof raw === "string" ? raw : "") ||
569
+ toolCall?.title ||
570
+ "").trim();
571
+ const always = toolCall?.kind === "execute" && text.includes(" ") ? `${text.split(/\s+/)[0]} *` : text || undefined;
572
+ return { pattern: text || "*", always };
573
+ }
574
+ /** Emit a `question` tool-call to OpenCode (same deferred pattern as a real
575
+ * tool-call): the native tool's request becomes a dialog — Allow once /
576
+ * Always allow / Deny — and the answer arrives as the tool-result on the next
577
+ * doStream. The agent itself only ever sees the ACP permission outcome. */
578
+ emitPermissionCall(t, callId, toolCall, native, target) {
377
579
  if (!t.controller)
378
580
  return;
379
581
  this.closeBlocks(t);
582
+ // ExitPlanMode (switch_mode): render the PLAN as visible assistant text before the
583
+ // approval prompt — otherwise it's only buried in the permission metadata and the
584
+ // user would approve blind. Presenting the plan for approval IS the point of the tool.
585
+ if (toolCall?.kind === "switch_mode") {
586
+ const plan = this.planText(toolCall);
587
+ if (plan) {
588
+ const id = `plan${++this.idSeq}`;
589
+ this.emit(t, { type: "text-start", id });
590
+ this.emit(t, { type: "text-delta", id, delta: plan });
591
+ this.emit(t, { type: "text-end", id });
592
+ }
593
+ }
380
594
  const input = JSON.stringify({
381
- tool: this.permToolName(toolCall),
382
- kind: toolCall?.kind,
383
- title: toolCall?.title,
384
- input: toolCall?.rawInput,
595
+ questions: [
596
+ {
597
+ question: `${native}: ${toolCall?.title ?? target.pattern}`,
598
+ header: "Permission",
599
+ options: [
600
+ { label: ALLOW_ONCE, description: "Approve this action for this call only" },
601
+ ...(target.always
602
+ ? [{ label: ALWAYS_ALLOW, description: `Approve and stop asking for ${target.always}` }]
603
+ : []),
604
+ { label: DENY, description: "Block this action" },
605
+ ],
606
+ },
607
+ ],
385
608
  });
386
- t.controller.enqueue({ type: "tool-input-start", id: callId, toolName: "claude_permission" });
387
- t.controller.enqueue({ type: "tool-input-delta", id: callId, delta: input });
388
- t.controller.enqueue({ type: "tool-input-end", id: callId });
389
- t.controller.enqueue({ type: "tool-call", toolCallId: callId, toolName: "claude_permission", input });
390
- t.controller.enqueue({ type: "finish", usage: emptyUsage(), finishReason: { unified: "tool-calls", raw: "tool_use" } });
609
+ this.emit(t, { type: "tool-input-start", id: callId, toolName: "question" });
610
+ this.emit(t, { type: "tool-input-delta", id: callId, delta: input });
611
+ this.emit(t, { type: "tool-input-end", id: callId });
612
+ this.emit(t, { type: "tool-call", toolCallId: callId, toolName: "question", input });
613
+ this.emit(t, { type: "finish", usage: emptyUsage(), finishReason: { unified: "tool-calls", raw: "tool_use" } });
391
614
  try {
392
- t.controller.close();
615
+ t.controller?.close();
393
616
  }
394
617
  catch { /* ignore */ }
395
618
  t.controller = null;
396
619
  }
397
620
  /** Fired by the ACP client on session/update. */
398
- onSessionUpdate(update) {
399
- const t = this.current;
400
- if (!t || !t.controller)
621
+ onSessionUpdate(params) {
622
+ const t = this.byAcpSession.get(String(params?.sessionId ?? ""));
623
+ if (!t)
401
624
  return;
625
+ const update = params?.update;
626
+ // Mode switch (e.g. ExitPlanMode approved: plan → default). Track it even without a
627
+ // live controller so the bridge stays in sync and won't re-force the agent's
628
+ // configured mode on the next turn (which would undo the plan-exit).
629
+ if (update?.sessionUpdate === "current_mode_update") {
630
+ if (update.currentModeId) {
631
+ const from = t.appliedMode ?? "?";
632
+ t.appliedMode = String(update.currentModeId);
633
+ t.modeChangedByAgent = true;
634
+ dbg(`current_mode_update → ${t.appliedMode}`);
635
+ // Make it visible: the session's mode just changed under the user's feet, and
636
+ // OpenCode still shows whatever agent they picked. The two agents share the
637
+ // same tool profile, so this is informational, not a call to action.
638
+ const id = `mode${++this.idSeq}`;
639
+ this.emit(t, { type: "text-start", id });
640
+ this.emit(t, { type: "text-delta", id, delta: `\n_Modo de sesión: ${from} → ${t.appliedMode}_\n` });
641
+ this.emit(t, { type: "text-end", id });
642
+ }
643
+ return;
644
+ }
402
645
  switch (update?.sessionUpdate) {
403
646
  case "agent_message_chunk":
404
647
  if (update.content?.type === "text") {
405
648
  if (!t.textId) {
406
649
  t.textId = `t${++this.idSeq}`;
407
- t.controller.enqueue({ type: "text-start", id: t.textId });
650
+ this.emit(t, { type: "text-start", id: t.textId });
408
651
  }
409
- t.controller.enqueue({ type: "text-delta", id: t.textId, delta: update.content.text });
652
+ this.emit(t, { type: "text-delta", id: t.textId, delta: update.content.text });
410
653
  }
411
654
  break;
412
655
  case "agent_thought_chunk":
413
656
  if (update.content?.type === "text") {
414
657
  if (!t.reasoningId) {
415
658
  t.reasoningId = `r${++this.idSeq}`;
416
- t.controller.enqueue({ type: "reasoning-start", id: t.reasoningId });
659
+ this.emit(t, { type: "reasoning-start", id: t.reasoningId });
417
660
  }
418
- t.controller.enqueue({ type: "reasoning-delta", id: t.reasoningId, delta: update.content.text });
661
+ this.emit(t, { type: "reasoning-delta", id: t.reasoningId, delta: update.content.text });
419
662
  }
420
663
  break;
421
664
  default:
@@ -423,20 +666,17 @@ export class ACPOrchestratorModel {
423
666
  }
424
667
  }
425
668
  closeBlocks(t) {
426
- if (t.textId && t.controller) {
427
- t.controller.enqueue({ type: "text-end", id: t.textId });
669
+ if (t.textId) {
670
+ this.emit(t, { type: "text-end", id: t.textId });
428
671
  t.textId = null;
429
672
  }
430
- if (t.reasoningId && t.controller) {
431
- t.controller.enqueue({ type: "reasoning-end", id: t.reasoningId });
673
+ if (t.reasoningId) {
674
+ this.emit(t, { type: "reasoning-end", id: t.reasoningId });
432
675
  t.reasoningId = null;
433
676
  }
434
677
  }
435
- endTurn() {
436
- this.clearCancelWatchdog();
437
- const t = this.current;
438
- if (!t)
439
- return;
678
+ endTurn(t) {
679
+ this.clearCancelWatchdog(t);
440
680
  // Settle any deferred permission requests (deny/cancel) so the agent never
441
681
  // stays blocked awaiting a verdict that will no longer arrive.
442
682
  this.drainPermissions(t);
@@ -446,29 +686,72 @@ export class ACPOrchestratorModel {
446
686
  }
447
687
  catch { /* ignore */ }
448
688
  t.host.stop();
449
- this.current = null;
689
+ if (this.sessions.get(t.key) === t)
690
+ this.sessions.delete(t.key);
691
+ this.byAcpSession.delete(t.sessionId);
692
+ }
693
+ /** Keep at most MAX_LIVE_SESSIONS conversations alive; tear down the oldest idle ones
694
+ * (never one with work in flight) so hosts and agent sessions don't pile up. */
695
+ evictIdleSessions() {
696
+ if (this.sessions.size <= MAX_LIVE_SESSIONS)
697
+ return;
698
+ const idle = [...this.sessions.values()]
699
+ .filter((s) => !s.controller && s.pendingTools.size === 0 && s.pendingPermissions.size === 0)
700
+ .sort((a, b) => a.lastActive - b.lastActive);
701
+ while (this.sessions.size > MAX_LIVE_SESSIONS && idle.length) {
702
+ const victim = idle.shift();
703
+ dbg(`evicting idle session ${victim.sessionId} (LRU)`);
704
+ this.endTurn(victim);
705
+ }
450
706
  }
451
707
  /** Resolve every outstanding bridged permission as denied so the agent unblocks. */
452
708
  drainPermissions(t) {
453
709
  if (t.pendingPermissions.size === 0)
454
710
  return;
711
+ const denied = { approved: false, always: false };
455
712
  for (const resolve of [...t.pendingPermissions.values()]) {
456
713
  try {
457
- resolve(false);
714
+ resolve(denied);
458
715
  }
459
716
  catch { /* ignore */ }
460
717
  }
461
718
  t.pendingPermissions.clear();
462
719
  }
720
+ /** Per-call provider options: V2 nests them under `providerOptionKey(package,
721
+ * providerID)` = the providerID. El fallback al primer objeto del mapa sería
722
+ * voraz (podría tomar opciones de OTRO provider): solo se acepta si la key
723
+ * contiene nuestro provider id (`acp`) o el objeto trae forma conocida
724
+ * (ocSession/ocAgent/resumeId/…/mode/effort/native*); si no, como ausente. */
725
+ providerOptions(options) {
726
+ const all = (options.providerOptions ?? {});
727
+ const own = all[this.provider];
728
+ if (own && typeof own === "object")
729
+ return own;
730
+ const SHAPE_KEYS = new Set([
731
+ "ocSession", "ocAgent", "resumeId", "resumeLen", "resumeConvKey", "resumeLastUsage",
732
+ "mode", "effort", "thinking", "systemPromptMode", "forwardEnvContext",
733
+ "tools", "allowedTools", "disallowedTools", "settingSources", "strictMcpConfig",
734
+ "nativeTools", "resourceSearch", "nativeSubagents", "nativeSkills", "projectMemory", "skillShell",
735
+ ]);
736
+ for (const [key, value] of Object.entries(all)) {
737
+ if (!value || typeof value !== "object" || Array.isArray(value))
738
+ continue;
739
+ if (String(key).toLowerCase().includes(this.provider))
740
+ return value;
741
+ if (Object.keys(value).some((k) => SHAPE_KEYS.has(k) || k.startsWith("native")))
742
+ return value;
743
+ }
744
+ return {};
745
+ }
463
746
  /** Provider config overlaid with per-call `providerOptions.acp` (per-agent mode/effort/…). */
464
747
  effectiveCtrl(options) {
465
748
  const ctrl = { ...(this.config.claudeCode ?? {}) };
466
- const po = options.providerOptions?.[this.provider];
749
+ const po = this.providerOptions(options);
467
750
  if (po && typeof po === "object") {
468
751
  // Per-agent overrides from `agent.<name>.options` (→ providerOptions.acp):
469
752
  // mode/effort/reasoning plus the native-feature toggles.
470
753
  const KEYS = [
471
- "mode", "effort", "thinking", "systemPromptMode",
754
+ "mode", "effort", "thinking", "systemPromptMode", "forwardEnvContext",
472
755
  "tools", "allowedTools", "disallowedTools", "settingSources", "strictMcpConfig",
473
756
  "nativeTools", "resourceSearch", "nativeSubagents", "nativeSkills", "projectMemory", "skillShell",
474
757
  ];
@@ -483,7 +766,16 @@ export class ACPOrchestratorModel {
483
766
  }
484
767
  /** Apply runtime config (mode/effort) to a live ACP session via set_mode/set_config_option. */
485
768
  async applySessionConfig(t, ctrl) {
486
- if (ctrl.mode && ctrl.mode !== t.appliedMode) {
769
+ // A CHANGED request (the user reselected the plan agent) overrides a mode the agent
770
+ // set for itself. Without this reset an ExitPlanMode would permanently pin the
771
+ // session out of plan mode, and going back to the plan agent would do nothing.
772
+ if (ctrl.mode !== t.requestedMode) {
773
+ t.requestedMode = ctrl.mode;
774
+ t.modeChangedByAgent = false;
775
+ }
776
+ // Don't re-force the configured mode once the agent switched it itself (ExitPlanMode):
777
+ // the user approved leaving plan mode, so the next turn must not snap back to plan.
778
+ if (ctrl.mode && ctrl.mode !== t.appliedMode && !t.modeChangedByAgent) {
487
779
  try {
488
780
  await this.connection.setSessionMode({ sessionId: t.sessionId, modeId: ctrl.mode });
489
781
  t.appliedMode = ctrl.mode;
@@ -500,7 +792,9 @@ export class ACPOrchestratorModel {
500
792
  dbg(`effort → ${ctrl.effort}`);
501
793
  }
502
794
  catch (e) {
503
- dbg(`setSessionConfigOption(effort=${ctrl.effort}) failed: ${e instanceof Error ? e.message : String(e)}`);
795
+ // Not a debug detail: a rejected effort means the user picked `:max` and is
796
+ // silently getting something else — including no visible reasoning.
797
+ note(`aviso: no se pudo aplicar effort=${ctrl.effort} (${e instanceof Error ? e.message : String(e)})`);
504
798
  }
505
799
  }
506
800
  }
@@ -510,7 +804,9 @@ export class ACPOrchestratorModel {
510
804
  return Promise.resolve();
511
805
  if (this.connecting)
512
806
  return this.connecting;
513
- this.connecting = this.connect();
807
+ // Si `connect()` lanza, `connecting` debe resetearse: si no, todos los
808
+ // `ensureConnected()` futuros reutilizarían la promesa rechazada y colgarían.
809
+ this.connecting = this.connect().then(() => undefined, (err) => { this.connecting = null; throw err; });
514
810
  return this.connecting;
515
811
  }
516
812
  async connect() {
@@ -551,7 +847,9 @@ export class ACPOrchestratorModel {
551
847
  const stream = ndJsonStream(Writable.toWeb(this.agent.stdin), Readable.toWeb(this.agent.stdout));
552
848
  const self = this;
553
849
  this.connection = new ClientSideConnection(() => ({
554
- async sessionUpdate(params) { self.onSessionUpdate(params.update); },
850
+ // Keep the whole params object: `sessionId` is what routes the update to the
851
+ // right conversation now that several can be live at once.
852
+ async sessionUpdate(params) { self.onSessionUpdate(params); },
555
853
  async requestPermission(params) {
556
854
  return self.onRequestPermission(params);
557
855
  },
@@ -565,42 +863,54 @@ export class ACPOrchestratorModel {
565
863
  this.promptCaps = (initResult?.agentCapabilities?.promptCapabilities ?? {});
566
864
  dbg(`connected to agent — promptCapabilities: ${JSON.stringify(this.promptCaps)}`);
567
865
  }
568
- onCancel() {
866
+ onCancel(ref) {
867
+ const t = ref.t;
868
+ if (!t)
869
+ return;
569
870
  // A stream cancel WHILE a tool-call or permission is deferred is OpenCode
570
871
  // PAUSING (e.g. to show a permission prompt), not a real abort — tearing the
571
872
  // host down here kills the pending tools/call with "host closed". Keep the
572
873
  // session/host alive; the continuation doStream resolves them. A WATCHDOG
573
874
  // guarantees teardown if the continuation never arrives (session truly aborted,
574
875
  // prompt dropped) so the agent can't hang forever.
575
- const t = this.current;
576
- if (t && (t.pendingTools.size > 0 || t.pendingPermissions.size > 0)) {
876
+ if (t.pendingTools.size > 0 || t.pendingPermissions.size > 0) {
577
877
  dbg("onCancel ignored — deferred tool-call/permission in flight (likely a permission pause)");
578
- this.armCancelWatchdog();
878
+ this.armCancelWatchdog(t);
579
879
  return;
580
880
  }
581
- this.endTurn();
881
+ // A plain cancel ends the TURN, not the conversation: keep the session (and its
882
+ // prompt cache) so the next message continues where this one stopped.
883
+ try {
884
+ this.connection?.cancel?.({ sessionId: t.sessionId });
885
+ }
886
+ catch { /* ignore */ }
887
+ t.controller = null;
888
+ this.closeBlocks(t);
582
889
  }
583
890
  /** If a cancel was ignored (deferred work in flight) but no continuation comes,
584
891
  * force teardown so the agent doesn't stay blocked. Cleared by a continuation. */
585
- armCancelWatchdog() {
586
- this.clearCancelWatchdog();
587
- this.cancelWatchdog = setTimeout(() => {
588
- this.cancelWatchdog = null;
589
- if (this.current) {
590
- dbg("cancel watchdog fired — no continuation arrived; tearing down");
591
- this.endTurn();
592
- }
892
+ armCancelWatchdog(t) {
893
+ this.clearCancelWatchdog(t);
894
+ const timer = setTimeout(() => {
895
+ t.cancelWatchdogs.delete(timer);
896
+ dbg("cancel watchdog fired — no continuation arrived; tearing down");
897
+ this.endTurn(t);
593
898
  }, this.config.streamCloseTimeoutMs ?? 600_000);
594
- this.cancelWatchdog.unref?.();
899
+ timer.unref?.();
900
+ t.cancelWatchdogs.add(timer);
595
901
  }
596
- clearCancelWatchdog() {
597
- if (this.cancelWatchdog) {
598
- clearTimeout(this.cancelWatchdog);
599
- this.cancelWatchdog = null;
600
- }
902
+ /** Barre TODOS los watchdogs del turno (cada `onCancel` ignorado arma uno);
903
+ * llamado desde endTurn/cleanup y al continuar el turno. */
904
+ clearCancelWatchdog(t) {
905
+ for (const timer of t.cancelWatchdogs)
906
+ clearTimeout(timer);
907
+ t.cancelWatchdogs.clear();
601
908
  }
602
909
  cleanup() {
603
- this.endTurn();
910
+ for (const t of [...this.sessions.values()])
911
+ this.endTurn(t);
912
+ this.sessions.clear();
913
+ this.byAcpSession.clear();
604
914
  try {
605
915
  this.agent?.kill();
606
916
  }
@@ -615,21 +925,28 @@ export class ACPOrchestratorModel {
615
925
  return [];
616
926
  const out = [];
617
927
  for (const t of tools) {
618
- // Skip the permission-bridge meta-tool: the provider emits `claude_permission`
619
- // itself and OpenCode runs it via the plugin, so the AGENT must NOT see it
620
- // (otherwise it surfaces as mcp__opencode__claude_permission and confuses it).
621
- if (t.name === "claude_permission")
622
- continue;
623
928
  if (t.type === "function") {
624
929
  out.push({
625
930
  name: t.name,
626
- description: t.description,
931
+ description: this.toolDescription(t.name, t.description),
627
932
  inputSchema: t.inputSchema ?? { type: "object", properties: {} },
628
933
  });
629
934
  }
630
935
  }
631
936
  return out;
632
937
  }
938
+ /** Nudges the agent can only get from the tool description. Under the default
939
+ * `systemPromptMode: "preset"` OpenCode's system prompt never reaches the agent,
940
+ * so the instruction that would normally push it toward `question` is missing —
941
+ * and its own `AskUserQuestion` is disabled by the ACP agent. Without this the
942
+ * agent silently assumes instead of asking. A tool description is NOT a system
943
+ * prompt, so this doesn't affect how Anthropic bills the session. */
944
+ toolDescription(name, description) {
945
+ if (name === "question") {
946
+ return `${description ?? ""}\n\nIMPORTANT: this is the ONLY way to ask the user something — the native AskUserQuestion tool is unavailable here. Use it whenever the request is ambiguous or a decision is the user's to make, instead of assuming.`.trim();
947
+ }
948
+ return description;
949
+ }
633
950
  /** Text of the first user message — stable identifier for the conversation. */
634
951
  firstUserText(prompt) {
635
952
  for (const m of prompt) {
@@ -641,7 +958,60 @@ export class ACPOrchestratorModel {
641
958
  }
642
959
  return "";
643
960
  }
644
- messageToBlocks(msg, withPrefix) {
961
+ /** The conversation proper: system messages are excluded because they're forwarded
962
+ * separately (or not at all) and OpenCode rewrites them every turn — including them
963
+ * would make every history comparison look like a divergence. */
964
+ history(prompt) {
965
+ return prompt.filter((m) => m.role !== "system");
966
+ }
967
+ /** Cheap, stable per-message identity. Deliberately keyed on tool-call IDs rather
968
+ * than payloads: it must survive re-serialization but change if the turn changes. */
969
+ msgKey(msg) {
970
+ let body = "";
971
+ if (typeof msg.content === "string")
972
+ body = msg.content;
973
+ else if (Array.isArray(msg.content)) {
974
+ for (const p of msg.content) {
975
+ if (p?.type === "text")
976
+ body += `t:${p.text}`;
977
+ else if (p?.type === "tool-call")
978
+ body += `c:${p.toolCallId}`;
979
+ else if (p?.type === "tool-result")
980
+ body += `r:${p.toolCallId}`;
981
+ else if (p?.type === "file")
982
+ body += `f:${p.filename ?? p.mediaType ?? ""}`;
983
+ else
984
+ body += `?${p?.type}`;
985
+ }
986
+ }
987
+ return `${msg.role}:${hashText(body)}`;
988
+ }
989
+ /** How the incoming history relates to what the agent already knows.
990
+ * - append → normal turn (or another agent ran turns meanwhile): send the tail.
991
+ * - revert → the user rewound: the agent can't unremember, so it needs a new session.
992
+ * - diverged → compaction/rollback replaced the middle: same, a new session. */
993
+ classifyHistory(t, keys) {
994
+ const sent = t.sentKeys;
995
+ let i = 0;
996
+ while (i < sent.length && i < keys.length && sent[i] === keys[i])
997
+ i++;
998
+ if (i === sent.length)
999
+ return { kind: "append", fromIndex: i };
1000
+ // Prefijo estricto = revert SOLO si incoming es más corto; si son iguales no hay
1001
+ // mensajes nuevos → append desde el final (evita falsos revert).
1002
+ if (i === keys.length)
1003
+ return keys.length < sent.length
1004
+ ? { kind: "revert", fromIndex: i }
1005
+ : { kind: "append", fromIndex: keys.length };
1006
+ return { kind: "diverged", fromIndex: i };
1007
+ }
1008
+ blocksFor(msgs, t) {
1009
+ const blocks = [];
1010
+ for (const msg of msgs)
1011
+ blocks.push(...this.messageToBlocks(msg, true, t));
1012
+ return blocks;
1013
+ }
1014
+ messageToBlocks(msg, withPrefix, t) {
645
1015
  const prefixes = { system: "System: ", assistant: "Assistant: ", tool: "", user: "" };
646
1016
  const prefix = withPrefix ? (prefixes[msg.role] ?? "") : "";
647
1017
  if (typeof msg.content === "string")
@@ -650,6 +1020,11 @@ export class ACPOrchestratorModel {
650
1020
  let first = true;
651
1021
  for (const part of msg.content) {
652
1022
  const px = first ? prefix : "";
1023
+ // OUR OWN tool traffic: the agent already holds these in its session (they came
1024
+ // back over MCP). Replaying them as text duplicated whole file/shell outputs on
1025
+ // every turn and blew the prompt cache — by far the biggest token sink.
1026
+ if ((part.type === "tool-call" || part.type === "tool-result") && t && String(part.toolCallId ?? "").startsWith(t.idPrefix))
1027
+ continue;
653
1028
  if (part.type === "text") {
654
1029
  blocks.push({ type: "text", text: px + part.text });
655
1030
  first = false;
@@ -659,7 +1034,7 @@ export class ACPOrchestratorModel {
659
1034
  first = false;
660
1035
  }
661
1036
  else if (part.type === "tool-result") {
662
- blocks.push({ type: "text", text: `${px}[Tool ${part.toolName} result: ${this.outputToText(part.output)}]` });
1037
+ blocks.push({ type: "text", text: `${px}[Tool ${part.toolName} result: ${this.truncate(this.outputToText(part.output))}]` });
663
1038
  first = false;
664
1039
  }
665
1040
  else if (part.type === "file") {
@@ -670,6 +1045,11 @@ export class ACPOrchestratorModel {
670
1045
  }
671
1046
  return blocks;
672
1047
  }
1048
+ /** A foreign tool-result is replayed only so the agent can follow the thread —
1049
+ * the full payload isn't worth the tokens. */
1050
+ truncate(s) {
1051
+ return s.length <= CATCHUP_RESULT_CHARS ? s : `${s.slice(0, CATCHUP_RESULT_CHARS)}…[truncado, ${s.length} chars]`;
1052
+ }
673
1053
  /** Map an AI SDK file part to an ACP ContentBlock, honoring the agent's promptCapabilities. */
674
1054
  fileToBlock(part) {
675
1055
  const mt = part.mediaType || "application/octet-stream";
@@ -696,16 +1076,6 @@ export class ACPOrchestratorModel {
696
1076
  return data.includes(",") ? data.split(",")[1] : data; // data URL or raw base64
697
1077
  return null; // URL or other — not embeddable
698
1078
  }
699
- /** Full prompt flattened to ACP ContentBlocks (first turn of a conversation). */
700
- convertMessages(prompt) {
701
- const blocks = [];
702
- for (const msg of prompt) {
703
- if (msg.role === "system")
704
- continue; // forwarded via _meta.systemPrompt
705
- blocks.push(...this.messageToBlocks(msg, true));
706
- }
707
- return blocks.length ? blocks : [{ type: "text", text: "" }];
708
- }
709
1079
  /** OpenCode's system text → `_meta.systemPrompt` per mode. */
710
1080
  buildSystemPromptMeta(prompt, mode) {
711
1081
  if (mode === "preset")
@@ -726,32 +1096,95 @@ export class ACPOrchestratorModel {
726
1096
  }
727
1097
  return parts.join("\n").trim();
728
1098
  }
1099
+ /** The FACTUAL part of OpenCode's system prompt: where we are, what the workspace is,
1100
+ * what references exist. Under `preset` the system prompt itself never reaches the
1101
+ * agent (forwarding it would get the session billed as extra usage), but this
1102
+ * context is genuinely useful and carries no instructions, so it rides along as
1103
+ * user content instead. Everything else — OpenCode's behavioural instructions,
1104
+ * AGENTS.md (the agent loads it itself via projectMemory), MCP/skill catalogues —
1105
+ * is deliberately left out. */
1106
+ extractContextBlock(prompt) {
1107
+ const sys = this.systemText(prompt);
1108
+ if (!sys)
1109
+ return "";
1110
+ const out = [];
1111
+ for (const tag of CONTEXT_TAGS) {
1112
+ const m = sys.match(new RegExp(`<${tag}>[\\s\\S]*?</${tag}>`));
1113
+ if (m)
1114
+ out.push(m[0]);
1115
+ }
1116
+ return out.join("\n");
1117
+ }
1118
+ /** Send the context block once per session, then only what changed. Appending a
1119
+ * small delta at the END of the conversation is cache-safe (the cached prefix is
1120
+ * untouched); resending the whole block every turn would not be. */
1121
+ contextBlocks(t, prompt, ctrl) {
1122
+ if (ctrl.forwardEnvContext === false)
1123
+ return [];
1124
+ const block = this.extractContextBlock(prompt);
1125
+ if (!block)
1126
+ return [];
1127
+ if (!t.lastContextBlock) {
1128
+ t.lastContextBlock = block;
1129
+ // The time is included only here: OpenCode's <env> is day-granular, and a
1130
+ // per-turn clock update would be pure noise.
1131
+ const now = new Date();
1132
+ return [{
1133
+ type: "text",
1134
+ text: `<opencode_context>\n${block}\n Session started: ${now.toLocaleString()} (${Intl.DateTimeFormat().resolvedOptions().timeZone})\n</opencode_context>`,
1135
+ }];
1136
+ }
1137
+ const prev = new Set(t.lastContextBlock.split("\n").map((l) => l.trim()).filter(Boolean));
1138
+ const changed = block.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("<") && !prev.has(l));
1139
+ t.lastContextBlock = block;
1140
+ if (!changed.length)
1141
+ return [];
1142
+ dbg(`context delta (${changed.length} line(s))`);
1143
+ return [{ type: "text", text: `<opencode_context_update>\n${changed.join("\n")}\n</opencode_context_update>` }];
1144
+ }
729
1145
  /** Only the last user message (delta for a persistent session). */
730
1146
  lastUserBlocks(prompt) {
731
1147
  for (let i = prompt.length - 1; i >= 0; i--) {
732
1148
  if (prompt[i].role === "user") {
733
- const b = this.messageToBlocks(prompt[i], false);
1149
+ const b = this.messageToBlocks(prompt[i], false, null);
734
1150
  if (b.length)
735
1151
  return b;
736
1152
  }
737
1153
  }
738
1154
  return [{ type: "text", text: "" }];
739
1155
  }
740
- detectContinuation(prompt) {
741
- const t = this.current;
742
- if (!t || (t.pendingTools.size === 0 && t.pendingPermissions.size === 0))
743
- return null;
744
- const results = [];
745
- for (const msg of prompt) {
746
- if (msg.role !== "tool" && msg.role !== "assistant")
1156
+ /** Find the live conversation whose deferred tool-calls/permissions this prompt
1157
+ * answers. Acotado a la conversación actual (`ocSession`/convKey de ESTA llamada):
1158
+ * iterar todas las sesiones cruzaba continuaciones de chats concurrentes. */
1159
+ detectContinuation(prompt, options) {
1160
+ let candidates;
1161
+ if (options) {
1162
+ const po = this.providerOptions(options);
1163
+ const baseKey = typeof po.ocSession === "string" ? po.ocSession : hashText(this.firstUserText(prompt));
1164
+ candidates = [this.sessions.get(baseKey), this.sessions.get(`${baseKey}:notools`)];
1165
+ }
1166
+ else {
1167
+ candidates = [...this.sessions.values()];
1168
+ }
1169
+ for (const t of candidates) {
1170
+ if (!t)
747
1171
  continue;
748
- for (const part of msg.content) {
749
- if (part?.type === "tool-result" && (t.pendingTools.has(part.toolCallId) || t.pendingPermissions.has(part.toolCallId))) {
750
- results.push({ toolCallId: part.toolCallId, result: this.toMcpResult(part.output), output: part.output });
1172
+ if (t.pendingTools.size === 0 && t.pendingPermissions.size === 0)
1173
+ continue;
1174
+ const results = [];
1175
+ for (const msg of prompt) {
1176
+ if (msg.role !== "tool" && msg.role !== "assistant")
1177
+ continue;
1178
+ for (const part of msg.content) {
1179
+ if (part?.type === "tool-result" && (t.pendingTools.has(part.toolCallId) || t.pendingPermissions.has(part.toolCallId))) {
1180
+ results.push({ toolCallId: part.toolCallId, result: this.toMcpResult(part.output), output: part.output });
1181
+ }
751
1182
  }
752
1183
  }
1184
+ if (results.length)
1185
+ return { t, results };
753
1186
  }
754
- return results.length ? results : null;
1187
+ return null;
755
1188
  }
756
1189
  /** A tool-result is an error/denial when its output type is error-* (OpenCode
757
1190
  * RejectedError) — used by the permission bridge to map approve vs reject. */
@@ -759,13 +1192,46 @@ export class ACPOrchestratorModel {
759
1192
  const ty = output?.type;
760
1193
  return ty === "error-text" || ty === "error-json" || ty === "error";
761
1194
  }
762
- /** Approve a bridged permission ONLY on an explicit positive verdict (the
763
- * claude_permission meta-tool returns "approved: …"). Errors, denials, and any
764
- * ambiguous output fail CLOSED so an unclear verdict never runs the native tool. */
765
- isApprovedOutput(output) {
1195
+ /** Approve a bridged permission ONLY on an explicit positive answer to the
1196
+ * `question` dialog. Errors, dismissals, and any ambiguous output (including
1197
+ * a typed-in answer) fail CLOSED so an unclear verdict never runs the tool.
1198
+ * Verificado: OpenCode V2 no expone identificador estable (sin schema de la tool
1199
+ * `question` en node_modules/@opencode-ai ni en /opt/OpenCode/resources; el shape
1200
+ * documentado es etiqueta en `{ answers: [["…"]] }` o texto renderizado) → match
1201
+ * por etiqueta normalizada (minúsculas, trim, "_" y espacios colapsados) con
1202
+ * fallback deny ante cualquier cosa no reconocida. Flujo de 3 opciones intacto. */
1203
+ questionVerdict(output) {
766
1204
  if (this.isErrorOutput(output))
767
- return false;
768
- return this.outputToText(output).toLowerCase().includes("approved");
1205
+ return { approved: false, always: false };
1206
+ const answer = this.normalizeAnswer(this.answerLabel(output));
1207
+ if (answer.includes("always allow"))
1208
+ return { approved: true, always: true };
1209
+ if (answer.includes("allow once"))
1210
+ return { approved: true, always: false };
1211
+ return { approved: false, always: false };
1212
+ }
1213
+ /** Normaliza una etiqueta de respuesta para el match robusto. */
1214
+ normalizeAnswer(s) {
1215
+ return String(s ?? "").trim().toLowerCase().replace(/[_-]+/g, " ").replace(/\s+/g, " ");
1216
+ }
1217
+ /** The chosen label: typed output (`{ answers: [["Always allow"]] }`) first,
1218
+ * then the rendered text fallback (`"question"="Always allow"`). */
1219
+ answerLabel(output) {
1220
+ const answers = output?.value?.answers;
1221
+ if (Array.isArray(answers)) {
1222
+ const first = answers[0];
1223
+ const cand = Array.isArray(first) ? first[0] : first;
1224
+ if (typeof cand === "string")
1225
+ return cand;
1226
+ // Por si OpenCode V2 tipa la respuesta algún día (objeto con optionId/id
1227
+ // estable): preferir el identificador antes que el texto renderizado.
1228
+ if (cand && typeof cand === "object") {
1229
+ const stable = cand.label ?? cand.value ?? cand.text ?? cand.optionId ?? cand.id;
1230
+ if (typeof stable === "string")
1231
+ return stable;
1232
+ }
1233
+ }
1234
+ return this.outputToText(output);
769
1235
  }
770
1236
  outputToText(output) {
771
1237
  if (!output)
@@ -778,8 +1244,27 @@ export class ACPOrchestratorModel {
778
1244
  return output.value.map((c) => (c.type === "text" ? c.text : "")).join("");
779
1245
  return typeof output === "string" ? output : JSON.stringify(output);
780
1246
  }
1247
+ /** OpenCode tool output → MCP CallToolResult. Structured content (images from a
1248
+ * `read`, mixed blocks) is mapped through rather than flattened to a string, so
1249
+ * the agent sees what OpenCode actually returned. */
781
1250
  toMcpResult(output) {
782
1251
  const isErr = output?.type === "error-text" || output?.type === "error-json";
1252
+ if (output?.type === "content" && Array.isArray(output.value)) {
1253
+ const content = output.value
1254
+ .map((c) => {
1255
+ if (c?.type === "text")
1256
+ return { type: "text", text: String(c.text ?? "") };
1257
+ if (c?.type === "media" || c?.type === "image") {
1258
+ const data = c.data ?? c.value;
1259
+ if (typeof data === "string")
1260
+ return { type: "image", data, mimeType: c.mediaType ?? c.mimeType ?? "image/png" };
1261
+ }
1262
+ return null;
1263
+ })
1264
+ .filter(Boolean);
1265
+ if (content.length)
1266
+ return { content, ...(isErr ? { isError: true } : {}) };
1267
+ }
783
1268
  return { content: [{ type: "text", text: this.outputToText(output) }], ...(isErr ? { isError: true } : {}) };
784
1269
  }
785
1270
  }