opencode-claude-code-acpbridge 0.6.0 → 0.8.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.
@@ -3,20 +3,23 @@
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";
@@ -24,6 +27,15 @@ import { setLink, updateUsage } from "../plugin/sessions.js";
24
27
  const DEBUG = !!process.env.ACP_DEBUG;
25
28
  const dbg = (m) => { if (DEBUG)
26
29
  process.stderr.write(`[acp-orchestrator] ${m}\n`); };
30
+ /** Always-on notices (session lifecycle) — the user needs these without ACP_DEBUG. */
31
+ const note = (m) => process.stderr.write(`[acp] ${m}\n`);
32
+ /** Max live conversations kept per model instance (LRU); older idle ones are torn down. */
33
+ const MAX_LIVE_SESSIONS = 8;
34
+ /** Cap on a foreign tool-result replayed as text during catch-up. */
35
+ const CATCHUP_RESULT_CHARS = 2000;
36
+ /** System-prompt blocks worth forwarding to the agent as FACTUAL context (never as
37
+ * a system prompt — that would make Anthropic bill the session as extra usage). */
38
+ const CONTEXT_TAGS = ["env", "available_references"];
27
39
  function emptyUsage() {
28
40
  return {
29
41
  inputTokens: { total: undefined, noCache: undefined, cacheRead: undefined, cacheWrite: undefined },
@@ -73,7 +85,12 @@ export class ACPOrchestratorModel {
73
85
  agent = null;
74
86
  connection = null;
75
87
  connecting = null;
76
- current = null;
88
+ /** Live conversations, keyed by OpenCode sessionID (or the conversation hash).
89
+ * ONE state per conversation: a single shared state made two open chats — or a
90
+ * subagent — tear each other's session down and replay the history every turn. */
91
+ sessions = new Map();
92
+ /** Same states indexed by ACP sessionId, to route agent-initiated callbacks. */
93
+ byAcpSession = new Map();
77
94
  idSeq = 0;
78
95
  promptCaps = {};
79
96
  constructor(config) {
@@ -83,9 +100,10 @@ export class ACPOrchestratorModel {
83
100
  // ---- LanguageModelV3 ------------------------------------------------------
84
101
  async doStream(options) {
85
102
  const continuation = this.detectContinuation(options.prompt);
103
+ const ref = { t: continuation?.t ?? null };
86
104
  const stream = new ReadableStream({
87
- start: (controller) => void this.onStart(controller, options, continuation),
88
- cancel: () => this.onCancel(),
105
+ start: (controller) => void this.onStart(controller, options, continuation, ref),
106
+ cancel: () => this.onCancel(ref),
89
107
  });
90
108
  return { stream, warnings: [] };
91
109
  }
@@ -114,71 +132,136 @@ export class ACPOrchestratorModel {
114
132
  return { content, finishReason, usage, warnings: [] };
115
133
  }
116
134
  // ---- turn lifecycle -------------------------------------------------------
117
- async onStart(controller, options, continuation) {
135
+ async onStart(controller, options, continuation, ref) {
118
136
  try {
119
137
  controller.enqueue({ type: "stream-start", warnings: [] });
120
- // (1) Continuation of a deferred tool-call — resume the same agent turn.
121
- if (continuation && this.current) {
122
- this.current.controller = controller;
123
- this.current.textId = null;
124
- this.current.reasoningId = null;
125
- for (const { toolCallId, result } of continuation) {
126
- this.current.pendingTools.delete(toolCallId);
127
- this.current.host.resolveToolCall(toolCallId, result);
138
+ // (1) Continuation of a deferred tool-call OR a bridged permission — resume
139
+ // the same agent turn.
140
+ if (continuation) {
141
+ const t = continuation.t;
142
+ ref.t = t;
143
+ this.clearCancelWatchdog(t); // the turn DID continue — disarm the abort timer
144
+ t.controller = controller;
145
+ t.lastActive = Date.now();
146
+ // Everything in this prompt is already known to the agent: its own tool-calls
147
+ // and the results it will receive right now. Recording them here is what stops
148
+ // the next turn from replaying whole file/shell outputs it already has.
149
+ t.sentKeys = this.history(options.prompt).map((m) => this.msgKey(m));
150
+ // Text/thinking that arrived while the stream was closed goes out FIRST, in
151
+ // order, so nothing the agent said before calling the tool is lost.
152
+ this.flushPending(t);
153
+ for (const { toolCallId, result, output } of continuation.results) {
154
+ const permResolve = t.pendingPermissions.get(toolCallId);
155
+ if (permResolve) {
156
+ // Permission bridge: OpenCode's `ask` verdict came back as the
157
+ // claude_permission tool-result → resolve the deferred requestPermission.
158
+ t.pendingPermissions.delete(toolCallId);
159
+ permResolve(this.isApprovedOutput(output));
160
+ }
161
+ else {
162
+ t.pendingTools.delete(toolCallId);
163
+ t.host.resolveToolCall(toolCallId, result);
164
+ }
128
165
  }
129
166
  return;
130
167
  }
131
168
  await this.ensureConnected();
132
169
  const tools = this.convertTools(options.tools);
133
170
  const ctrl = this.effectiveCtrl(options);
171
+ const po = options.providerOptions?.[this.provider] ?? {};
172
+ const ocSession = po.ocSession;
134
173
  const convKey = hashText(this.firstUserText(options.prompt));
135
- const toolsKey = tools.map((t) => t.name).sort().join(",");
136
- // System prompt is part of the identity: OpenCode can switch agents within a
137
- // session (same history, different system prompt). The agent can't change its
138
- // system prompt mid-session, so a system change forces a fresh session that
139
- // replays the full history under the new system prompt.
140
- const systemKey = hashText(this.systemText(options.prompt));
174
+ const toolsKey = tools.map((x) => x.name).sort().join(",");
175
+ // The system prompt is part of the session identity ONLY when it actually
176
+ // travels. Under the default `preset` mode OpenCode's system is never sent
177
+ // (see buildSystemPromptMeta), so hashing it would tear the session down —
178
+ // and replay the whole history — every time OpenCode swaps agents or its
179
+ // dynamic blocks (date, AGENTS.md, skills) shift. The factual part of that
180
+ // system is forwarded separately as user context (see contextBlocks).
181
+ const systemMode = ctrl.systemPromptMode ?? "preset";
182
+ const systemKey = systemMode === "preset" ? "preset" : hashText(this.systemText(options.prompt));
141
183
  // Params baked into newSession's _meta (thinking/systemPromptMode) can't change
142
184
  // mid-session → a change forces a fresh session. mode/effort are applied at
143
185
  // runtime via set_mode/set_config_option instead (no reset needed).
144
- const cfgKey = hashText(JSON.stringify({ t: ctrl.thinking, s: ctrl.systemPromptMode ?? "preset" }));
145
- // Session registry plumbing (chat.params → providerOptions.acp): `ocSession`
146
- // is the OpenCode key; `resumeId`/`resumeLen` come from the persistent registry.
147
- const po = options.providerOptions?.[this.provider] ?? {};
148
- const ocSession = po.ocSession;
149
- const histLen = options.prompt.length;
150
- // (2) Same conversation + tools + system + creation-cfg → reuse session, send only the delta.
151
- if (this.current &&
152
- this.current.convKey === convKey &&
153
- this.current.toolsKey === toolsKey &&
154
- this.current.systemKey === systemKey &&
155
- this.current.cfgKey === cfgKey) {
156
- dbg(`reuse session ${this.current.sessionId} — delta only (cache-friendly)`);
157
- this.current.controller = controller;
158
- this.current.textId = null;
159
- this.current.reasoningId = null;
160
- if (ocSession)
161
- this.current.ocSession = ocSession;
162
- await this.applySessionConfig(this.current, ctrl); // runtime mode/effort change
163
- if (ocSession)
164
- setLink(ocSession, this.current.sessionId, histLen);
165
- const blocks = this.lastUserBlocks(options.prompt);
166
- this.connection
167
- .prompt({ sessionId: this.current.sessionId, prompt: blocks })
168
- .then((resp) => this.onPromptDone(resp))
169
- .catch((err) => this.onPromptError(err));
170
- return;
186
+ const cfgKey = hashText(JSON.stringify({ t: ctrl.thinking, s: systemMode }));
187
+ const hist = this.history(options.prompt);
188
+ const keys = hist.map((m) => this.msgKey(m));
189
+ // OpenCode's title/summary call arrives on the same model and session but with
190
+ // NO tools. Give it a throwaway session instead of letting it evict the real
191
+ // conversation. Only when the live conversation DOES have tools — a genuinely
192
+ // tool-less conversation (programmatic use) must keep reusing its own session.
193
+ const baseKey = ocSession ?? convKey;
194
+ const live = this.sessions.get(baseKey);
195
+ const key = tools.length === 0 && live && live.toolsKey !== "" ? `${baseKey}:notools` : baseKey;
196
+ let t = this.sessions.get(key);
197
+ if (t && t.convKey !== convKey) {
198
+ this.endTurn(t);
199
+ t = undefined;
200
+ } // key reused for another conversation
201
+ // (2) Reuse the live session whenever we can — this is what keeps the cache warm.
202
+ if (t) {
203
+ let drop = null;
204
+ if (t.systemKey !== systemKey)
205
+ drop = "system prompt changed";
206
+ else if (t.cfgKey !== cfgKey)
207
+ drop = "creation config changed";
208
+ if (!drop) {
209
+ // A changed tool set is applied to the LIVE session (MCP list_changed)
210
+ // rather than forcing a new one.
211
+ if (t.toolsKey !== toolsKey) {
212
+ t.host.setTools(tools);
213
+ t.host.notifyToolsChanged();
214
+ t.toolsKey = toolsKey;
215
+ dbg(`tools changed (${tools.length}) — refreshed in place, session kept`);
216
+ }
217
+ const cls = this.classifyHistory(t, keys);
218
+ if (cls.kind !== "append") {
219
+ drop = cls.kind === "revert" ? "history reverted" : "history diverged (compaction/rollback)";
220
+ }
221
+ else {
222
+ const live = t;
223
+ ref.t = live;
224
+ dbg(`reuse session ${live.sessionId} — ${keys.length - cls.fromIndex} new msg(s) (cache-friendly)`);
225
+ // A fresh user turn: drop any deferred state left by a prior turn that was
226
+ // abandoned (continuation never arrived) so it can't hang or leak.
227
+ this.clearCancelWatchdog(live);
228
+ this.drainPermissions(live);
229
+ live.pendingTools.clear();
230
+ live.controller = controller;
231
+ live.lastActive = Date.now();
232
+ if (ocSession)
233
+ live.ocSession = ocSession;
234
+ if (po.ocAgent)
235
+ live.ocAgent = String(po.ocAgent);
236
+ this.flushPending(live);
237
+ await this.applySessionConfig(live, ctrl);
238
+ const tail = hist.slice(cls.fromIndex);
239
+ const blocks = [
240
+ ...this.contextBlocks(live, options.prompt, ctrl),
241
+ ...(tail.length ? this.blocksFor(tail, live) : this.lastUserBlocks(options.prompt)),
242
+ ];
243
+ live.sentKeys = keys;
244
+ if (ocSession)
245
+ setLink(ocSession, live.sessionId, hist.length, convKey);
246
+ this.connection
247
+ .prompt({ sessionId: live.sessionId, prompt: blocks })
248
+ .then((resp) => this.onPromptDone(live, resp))
249
+ .catch((err) => this.onPromptError(live, err));
250
+ return;
251
+ }
252
+ }
253
+ dbg(`dropping session ${t.sessionId} — ${drop}`);
254
+ this.endTurn(t);
255
+ t = undefined;
171
256
  }
172
- // (3) Need a session: new conversation / tools / system / cfg changed, OR a
257
+ // (3) Need a session: new conversation, or the history diverged, or a
173
258
  // resumable session from a new process. Set up the MCP host once.
174
- const reason = !this.current ? "new conversation"
175
- : this.current.convKey !== convKey ? "new conversation"
176
- : this.current.toolsKey !== toolsKey ? "tools changed"
177
- : this.current.systemKey !== systemKey ? "system prompt changed"
178
- : "config changed";
179
- this.endTurn();
180
- const host = new McpHost("opencode");
181
- host.onToolCall((c) => this.onToolCall(c));
259
+ // Unique per-host prefix so minted toolCallIds NEVER collide with ids from a
260
+ // previous session still present in OpenCode's replayed history (a fresh host is
261
+ // created on every session reset). A random nonce is robust across resets, process
262
+ // restarts and resume — unlike a per-host counter, which restarts at 0.
263
+ const idPrefix = `acp_${randomBytes(5).toString("hex")}_`;
264
+ const host = new McpHost("opencode", idPrefix);
182
265
  await host.start();
183
266
  host.setTools(tools);
184
267
  const serverConfig = host.getServerConfig();
@@ -186,9 +269,13 @@ export class ACPOrchestratorModel {
186
269
  // history grew rather than diverged) → no history replay (saves tokens). Else
187
270
  // create a fresh session and replay the full history.
188
271
  const resumeId = po.resumeId;
272
+ const resumeLen = typeof po.resumeLen === "number" ? po.resumeLen : 0;
189
273
  let sessionId;
190
274
  let replayFull = true;
191
- if (!this.current && resumeId && histLen > (po.resumeLen ?? 0)) {
275
+ if (DEBUG && po.resumeConvKey && po.resumeConvKey !== convKey) {
276
+ dbg(`resumeConvKey mismatch (registry=${po.resumeConvKey} current=${convKey}) — resuming anyway`);
277
+ }
278
+ if (resumeId && resumeLen > 0 && hist.length > resumeLen) {
192
279
  try {
193
280
  await this.connection.unstable_resumeSession({
194
281
  sessionId: resumeId,
@@ -197,8 +284,7 @@ export class ACPOrchestratorModel {
197
284
  // Re-apply the clean-brain options on resume too. Without this the agent
198
285
  // falls back to its defaults (--tools default, --setting-sources=user,
199
286
  // project,local, no --strict-mcp-config) and the resumed session regains
200
- // native tools + the claude.ai connectors. getOrCreateSession forwards
201
- // this _meta to createSession when the session isn't live in-process.
287
+ // native tools + the claude.ai connectors.
202
288
  _meta: { claudeCode: { options: buildClaudeCodeOptions(ctrl) } },
203
289
  });
204
290
  sessionId = resumeId;
@@ -212,7 +298,7 @@ export class ACPOrchestratorModel {
212
298
  if (!sessionId) {
213
299
  // OpenCode's system prompt → _meta.systemPrompt (preset/append/replace).
214
300
  const meta = { claudeCode: { options: buildClaudeCodeOptions(ctrl) } };
215
- const sysMeta = this.buildSystemPromptMeta(options.prompt, ctrl.systemPromptMode ?? "preset");
301
+ const sysMeta = this.buildSystemPromptMeta(options.prompt, systemMode);
216
302
  if (sysMeta !== undefined)
217
303
  meta.systemPrompt = sysMeta;
218
304
  const session = await this.connection.newSession({
@@ -221,50 +307,106 @@ export class ACPOrchestratorModel {
221
307
  _meta: meta,
222
308
  });
223
309
  sessionId = session.sessionId;
224
- dbg(`new session ${sessionId} (${reason}) model=${session.models?.currentModelId ?? "?"} (requested: ${ctrl.model ?? "default"}, mode: ${ctrl.mode ?? "default"}, effort: ${ctrl.effort ?? "default"}) — tools(${tools.length})`);
310
+ dbg(`model=${session.models?.currentModelId ?? "?"} (requested: ${ctrl.model ?? "default"}, mode: ${ctrl.mode ?? "default"}, effort: ${ctrl.effort ?? "default"}) — tools(${tools.length})`);
225
311
  }
226
312
  if (!sessionId)
227
313
  throw new Error("failed to create or resume an ACP session");
228
- const t = {
314
+ // The ACP sessionId IS the Claude Code session id: surfacing it lets the user
315
+ // pick the conversation back up natively.
316
+ note(`session ${sessionId}${replayFull ? "" : " (resumed)"} — retomable con: claude --resume ${sessionId}`);
317
+ t = {
318
+ key,
229
319
  host,
320
+ idPrefix,
230
321
  sessionId,
231
322
  convKey,
232
323
  toolsKey,
233
324
  systemKey,
234
325
  cfgKey,
235
326
  ocSession,
327
+ ocAgent: po.ocAgent ? String(po.ocAgent) : undefined,
236
328
  // Resume path: seed the cumulative usage snapshot from the persisted
237
329
  // registry so the first post-resume `subtractUsage` produces a real
238
330
  // turn delta instead of the full cumulative.
239
331
  lastUsage: replayFull ? undefined : po.resumeLastUsage,
332
+ // Full replay covers the whole history; a bare resume only covers up to what
333
+ // the registry last recorded — the rest still needs sending below.
334
+ sentKeys: replayFull ? [] : keys.slice(0, resumeLen),
240
335
  controller,
336
+ pending: [],
241
337
  pendingTools: new Set(),
338
+ pendingPermissions: new Map(),
242
339
  textId: null,
243
340
  reasoningId: null,
341
+ cancelWatchdog: null,
342
+ lastActive: Date.now(),
244
343
  };
245
- this.current = t;
246
- await this.applySessionConfig(t, ctrl); // mode/effort at runtime
344
+ ref.t = t;
345
+ host.onToolCall((c) => this.onToolCall(t, c));
346
+ this.sessions.set(key, t);
347
+ this.byAcpSession.set(sessionId, t);
348
+ this.evictIdleSessions();
349
+ await this.applySessionConfig(t, ctrl);
247
350
  if (ocSession)
248
- setLink(ocSession, sessionId, histLen);
351
+ setLink(ocSession, sessionId, hist.length, convKey);
352
+ const tail = replayFull ? hist : hist.slice(resumeLen);
353
+ if (DEBUG && !replayFull)
354
+ dbg(`resume — catch-up ${tail.length} msg(s)`);
355
+ const promptBlocks = [
356
+ ...this.contextBlocks(t, options.prompt, ctrl),
357
+ ...(tail.length ? this.blocksFor(tail, t) : [{ type: "text", text: "" }]),
358
+ ];
359
+ t.sentKeys = keys;
360
+ const started = t;
249
361
  this.connection
250
- .prompt({ sessionId, prompt: replayFull ? this.convertMessages(options.prompt) : this.lastUserBlocks(options.prompt) })
251
- .then((resp) => this.onPromptDone(resp))
252
- .catch((err) => this.onPromptError(err));
362
+ .prompt({ sessionId, prompt: promptBlocks })
363
+ .then((resp) => this.onPromptDone(started, resp))
364
+ .catch((err) => this.onPromptError(started, err));
253
365
  }
254
366
  catch (err) {
255
367
  dbg(`onStart error: ${err instanceof Error ? err.message : String(err)}`);
256
- controller.enqueue({ type: "error", error: err });
368
+ try {
369
+ controller.enqueue({ type: "error", error: err });
370
+ }
371
+ catch { /* ignore */ }
257
372
  try {
258
373
  controller.close();
259
374
  }
260
375
  catch { /* ignore */ }
261
376
  }
262
377
  }
263
- onPromptDone(resp) {
264
- const t = this.current;
265
- if (!t || !t.controller)
378
+ /** Enqueue if a stream is attached; otherwise BUFFER. The stream is closed between
379
+ * a tool-call and its continuation, and text/thought chunks keep arriving on the
380
+ * (independent) ACP stdio channel meanwhile — dropping them truncated answers and
381
+ * hid the reasoning block entirely. */
382
+ emit(t, part) {
383
+ if (t.controller) {
384
+ try {
385
+ t.controller.enqueue(part);
386
+ return;
387
+ }
388
+ catch { /* closed underneath us */ }
389
+ }
390
+ t.pending.push(part);
391
+ }
392
+ flushPending(t) {
393
+ if (!t.controller || t.pending.length === 0)
394
+ return;
395
+ const parts = t.pending;
396
+ t.pending = [];
397
+ dbg(`flushing ${parts.length} buffered chunk(s) into the continuation stream`);
398
+ for (const p of parts) {
399
+ try {
400
+ t.controller.enqueue(p);
401
+ }
402
+ catch { /* ignore */ }
403
+ }
404
+ }
405
+ onPromptDone(t, resp) {
406
+ if (!t.controller)
266
407
  return; // cut for a pending tool-call
267
408
  this.closeBlocks(t);
409
+ this.flushPending(t);
268
410
  const turn = subtractUsage(resp?.usage, t.lastUsage); // ACP usage is cumulative per session
269
411
  if (resp?.usage) {
270
412
  t.lastUsage = resp.usage;
@@ -273,71 +415,186 @@ export class ACPOrchestratorModel {
273
415
  }
274
416
  if (DEBUG && turn)
275
417
  dbg(`usage(turn): in=${turn.inputTokens} out=${turn.outputTokens} cacheR=${turn.cachedReadTokens} cacheW=${turn.cachedWriteTokens}`);
276
- t.controller.enqueue({
277
- type: "finish",
278
- usage: mapUsage(turn),
279
- finishReason: { unified: resp?.stopReason === "max_tokens" ? "length" : "stop", raw: resp?.stopReason },
280
- });
281
418
  try {
419
+ t.controller.enqueue({
420
+ type: "finish",
421
+ usage: mapUsage(turn),
422
+ finishReason: { unified: resp?.stopReason === "max_tokens" ? "length" : "stop", raw: resp?.stopReason },
423
+ });
282
424
  t.controller.close();
283
425
  }
284
426
  catch { /* ignore */ }
285
427
  t.controller = null; // keep the session for the next turn (delta)
286
428
  }
287
- onPromptError(err) {
288
- const t = this.current;
289
- if (!t || !t.controller)
429
+ onPromptError(t, err) {
430
+ if (!t.controller)
290
431
  return;
291
432
  dbg(`prompt error: ${err instanceof Error ? err.message : String(err)}`);
292
- t.controller.enqueue({ type: "error", error: err });
293
433
  try {
434
+ t.controller.enqueue({ type: "error", error: err });
294
435
  t.controller.close();
295
436
  }
296
437
  catch { /* ignore */ }
297
438
  t.controller = null;
298
439
  }
299
440
  /** Fired by the MCP host when the agent calls an OpenCode tool. */
300
- onToolCall(call) {
301
- const t = this.current;
302
- if (!t || !t.controller)
441
+ onToolCall(t, call) {
442
+ if (!t.controller)
303
443
  return;
304
444
  dbg(`agent → tool-call ${call.name} (${call.toolCallId}) → emit to OpenCode`);
305
445
  this.closeBlocks(t);
306
446
  t.pendingTools.add(call.toolCallId);
307
447
  const inputJson = JSON.stringify(call.args ?? {});
308
- t.controller.enqueue({ type: "tool-input-start", id: call.toolCallId, toolName: call.name });
309
- t.controller.enqueue({ type: "tool-input-delta", id: call.toolCallId, delta: inputJson });
310
- t.controller.enqueue({ type: "tool-input-end", id: call.toolCallId });
311
- t.controller.enqueue({ type: "tool-call", toolCallId: call.toolCallId, toolName: call.name, input: inputJson });
312
- t.controller.enqueue({ type: "finish", usage: emptyUsage(), finishReason: { unified: "tool-calls", raw: "tool_use" } });
448
+ this.emit(t, { type: "tool-input-start", id: call.toolCallId, toolName: call.name });
449
+ this.emit(t, { type: "tool-input-delta", id: call.toolCallId, delta: inputJson });
450
+ this.emit(t, { type: "tool-input-end", id: call.toolCallId });
451
+ this.emit(t, { type: "tool-call", toolCallId: call.toolCallId, toolName: call.name, input: inputJson });
452
+ this.emit(t, { type: "finish", usage: emptyUsage(), finishReason: { unified: "tool-calls", raw: "tool_use" } });
313
453
  try {
314
- t.controller.close();
454
+ t.controller?.close();
315
455
  }
316
456
  catch { /* ignore */ }
317
457
  t.controller = null; // DO NOT resolve yet — wait for the continuation doStream
318
458
  }
319
- /** Fired by the ACP client on session/update. */
320
- onSessionUpdate(update) {
321
- const t = this.current;
459
+ // ---- permission bridge -----------------------------------------------------
460
+ /** Map approve/reject to one of the options the agent offered (by kind/optionId). */
461
+ permOutcome(params, approved) {
462
+ const opts = params?.options ?? [];
463
+ if (!opts.length)
464
+ return { outcome: { outcome: "cancelled" } };
465
+ if (!approved) {
466
+ const rej = opts.find((o) => o.kind === "reject_once" || o.kind === "reject_always" || o.optionId === "reject");
467
+ return rej ? { outcome: { outcome: "selected", optionId: rej.optionId } } : { outcome: { outcome: "cancelled" } };
468
+ }
469
+ // Approving an ExitPlanMode must NOT silently hand out bypass/auto. The agent
470
+ // offers, in order, `bypassPermissions`, `auto`, `acceptEdits`, `default` — and
471
+ // picking the first `allow_*` would grant the broadest one. Approving a plan means
472
+ // "go ahead, still asking me about edits" → prefer `default`.
473
+ if (params?.toolCall?.kind === "switch_mode") {
474
+ const safe = opts.find((o) => o.optionId === "default") ?? opts.find((o) => o.optionId === "acceptEdits");
475
+ if (safe)
476
+ return { outcome: { outcome: "selected", optionId: safe.optionId } };
477
+ }
478
+ const opt = opts.find((o) => o.kind === "allow_once" || o.kind === "allow_always" || o.optionId === "allow") ?? opts[0];
479
+ return opt ? { outcome: { outcome: "selected", optionId: opt.optionId } } : { outcome: { outcome: "cancelled" } };
480
+ }
481
+ /** Tool name the agent wants permission for. The ACP toolCall carries NO bare
482
+ * name — `title` is a human label like "Read /path", "Write /path", "Skill" — so
483
+ * we take the first token. This becomes the permission key, so per-tool rules
484
+ * (`permission: { Read: … }`) match. The full title travels separately as metadata. */
485
+ permToolName(toolCall) {
486
+ // ExitPlanMode surfaces as a `switch_mode` permission — give it a stable, rule-able
487
+ // name so the prompt reads clearly and `permission: { ExitPlanMode: … }` matches.
488
+ if (toolCall?.kind === "switch_mode")
489
+ return "ExitPlanMode";
490
+ const title = String(toolCall?.title ?? "").trim();
491
+ return title.split(/\s+/)[0] || String(toolCall?.kind ?? "") || "tool";
492
+ }
493
+ /** Extract the markdown plan from an ExitPlanMode (`switch_mode`) tool call: it rides
494
+ * in `rawInput.plan`, with the tool-call text content as a fallback. */
495
+ planText(toolCall) {
496
+ const raw = toolCall?.rawInput;
497
+ if (raw && typeof raw === "object" && typeof raw.plan === "string")
498
+ return raw.plan;
499
+ const content = Array.isArray(toolCall?.content) ? toolCall.content : [];
500
+ return content
501
+ .map((c) => (c?.type === "content" && c.content?.type === "text" ? c.content.text : typeof c?.text === "string" ? c.text : ""))
502
+ .filter(Boolean)
503
+ .join("\n");
504
+ }
505
+ /** ACP requestPermission → OpenCode `ask`, via the claude_permission meta-tool.
506
+ * Deferred: returns a Promise the agent awaits until OpenCode's verdict comes
507
+ * back as the meta-tool's result (resolved in onStart's continuation branch). */
508
+ onRequestPermission(params) {
509
+ const t = this.byAcpSession.get(String(params?.sessionId ?? ""));
510
+ // No live turn/controller → approve so the agent never hangs.
322
511
  if (!t || !t.controller)
512
+ return Promise.resolve(this.permOutcome(params, true));
513
+ const callId = `perm_${++this.idSeq}`;
514
+ dbg(`requestPermission(${this.permToolName(params?.toolCall)}) → bridge as claude_permission (${callId})`);
515
+ return new Promise((resolve) => {
516
+ t.pendingPermissions.set(callId, (approved) => resolve(this.permOutcome(params, approved)));
517
+ this.emitPermissionCall(t, callId, params?.toolCall);
518
+ });
519
+ }
520
+ /** Emit a claude_permission tool-call to OpenCode (same deferred pattern as a
521
+ * real tool-call): OpenCode applies its `ask` permission and returns the
522
+ * verdict as the tool-result on the next doStream. */
523
+ emitPermissionCall(t, callId, toolCall) {
524
+ if (!t.controller)
323
525
  return;
526
+ this.closeBlocks(t);
527
+ // ExitPlanMode (switch_mode): render the PLAN as visible assistant text before the
528
+ // approval prompt — otherwise it's only buried in the permission metadata and the
529
+ // user would approve blind. Presenting the plan for approval IS the point of the tool.
530
+ if (toolCall?.kind === "switch_mode") {
531
+ const plan = this.planText(toolCall);
532
+ if (plan) {
533
+ const id = `plan${++this.idSeq}`;
534
+ this.emit(t, { type: "text-start", id });
535
+ this.emit(t, { type: "text-delta", id, delta: plan });
536
+ this.emit(t, { type: "text-end", id });
537
+ }
538
+ }
539
+ const input = JSON.stringify({
540
+ tool: this.permToolName(toolCall),
541
+ kind: toolCall?.kind,
542
+ title: toolCall?.title,
543
+ input: toolCall?.rawInput,
544
+ });
545
+ this.emit(t, { type: "tool-input-start", id: callId, toolName: "claude_permission" });
546
+ this.emit(t, { type: "tool-input-delta", id: callId, delta: input });
547
+ this.emit(t, { type: "tool-input-end", id: callId });
548
+ this.emit(t, { type: "tool-call", toolCallId: callId, toolName: "claude_permission", input });
549
+ this.emit(t, { type: "finish", usage: emptyUsage(), finishReason: { unified: "tool-calls", raw: "tool_use" } });
550
+ try {
551
+ t.controller?.close();
552
+ }
553
+ catch { /* ignore */ }
554
+ t.controller = null;
555
+ }
556
+ /** Fired by the ACP client on session/update. */
557
+ onSessionUpdate(params) {
558
+ const t = this.byAcpSession.get(String(params?.sessionId ?? ""));
559
+ if (!t)
560
+ return;
561
+ const update = params?.update;
562
+ // Mode switch (e.g. ExitPlanMode approved: plan → default). Track it even without a
563
+ // live controller so the bridge stays in sync and won't re-force the agent's
564
+ // configured mode on the next turn (which would undo the plan-exit).
565
+ if (update?.sessionUpdate === "current_mode_update") {
566
+ if (update.currentModeId) {
567
+ const from = t.appliedMode ?? "?";
568
+ t.appliedMode = String(update.currentModeId);
569
+ t.modeChangedByAgent = true;
570
+ dbg(`current_mode_update → ${t.appliedMode}`);
571
+ // Make it visible: the session's mode just changed under the user's feet, and
572
+ // OpenCode still shows whatever agent they picked. The two agents share the
573
+ // same tool profile, so this is informational, not a call to action.
574
+ const id = `mode${++this.idSeq}`;
575
+ this.emit(t, { type: "text-start", id });
576
+ this.emit(t, { type: "text-delta", id, delta: `\n_Modo de sesión: ${from} → ${t.appliedMode}_\n` });
577
+ this.emit(t, { type: "text-end", id });
578
+ }
579
+ return;
580
+ }
324
581
  switch (update?.sessionUpdate) {
325
582
  case "agent_message_chunk":
326
583
  if (update.content?.type === "text") {
327
584
  if (!t.textId) {
328
585
  t.textId = `t${++this.idSeq}`;
329
- t.controller.enqueue({ type: "text-start", id: t.textId });
586
+ this.emit(t, { type: "text-start", id: t.textId });
330
587
  }
331
- t.controller.enqueue({ type: "text-delta", id: t.textId, delta: update.content.text });
588
+ this.emit(t, { type: "text-delta", id: t.textId, delta: update.content.text });
332
589
  }
333
590
  break;
334
591
  case "agent_thought_chunk":
335
592
  if (update.content?.type === "text") {
336
593
  if (!t.reasoningId) {
337
594
  t.reasoningId = `r${++this.idSeq}`;
338
- t.controller.enqueue({ type: "reasoning-start", id: t.reasoningId });
595
+ this.emit(t, { type: "reasoning-start", id: t.reasoningId });
339
596
  }
340
- t.controller.enqueue({ type: "reasoning-delta", id: t.reasoningId, delta: update.content.text });
597
+ this.emit(t, { type: "reasoning-delta", id: t.reasoningId, delta: update.content.text });
341
598
  }
342
599
  break;
343
600
  default:
@@ -345,40 +602,71 @@ export class ACPOrchestratorModel {
345
602
  }
346
603
  }
347
604
  closeBlocks(t) {
348
- if (t.textId && t.controller) {
349
- t.controller.enqueue({ type: "text-end", id: t.textId });
605
+ if (t.textId) {
606
+ this.emit(t, { type: "text-end", id: t.textId });
350
607
  t.textId = null;
351
608
  }
352
- if (t.reasoningId && t.controller) {
353
- t.controller.enqueue({ type: "reasoning-end", id: t.reasoningId });
609
+ if (t.reasoningId) {
610
+ this.emit(t, { type: "reasoning-end", id: t.reasoningId });
354
611
  t.reasoningId = null;
355
612
  }
356
613
  }
357
- endTurn() {
358
- const t = this.current;
359
- if (!t)
360
- return;
614
+ endTurn(t) {
615
+ this.clearCancelWatchdog(t);
616
+ // Settle any deferred permission requests (deny/cancel) so the agent never
617
+ // stays blocked awaiting a verdict that will no longer arrive.
618
+ this.drainPermissions(t);
361
619
  try {
362
620
  if (this.connection && t.sessionId)
363
621
  this.connection.cancel?.({ sessionId: t.sessionId });
364
622
  }
365
623
  catch { /* ignore */ }
366
624
  t.host.stop();
367
- this.current = null;
625
+ if (this.sessions.get(t.key) === t)
626
+ this.sessions.delete(t.key);
627
+ this.byAcpSession.delete(t.sessionId);
628
+ }
629
+ /** Keep at most MAX_LIVE_SESSIONS conversations alive; tear down the oldest idle ones
630
+ * (never one with work in flight) so hosts and agent sessions don't pile up. */
631
+ evictIdleSessions() {
632
+ if (this.sessions.size <= MAX_LIVE_SESSIONS)
633
+ return;
634
+ const idle = [...this.sessions.values()]
635
+ .filter((s) => !s.controller && s.pendingTools.size === 0 && s.pendingPermissions.size === 0)
636
+ .sort((a, b) => a.lastActive - b.lastActive);
637
+ while (this.sessions.size > MAX_LIVE_SESSIONS && idle.length) {
638
+ const victim = idle.shift();
639
+ dbg(`evicting idle session ${victim.sessionId} (LRU)`);
640
+ this.endTurn(victim);
641
+ }
642
+ }
643
+ /** Resolve every outstanding bridged permission as denied so the agent unblocks. */
644
+ drainPermissions(t) {
645
+ if (t.pendingPermissions.size === 0)
646
+ return;
647
+ for (const resolve of [...t.pendingPermissions.values()]) {
648
+ try {
649
+ resolve(false);
650
+ }
651
+ catch { /* ignore */ }
652
+ }
653
+ t.pendingPermissions.clear();
368
654
  }
369
655
  /** Provider config overlaid with per-call `providerOptions.acp` (per-agent mode/effort/…). */
370
656
  effectiveCtrl(options) {
371
657
  const ctrl = { ...(this.config.claudeCode ?? {}) };
372
658
  const po = options.providerOptions?.[this.provider];
373
659
  if (po && typeof po === "object") {
374
- if (po.mode)
375
- ctrl.mode = po.mode;
376
- if (po.effort)
377
- ctrl.effort = po.effort;
378
- if (po.thinking)
379
- ctrl.thinking = po.thinking;
380
- if (po.systemPromptMode)
381
- ctrl.systemPromptMode = po.systemPromptMode;
660
+ // Per-agent overrides from `agent.<name>.options` (→ providerOptions.acp):
661
+ // mode/effort/reasoning plus the native-feature toggles.
662
+ const KEYS = [
663
+ "mode", "effort", "thinking", "systemPromptMode", "forwardEnvContext",
664
+ "tools", "allowedTools", "disallowedTools", "settingSources", "strictMcpConfig",
665
+ "nativeTools", "resourceSearch", "nativeSubagents", "nativeSkills", "projectMemory", "skillShell",
666
+ ];
667
+ for (const k of KEYS)
668
+ if (po[k] !== undefined)
669
+ ctrl[k] = po[k];
382
670
  }
383
671
  // OpenCode's modelId maps to Claude's model unless claudeCode.model overrides it.
384
672
  if (!ctrl.model && this.modelId && this.modelId !== "claude-code")
@@ -387,7 +675,16 @@ export class ACPOrchestratorModel {
387
675
  }
388
676
  /** Apply runtime config (mode/effort) to a live ACP session via set_mode/set_config_option. */
389
677
  async applySessionConfig(t, ctrl) {
390
- if (ctrl.mode && ctrl.mode !== t.appliedMode) {
678
+ // A CHANGED request (the user reselected the plan agent) overrides a mode the agent
679
+ // set for itself. Without this reset an ExitPlanMode would permanently pin the
680
+ // session out of plan mode, and going back to the plan agent would do nothing.
681
+ if (ctrl.mode !== t.requestedMode) {
682
+ t.requestedMode = ctrl.mode;
683
+ t.modeChangedByAgent = false;
684
+ }
685
+ // Don't re-force the configured mode once the agent switched it itself (ExitPlanMode):
686
+ // the user approved leaving plan mode, so the next turn must not snap back to plan.
687
+ if (ctrl.mode && ctrl.mode !== t.appliedMode && !t.modeChangedByAgent) {
391
688
  try {
392
689
  await this.connection.setSessionMode({ sessionId: t.sessionId, modeId: ctrl.mode });
393
690
  t.appliedMode = ctrl.mode;
@@ -404,7 +701,9 @@ export class ACPOrchestratorModel {
404
701
  dbg(`effort → ${ctrl.effort}`);
405
702
  }
406
703
  catch (e) {
407
- dbg(`setSessionConfigOption(effort=${ctrl.effort}) failed: ${e instanceof Error ? e.message : String(e)}`);
704
+ // Not a debug detail: a rejected effort means the user picked `:max` and is
705
+ // silently getting something else — including no visible reasoning.
706
+ note(`aviso: no se pudo aplicar effort=${ctrl.effort} (${e instanceof Error ? e.message : String(e)})`);
408
707
  }
409
708
  }
410
709
  }
@@ -455,10 +754,11 @@ export class ACPOrchestratorModel {
455
754
  const stream = ndJsonStream(Writable.toWeb(this.agent.stdin), Readable.toWeb(this.agent.stdout));
456
755
  const self = this;
457
756
  this.connection = new ClientSideConnection(() => ({
458
- async sessionUpdate(params) { self.onSessionUpdate(params.update); },
757
+ // Keep the whole params object: `sessionId` is what routes the update to the
758
+ // right conversation now that several can be live at once.
759
+ async sessionUpdate(params) { self.onSessionUpdate(params); },
459
760
  async requestPermission(params) {
460
- const opt = params.options?.find((o) => o.optionId === "allow" || o.kind === "allow_once") ?? params.options?.[0];
461
- return { outcome: { outcome: "selected", optionId: opt?.optionId ?? "allow" } };
761
+ return self.onRequestPermission(params);
462
762
  },
463
763
  async writeTextFile() { return {}; },
464
764
  async readTextFile() { return { content: "" }; },
@@ -470,11 +770,52 @@ export class ACPOrchestratorModel {
470
770
  this.promptCaps = (initResult?.agentCapabilities?.promptCapabilities ?? {});
471
771
  dbg(`connected to agent — promptCapabilities: ${JSON.stringify(this.promptCaps)}`);
472
772
  }
473
- onCancel() {
474
- this.endTurn();
773
+ onCancel(ref) {
774
+ const t = ref.t;
775
+ if (!t)
776
+ return;
777
+ // A stream cancel WHILE a tool-call or permission is deferred is OpenCode
778
+ // PAUSING (e.g. to show a permission prompt), not a real abort — tearing the
779
+ // host down here kills the pending tools/call with "host closed". Keep the
780
+ // session/host alive; the continuation doStream resolves them. A WATCHDOG
781
+ // guarantees teardown if the continuation never arrives (session truly aborted,
782
+ // prompt dropped) so the agent can't hang forever.
783
+ if (t.pendingTools.size > 0 || t.pendingPermissions.size > 0) {
784
+ dbg("onCancel ignored — deferred tool-call/permission in flight (likely a permission pause)");
785
+ this.armCancelWatchdog(t);
786
+ return;
787
+ }
788
+ // A plain cancel ends the TURN, not the conversation: keep the session (and its
789
+ // prompt cache) so the next message continues where this one stopped.
790
+ try {
791
+ this.connection?.cancel?.({ sessionId: t.sessionId });
792
+ }
793
+ catch { /* ignore */ }
794
+ t.controller = null;
795
+ this.closeBlocks(t);
796
+ }
797
+ /** If a cancel was ignored (deferred work in flight) but no continuation comes,
798
+ * force teardown so the agent doesn't stay blocked. Cleared by a continuation. */
799
+ armCancelWatchdog(t) {
800
+ this.clearCancelWatchdog(t);
801
+ t.cancelWatchdog = setTimeout(() => {
802
+ t.cancelWatchdog = null;
803
+ dbg("cancel watchdog fired — no continuation arrived; tearing down");
804
+ this.endTurn(t);
805
+ }, this.config.streamCloseTimeoutMs ?? 600_000);
806
+ t.cancelWatchdog.unref?.();
807
+ }
808
+ clearCancelWatchdog(t) {
809
+ if (t.cancelWatchdog) {
810
+ clearTimeout(t.cancelWatchdog);
811
+ t.cancelWatchdog = null;
812
+ }
475
813
  }
476
814
  cleanup() {
477
- this.endTurn();
815
+ for (const t of [...this.sessions.values()])
816
+ this.endTurn(t);
817
+ this.sessions.clear();
818
+ this.byAcpSession.clear();
478
819
  try {
479
820
  this.agent?.kill();
480
821
  }
@@ -489,16 +830,33 @@ export class ACPOrchestratorModel {
489
830
  return [];
490
831
  const out = [];
491
832
  for (const t of tools) {
833
+ // Skip the permission-bridge meta-tool: the provider emits `claude_permission`
834
+ // itself and OpenCode runs it via the plugin, so the AGENT must NOT see it
835
+ // (otherwise it surfaces as mcp__opencode__claude_permission and confuses it).
836
+ if (t.name === "claude_permission")
837
+ continue;
492
838
  if (t.type === "function") {
493
839
  out.push({
494
840
  name: t.name,
495
- description: t.description,
841
+ description: this.toolDescription(t.name, t.description),
496
842
  inputSchema: t.inputSchema ?? { type: "object", properties: {} },
497
843
  });
498
844
  }
499
845
  }
500
846
  return out;
501
847
  }
848
+ /** Nudges the agent can only get from the tool description. Under the default
849
+ * `systemPromptMode: "preset"` OpenCode's system prompt never reaches the agent,
850
+ * so the instruction that would normally push it toward `question` is missing —
851
+ * and its own `AskUserQuestion` is disabled by the ACP agent. Without this the
852
+ * agent silently assumes instead of asking. A tool description is NOT a system
853
+ * prompt, so this doesn't affect how Anthropic bills the session. */
854
+ toolDescription(name, description) {
855
+ if (name === "question") {
856
+ 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();
857
+ }
858
+ return description;
859
+ }
502
860
  /** Text of the first user message — stable identifier for the conversation. */
503
861
  firstUserText(prompt) {
504
862
  for (const m of prompt) {
@@ -510,7 +868,56 @@ export class ACPOrchestratorModel {
510
868
  }
511
869
  return "";
512
870
  }
513
- messageToBlocks(msg, withPrefix) {
871
+ /** The conversation proper: system messages are excluded because they're forwarded
872
+ * separately (or not at all) and OpenCode rewrites them every turn — including them
873
+ * would make every history comparison look like a divergence. */
874
+ history(prompt) {
875
+ return prompt.filter((m) => m.role !== "system");
876
+ }
877
+ /** Cheap, stable per-message identity. Deliberately keyed on tool-call IDs rather
878
+ * than payloads: it must survive re-serialization but change if the turn changes. */
879
+ msgKey(msg) {
880
+ let body = "";
881
+ if (typeof msg.content === "string")
882
+ body = msg.content;
883
+ else if (Array.isArray(msg.content)) {
884
+ for (const p of msg.content) {
885
+ if (p?.type === "text")
886
+ body += `t:${p.text}`;
887
+ else if (p?.type === "tool-call")
888
+ body += `c:${p.toolCallId}`;
889
+ else if (p?.type === "tool-result")
890
+ body += `r:${p.toolCallId}`;
891
+ else if (p?.type === "file")
892
+ body += `f:${p.filename ?? p.mediaType ?? ""}`;
893
+ else
894
+ body += `?${p?.type}`;
895
+ }
896
+ }
897
+ return `${msg.role}:${hashText(body)}`;
898
+ }
899
+ /** How the incoming history relates to what the agent already knows.
900
+ * - append → normal turn (or another agent ran turns meanwhile): send the tail.
901
+ * - revert → the user rewound: the agent can't unremember, so it needs a new session.
902
+ * - diverged → compaction/rollback replaced the middle: same, a new session. */
903
+ classifyHistory(t, keys) {
904
+ const sent = t.sentKeys;
905
+ let i = 0;
906
+ while (i < sent.length && i < keys.length && sent[i] === keys[i])
907
+ i++;
908
+ if (i === sent.length)
909
+ return { kind: "append", fromIndex: i };
910
+ if (i === keys.length)
911
+ return { kind: "revert", fromIndex: i };
912
+ return { kind: "diverged", fromIndex: i };
913
+ }
914
+ blocksFor(msgs, t) {
915
+ const blocks = [];
916
+ for (const msg of msgs)
917
+ blocks.push(...this.messageToBlocks(msg, true, t));
918
+ return blocks;
919
+ }
920
+ messageToBlocks(msg, withPrefix, t) {
514
921
  const prefixes = { system: "System: ", assistant: "Assistant: ", tool: "", user: "" };
515
922
  const prefix = withPrefix ? (prefixes[msg.role] ?? "") : "";
516
923
  if (typeof msg.content === "string")
@@ -519,6 +926,11 @@ export class ACPOrchestratorModel {
519
926
  let first = true;
520
927
  for (const part of msg.content) {
521
928
  const px = first ? prefix : "";
929
+ // OUR OWN tool traffic: the agent already holds these in its session (they came
930
+ // back over MCP). Replaying them as text duplicated whole file/shell outputs on
931
+ // every turn and blew the prompt cache — by far the biggest token sink.
932
+ if ((part.type === "tool-call" || part.type === "tool-result") && t && String(part.toolCallId ?? "").startsWith(t.idPrefix))
933
+ continue;
522
934
  if (part.type === "text") {
523
935
  blocks.push({ type: "text", text: px + part.text });
524
936
  first = false;
@@ -528,7 +940,7 @@ export class ACPOrchestratorModel {
528
940
  first = false;
529
941
  }
530
942
  else if (part.type === "tool-result") {
531
- blocks.push({ type: "text", text: `${px}[Tool ${part.toolName} result: ${this.outputToText(part.output)}]` });
943
+ blocks.push({ type: "text", text: `${px}[Tool ${part.toolName} result: ${this.truncate(this.outputToText(part.output))}]` });
532
944
  first = false;
533
945
  }
534
946
  else if (part.type === "file") {
@@ -539,6 +951,11 @@ export class ACPOrchestratorModel {
539
951
  }
540
952
  return blocks;
541
953
  }
954
+ /** A foreign tool-result is replayed only so the agent can follow the thread —
955
+ * the full payload isn't worth the tokens. */
956
+ truncate(s) {
957
+ return s.length <= CATCHUP_RESULT_CHARS ? s : `${s.slice(0, CATCHUP_RESULT_CHARS)}…[truncado, ${s.length} chars]`;
958
+ }
542
959
  /** Map an AI SDK file part to an ACP ContentBlock, honoring the agent's promptCapabilities. */
543
960
  fileToBlock(part) {
544
961
  const mt = part.mediaType || "application/octet-stream";
@@ -565,16 +982,6 @@ export class ACPOrchestratorModel {
565
982
  return data.includes(",") ? data.split(",")[1] : data; // data URL or raw base64
566
983
  return null; // URL or other — not embeddable
567
984
  }
568
- /** Full prompt flattened to ACP ContentBlocks (first turn of a conversation). */
569
- convertMessages(prompt) {
570
- const blocks = [];
571
- for (const msg of prompt) {
572
- if (msg.role === "system")
573
- continue; // forwarded via _meta.systemPrompt
574
- blocks.push(...this.messageToBlocks(msg, true));
575
- }
576
- return blocks.length ? blocks : [{ type: "text", text: "" }];
577
- }
578
985
  /** OpenCode's system text → `_meta.systemPrompt` per mode. */
579
986
  buildSystemPromptMeta(prompt, mode) {
580
987
  if (mode === "preset")
@@ -595,31 +1002,97 @@ export class ACPOrchestratorModel {
595
1002
  }
596
1003
  return parts.join("\n").trim();
597
1004
  }
1005
+ /** The FACTUAL part of OpenCode's system prompt: where we are, what the workspace is,
1006
+ * what references exist. Under `preset` the system prompt itself never reaches the
1007
+ * agent (forwarding it would get the session billed as extra usage), but this
1008
+ * context is genuinely useful and carries no instructions, so it rides along as
1009
+ * user content instead. Everything else — OpenCode's behavioural instructions,
1010
+ * AGENTS.md (the agent loads it itself via projectMemory), MCP/skill catalogues —
1011
+ * is deliberately left out. */
1012
+ extractContextBlock(prompt) {
1013
+ const sys = this.systemText(prompt);
1014
+ if (!sys)
1015
+ return "";
1016
+ const out = [];
1017
+ for (const tag of CONTEXT_TAGS) {
1018
+ const m = sys.match(new RegExp(`<${tag}>[\\s\\S]*?</${tag}>`));
1019
+ if (m)
1020
+ out.push(m[0]);
1021
+ }
1022
+ return out.join("\n");
1023
+ }
1024
+ /** Send the context block once per session, then only what changed. Appending a
1025
+ * small delta at the END of the conversation is cache-safe (the cached prefix is
1026
+ * untouched); resending the whole block every turn would not be. */
1027
+ contextBlocks(t, prompt, ctrl) {
1028
+ if (ctrl.forwardEnvContext === false)
1029
+ return [];
1030
+ const block = this.extractContextBlock(prompt);
1031
+ if (!block)
1032
+ return [];
1033
+ if (!t.lastContextBlock) {
1034
+ t.lastContextBlock = block;
1035
+ // The time is included only here: OpenCode's <env> is day-granular, and a
1036
+ // per-turn clock update would be pure noise.
1037
+ const now = new Date();
1038
+ return [{
1039
+ type: "text",
1040
+ text: `<opencode_context>\n${block}\n Session started: ${now.toLocaleString()} (${Intl.DateTimeFormat().resolvedOptions().timeZone})\n</opencode_context>`,
1041
+ }];
1042
+ }
1043
+ const prev = new Set(t.lastContextBlock.split("\n").map((l) => l.trim()).filter(Boolean));
1044
+ const changed = block.split("\n").map((l) => l.trim()).filter((l) => l && !l.startsWith("<") && !prev.has(l));
1045
+ t.lastContextBlock = block;
1046
+ if (!changed.length)
1047
+ return [];
1048
+ dbg(`context delta (${changed.length} line(s))`);
1049
+ return [{ type: "text", text: `<opencode_context_update>\n${changed.join("\n")}\n</opencode_context_update>` }];
1050
+ }
598
1051
  /** Only the last user message (delta for a persistent session). */
599
1052
  lastUserBlocks(prompt) {
600
1053
  for (let i = prompt.length - 1; i >= 0; i--) {
601
1054
  if (prompt[i].role === "user") {
602
- const b = this.messageToBlocks(prompt[i], false);
1055
+ const b = this.messageToBlocks(prompt[i], false, null);
603
1056
  if (b.length)
604
1057
  return b;
605
1058
  }
606
1059
  }
607
1060
  return [{ type: "text", text: "" }];
608
1061
  }
1062
+ /** Find the live conversation whose deferred tool-calls/permissions this prompt
1063
+ * answers. Scoped per session, so two concurrent chats can't cross-resolve. */
609
1064
  detectContinuation(prompt) {
610
- if (!this.current || this.current.pendingTools.size === 0)
611
- return null;
612
- const results = [];
613
- for (const msg of prompt) {
614
- if (msg.role !== "tool" && msg.role !== "assistant")
1065
+ for (const t of this.sessions.values()) {
1066
+ if (t.pendingTools.size === 0 && t.pendingPermissions.size === 0)
615
1067
  continue;
616
- for (const part of msg.content) {
617
- if (part?.type === "tool-result" && this.current.pendingTools.has(part.toolCallId)) {
618
- results.push({ toolCallId: part.toolCallId, result: this.toMcpResult(part.output) });
1068
+ const results = [];
1069
+ for (const msg of prompt) {
1070
+ if (msg.role !== "tool" && msg.role !== "assistant")
1071
+ continue;
1072
+ for (const part of msg.content) {
1073
+ if (part?.type === "tool-result" && (t.pendingTools.has(part.toolCallId) || t.pendingPermissions.has(part.toolCallId))) {
1074
+ results.push({ toolCallId: part.toolCallId, result: this.toMcpResult(part.output), output: part.output });
1075
+ }
619
1076
  }
620
1077
  }
1078
+ if (results.length)
1079
+ return { t, results };
621
1080
  }
622
- return results.length ? results : null;
1081
+ return null;
1082
+ }
1083
+ /** A tool-result is an error/denial when its output type is error-* (OpenCode
1084
+ * RejectedError) — used by the permission bridge to map approve vs reject. */
1085
+ isErrorOutput(output) {
1086
+ const ty = output?.type;
1087
+ return ty === "error-text" || ty === "error-json" || ty === "error";
1088
+ }
1089
+ /** Approve a bridged permission ONLY on an explicit positive verdict (the
1090
+ * claude_permission meta-tool returns "approved: …"). Errors, denials, and any
1091
+ * ambiguous output fail CLOSED so an unclear verdict never runs the native tool. */
1092
+ isApprovedOutput(output) {
1093
+ if (this.isErrorOutput(output))
1094
+ return false;
1095
+ return this.outputToText(output).toLowerCase().includes("approved");
623
1096
  }
624
1097
  outputToText(output) {
625
1098
  if (!output)
@@ -632,8 +1105,27 @@ export class ACPOrchestratorModel {
632
1105
  return output.value.map((c) => (c.type === "text" ? c.text : "")).join("");
633
1106
  return typeof output === "string" ? output : JSON.stringify(output);
634
1107
  }
1108
+ /** OpenCode tool output → MCP CallToolResult. Structured content (images from a
1109
+ * `read`, mixed blocks) is mapped through rather than flattened to a string, so
1110
+ * the agent sees what OpenCode actually returned. */
635
1111
  toMcpResult(output) {
636
1112
  const isErr = output?.type === "error-text" || output?.type === "error-json";
1113
+ if (output?.type === "content" && Array.isArray(output.value)) {
1114
+ const content = output.value
1115
+ .map((c) => {
1116
+ if (c?.type === "text")
1117
+ return { type: "text", text: String(c.text ?? "") };
1118
+ if (c?.type === "media" || c?.type === "image") {
1119
+ const data = c.data ?? c.value;
1120
+ if (typeof data === "string")
1121
+ return { type: "image", data, mimeType: c.mediaType ?? c.mimeType ?? "image/png" };
1122
+ }
1123
+ return null;
1124
+ })
1125
+ .filter(Boolean);
1126
+ if (content.length)
1127
+ return { content, ...(isErr ? { isError: true } : {}) };
1128
+ }
637
1129
  return { content: [{ type: "text", text: this.outputToText(output) }], ...(isErr ? { isError: true } : {}) };
638
1130
  }
639
1131
  }