opencode-claude-code-acpbridge 0.7.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,10 +85,14 @@ 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
- cancelWatchdog = null;
80
96
  constructor(config) {
81
97
  this.config = config;
82
98
  this.modelId = config.modelId ?? "claude-code";
@@ -84,9 +100,10 @@ export class ACPOrchestratorModel {
84
100
  // ---- LanguageModelV3 ------------------------------------------------------
85
101
  async doStream(options) {
86
102
  const continuation = this.detectContinuation(options.prompt);
103
+ const ref = { t: continuation?.t ?? null };
87
104
  const stream = new ReadableStream({
88
- start: (controller) => void this.onStart(controller, options, continuation),
89
- cancel: () => this.onCancel(),
105
+ start: (controller) => void this.onStart(controller, options, continuation, ref),
106
+ cancel: () => this.onCancel(ref),
90
107
  });
91
108
  return { stream, warnings: [] };
92
109
  }
@@ -115,18 +132,25 @@ export class ACPOrchestratorModel {
115
132
  return { content, finishReason, usage, warnings: [] };
116
133
  }
117
134
  // ---- turn lifecycle -------------------------------------------------------
118
- async onStart(controller, options, continuation) {
135
+ async onStart(controller, options, continuation, ref) {
119
136
  try {
120
137
  controller.enqueue({ type: "stream-start", warnings: [] });
121
138
  // (1) Continuation of a deferred tool-call OR a bridged permission — resume
122
139
  // 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
140
+ if (continuation) {
141
+ const t = continuation.t;
142
+ ref.t = t;
143
+ this.clearCancelWatchdog(t); // the turn DID continue — disarm the abort timer
126
144
  t.controller = controller;
127
- t.textId = null;
128
- t.reasoningId = null;
129
- for (const { toolCallId, result, output } of continuation) {
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) {
130
154
  const permResolve = t.pendingPermissions.get(toolCallId);
131
155
  if (permResolve) {
132
156
  // Permission bridge: OpenCode's `ask` verdict came back as the
@@ -144,59 +168,100 @@ export class ACPOrchestratorModel {
144
168
  await this.ensureConnected();
145
169
  const tools = this.convertTools(options.tools);
146
170
  const ctrl = this.effectiveCtrl(options);
171
+ const po = options.providerOptions?.[this.provider] ?? {};
172
+ const ocSession = po.ocSession;
147
173
  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));
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));
154
183
  // Params baked into newSession's _meta (thinking/systemPromptMode) can't change
155
184
  // mid-session → a change forces a fresh session. mode/effort are applied at
156
185
  // 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;
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;
189
256
  }
190
- // (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
191
258
  // 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));
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);
200
265
  await host.start();
201
266
  host.setTools(tools);
202
267
  const serverConfig = host.getServerConfig();
@@ -204,9 +269,13 @@ export class ACPOrchestratorModel {
204
269
  // history grew rather than diverged) → no history replay (saves tokens). Else
205
270
  // create a fresh session and replay the full history.
206
271
  const resumeId = po.resumeId;
272
+ const resumeLen = typeof po.resumeLen === "number" ? po.resumeLen : 0;
207
273
  let sessionId;
208
274
  let replayFull = true;
209
- 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) {
210
279
  try {
211
280
  await this.connection.unstable_resumeSession({
212
281
  sessionId: resumeId,
@@ -215,8 +284,7 @@ export class ACPOrchestratorModel {
215
284
  // Re-apply the clean-brain options on resume too. Without this the agent
216
285
  // falls back to its defaults (--tools default, --setting-sources=user,
217
286
  // 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.
287
+ // native tools + the claude.ai connectors.
220
288
  _meta: { claudeCode: { options: buildClaudeCodeOptions(ctrl) } },
221
289
  });
222
290
  sessionId = resumeId;
@@ -230,7 +298,7 @@ export class ACPOrchestratorModel {
230
298
  if (!sessionId) {
231
299
  // OpenCode's system prompt → _meta.systemPrompt (preset/append/replace).
232
300
  const meta = { claudeCode: { options: buildClaudeCodeOptions(ctrl) } };
233
- const sysMeta = this.buildSystemPromptMeta(options.prompt, ctrl.systemPromptMode ?? "preset");
301
+ const sysMeta = this.buildSystemPromptMeta(options.prompt, systemMode);
234
302
  if (sysMeta !== undefined)
235
303
  meta.systemPrompt = sysMeta;
236
304
  const session = await this.connection.newSession({
@@ -239,51 +307,106 @@ export class ACPOrchestratorModel {
239
307
  _meta: meta,
240
308
  });
241
309
  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})`);
310
+ dbg(`model=${session.models?.currentModelId ?? "?"} (requested: ${ctrl.model ?? "default"}, mode: ${ctrl.mode ?? "default"}, effort: ${ctrl.effort ?? "default"}) — tools(${tools.length})`);
243
311
  }
244
312
  if (!sessionId)
245
313
  throw new Error("failed to create or resume an ACP session");
246
- 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,
247
319
  host,
320
+ idPrefix,
248
321
  sessionId,
249
322
  convKey,
250
323
  toolsKey,
251
324
  systemKey,
252
325
  cfgKey,
253
326
  ocSession,
327
+ ocAgent: po.ocAgent ? String(po.ocAgent) : undefined,
254
328
  // Resume path: seed the cumulative usage snapshot from the persisted
255
329
  // registry so the first post-resume `subtractUsage` produces a real
256
330
  // turn delta instead of the full cumulative.
257
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),
258
335
  controller,
336
+ pending: [],
259
337
  pendingTools: new Set(),
260
338
  pendingPermissions: new Map(),
261
339
  textId: null,
262
340
  reasoningId: null,
341
+ cancelWatchdog: null,
342
+ lastActive: Date.now(),
263
343
  };
264
- this.current = t;
265
- 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);
266
350
  if (ocSession)
267
- 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;
268
361
  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));
362
+ .prompt({ sessionId, prompt: promptBlocks })
363
+ .then((resp) => this.onPromptDone(started, resp))
364
+ .catch((err) => this.onPromptError(started, err));
272
365
  }
273
366
  catch (err) {
274
367
  dbg(`onStart error: ${err instanceof Error ? err.message : String(err)}`);
275
- controller.enqueue({ type: "error", error: err });
368
+ try {
369
+ controller.enqueue({ type: "error", error: err });
370
+ }
371
+ catch { /* ignore */ }
276
372
  try {
277
373
  controller.close();
278
374
  }
279
375
  catch { /* ignore */ }
280
376
  }
281
377
  }
282
- onPromptDone(resp) {
283
- const t = this.current;
284
- 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)
285
407
  return; // cut for a pending tool-call
286
408
  this.closeBlocks(t);
409
+ this.flushPending(t);
287
410
  const turn = subtractUsage(resp?.usage, t.lastUsage); // ACP usage is cumulative per session
288
411
  if (resp?.usage) {
289
412
  t.lastUsage = resp.usage;
@@ -292,45 +415,43 @@ export class ACPOrchestratorModel {
292
415
  }
293
416
  if (DEBUG && turn)
294
417
  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
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
+ });
301
424
  t.controller.close();
302
425
  }
303
426
  catch { /* ignore */ }
304
427
  t.controller = null; // keep the session for the next turn (delta)
305
428
  }
306
- onPromptError(err) {
307
- const t = this.current;
308
- if (!t || !t.controller)
429
+ onPromptError(t, err) {
430
+ if (!t.controller)
309
431
  return;
310
432
  dbg(`prompt error: ${err instanceof Error ? err.message : String(err)}`);
311
- t.controller.enqueue({ type: "error", error: err });
312
433
  try {
434
+ t.controller.enqueue({ type: "error", error: err });
313
435
  t.controller.close();
314
436
  }
315
437
  catch { /* ignore */ }
316
438
  t.controller = null;
317
439
  }
318
440
  /** 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)
441
+ onToolCall(t, call) {
442
+ if (!t.controller)
322
443
  return;
323
444
  dbg(`agent → tool-call ${call.name} (${call.toolCallId}) → emit to OpenCode`);
324
445
  this.closeBlocks(t);
325
446
  t.pendingTools.add(call.toolCallId);
326
447
  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" } });
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" } });
332
453
  try {
333
- t.controller.close();
454
+ t.controller?.close();
334
455
  }
335
456
  catch { /* ignore */ }
336
457
  t.controller = null; // DO NOT resolve yet — wait for the continuation doStream
@@ -339,27 +460,53 @@ export class ACPOrchestratorModel {
339
460
  /** Map approve/reject to one of the options the agent offered (by kind/optionId). */
340
461
  permOutcome(params, approved) {
341
462
  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)
463
+ if (!opts.length)
347
464
  return { outcome: { outcome: "cancelled" } };
348
- return { outcome: { outcome: "selected", optionId: opt.optionId } };
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" } };
349
480
  }
350
481
  /** Tool name the agent wants permission for. The ACP toolCall carries NO bare
351
482
  * name — `title` is a human label like "Read /path", "Write /path", "Skill" — so
352
483
  * we take the first token. This becomes the permission key, so per-tool rules
353
484
  * (`permission: { Read: … }`) match. The full title travels separately as metadata. */
354
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";
355
490
  const title = String(toolCall?.title ?? "").trim();
356
491
  return title.split(/\s+/)[0] || String(toolCall?.kind ?? "") || "tool";
357
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
+ }
358
505
  /** ACP requestPermission → OpenCode `ask`, via the claude_permission meta-tool.
359
506
  * Deferred: returns a Promise the agent awaits until OpenCode's verdict comes
360
507
  * back as the meta-tool's result (resolved in onStart's continuation branch). */
361
508
  onRequestPermission(params) {
362
- const t = this.current;
509
+ const t = this.byAcpSession.get(String(params?.sessionId ?? ""));
363
510
  // No live turn/controller → approve so the agent never hangs.
364
511
  if (!t || !t.controller)
365
512
  return Promise.resolve(this.permOutcome(params, true));
@@ -377,45 +524,77 @@ export class ACPOrchestratorModel {
377
524
  if (!t.controller)
378
525
  return;
379
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
+ }
380
539
  const input = JSON.stringify({
381
540
  tool: this.permToolName(toolCall),
382
541
  kind: toolCall?.kind,
383
542
  title: toolCall?.title,
384
543
  input: toolCall?.rawInput,
385
544
  });
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" } });
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" } });
391
550
  try {
392
- t.controller.close();
551
+ t.controller?.close();
393
552
  }
394
553
  catch { /* ignore */ }
395
554
  t.controller = null;
396
555
  }
397
556
  /** Fired by the ACP client on session/update. */
398
- onSessionUpdate(update) {
399
- const t = this.current;
400
- if (!t || !t.controller)
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
+ }
401
579
  return;
580
+ }
402
581
  switch (update?.sessionUpdate) {
403
582
  case "agent_message_chunk":
404
583
  if (update.content?.type === "text") {
405
584
  if (!t.textId) {
406
585
  t.textId = `t${++this.idSeq}`;
407
- t.controller.enqueue({ type: "text-start", id: t.textId });
586
+ this.emit(t, { type: "text-start", id: t.textId });
408
587
  }
409
- 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 });
410
589
  }
411
590
  break;
412
591
  case "agent_thought_chunk":
413
592
  if (update.content?.type === "text") {
414
593
  if (!t.reasoningId) {
415
594
  t.reasoningId = `r${++this.idSeq}`;
416
- t.controller.enqueue({ type: "reasoning-start", id: t.reasoningId });
595
+ this.emit(t, { type: "reasoning-start", id: t.reasoningId });
417
596
  }
418
- 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 });
419
598
  }
420
599
  break;
421
600
  default:
@@ -423,20 +602,17 @@ export class ACPOrchestratorModel {
423
602
  }
424
603
  }
425
604
  closeBlocks(t) {
426
- if (t.textId && t.controller) {
427
- t.controller.enqueue({ type: "text-end", id: t.textId });
605
+ if (t.textId) {
606
+ this.emit(t, { type: "text-end", id: t.textId });
428
607
  t.textId = null;
429
608
  }
430
- if (t.reasoningId && t.controller) {
431
- t.controller.enqueue({ type: "reasoning-end", id: t.reasoningId });
609
+ if (t.reasoningId) {
610
+ this.emit(t, { type: "reasoning-end", id: t.reasoningId });
432
611
  t.reasoningId = null;
433
612
  }
434
613
  }
435
- endTurn() {
436
- this.clearCancelWatchdog();
437
- const t = this.current;
438
- if (!t)
439
- return;
614
+ endTurn(t) {
615
+ this.clearCancelWatchdog(t);
440
616
  // Settle any deferred permission requests (deny/cancel) so the agent never
441
617
  // stays blocked awaiting a verdict that will no longer arrive.
442
618
  this.drainPermissions(t);
@@ -446,7 +622,23 @@ export class ACPOrchestratorModel {
446
622
  }
447
623
  catch { /* ignore */ }
448
624
  t.host.stop();
449
- 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
+ }
450
642
  }
451
643
  /** Resolve every outstanding bridged permission as denied so the agent unblocks. */
452
644
  drainPermissions(t) {
@@ -468,7 +660,7 @@ export class ACPOrchestratorModel {
468
660
  // Per-agent overrides from `agent.<name>.options` (→ providerOptions.acp):
469
661
  // mode/effort/reasoning plus the native-feature toggles.
470
662
  const KEYS = [
471
- "mode", "effort", "thinking", "systemPromptMode",
663
+ "mode", "effort", "thinking", "systemPromptMode", "forwardEnvContext",
472
664
  "tools", "allowedTools", "disallowedTools", "settingSources", "strictMcpConfig",
473
665
  "nativeTools", "resourceSearch", "nativeSubagents", "nativeSkills", "projectMemory", "skillShell",
474
666
  ];
@@ -483,7 +675,16 @@ export class ACPOrchestratorModel {
483
675
  }
484
676
  /** Apply runtime config (mode/effort) to a live ACP session via set_mode/set_config_option. */
485
677
  async applySessionConfig(t, ctrl) {
486
- 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) {
487
688
  try {
488
689
  await this.connection.setSessionMode({ sessionId: t.sessionId, modeId: ctrl.mode });
489
690
  t.appliedMode = ctrl.mode;
@@ -500,7 +701,9 @@ export class ACPOrchestratorModel {
500
701
  dbg(`effort → ${ctrl.effort}`);
501
702
  }
502
703
  catch (e) {
503
- 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)})`);
504
707
  }
505
708
  }
506
709
  }
@@ -551,7 +754,9 @@ export class ACPOrchestratorModel {
551
754
  const stream = ndJsonStream(Writable.toWeb(this.agent.stdin), Readable.toWeb(this.agent.stdout));
552
755
  const self = this;
553
756
  this.connection = new ClientSideConnection(() => ({
554
- 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); },
555
760
  async requestPermission(params) {
556
761
  return self.onRequestPermission(params);
557
762
  },
@@ -565,42 +770,52 @@ export class ACPOrchestratorModel {
565
770
  this.promptCaps = (initResult?.agentCapabilities?.promptCapabilities ?? {});
566
771
  dbg(`connected to agent — promptCapabilities: ${JSON.stringify(this.promptCaps)}`);
567
772
  }
568
- onCancel() {
773
+ onCancel(ref) {
774
+ const t = ref.t;
775
+ if (!t)
776
+ return;
569
777
  // A stream cancel WHILE a tool-call or permission is deferred is OpenCode
570
778
  // PAUSING (e.g. to show a permission prompt), not a real abort — tearing the
571
779
  // host down here kills the pending tools/call with "host closed". Keep the
572
780
  // session/host alive; the continuation doStream resolves them. A WATCHDOG
573
781
  // guarantees teardown if the continuation never arrives (session truly aborted,
574
782
  // 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)) {
783
+ if (t.pendingTools.size > 0 || t.pendingPermissions.size > 0) {
577
784
  dbg("onCancel ignored — deferred tool-call/permission in flight (likely a permission pause)");
578
- this.armCancelWatchdog();
785
+ this.armCancelWatchdog(t);
579
786
  return;
580
787
  }
581
- this.endTurn();
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);
582
796
  }
583
797
  /** If a cancel was ignored (deferred work in flight) but no continuation comes,
584
798
  * 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
- }
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);
593
805
  }, this.config.streamCloseTimeoutMs ?? 600_000);
594
- this.cancelWatchdog.unref?.();
806
+ t.cancelWatchdog.unref?.();
595
807
  }
596
- clearCancelWatchdog() {
597
- if (this.cancelWatchdog) {
598
- clearTimeout(this.cancelWatchdog);
599
- this.cancelWatchdog = null;
808
+ clearCancelWatchdog(t) {
809
+ if (t.cancelWatchdog) {
810
+ clearTimeout(t.cancelWatchdog);
811
+ t.cancelWatchdog = null;
600
812
  }
601
813
  }
602
814
  cleanup() {
603
- this.endTurn();
815
+ for (const t of [...this.sessions.values()])
816
+ this.endTurn(t);
817
+ this.sessions.clear();
818
+ this.byAcpSession.clear();
604
819
  try {
605
820
  this.agent?.kill();
606
821
  }
@@ -623,13 +838,25 @@ export class ACPOrchestratorModel {
623
838
  if (t.type === "function") {
624
839
  out.push({
625
840
  name: t.name,
626
- description: t.description,
841
+ description: this.toolDescription(t.name, t.description),
627
842
  inputSchema: t.inputSchema ?? { type: "object", properties: {} },
628
843
  });
629
844
  }
630
845
  }
631
846
  return out;
632
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
+ }
633
860
  /** Text of the first user message — stable identifier for the conversation. */
634
861
  firstUserText(prompt) {
635
862
  for (const m of prompt) {
@@ -641,7 +868,56 @@ export class ACPOrchestratorModel {
641
868
  }
642
869
  return "";
643
870
  }
644
- 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) {
645
921
  const prefixes = { system: "System: ", assistant: "Assistant: ", tool: "", user: "" };
646
922
  const prefix = withPrefix ? (prefixes[msg.role] ?? "") : "";
647
923
  if (typeof msg.content === "string")
@@ -650,6 +926,11 @@ export class ACPOrchestratorModel {
650
926
  let first = true;
651
927
  for (const part of msg.content) {
652
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;
653
934
  if (part.type === "text") {
654
935
  blocks.push({ type: "text", text: px + part.text });
655
936
  first = false;
@@ -659,7 +940,7 @@ export class ACPOrchestratorModel {
659
940
  first = false;
660
941
  }
661
942
  else if (part.type === "tool-result") {
662
- 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))}]` });
663
944
  first = false;
664
945
  }
665
946
  else if (part.type === "file") {
@@ -670,6 +951,11 @@ export class ACPOrchestratorModel {
670
951
  }
671
952
  return blocks;
672
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
+ }
673
959
  /** Map an AI SDK file part to an ACP ContentBlock, honoring the agent's promptCapabilities. */
674
960
  fileToBlock(part) {
675
961
  const mt = part.mediaType || "application/octet-stream";
@@ -696,16 +982,6 @@ export class ACPOrchestratorModel {
696
982
  return data.includes(",") ? data.split(",")[1] : data; // data URL or raw base64
697
983
  return null; // URL or other — not embeddable
698
984
  }
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
985
  /** OpenCode's system text → `_meta.systemPrompt` per mode. */
710
986
  buildSystemPromptMeta(prompt, mode) {
711
987
  if (mode === "preset")
@@ -726,32 +1002,83 @@ export class ACPOrchestratorModel {
726
1002
  }
727
1003
  return parts.join("\n").trim();
728
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
+ }
729
1051
  /** Only the last user message (delta for a persistent session). */
730
1052
  lastUserBlocks(prompt) {
731
1053
  for (let i = prompt.length - 1; i >= 0; i--) {
732
1054
  if (prompt[i].role === "user") {
733
- const b = this.messageToBlocks(prompt[i], false);
1055
+ const b = this.messageToBlocks(prompt[i], false, null);
734
1056
  if (b.length)
735
1057
  return b;
736
1058
  }
737
1059
  }
738
1060
  return [{ type: "text", text: "" }];
739
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. */
740
1064
  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")
1065
+ for (const t of this.sessions.values()) {
1066
+ if (t.pendingTools.size === 0 && t.pendingPermissions.size === 0)
747
1067
  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 });
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
+ }
751
1076
  }
752
1077
  }
1078
+ if (results.length)
1079
+ return { t, results };
753
1080
  }
754
- return results.length ? results : null;
1081
+ return null;
755
1082
  }
756
1083
  /** A tool-result is an error/denial when its output type is error-* (OpenCode
757
1084
  * RejectedError) — used by the permission bridge to map approve vs reject. */
@@ -778,8 +1105,27 @@ export class ACPOrchestratorModel {
778
1105
  return output.value.map((c) => (c.type === "text" ? c.text : "")).join("");
779
1106
  return typeof output === "string" ? output : JSON.stringify(output);
780
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. */
781
1111
  toMcpResult(output) {
782
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
+ }
783
1129
  return { content: [{ type: "text", text: this.outputToText(output) }], ...(isErr ? { isError: true } : {}) };
784
1130
  }
785
1131
  }