opencode-claude-code-acpbridge 0.8.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/CHANGELOG.md +122 -0
  2. package/README.md +139 -68
  3. package/dist/acp/claude-config.d.ts +52 -0
  4. package/dist/acp/claude-config.d.ts.map +1 -1
  5. package/dist/acp/claude-config.js +23 -7
  6. package/dist/acp/claude-config.js.map +1 -1
  7. package/dist/acp/mcp-host.d.ts +10 -0
  8. package/dist/acp/mcp-host.d.ts.map +1 -1
  9. package/dist/acp/mcp-host.js +17 -4
  10. package/dist/acp/mcp-host.js.map +1 -1
  11. package/dist/acp/mcp-runtime.js +112 -11
  12. package/dist/acp/mcp-runtime.js.map +1 -1
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +3 -2
  15. package/dist/index.js.map +1 -1
  16. package/dist/log.d.ts +11 -0
  17. package/dist/log.d.ts.map +1 -0
  18. package/dist/log.js +50 -0
  19. package/dist/log.js.map +1 -0
  20. package/dist/plugin/bridge-rules.d.ts +22 -0
  21. package/dist/plugin/bridge-rules.d.ts.map +1 -0
  22. package/dist/plugin/bridge-rules.js +104 -0
  23. package/dist/plugin/bridge-rules.js.map +1 -0
  24. package/dist/plugin/catalog.d.ts +7 -0
  25. package/dist/plugin/catalog.d.ts.map +1 -1
  26. package/dist/plugin/catalog.js +38 -0
  27. package/dist/plugin/catalog.js.map +1 -1
  28. package/dist/plugin/index.d.ts +6 -13
  29. package/dist/plugin/index.d.ts.map +1 -1
  30. package/dist/plugin/index.js +305 -241
  31. package/dist/plugin/index.js.map +1 -1
  32. package/dist/plugin/sessions.d.ts +11 -8
  33. package/dist/plugin/sessions.d.ts.map +1 -1
  34. package/dist/plugin/sessions.js +47 -7
  35. package/dist/plugin/sessions.js.map +1 -1
  36. package/dist/provider/factory.d.ts.map +1 -1
  37. package/dist/provider/factory.js +5 -3
  38. package/dist/provider/factory.js.map +1 -1
  39. package/dist/provider/history.d.ts +44 -0
  40. package/dist/provider/history.d.ts.map +1 -0
  41. package/dist/provider/history.js +145 -0
  42. package/dist/provider/history.js.map +1 -0
  43. package/dist/provider/model.d.ts +193 -32
  44. package/dist/provider/model.d.ts.map +1 -1
  45. package/dist/provider/model.js +1521 -500
  46. package/dist/provider/model.js.map +1 -1
  47. package/dist/provider/recorder.d.ts +5 -0
  48. package/dist/provider/recorder.d.ts.map +1 -0
  49. package/dist/provider/recorder.js +63 -0
  50. package/dist/provider/recorder.js.map +1 -0
  51. package/docs/DEVELOPMENT.md +56 -27
  52. package/examples/01-minimal.jsonc +9 -6
  53. package/examples/02-permisos-por-agente.jsonc +22 -17
  54. package/examples/03-fidelidad-opencode.jsonc +8 -7
  55. package/examples/04-modelo-y-esfuerzo.jsonc +29 -23
  56. package/examples/05-agentes-personalizados.jsonc +24 -14
  57. package/examples/06-ecosistema-claude.jsonc +12 -11
  58. package/examples/07-provider-manual.jsonc +12 -8
  59. package/examples/08-puente-permisos.jsonc +43 -25
  60. package/examples/README.md +10 -9
  61. package/package.json +6 -5
@@ -8,34 +8,108 @@
8
8
  // tool-results it received over MCP) and reuses Claude's prompt cache, which
9
9
  // lives and dies with the session — so NOT recreating the session is exactly
10
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.
11
+ // - What it has seen: a fingerprint of the history already sent (history.ts,
12
+ // `historyMode`), plus its own output — answers it emitted and ids it minted —
13
+ // which OpenCode stores and sends back next turn and is never forwarded again.
14
+ // - Turns of ANOTHER model in between are caught up, labelled as such. A different
15
+ // agent or tool set keeps the session; another creation profile forks it; another
16
+ // acp model is a set_model. Only a genuine divergence (revert, compaction) starts
17
+ // over — and even those can fork back (`smartRevert`) or be adopted (`v2`).
14
18
  //
15
19
  // Tool flow: when the agent calls an MCP tool, the host fires onToolCall → we
16
20
  // emit a `tool-call` with the REAL OpenCode tool name, finish `tool-calls`, and
17
21
  // leave the MCP tools/call DEFERRED; the next doStream brings OpenCode's
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.
22
+ // tool-result → we resolve it and the same agent turn continues. Calls issued
23
+ // together share a step; calls arriving while the stream is closed are queued.
24
+ // Text/thinking arriving meanwhile is BUFFERED, never dropped. Whatever the user
25
+ // wrote in between (steer) is delivered into the running turn; an interrupt stops it.
20
26
  import { spawn } from "node:child_process";
21
27
  import { Writable, Readable } from "node:stream";
22
28
  import { randomBytes } from "node:crypto";
29
+ import { closeSync, fstatSync, openSync, readSync } from "node:fs";
30
+ import { homedir } from "node:os";
31
+ import { join } from "node:path";
23
32
  import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
24
33
  import { McpHost } from "../acp/mcp-host.js";
25
34
  import { buildClaudeCodeOptions, resolveConfigDir, } from "../acp/claude-config.js";
26
35
  import { setLink, updateUsage } from "../plugin/sessions.js";
27
- const DEBUG = !!process.env.ACP_DEBUG;
28
- const dbg = (m) => { if (DEBUG)
29
- process.stderr.write(`[acp-orchestrator] ${m}\n`); };
36
+ import { addAlwaysRule, evaluate as evaluateBridge } from "../plugin/bridge-rules.js";
37
+ import { DEBUG, logger } from "../log.js";
38
+ import { record, recording, sanitizePrompt } from "./recorder.js";
39
+ import { anchorsOf, classifyAnchors, classifyHistory, firstUserText, hashText, historyOf, isTransient, msgKey, stripInjected, systemText, } from "./history.js";
40
+ const log = logger("acp-orchestrator");
41
+ const dbg = log.dbg;
30
42
  /** 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;
43
+ const note = log.note;
44
+ /** Max live conversations (LRU, `maxLiveSessions`); older idle ones are closed. Each one
45
+ * is a Claude Code process (~250-400 MB) plus its MCP runtime. */
46
+ const MAX_LIVE_SESSIONS = 6;
47
+ /** Idle time before a resumable session is closed (`idleSessionTtlMs`). Coming back
48
+ * costs a process start: Anthropic keeps the prompt cache ~1 h on subscriptions. */
49
+ const IDLE_TTL_MS = 15 * 60_000;
50
+ /** Same for subagent sessions (`childSessionTtlMs`): rarely continued. */
51
+ const CHILD_TTL_MS = 2 * 60_000;
52
+ /** A turn still waiting on OpenCode after this long was abandoned. */
53
+ const ABANDONED_TTL_MS = 2 * 60 * 60_000;
54
+ /** Cap on a foreign tool-result replayed as text during catch-up (`catchupResultChars`).
55
+ * Big enough that switching back from another model doesn't lose what it read. */
56
+ const CATCHUP_RESULT_CHARS = 8000;
57
+ /** Ceiling for a full-history replay into a new session (~100k tokens): beyond it the
58
+ * oldest turns are dropped — a 656k-char replay was seen in the wild. */
59
+ const REPLAY_BUDGET_CHARS = 400_000;
60
+ /** Tope del buffer `pending` (chunks emitidos sin controller vivo): sin cap un turno
61
+ * largo con el stream cerrado lo haría crecer sin límite (OOM). */
62
+ const MAX_PENDING_PARTS = 1000;
36
63
  /** System-prompt blocks worth forwarding to the agent as FACTUAL context (never as
37
64
  * a system prompt — that would make Anthropic bill the session as extra usage). */
38
65
  const CONTEXT_TAGS = ["env", "available_references"];
66
+ /** Bound on the hashes of emitted text kept per session (`ownTexts`). */
67
+ const MAX_OWN_TEXTS = 500;
68
+ /** How long a read-only tool-call waits for parallel siblings before its step closes. */
69
+ const TOOL_BATCH_MS = 40;
70
+ /** OpenCode V2 tools that are safe to run in parallel: announced to the agent with MCP
71
+ * `readOnlyHint`, so Claude Code issues them concurrently and they share one step. */
72
+ const PARALLEL_TOOLS = ["read", "glob", "grep", "webfetch", "websearch", "skill", "subagent"];
73
+ /** Native tools whose completion is not worth a line (the bridge shows them already). */
74
+ const NATIVE_SILENT = new Set(["ExitPlanMode", "EnterPlanMode", "TodoWrite"]);
75
+ /** Native tools whose RESULT matters to whoever continues the conversation. */
76
+ const NATIVE_WITH_RESULT = new Set(["Task", "Agent", "WebSearch", "WebFetch", "Skill"]);
77
+ /** Cap on a native tool result written into the answer (`nativeActivityChars`). */
78
+ const NATIVE_RESULT_CHARS = 2000;
79
+ /** How long the next turn waits for a native /compact still running. */
80
+ const COMPACT_WAIT_MS = 180_000;
81
+ /** Lead-in when another model's compaction summary is caught up into this session. */
82
+ const CHECKPOINT_NOTE = "<context_update>\n(The conversation continued in OpenCode with another model and was then compacted. " +
83
+ "OpenCode's checkpoint follows: it summarizes everything, including what happened after your last turn. " +
84
+ "Keep what you remember; use it to catch up on what you did not see.)\n</context_update>";
85
+ /** How long a turn being replaced may take to wind down after a cancel. */
86
+ const SETTLE_MS = 5000;
87
+ /** The `# Code Mode` section of OpenCode's system prompt (up to the next top-level
88
+ * heading or tag block), or "" when Code Mode is off. */
89
+ function codeModeSection(system) {
90
+ const start = system.search(/^# Code Mode\s*$/m);
91
+ if (start < 0)
92
+ return "";
93
+ const rest = system.slice(start);
94
+ const end = rest.slice(1).search(/^(# (?!#)|<[a-z_-]+>)/m);
95
+ return (end < 0 ? rest : rest.slice(0, end + 1)).trim();
96
+ }
97
+ /** OpenCode's record of a tool the user interrupted (or that never got a result):
98
+ * V2 sends it as a TEXT output holding `{"error":{"type":"aborted",…}}`. */
99
+ function isInterrupted(output) {
100
+ const v = output?.value;
101
+ const text = typeof v === "string" ? v : v != null ? JSON.stringify(v) : "";
102
+ if (/"type"\s*:\s*"aborted"/.test(text))
103
+ return true;
104
+ return /^(Tool execution interrupted|Tool result missing)/.test(text.trim());
105
+ }
106
+ function ownTextKey(text) {
107
+ return hashText(stripInjected(text).trim());
108
+ }
109
+ /** Dialog labels — also the strings the verdict parser looks for (see `questionVerdict`). */
110
+ const ALLOW_ONCE = "Allow once";
111
+ const ALWAYS_ALLOW = "Always allow";
112
+ const DENY = "Deny";
39
113
  function emptyUsage() {
40
114
  return {
41
115
  inputTokens: { total: undefined, noCache: undefined, cacheRead: undefined, cacheWrite: undefined },
@@ -55,26 +129,72 @@ function mapUsage(u) {
55
129
  outputTokens: { total: u.outputTokens ?? undefined, text: u.outputTokens ?? undefined },
56
130
  };
57
131
  }
58
- /** ACP usage is cumulative per session → subtract the previous snapshot to get this turn's. */
59
- function subtractUsage(acc, prev) {
60
- if (!acc || typeof acc !== "object")
61
- return acc;
62
- if (!prev)
63
- return acc;
64
- const d = (a, b) => Math.max(0, (a ?? 0) - (b ?? 0));
65
- return {
66
- inputTokens: d(acc.inputTokens, prev.inputTokens),
67
- outputTokens: d(acc.outputTokens, prev.outputTokens),
68
- cachedReadTokens: d(acc.cachedReadTokens, prev.cachedReadTokens),
69
- cachedWriteTokens: d(acc.cachedWriteTokens, prev.cachedWriteTokens),
70
- totalTokens: d(acc.totalTokens, prev.totalTokens),
71
- };
132
+ /** Usage accounting (claude-agent-acp 0.31): `PromptResponse.usage` is the SUM over
133
+ * every API request of the turn — neither per request nor per session — so it is
134
+ * only used for ratios; the context size comes from `usage_update.used` (see
135
+ * `usageNow`). Subtracting snapshots (≤0.8) or reporting the sum as-is (0.9 working
136
+ * tree) both misled OpenCode's auto-compaction. */
137
+ async function collectGenerate(stream) {
138
+ const content = [];
139
+ let text = "";
140
+ let finishReason = { unified: "stop", raw: undefined };
141
+ let usage = emptyUsage();
142
+ const reader = stream.getReader();
143
+ for (;;) {
144
+ const { done, value } = await reader.read();
145
+ if (done)
146
+ break;
147
+ if (value.type === "text-delta")
148
+ text += value.delta;
149
+ else if (value.type === "tool-call")
150
+ content.push(value);
151
+ else if (value.type === "finish") {
152
+ finishReason = value.finishReason;
153
+ usage = value.usage;
154
+ }
155
+ }
156
+ if (text)
157
+ content.unshift({ type: "text", text });
158
+ return { content, finishReason, usage, warnings: [] };
159
+ }
160
+ /** The call comes from an OpenCode subagent session (V2 sends the parent's id). */
161
+ function isChildCall(options) {
162
+ const h = options.headers ?? {};
163
+ return !!(h["x-parent-session-id"] ?? h["X-Parent-Session-Id"]);
164
+ }
165
+ /** Identity of what a session is CREATED with (`_meta.claudeCode.options` + system
166
+ * prompt mode). Model, effort and mode are applied live, so they don't count. */
167
+ function profileKey(ctrl, systemMode) {
168
+ const { model: _m, effort: _e, ...creation } = buildClaudeCodeOptions(ctrl);
169
+ return hashText(JSON.stringify({ o: creation, s: systemMode }));
170
+ }
171
+ /** Message + structured data of an ACP error (`RequestError.data.errorKind`, details). */
172
+ function errorText(err) {
173
+ if (!err || typeof err !== "object")
174
+ return String(err ?? "");
175
+ const e = err;
176
+ return [e.message, e.data !== undefined ? JSON.stringify(e.data) : ""].filter(Boolean).join(" ");
72
177
  }
73
- function hashText(s) {
74
- let h = 5381;
75
- for (let i = 0; i < s.length; i++)
76
- h = ((h << 5) + h) ^ s.charCodeAt(i);
77
- return (h >>> 0).toString(36);
178
+ /** Claude's usage/rate limit, rewritten so the user knows to switch models — and in
179
+ * words OpenCode's retry classifier doesn't match ("try again", "overloaded"…), so it
180
+ * isn't retried in a loop against an exhausted subscription. */
181
+ export function limitError(err) {
182
+ const raw = errorText(err);
183
+ if (!/usage limit|rate[ _-]?limit|billing_error|hit your limit|limit reached|out of (?:extra )?usage|quota exceeded|\b429\b/i.test(raw))
184
+ return undefined;
185
+ const epoch = raw.match(/\|(\d{10})\b/)?.[1];
186
+ const resets = raw.match(/resets? (?:at )?([^.,;\n"]+)/i)?.[1]?.trim();
187
+ const when = epoch ? new Date(Number(epoch) * 1000).toLocaleString() : resets;
188
+ const e = new Error(`Claude Code: límite de uso alcanzado${when ? ` (se restablece: ${when})` : ""}. Cambia de modelo en OpenCode para continuar; la sesión de Claude se conserva para cuando vuelvas.`);
189
+ e.name = "ClaudeUsageLimit";
190
+ return e;
191
+ }
192
+ /** Total text size of a prompt (diagnostics). */
193
+ function blocksChars(blocks) {
194
+ let n = 0;
195
+ for (const b of blocks)
196
+ n += typeof b?.text === "string" ? b.text.length : 0;
197
+ return n;
78
198
  }
79
199
  export class ACPOrchestratorModel {
80
200
  config;
@@ -83,6 +203,7 @@ export class ACPOrchestratorModel {
83
203
  modelId;
84
204
  supportedUrls = {};
85
205
  agent = null;
206
+ closeTransport = null;
86
207
  connection = null;
87
208
  connecting = null;
88
209
  /** Live conversations, keyed by OpenCode sessionID (or the conversation hash).
@@ -91,15 +212,39 @@ export class ACPOrchestratorModel {
91
212
  sessions = new Map();
92
213
  /** Same states indexed by ACP sessionId, to route agent-initiated callbacks. */
93
214
  byAcpSession = new Map();
215
+ /** Per-conversation lock for session lookup/creation (see `startFresh`). */
216
+ locks = new Map();
217
+ /** Per-call model override (see `doStream`). */
218
+ callModel = new WeakMap();
94
219
  idSeq = 0;
95
220
  promptCaps = {};
221
+ /** The agent merges a prompt sent mid-turn into the running turn (claude-agent-acp). */
222
+ promptQueueing = false;
96
223
  constructor(config) {
97
224
  this.config = config;
98
225
  this.modelId = config.modelId ?? "claude-code";
99
226
  }
100
227
  // ---- LanguageModelV3 ------------------------------------------------------
101
- async doStream(options) {
102
- const continuation = this.detectContinuation(options.prompt);
228
+ async doStream(options,
229
+ /** Model for THIS call when one orchestrator (one agent process) serves several
230
+ * OpenCode models — see `ACPModelView`. */
231
+ modelId) {
232
+ if (modelId)
233
+ this.callModel.set(options, modelId);
234
+ if (recording()) {
235
+ const po = this.providerOptions(options);
236
+ record(this.convId(options), {
237
+ kind: "call",
238
+ modelId: this.callModel.get(options) ?? this.modelId,
239
+ ocAgent: po.ocAgent,
240
+ poKeys: Object.keys(po),
241
+ headers: Object.fromEntries(Object.entries(options.headers ?? {}).filter(([k]) => /^x-/i.test(k))),
242
+ tools: (options.tools ?? []).map((x) => x.name),
243
+ toolChoice: options.toolChoice,
244
+ prompt: sanitizePrompt(options.prompt),
245
+ });
246
+ }
247
+ const continuation = this.detectContinuation(options.prompt, options);
103
248
  const ref = { t: continuation?.t ?? null };
104
249
  const stream = new ReadableStream({
105
250
  start: (controller) => void this.onStart(controller, options, continuation, ref),
@@ -109,27 +254,7 @@ export class ACPOrchestratorModel {
109
254
  }
110
255
  async doGenerate(options) {
111
256
  const { stream } = await this.doStream(options);
112
- const content = [];
113
- let text = "";
114
- let finishReason = { unified: "stop", raw: undefined };
115
- let usage = emptyUsage();
116
- const reader = stream.getReader();
117
- for (;;) {
118
- const { done, value } = await reader.read();
119
- if (done)
120
- break;
121
- if (value.type === "text-delta")
122
- text += value.delta;
123
- else if (value.type === "tool-call")
124
- content.push(value);
125
- else if (value.type === "finish") {
126
- finishReason = value.finishReason;
127
- usage = value.usage;
128
- }
129
- }
130
- if (text)
131
- content.unshift({ type: "text", text });
132
- return { content, finishReason, usage, warnings: [] };
257
+ return collectGenerate(stream);
133
258
  }
134
259
  // ---- turn lifecycle -------------------------------------------------------
135
260
  async onStart(controller, options, continuation, ref) {
@@ -137,231 +262,74 @@ export class ACPOrchestratorModel {
137
262
  controller.enqueue({ type: "stream-start", warnings: [] });
138
263
  // (1) Continuation of a deferred tool-call OR a bridged permission — resume
139
264
  // the same agent turn.
265
+ if (continuation?.aborted && continuation.extras.length) {
266
+ // The user interrupted the turn while a tool ran and then wrote again: OpenCode
267
+ // records the tool as `aborted` and appends the new message. Resolving the tool
268
+ // would continue the OLD turn and swallow that message — stop the turn instead,
269
+ // then handle the prompt as a fresh turn whose tail is the new message.
270
+ const t = continuation.t;
271
+ this.decide(options, { decision: "interrupted", session: t.sessionId, results: continuation.results.map((r) => r.toolCallId), extras: continuation.extras.length });
272
+ this.abortTurn(t, "tool interrupted by the user");
273
+ await this.settle(t);
274
+ this.markKnown(t, historyOf(options.prompt).slice(0, continuation.lastResultAt + 1));
275
+ continuation = null;
276
+ }
140
277
  if (continuation) {
141
278
  const t = continuation.t;
142
279
  ref.t = t;
143
- this.clearCancelWatchdog(t); // the turn DID continue — disarm the abort timer
144
280
  t.controller = controller;
145
281
  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));
282
+ // Everything in this prompt is known to the agent once this branch is done: its
283
+ // own tool-calls, the results it receives right now and the extras delivered
284
+ // below. Recording them is what stops the next turn from replaying them.
285
+ this.markKnown(t, historyOf(options.prompt));
150
286
  // Text/thinking that arrived while the stream was closed goes out FIRST, in
151
287
  // order, so nothing the agent said before calling the tool is lost.
152
288
  this.flushPending(t);
153
- for (const { toolCallId, result, output } of continuation.results) {
289
+ this.decide(options, {
290
+ decision: "continuation", session: t.sessionId,
291
+ results: continuation.results.map((r) => r.toolCallId), extras: continuation.extras.length,
292
+ });
293
+ // Steered message / update: queued into the RUNNING turn, exactly like typing
294
+ // while Claude Code works (claude-agent-acp `promptQueueing`). The original
295
+ // prompt then resolves early; the generation guard keeps it off this stream.
296
+ // Without queueing it rides on the last tool result instead.
297
+ // Keep the registry in step mid-turn too: a restart now resumes right here
298
+ // instead of replaying every tool round-trip since the user's message.
299
+ if (t.ocSession)
300
+ setLink(t.ocSession, t.sessionId, t.sentKeys.length, t.convKey, t.ownPrefixes);
301
+ const extraBlocks = continuation.extras.length ? this.midTurnBlocks(t, continuation.extras) : [];
302
+ const results = continuation.results;
303
+ const lastTool = results.map((r) => !t.pendingPermissions.has(r.toolCallId)).lastIndexOf(true);
304
+ const piggyback = extraBlocks.length > 0 && !this.promptQueueing && lastTool >= 0;
305
+ results.forEach(({ toolCallId, result, output }, i) => {
154
306
  const permResolve = t.pendingPermissions.get(toolCallId);
155
307
  if (permResolve) {
156
- // Permission bridge: OpenCode's `ask` verdict came back as the
157
- // claude_permission tool-result → resolve the deferred requestPermission.
308
+ // Permission bridge: the user's `question` answer came back as the
309
+ // tool-result → resolve the deferred requestPermission.
158
310
  t.pendingPermissions.delete(toolCallId);
159
- permResolve(this.isApprovedOutput(output));
160
- }
161
- else {
162
- t.pendingTools.delete(toolCallId);
163
- t.host.resolveToolCall(toolCallId, result);
164
- }
165
- }
166
- return;
167
- }
168
- await this.ensureConnected();
169
- const tools = this.convertTools(options.tools);
170
- const ctrl = this.effectiveCtrl(options);
171
- const po = options.providerOptions?.[this.provider] ?? {};
172
- const ocSession = po.ocSession;
173
- const convKey = hashText(this.firstUserText(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));
183
- // Params baked into newSession's _meta (thinking/systemPromptMode) can't change
184
- // mid-session → a change forces a fresh session. mode/effort are applied at
185
- // runtime via set_mode/set_config_option instead (no reset needed).
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));
311
+ permResolve(output);
250
312
  return;
251
313
  }
252
- }
253
- dbg(`dropping session ${t.sessionId} — ${drop}`);
254
- this.endTurn(t);
255
- t = undefined;
256
- }
257
- // (3) Need a session: new conversation, or the history diverged, or a
258
- // resumable session from a new process. Set up the MCP host once.
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);
265
- await host.start();
266
- host.setTools(tools);
267
- const serverConfig = host.getServerConfig();
268
- // Try to RESUME a registered Claude Code session (new process, no live state,
269
- // history grew rather than diverged) → no history replay (saves tokens). Else
270
- // create a fresh session and replay the full history.
271
- const resumeId = po.resumeId;
272
- const resumeLen = typeof po.resumeLen === "number" ? po.resumeLen : 0;
273
- let sessionId;
274
- let replayFull = true;
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) {
279
- try {
280
- await this.connection.unstable_resumeSession({
281
- sessionId: resumeId,
282
- cwd: this.config.cwd ?? process.cwd(),
283
- mcpServers: [serverConfig],
284
- // Re-apply the clean-brain options on resume too. Without this the agent
285
- // falls back to its defaults (--tools default, --setting-sources=user,
286
- // project,local, no --strict-mcp-config) and the resumed session regains
287
- // native tools + the claude.ai connectors.
288
- _meta: { claudeCode: { options: buildClaudeCodeOptions(ctrl) } },
289
- });
290
- sessionId = resumeId;
291
- replayFull = false;
292
- dbg(`resume ${resumeId} (oc=${ocSession ?? "?"}) — no history replay`);
293
- }
294
- catch (e) {
295
- dbg(`resume ${resumeId} failed (${e instanceof Error ? e.message : String(e)}) — fresh session`);
296
- }
297
- }
298
- if (!sessionId) {
299
- // OpenCode's system prompt → _meta.systemPrompt (preset/append/replace).
300
- const meta = { claudeCode: { options: buildClaudeCodeOptions(ctrl) } };
301
- const sysMeta = this.buildSystemPromptMeta(options.prompt, systemMode);
302
- if (sysMeta !== undefined)
303
- meta.systemPrompt = sysMeta;
304
- const session = await this.connection.newSession({
305
- cwd: this.config.cwd ?? process.cwd(),
306
- mcpServers: [serverConfig],
307
- _meta: meta,
314
+ t.pendingTools.delete(toolCallId);
315
+ t.host.resolveToolCall(toolCallId, piggyback && i === lastTool ? this.appendToResult(result, extraBlocks) : result);
308
316
  });
309
- sessionId = session.sessionId;
310
- dbg(`model=${session.models?.currentModelId ?? "?"} (requested: ${ctrl.model ?? "default"}, mode: ${ctrl.mode ?? "default"}, effort: ${ctrl.effort ?? "default"}) — tools(${tools.length})`);
317
+ if (extraBlocks.length && !piggyback)
318
+ this.sendPrompt(t, extraBlocks);
319
+ // Calls that arrived while OpenCode ran the previous step go out now as the next one.
320
+ if (t.queuedItems.length) {
321
+ t.stepItems.push(...t.queuedItems);
322
+ t.queuedItems = [];
323
+ this.closeStep(t);
324
+ }
325
+ else if (t.doneResp && !(extraBlocks.length && !piggyback))
326
+ this.finishFromDone(t);
327
+ return;
311
328
  }
312
- if (!sessionId)
313
- throw new Error("failed to create or resume an ACP session");
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,
319
- host,
320
- idPrefix,
321
- sessionId,
322
- convKey,
323
- toolsKey,
324
- systemKey,
325
- cfgKey,
326
- ocSession,
327
- ocAgent: po.ocAgent ? String(po.ocAgent) : undefined,
328
- // Resume path: seed the cumulative usage snapshot from the persisted
329
- // registry so the first post-resume `subtractUsage` produces a real
330
- // turn delta instead of the full cumulative.
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),
335
- controller,
336
- pending: [],
337
- pendingTools: new Set(),
338
- pendingPermissions: new Map(),
339
- textId: null,
340
- reasoningId: null,
341
- cancelWatchdog: null,
342
- lastActive: Date.now(),
343
- };
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);
350
- if (ocSession)
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;
361
- this.connection
362
- .prompt({ sessionId, prompt: promptBlocks })
363
- .then((resp) => this.onPromptDone(started, resp))
364
- .catch((err) => this.onPromptError(started, err));
329
+ // Serialized per conversation: two calls racing for the same key (title + first
330
+ // turn in programmatic use, a retry) must not both create a session — the loser
331
+ // would be orphaned with its Claude Code process.
332
+ await this.withLock(this.convId(options), () => this.startFresh(controller, options, ref));
365
333
  }
366
334
  catch (err) {
367
335
  dbg(`onStart error: ${err instanceof Error ? err.message : String(err)}`);
@@ -380,6 +348,9 @@ export class ACPOrchestratorModel {
380
348
  * (independent) ACP stdio channel meanwhile — dropping them truncated answers and
381
349
  * hid the reasoning block entirely. */
382
350
  emit(t, part) {
351
+ if (t.hidden)
352
+ return; // native /compact chatter ("Compacting…") is not part of the answer
353
+ this.trackOwnText(t, part);
383
354
  if (t.controller) {
384
355
  try {
385
356
  t.controller.enqueue(part);
@@ -388,6 +359,609 @@ export class ACPOrchestratorModel {
388
359
  catch { /* closed underneath us */ }
389
360
  }
390
361
  t.pending.push(part);
362
+ // Cap anti-OOM: con el controller cerrado mucho rato `pending` crecería sin
363
+ // límite — se descartan los chunks más antiguos.
364
+ if (t.pending.length > MAX_PENDING_PARTS) {
365
+ t.pending.splice(0, t.pending.length - MAX_PENDING_PARTS);
366
+ dbg(`pending desbordado (>${MAX_PENDING_PARTS}) — descartados los más antiguos`);
367
+ }
368
+ }
369
+ /** A turn that is not a continuation: reuse the live session (append), or create /
370
+ * resume one. Runs under the conversation lock. */
371
+ async startFresh(controller, options, ref) {
372
+ await this.ensureConnected();
373
+ const tools = this.convertTools(options.tools);
374
+ const ctrl = this.effectiveCtrl(options);
375
+ const po = this.providerOptions(options);
376
+ const ocSession = po.ocSession;
377
+ const convKey = hashText(firstUserText(options.prompt));
378
+ const toolsKey = tools.map((x) => x.name).sort().join(",");
379
+ // The system prompt is part of the session identity ONLY when it actually
380
+ // travels. Under the default `preset` mode OpenCode's system is never sent
381
+ // (see buildSystemPromptMeta), so hashing it would tear the session down —
382
+ // and replay the whole history — every time OpenCode swaps agents or its
383
+ // dynamic blocks (date, AGENTS.md, skills) shift. The factual part of that
384
+ // system is forwarded separately as user context (see contextBlocks).
385
+ const systemMode = ctrl.systemPromptMode ?? "preset";
386
+ const systemKey = systemMode === "preset" ? "preset" : hashText(systemText(options.prompt));
387
+ // Params baked into newSession's _meta (thinking/systemPromptMode) can't change
388
+ // mid-session → a change forces a fresh session. mode/effort are applied at
389
+ // runtime via set_mode/set_config_option instead (no reset needed).
390
+ const cfgKey = profileKey(ctrl, systemMode);
391
+ const hist = historyOf(options.prompt);
392
+ const keys = hist.map((m) => msgKey(m));
393
+ // OpenCode's title/summary call arrives on the same model and session but with
394
+ // NO tools. Give it a throwaway session instead of letting it evict the real
395
+ // conversation. Only when the live conversation DOES have tools — a genuinely
396
+ // tool-less conversation (programmatic use) must keep reusing its own session.
397
+ const baseKey = ocSession ?? convKey;
398
+ const live = this.sessions.get(baseKey);
399
+ const key = tools.length === 0 && live && live.toolsKey !== "" ? `${baseKey}:notools` : baseKey;
400
+ const mode = this.historyMode(ctrl);
401
+ // OpenCode compacted (this session, or another model before switching back): the
402
+ // history now starts at its `<conversation-checkpoint>`.
403
+ const checkpoint = firstUserText(options.prompt).startsWith("<conversation-checkpoint>");
404
+ // An OpenCode compaction request: the live session holds the whole conversation
405
+ // with a warm cache — summarizing there costs a normal turn, not a cold replay of
406
+ // everything into a throwaway session.
407
+ if (po.requestKind === "compaction" && live && (await this.serveCompaction(live, controller, options, ref, mode)))
408
+ return;
409
+ let t = this.sessions.get(key);
410
+ if (t && t.convKey !== convKey) {
411
+ if (checkpoint && mode !== "legacy") {
412
+ this.decide(options, { decision: mode === "v2" ? "checkpoint-keep" : "shadow-checkpoint", session: t.sessionId, adopt: t.adoptCheckpoint });
413
+ }
414
+ // key reused for another conversation (or compacted, outside v2)
415
+ if (!(checkpoint && mode === "v2")) {
416
+ this.endTurn(t);
417
+ t = undefined;
418
+ }
419
+ }
420
+ // (2) Reuse the live session whenever we can — this is what keeps the cache warm.
421
+ if (t) {
422
+ let drop = null;
423
+ if (t.systemKey !== systemKey)
424
+ drop = "system prompt changed";
425
+ else if (t.cfgKey !== cfgKey) {
426
+ // Another agent profile (native tools, allowed tools, setting sources…): those are
427
+ // fixed at creation. Fork the live session with the new profile — same context,
428
+ // no replay — instead of starting over; only a failed fork falls back to that.
429
+ const cls = this.classify(t, hist, keys, ctrl);
430
+ if (cls.kind !== "append" || !(await this.forkInPlace(t, ctrl, tools, systemMode, options.prompt, cfgKey))) {
431
+ drop = "creation config changed";
432
+ }
433
+ }
434
+ if (!drop) {
435
+ // A changed tool set is applied to the LIVE session (MCP list_changed)
436
+ // rather than forcing a new one.
437
+ if (t.toolsKey !== toolsKey) {
438
+ t.host.setTools(tools);
439
+ t.host.notifyToolsChanged();
440
+ t.toolsKey = toolsKey;
441
+ dbg(`tools changed (${tools.length}) — refreshed in place, session kept`);
442
+ }
443
+ if (t.compacting)
444
+ await Promise.race([t.compacting, new Promise((r) => setTimeout(r, COMPACT_WAIT_MS))]);
445
+ let cls = this.classify(t, hist, keys, ctrl, options);
446
+ // v2: OpenCode's checkpoint replaced the history. Keep the session: either it
447
+ // compacted itself in step (adopt — only what follows the checkpoint is new), or
448
+ // another model ran meanwhile (its summary is what the agent hasn't seen).
449
+ let lead = [];
450
+ if (cls.kind !== "append" && checkpoint && mode === "v2" && t.convKey !== convKey) {
451
+ const adopt = t.adoptCheckpoint && hist.length > 1;
452
+ cls = { kind: "append", fromIndex: adopt ? 1 : 0 };
453
+ if (!adopt)
454
+ lead = [{ type: "text", text: CHECKPOINT_NOTE }];
455
+ t.convKey = convKey;
456
+ t.adoptCheckpoint = false;
457
+ }
458
+ // smartRevert: the user rewound to a message that opened a turn of this session →
459
+ // fork the session at Claude's state right before it. Nothing is replayed and the
460
+ // shared prefix stays cached; anything unexpected falls back to a new session.
461
+ if (cls.kind !== "append" && ctrl.smartRevert !== false) {
462
+ const at = classifyHistory(t.sentKeys, keys).fromIndex;
463
+ const cp = t.checkpoints.find((c) => c.at === at);
464
+ if (cp && (await this.forkInPlace(t, ctrl, tools, systemMode, options.prompt, cfgKey, { resumeSessionAt: cp.uuid }, "revert"))) {
465
+ this.markKnown(t, hist.slice(0, at));
466
+ t.checkpoints = t.checkpoints.filter((c) => c.at < at);
467
+ this.decide(options, { decision: "smart-revert", session: t.sessionId, at, uuid: cp.uuid });
468
+ cls = { kind: "append", fromIndex: at };
469
+ }
470
+ }
471
+ if (cls.kind !== "append") {
472
+ drop = cls.kind === "revert" ? "history reverted" : "history diverged (compaction/rollback)";
473
+ }
474
+ else {
475
+ const live = t;
476
+ ref.t = live;
477
+ dbg(`reuse session ${live.sessionId} — ${keys.length - cls.fromIndex} new msg(s) (cache-friendly)`);
478
+ // A fresh user turn: a prior turn that is still running or was abandoned
479
+ // (continuation never arrived) is stopped first, so it can neither hang the
480
+ // agent nor leak its leftovers into this answer.
481
+ if (live.inflight || live.pendingTools.size || live.pendingPermissions.size) {
482
+ this.abortTurn(live, "superseded by a new user turn");
483
+ await this.settle(live);
484
+ }
485
+ live.pending = [];
486
+ live.doneResp = null;
487
+ live.controller = controller;
488
+ live.lastActive = Date.now();
489
+ live.isChild = isChildCall(options);
490
+ if (ocSession)
491
+ live.ocSession = ocSession;
492
+ if (po.ocAgent)
493
+ live.ocAgent = String(po.ocAgent);
494
+ live.hasQuestion = typeof po.hasQuestion === "boolean" ? po.hasQuestion : undefined;
495
+ await this.applySessionConfig(live, ctrl);
496
+ // The tail opens with the agent's OWN previous answer (V2 stores it after we
497
+ // sent the prompt): it already has it, so it isn't sent back.
498
+ const rawTail = hist.slice(cls.fromIndex);
499
+ const tail = this.dropOwnLead(live, rawTail);
500
+ const blocks = [
501
+ ...this.contextBlocks(live, options.prompt, ctrl),
502
+ ...lead,
503
+ ...(tail.length ? this.blocksFor(tail, live) : rawTail.length ? [] : this.lastUserBlocks(options.prompt)),
504
+ ];
505
+ this.decide(options, {
506
+ decision: "reuse", session: live.sessionId, from: cls.fromIndex, sent: live.sentKeys.length,
507
+ keys: keys.length, tail: tail.length, ownSkipped: rawTail.length - tail.length, chars: blocksChars(blocks),
508
+ });
509
+ if (ctrl.smartRevert !== false)
510
+ this.recordCheckpoint(live, hist, cls.fromIndex);
511
+ this.markKnown(live, hist);
512
+ if (ocSession)
513
+ setLink(ocSession, live.sessionId, hist.length, convKey, live.ownPrefixes);
514
+ this.sendPrompt(live, blocks.length ? blocks : [{ type: "text", text: "" }]);
515
+ return;
516
+ }
517
+ }
518
+ dbg(`dropping session ${t.sessionId} — ${drop}`);
519
+ {
520
+ const at = this.classify(t, hist, keys, ctrl).fromIndex;
521
+ this.decide(options, {
522
+ decision: "drop", session: t.sessionId, reason: drop, at, sent: t.sentKeys.length, keys: keys.length,
523
+ sentKey: t.sentKeys[at], inKey: keys[at],
524
+ });
525
+ }
526
+ this.endTurn(t);
527
+ t = undefined;
528
+ }
529
+ // (3) Need a session: new conversation, or the history diverged, or a
530
+ // resumable session from a new process. Set up the MCP host once.
531
+ // Unique per-host prefix so minted toolCallIds NEVER collide with ids from a
532
+ // previous session still present in OpenCode's replayed history (a fresh host is
533
+ // created on every session reset). A random nonce is robust across resets, process
534
+ // restarts and resume — unlike a per-host counter, which restarts at 0.
535
+ const idPrefix = `acp_${randomBytes(5).toString("hex")}_`;
536
+ const host = new McpHost("opencode", idPrefix);
537
+ await host.start();
538
+ host.setTools(tools);
539
+ const serverConfig = host.getServerConfig();
540
+ // Try to RESUME a registered Claude Code session (new process, no live state,
541
+ // history grew rather than diverged) → no history replay (saves tokens). Else
542
+ // create a fresh session and replay the full history.
543
+ const resumeId = po.resumeId;
544
+ const resumeLen = typeof po.resumeLen === "number" ? po.resumeLen : 0;
545
+ const resumePrefixes = Array.isArray(po.resumeIdPrefixes) ? po.resumeIdPrefixes.map(String) : [];
546
+ let sessionId;
547
+ let replayFull = true;
548
+ // A registry entry for a DIFFERENT conversation (first message changed: compaction,
549
+ // or a reused id) must not be resumed — the agent would carry the wrong context.
550
+ const sameConv = !po.resumeConvKey || po.resumeConvKey === convKey;
551
+ if (!sameConv)
552
+ dbg(`resumeConvKey mismatch (registry=${po.resumeConvKey} current=${convKey}) — not resuming`);
553
+ if (resumeId && sameConv && resumeLen > 0 && hist.length > resumeLen) {
554
+ try {
555
+ await this.connection.unstable_resumeSession({
556
+ sessionId: resumeId,
557
+ cwd: this.config.cwd ?? process.cwd(),
558
+ mcpServers: [serverConfig],
559
+ // Re-apply the clean-brain options on resume too. Without this the agent
560
+ // falls back to its defaults (--tools default, --setting-sources=user,
561
+ // project,local, no --strict-mcp-config) and the resumed session regains
562
+ // native tools + the claude.ai connectors.
563
+ _meta: { claudeCode: { options: buildClaudeCodeOptions(ctrl) } },
564
+ });
565
+ sessionId = resumeId;
566
+ replayFull = false;
567
+ dbg(`resume ${resumeId} (oc=${ocSession ?? "?"}) — no history replay`);
568
+ }
569
+ catch (e) {
570
+ dbg(`resume ${resumeId} failed (${e instanceof Error ? e.message : String(e)}) — fresh session`);
571
+ }
572
+ }
573
+ if (!sessionId) {
574
+ // OpenCode's system prompt → _meta.systemPrompt (preset/append/replace).
575
+ const meta = { claudeCode: { options: buildClaudeCodeOptions(ctrl) } };
576
+ const sysMeta = this.buildSystemPromptMeta(options.prompt, systemMode);
577
+ if (sysMeta !== undefined)
578
+ meta.systemPrompt = sysMeta;
579
+ const session = await this.connection.newSession({
580
+ cwd: this.config.cwd ?? process.cwd(),
581
+ mcpServers: [serverConfig],
582
+ _meta: meta,
583
+ });
584
+ sessionId = session.sessionId;
585
+ dbg(`model=${session.models?.currentModelId ?? "?"} (requested: ${ctrl.model ?? "default"}, mode: ${ctrl.mode ?? "default"}, effort: ${ctrl.effort ?? "default"}) — tools(${tools.length})`);
586
+ }
587
+ if (!sessionId)
588
+ throw new Error("failed to create or resume an ACP session");
589
+ // The ACP sessionId IS the Claude Code session id: surfacing it lets the user
590
+ // pick the conversation back up natively.
591
+ note(`session ${sessionId}${replayFull ? "" : " (resumed)"} — retomable con: claude --resume ${sessionId}`);
592
+ t = {
593
+ key,
594
+ host,
595
+ idPrefix,
596
+ sessionId,
597
+ convKey,
598
+ toolsKey,
599
+ systemKey,
600
+ cfgKey,
601
+ ocSession,
602
+ ocAgent: po.ocAgent ? String(po.ocAgent) : undefined,
603
+ hasQuestion: typeof po.hasQuestion === "boolean" ? po.hasQuestion : undefined,
604
+ isChild: isChildCall(options),
605
+ // Resume path: carry the persisted snapshot over so the registry keeps a
606
+ // value even if the resumed session never completes another turn.
607
+ lastUsage: replayFull ? undefined : po.resumeLastUsage,
608
+ // Full replay covers the whole history; a bare resume only covers up to what
609
+ // the registry last recorded — the rest still needs sending below.
610
+ sentKeys: replayFull ? [] : keys.slice(0, resumeLen),
611
+ sentAnchors: replayFull ? [] : anchorsOf(hist.slice(0, resumeLen)).map((a) => a.key),
612
+ sentTransient: new Set(),
613
+ controller,
614
+ pending: [],
615
+ pendingTools: new Set(),
616
+ pendingPermissions: new Map(),
617
+ textId: null,
618
+ reasoningId: null,
619
+ ownPrefixes: [idPrefix, ...(replayFull ? [] : resumePrefixes)],
620
+ ownTexts: new Set(),
621
+ textAcc: new Map(),
622
+ stepText: "",
623
+ gen: 0,
624
+ inflight: null,
625
+ doneResp: null,
626
+ aborted: false,
627
+ stepItems: [],
628
+ stepTimer: null,
629
+ queuedItems: [],
630
+ nativeCalls: new Map(),
631
+ checkpoints: [],
632
+ compacting: null,
633
+ hidden: false,
634
+ adoptCheckpoint: false,
635
+ afterTurn: null,
636
+ lastActive: Date.now(),
637
+ };
638
+ ref.t = t;
639
+ host.onToolCall((c) => this.onToolCall(t, c));
640
+ host.onToolCancelled((id) => this.onToolCancelled(t, id));
641
+ this.sessions.set(key, t);
642
+ this.byAcpSession.set(sessionId, t);
643
+ this.evictIdleSessions();
644
+ this.startSweeper();
645
+ await this.applySessionConfig(t, ctrl);
646
+ if (ocSession)
647
+ setLink(ocSession, sessionId, hist.length, convKey, t.ownPrefixes);
648
+ // Resume: the registry may lag behind (process died mid-turn), and the agent's own
649
+ // last answer follows the recorded point — the resumed session already has it.
650
+ const tail = replayFull ? hist : this.dropOwnLead(t, hist.slice(resumeLen));
651
+ if (DEBUG && !replayFull)
652
+ dbg(`resume — catch-up ${tail.length} msg(s)`);
653
+ const promptBlocks = [
654
+ ...this.contextBlocks(t, options.prompt, ctrl),
655
+ ...(tail.length ? this.blocksFor(tail, t, replayFull ? "replay" : "tail") : [{ type: "text", text: "" }]),
656
+ ];
657
+ this.decide(options, {
658
+ decision: replayFull ? "new" : "resume", session: sessionId, keys: keys.length,
659
+ tail: tail.length, chars: blocksChars(promptBlocks),
660
+ });
661
+ this.markKnown(t, hist);
662
+ this.sendPrompt(t, promptBlocks);
663
+ }
664
+ /** Swap `t` onto a fork of its ACP session created with the current profile. The
665
+ * fork carries the whole transcript, so what `t` knows (sentKeys, own output) still
666
+ * holds; it gets its own MCP host. The old session is closed. */
667
+ async forkInPlace(t, ctrl, tools, systemMode, prompt, cfgKey, extra, why = "agent profile changed") {
668
+ if (t.inflight || t.pendingTools.size || t.pendingPermissions.size) {
669
+ this.abortTurn(t, why);
670
+ await this.settle(t);
671
+ }
672
+ const idPrefix = `acp_${randomBytes(5).toString("hex")}_`;
673
+ const host = new McpHost("opencode", idPrefix);
674
+ try {
675
+ await host.start();
676
+ host.setTools(tools);
677
+ const meta = { claudeCode: { options: { ...buildClaudeCodeOptions(ctrl), ...(extra ?? {}) } } };
678
+ const sysMeta = this.buildSystemPromptMeta(prompt, systemMode);
679
+ if (sysMeta !== undefined)
680
+ meta.systemPrompt = sysMeta;
681
+ const res = await this.connection.unstable_forkSession({
682
+ sessionId: t.sessionId,
683
+ cwd: this.config.cwd ?? process.cwd(),
684
+ mcpServers: [host.getServerConfig()],
685
+ _meta: meta,
686
+ });
687
+ if (!res?.sessionId)
688
+ throw new Error("fork returned no sessionId");
689
+ const old = { id: t.sessionId, host: t.host };
690
+ this.byAcpSession.delete(old.id);
691
+ t.sessionId = res.sessionId;
692
+ t.host = host;
693
+ t.idPrefix = idPrefix;
694
+ t.ownPrefixes = [idPrefix, ...t.ownPrefixes].slice(0, 8);
695
+ t.cfgKey = cfgKey;
696
+ t.appliedMode = undefined; // re-applied on the fork by applySessionConfig
697
+ t.appliedEffort = undefined;
698
+ t.appliedModel = undefined;
699
+ host.onToolCall((c) => this.onToolCall(t, c));
700
+ host.onToolCancelled((id) => this.onToolCancelled(t, id));
701
+ this.byAcpSession.set(t.sessionId, t);
702
+ old.host.stop();
703
+ this.closeAcpSession(old.id);
704
+ note(`session ${old.id} → fork ${t.sessionId} (${why}, context kept) — retomable con: claude --resume ${t.sessionId}`);
705
+ return true;
706
+ }
707
+ catch (e) {
708
+ host.stop();
709
+ dbg(`fork of ${t.sessionId} failed (${e instanceof Error ? e.message : String(e)}) — new session instead`);
710
+ return false;
711
+ }
712
+ }
713
+ /** Remember where this turn starts (index of its first user message) and Claude's
714
+ * last transcript entry before it. */
715
+ recordCheckpoint(t, hist, from) {
716
+ let at = from;
717
+ while (at < hist.length && hist[at].role !== "user")
718
+ at++;
719
+ if (at >= hist.length || t.checkpoints.some((c) => c.at === at))
720
+ return;
721
+ const uuid = this.lastAssistantUuid(t);
722
+ if (uuid)
723
+ t.checkpoints.push({ at, uuid });
724
+ }
725
+ /** uuid of the last main-thread assistant entry in the session's transcript
726
+ * (`<configDir>/projects/<cwd as slug>/<sessionId>.jsonl`), read from its tail. */
727
+ lastAssistantUuid(t) {
728
+ try {
729
+ const dir = resolveConfigDir(this.config.claudeCode ?? {}) ?? join(homedir(), ".claude");
730
+ const slug = (this.config.cwd ?? process.cwd()).replace(/[^a-zA-Z0-9]/g, "-");
731
+ const file = join(dir, "projects", slug, `${t.sessionId}.jsonl`);
732
+ const fd = openSync(file, "r");
733
+ try {
734
+ const size = fstatSync(fd).size;
735
+ const len = Math.min(size, 256 * 1024);
736
+ const buf = Buffer.alloc(len);
737
+ readSync(fd, buf, 0, len, size - len);
738
+ const lines = buf.toString("utf8").split("\n");
739
+ for (let i = lines.length - 1; i >= 0; i--) {
740
+ try {
741
+ const e = JSON.parse(lines[i]);
742
+ if (e?.type === "assistant" && typeof e.uuid === "string" && !e.isSidechain)
743
+ return e.uuid;
744
+ }
745
+ catch { /* partial first line */ }
746
+ }
747
+ }
748
+ finally {
749
+ closeSync(fd);
750
+ }
751
+ }
752
+ catch { /* no transcript (other configDir, agent not writing one) */ }
753
+ return undefined;
754
+ }
755
+ /** Free the agent-side session (its Claude Code process and MCP servers). The client
756
+ * SDK has no method for it; the agent implements `session/close`. */
757
+ closeAcpSession(sessionId) {
758
+ try {
759
+ Promise.resolve(this.connection?.extMethod?.("session/close", { sessionId })).catch(() => { });
760
+ }
761
+ catch { /* ignore */ }
762
+ }
763
+ /** Answer OpenCode's compaction request inside the live session (it already holds
764
+ * the conversation and its cache): only the summary instruction is sent. In v2 the
765
+ * session then compacts itself natively, so the checkpoint can be adopted next turn.
766
+ * Returns false when the session is busy (V2 can compact mid tool loop). */
767
+ async serveCompaction(t, controller, options, ref, mode) {
768
+ if (t.compacting)
769
+ await Promise.race([t.compacting, new Promise((r) => setTimeout(r, COMPACT_WAIT_MS))]);
770
+ if (t.inflight || t.pendingTools.size || t.pendingPermissions.size || t.queuedItems.length)
771
+ return false;
772
+ ref.t = t;
773
+ t.controller = controller;
774
+ t.pending = [];
775
+ t.doneResp = null;
776
+ t.lastActive = Date.now();
777
+ this.decide(options, { decision: "compaction-live", session: t.sessionId, mode });
778
+ t.afterTurn = mode === "v2" ? () => this.nativeCompact(t) : null;
779
+ this.sendPrompt(t, this.lastUserBlocks(options.prompt));
780
+ return true;
781
+ }
782
+ /** Native `/compact` of the live session, output hidden. */
783
+ nativeCompact(t) {
784
+ t.hidden = true;
785
+ const gen = ++t.gen;
786
+ const done = this.connection
787
+ .prompt({ sessionId: t.sessionId, prompt: [{ type: "text", text: "/compact" }] })
788
+ .then(() => { if (gen === t.gen)
789
+ t.adoptCheckpoint = true; }, (e) => dbg(`native /compact failed: ${errorText(e)}`))
790
+ .finally(() => {
791
+ t.hidden = false;
792
+ if (t.compacting === done)
793
+ t.compacting = null;
794
+ });
795
+ t.compacting = done;
796
+ }
797
+ async withLock(key, fn) {
798
+ const prev = this.locks.get(key) ?? Promise.resolve();
799
+ let release;
800
+ const mine = new Promise((r) => { release = r; });
801
+ const chained = prev.then(() => mine);
802
+ this.locks.set(key, chained);
803
+ await prev;
804
+ try {
805
+ return await fn();
806
+ }
807
+ finally {
808
+ release();
809
+ if (this.locks.get(key) === chained)
810
+ this.locks.delete(key);
811
+ }
812
+ }
813
+ /** Remember the text of every block we emit: OpenCode stores each block as one part of
814
+ * the assistant message it sends back next turn, which is how `dropOwnLead` knows the
815
+ * agent already has it. */
816
+ trackOwnText(t, part) {
817
+ switch (part.type) {
818
+ case "text-delta":
819
+ case "reasoning-delta":
820
+ t.textAcc.set(part.id, (t.textAcc.get(part.id) ?? "") + part.delta);
821
+ if (part.type === "text-delta")
822
+ t.stepText += part.delta;
823
+ break;
824
+ case "finish":
825
+ if (t.stepText.trim())
826
+ t.ownTexts.add(ownTextKey(t.stepText));
827
+ t.stepText = "";
828
+ break;
829
+ case "text-end":
830
+ case "reasoning-end": {
831
+ const text = t.textAcc.get(part.id);
832
+ t.textAcc.delete(part.id);
833
+ if (text)
834
+ t.ownTexts.add(ownTextKey(text));
835
+ if (t.ownTexts.size > MAX_OWN_TEXTS)
836
+ t.ownTexts.delete(t.ownTexts.values().next().value);
837
+ break;
838
+ }
839
+ }
840
+ }
841
+ isOwnId(t, id) {
842
+ const s = String(id ?? "");
843
+ return t.ownPrefixes.some((p) => s.startsWith(p));
844
+ }
845
+ /** Strip the agent's own output from the head of a tail: the assistant/tool messages
846
+ * before the next user message, as long as they carry only our ids and (when this
847
+ * process emitted them) only text we emitted. A message that fails the check — another
848
+ * model's turn — stops the skip, so it still reaches the agent. After a restart there
849
+ * is no emitted text to compare, and the position alone decides. */
850
+ dropOwnLead(t, tail) {
851
+ let i = 0;
852
+ for (; i < tail.length; i++) {
853
+ const m = tail[i];
854
+ if (m.role === "user" || m.role === "system" || !Array.isArray(m.content))
855
+ break;
856
+ const joined = m.content.filter((p) => p?.type === "text").map((p) => String(p.text ?? "")).join("");
857
+ const wholeOwn = !!joined.trim() && t.ownTexts.has(ownTextKey(joined));
858
+ const own = m.content.every((p) => {
859
+ if (p?.type === "tool-call" || p?.type === "tool-result")
860
+ return this.isOwnId(t, p.toolCallId);
861
+ if (p?.type === "text" || p?.type === "reasoning") {
862
+ const text = String(p.text ?? "");
863
+ return !text.trim() || t.ownTexts.size === 0 || t.ownTexts.has(ownTextKey(text)) || (p.type === "text" && wholeOwn);
864
+ }
865
+ return true;
866
+ });
867
+ if (!own)
868
+ break;
869
+ }
870
+ return tail.slice(i);
871
+ }
872
+ /** Everything in `hist` is now known to the agent (both fingerprints). */
873
+ markKnown(t, hist) {
874
+ t.sentKeys = hist.map((m) => msgKey(m));
875
+ t.sentAnchors = anchorsOf(hist).map((a) => a.key);
876
+ }
877
+ historyMode(ctrl) {
878
+ return ctrl.historyMode ?? process.env.ACP_HISTORY_MODE ?? "shadow";
879
+ }
880
+ /** Legacy per-message keys or anchors, per `historyMode`. In `shadow` (the default
881
+ * while the anchor fingerprint proves itself on real sessions) both are computed, the
882
+ * legacy one decides, and every disagreement is logged for review. */
883
+ classify(t, hist, keys, ctrl, options) {
884
+ const mode = this.historyMode(ctrl);
885
+ const legacy = classifyHistory(t.sentKeys, keys);
886
+ if (mode === "legacy")
887
+ return legacy;
888
+ const anchors = classifyAnchors(t.sentAnchors, anchorsOf(hist));
889
+ // Cut points are comparable only for appends (for a divergence each scheme reports a
890
+ // different landmark), so only a different kind — or a different cut — is evidence.
891
+ const differs = legacy.kind !== anchors.kind || (legacy.kind === "append" && legacy.fromIndex !== anchors.fromIndex);
892
+ if (options && differs) {
893
+ this.decide(options, {
894
+ decision: "shadow-diff", mode, session: t.sessionId,
895
+ legacy: `${legacy.kind}@${legacy.fromIndex}`, anchors: `${anchors.kind}@${anchors.fromIndex}`,
896
+ legacyKey: [t.sentKeys[legacy.fromIndex], keys[legacy.fromIndex]],
897
+ });
898
+ }
899
+ return mode === "v2" ? anchors : legacy;
900
+ }
901
+ /** Send a prompt as the session's newest generation. Completions of older ones — a
902
+ * cancelled turn, or the original prompt the agent resolves early when it merges a
903
+ * queued one — are ignored instead of closing the stream of the current turn. */
904
+ sendPrompt(t, blocks) {
905
+ const gen = ++t.gen;
906
+ t.aborted = false;
907
+ t.doneResp = null;
908
+ const settled = this.connection
909
+ .prompt({ sessionId: t.sessionId, prompt: blocks })
910
+ .then((resp) => {
911
+ if (gen === t.gen)
912
+ this.onPromptDone(t, resp);
913
+ else
914
+ dbg(`stale prompt completion ignored (gen ${gen} < ${t.gen}, ${resp?.stopReason})`);
915
+ }, (err) => {
916
+ if (gen === t.gen)
917
+ this.onPromptError(t, err);
918
+ else
919
+ dbg(`stale prompt error ignored (gen ${gen} < ${t.gen})`);
920
+ })
921
+ .then(() => { if (t.inflight === settled)
922
+ t.inflight = null; });
923
+ t.inflight = settled;
924
+ }
925
+ /** Wait (bounded) for the running prompt to settle — e.g. after a cancel. */
926
+ async settle(t, ms = SETTLE_MS) {
927
+ const p = t.inflight;
928
+ if (!p)
929
+ return;
930
+ let timer;
931
+ await Promise.race([p, new Promise((r) => { timer = setTimeout(r, ms); })]);
932
+ clearTimeout(timer);
933
+ }
934
+ /** Stop the current turn for good: cancel it agent-side, unblock everything it waits
935
+ * on (deferred tool calls, bridged permissions) and drop what it still produces. */
936
+ abortTurn(t, why) {
937
+ dbg(`abort turn of ${t.sessionId} (${why})`);
938
+ t.aborted = true;
939
+ try {
940
+ this.connection?.cancel?.({ sessionId: t.sessionId });
941
+ }
942
+ catch { /* ignore */ }
943
+ for (const id of t.pendingTools)
944
+ t.host.rejectToolCall(id, "Tool execution interrupted by the user");
945
+ t.pendingTools.clear();
946
+ this.drainPermissions(t);
947
+ t.controller = null;
948
+ t.textId = null;
949
+ t.reasoningId = null;
950
+ t.textAcc.clear();
951
+ t.pending = [];
952
+ t.doneResp = null;
953
+ if (t.stepTimer) {
954
+ clearTimeout(t.stepTimer);
955
+ t.stepTimer = null;
956
+ }
957
+ t.stepItems = [];
958
+ t.queuedItems = [];
959
+ }
960
+ /** The prompt completed while no stream was attached: close the current one with it. */
961
+ finishFromDone(t) {
962
+ const resp = t.doneResp;
963
+ t.doneResp = null;
964
+ this.onPromptDone(t, resp);
391
965
  }
392
966
  flushPending(t) {
393
967
  if (!t.controller || t.pending.length === 0)
@@ -403,53 +977,173 @@ export class ACPOrchestratorModel {
403
977
  }
404
978
  }
405
979
  onPromptDone(t, resp) {
406
- if (!t.controller)
407
- return; // cut for a pending tool-call
980
+ if (!t.controller) {
981
+ // Finished while detached. After an abort that's just the cancellation landing;
982
+ // otherwise keep it, so the next stream of this turn can still be finished.
983
+ if (!t.aborted && resp?.stopReason !== "cancelled")
984
+ t.doneResp = resp;
985
+ return;
986
+ }
987
+ if (t.stepItems.length) {
988
+ this.closeStep(t);
989
+ t.doneResp = resp;
990
+ return;
991
+ }
408
992
  this.closeBlocks(t);
409
993
  this.flushPending(t);
410
- const turn = subtractUsage(resp?.usage, t.lastUsage); // ACP usage is cumulative per session
411
- if (resp?.usage) {
412
- t.lastUsage = resp.usage;
994
+ const turn = resp?.usage; // sum over the turn's requests (see usageNow)
995
+ if (turn) {
996
+ t.lastUsage = turn;
413
997
  if (t.ocSession)
414
- updateUsage(t.ocSession, resp.usage); // survive process restarts
998
+ updateUsage(t.ocSession, turn); // survive process restarts
415
999
  }
416
1000
  if (DEBUG && turn)
417
1001
  dbg(`usage(turn): in=${turn.inputTokens} out=${turn.outputTokens} cacheR=${turn.cachedReadTokens} cacheW=${turn.cachedWriteTokens}`);
1002
+ const finish = {
1003
+ type: "finish",
1004
+ usage: this.usageNow(t, turn),
1005
+ finishReason: { unified: resp?.stopReason === "max_tokens" ? "length" : "stop", raw: resp?.stopReason },
1006
+ };
1007
+ this.trackOwnText(t, finish);
418
1008
  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
- });
1009
+ t.controller.enqueue(finish);
424
1010
  t.controller.close();
425
1011
  }
426
1012
  catch { /* ignore */ }
427
1013
  t.controller = null; // keep the session for the next turn (delta)
1014
+ t.lastActive = Date.now();
1015
+ const after = t.afterTurn;
1016
+ t.afterTurn = null;
1017
+ after?.();
1018
+ // A tool-less side call (title/summary in programmatic use) never continues.
1019
+ if (t.key.endsWith(":notools"))
1020
+ queueMicrotask(() => this.endTurn(t));
428
1021
  }
429
1022
  onPromptError(t, err) {
1023
+ // The agent dropped the session (its Claude Code process died): talking to it again
1024
+ // would fail every turn. Forget it here; the next turn resumes the transcript.
1025
+ if (/process exited unexpectedly|session not found/i.test(errorText(err))) {
1026
+ note(`session ${t.sessionId} lost agent-side — the next turn resumes it`);
1027
+ queueMicrotask(() => this.endTurn(t));
1028
+ }
430
1029
  if (!t.controller)
431
1030
  return;
432
- dbg(`prompt error: ${err instanceof Error ? err.message : String(err)}`);
1031
+ dbg(`prompt error: ${errorText(err)}`);
433
1032
  try {
434
- t.controller.enqueue({ type: "error", error: err });
1033
+ t.controller.enqueue({ type: "error", error: limitError(err) ?? err });
435
1034
  t.controller.close();
436
1035
  }
437
1036
  catch { /* ignore */ }
438
1037
  t.controller = null;
439
1038
  }
440
- /** Fired by the MCP host when the agent calls an OpenCode tool. */
1039
+ /** Fired by the MCP host when the agent calls an OpenCode tool. The call is NOT
1040
+ * resolved here: it waits for OpenCode to run the tool and send the continuation. */
441
1041
  onToolCall(t, call) {
442
- if (!t.controller)
1042
+ if (t.aborted) {
1043
+ t.host.rejectToolCall(call.toolCallId, "Turn aborted");
443
1044
  return;
1045
+ }
444
1046
  dbg(`agent → tool-call ${call.name} (${call.toolCallId}) → emit to OpenCode`);
445
- this.closeBlocks(t);
446
1047
  t.pendingTools.add(call.toolCallId);
447
- const inputJson = JSON.stringify(call.args ?? {});
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" } });
1048
+ // `call.args` puede traer refs circulares/BigInt → JSON.stringify lanzaría y
1049
+ // tumbaría el turno: degradar a marcador en vez de crashear.
1050
+ let inputJson;
1051
+ try {
1052
+ inputJson = JSON.stringify(call.args ?? {});
1053
+ }
1054
+ catch (e) {
1055
+ dbg(`tool-call ${call.name}: args no serializables (${e instanceof Error ? e.message : String(e)}) — input="<serialization error>"`);
1056
+ inputJson = '"<serialization error>"';
1057
+ }
1058
+ this.addStepItem(t, { id: call.toolCallId, toolName: call.name, input: inputJson, parallel: this.parallelTools().includes(call.name) });
1059
+ }
1060
+ /** The agent cancelled a call: if OpenCode hasn't been given it yet, it never will be.
1061
+ * (An already emitted one stays pending so its continuation is still recognised.) */
1062
+ onToolCancelled(t, toolCallId) {
1063
+ const queued = (items) => items.filter((it) => it.id !== toolCallId);
1064
+ const before = t.queuedItems.length + t.stepItems.length;
1065
+ t.queuedItems = queued(t.queuedItems);
1066
+ t.stepItems = queued(t.stepItems);
1067
+ if (t.queuedItems.length + t.stepItems.length < before)
1068
+ t.pendingTools.delete(toolCallId);
1069
+ dbg(`agent cancelled tool-call ${toolCallId}`);
1070
+ }
1071
+ parallelTools() {
1072
+ return this.config.claudeCode?.parallelTools ?? PARALLEL_TOOLS;
1073
+ }
1074
+ /** Collect a call into the current step. Serial tools close the step at once; a
1075
+ * read-only one waits TOOL_BATCH_MS for the siblings Claude Code issues in parallel,
1076
+ * so OpenCode gets them in ONE step and runs them in parallel too. With no stream
1077
+ * attached the call is queued for the next continuation — never dropped. */
1078
+ addStepItem(t, item) {
1079
+ if (!t.controller) {
1080
+ t.queuedItems.push(item);
1081
+ return;
1082
+ }
1083
+ t.stepItems.push(item);
1084
+ if (!item.parallel) {
1085
+ this.closeStep(t);
1086
+ return;
1087
+ }
1088
+ if (!t.stepTimer) {
1089
+ t.stepTimer = setTimeout(() => this.closeStep(t), this.config.claudeCode?.toolBatchMs ?? TOOL_BATCH_MS);
1090
+ t.stepTimer.unref?.();
1091
+ }
1092
+ }
1093
+ /** Usage for a `finish`: the CURRENT context size (OpenCode reads input + cache +
1094
+ * output of the last step as the prompt size when deciding to compact), split into
1095
+ * cache read/write/no-cache with the ratios of the turn's totals. The turn totals
1096
+ * themselves are a sum over all its requests — reporting them inflated the context
1097
+ * N-fold and triggered compactions early. */
1098
+ usageNow(t, turn) {
1099
+ const used = t.contextUsed;
1100
+ if (used === undefined)
1101
+ return turn ? mapUsage(turn) : emptyUsage(); // agent without usage_update
1102
+ if (used === 0) {
1103
+ // just compacted: tiny but non-zero, so OpenCode keeps this step as its anchor
1104
+ return { inputTokens: { total: 1, noCache: 1, cacheRead: 0, cacheWrite: 0 }, outputTokens: { total: 0, text: 0 } };
1105
+ }
1106
+ const ratios = turn ?? t.lastUsage ?? {};
1107
+ const out = Math.min(turn?.outputTokens ?? 0, used);
1108
+ const input = used - out;
1109
+ const nc = ratios.inputTokens ?? 0, cr = ratios.cachedReadTokens ?? 0, cw = ratios.cachedWriteTokens ?? 0;
1110
+ const all = nc + cr + cw;
1111
+ const cacheRead = all ? Math.round((input * cr) / all) : 0;
1112
+ const cacheWrite = all ? Math.round((input * cw) / all) : 0;
1113
+ return {
1114
+ inputTokens: { total: input, noCache: Math.max(0, input - cacheRead - cacheWrite), cacheRead, cacheWrite },
1115
+ outputTokens: { total: out, text: out },
1116
+ };
1117
+ }
1118
+ /** Emit the collected calls and end the stream with ONE `tool-calls` finish (OpenCode
1119
+ * rejects a second finish in a step). */
1120
+ closeStep(t) {
1121
+ if (t.stepTimer) {
1122
+ clearTimeout(t.stepTimer);
1123
+ t.stepTimer = null;
1124
+ }
1125
+ const items = t.stepItems;
1126
+ t.stepItems = [];
1127
+ if (!items.length)
1128
+ return;
1129
+ if (!t.controller) {
1130
+ t.queuedItems.push(...items);
1131
+ return;
1132
+ }
1133
+ this.closeBlocks(t);
1134
+ for (const it of items) {
1135
+ if (it.preface) {
1136
+ const id = `plan${++this.idSeq}`;
1137
+ this.emit(t, { type: "text-start", id });
1138
+ this.emit(t, { type: "text-delta", id, delta: it.preface });
1139
+ this.emit(t, { type: "text-end", id });
1140
+ }
1141
+ this.emit(t, { type: "tool-input-start", id: it.id, toolName: it.toolName });
1142
+ this.emit(t, { type: "tool-input-delta", id: it.id, delta: it.input });
1143
+ this.emit(t, { type: "tool-input-end", id: it.id });
1144
+ this.emit(t, { type: "tool-call", toolCallId: it.id, toolName: it.toolName, input: it.input });
1145
+ }
1146
+ this.emit(t, { type: "finish", usage: this.usageNow(t), finishReason: { unified: "tool-calls", raw: "tool_use" } });
453
1147
  try {
454
1148
  t.controller?.close();
455
1149
  }
@@ -502,56 +1196,119 @@ export class ACPOrchestratorModel {
502
1196
  .filter(Boolean)
503
1197
  .join("\n");
504
1198
  }
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). */
1199
+ /** ACP requestPermission → the agent's own rules first, then the `question` dialog.
1200
+ * Deferred: returns a Promise the agent awaits until the verdict comes back as
1201
+ * the `question` tool-result (resolved in onStart's continuation branch). */
508
1202
  onRequestPermission(params) {
509
1203
  const t = this.byAcpSession.get(String(params?.sessionId ?? ""));
510
- // No live turn/controller → approve so the agent never hangs.
511
- if (!t || !t.controller)
1204
+ // Sin turno vivo (crash/reinicio, turno abortado) — denegar es más seguro que aprobar
1205
+ // a ciegas. Con el stream cerrado por un paso de tools, la pregunta se encola.
1206
+ if (!t || t.aborted)
1207
+ return Promise.resolve(this.permOutcome(params, false));
1208
+ const toolCall = params?.toolCall;
1209
+ const native = this.permToolName(toolCall);
1210
+ const target = this.bridgeTarget(toolCall);
1211
+ const agent = t.ocAgent ?? "default";
1212
+ // (1) allow/deny rules answer outright — no dialog, same as a native tool
1213
+ // OpenCode would resolve itself.
1214
+ const rules = evaluateBridge(agent, native, target.pattern);
1215
+ dbg(`requestPermission(${native} → ${target.pattern}) agent=${agent} rules=${rules}`);
1216
+ if (rules === "allow")
512
1217
  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})`);
1218
+ if (rules === "deny")
1219
+ return Promise.resolve(this.permOutcome(params, false));
1220
+ // An agent without `question` (OpenCode's `general` subagent denies it) can't show
1221
+ // the dialog: the call would just fail. Deny now, with nothing left hanging.
1222
+ if (t.hasQuestion === false) {
1223
+ dbg(`requestPermission(${native}) → denied: agent ${agent} has no question tool`);
1224
+ return Promise.resolve(this.permOutcome(params, false));
1225
+ }
1226
+ // (2) "ask": raise a `question` dialog and wait for its tool-result.
1227
+ // Own prefix: unique across processes (a bare counter restarts at 0 and collided
1228
+ // with old `perm_N` answers still in the history) and recognised as own traffic.
1229
+ const callId = `${t.idPrefix}perm_${++this.idSeq}`;
1230
+ dbg(`requestPermission(${native}) → bridge as question (${callId})`);
1231
+ if (toolCall?.kind === "switch_mode")
1232
+ return this.askPlanApproval(t, callId, params);
515
1233
  return new Promise((resolve) => {
516
- t.pendingPermissions.set(callId, (approved) => resolve(this.permOutcome(params, approved)));
517
- this.emitPermissionCall(t, callId, params?.toolCall);
1234
+ t.pendingPermissions.set(callId, (output) => {
1235
+ const verdict = this.questionVerdict(output);
1236
+ if (verdict.approved && verdict.always && target.always)
1237
+ addAlwaysRule(agent, native, target.always);
1238
+ resolve(this.permOutcome(params, verdict.approved));
1239
+ });
1240
+ this.emitPermissionCall(t, callId, toolCall, native, target);
518
1241
  });
519
1242
  }
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)
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
- }
1243
+ /** ExitPlanMode: offer the agent's OWN choices (auto / accept edits / approve each
1244
+ * edit / keep planning) instead of a generic allow/deny that always meant "approve
1245
+ * each edit". A typed answer means "keep planning, and here's why": the plan is
1246
+ * rejected and the text reaches the agent as a message, so it revises the plan. */
1247
+ askPlanApproval(t, callId, params) {
1248
+ const options = (params?.options ?? []).filter((o) => o?.optionId && o?.name);
1249
+ const reject = options.find((o) => o.kind === "reject_once" || o.kind === "reject_always");
539
1250
  const input = JSON.stringify({
540
- tool: this.permToolName(toolCall),
541
- kind: toolCall?.kind,
542
- title: toolCall?.title,
543
- input: toolCall?.rawInput,
1251
+ questions: [{
1252
+ question: "Approve the plan above?",
1253
+ header: "Plan",
1254
+ options: options.map((o) => ({
1255
+ label: String(o.name),
1256
+ description: o.optionId === "plan" ? "Reject and keep refining the plan (or type what to change)" : `Approve; session mode → ${o.optionId}`,
1257
+ })),
1258
+ }],
544
1259
  });
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;
1260
+ return new Promise((resolve) => {
1261
+ t.pendingPermissions.set(callId, (output) => {
1262
+ const picked = this.isErrorOutput(output) ? undefined : this.answerLabel(output);
1263
+ const norm = this.normalizeAnswer(picked ?? "");
1264
+ const match = norm ? options.find((o) => this.normalizeAnswer(String(o.name)) === norm) : undefined;
1265
+ if (match) {
1266
+ resolve({ outcome: { outcome: "selected", optionId: match.optionId } });
1267
+ return;
1268
+ }
1269
+ resolve(reject ? { outcome: { outcome: "selected", optionId: reject.optionId } } : { outcome: { outcome: "cancelled" } });
1270
+ const feedback = String(picked ?? "").trim();
1271
+ if (feedback && !t.aborted)
1272
+ this.sendPrompt(t, [{ type: "text", text: `Feedback on the proposed plan — keep planning and revise it:\n${feedback}` }]);
1273
+ });
1274
+ this.addStepItem(t, { id: callId, toolName: "question", input, preface: this.planText(params?.toolCall) || undefined });
1275
+ });
1276
+ }
1277
+ /** Action target of a native request (command / skill / path), plus the glob an
1278
+ * "Always allow" would persist. Shell commands collapse to their first token
1279
+ * (`git status` → `git *`); a request with no real target persists nothing, so
1280
+ * the dialog never offers a broad rule that would auto-approve everything. */
1281
+ bridgeTarget(toolCall) {
1282
+ const raw = toolCall?.rawInput;
1283
+ const inp = raw && typeof raw === "object" ? raw : {};
1284
+ const text = String((inp.command ?? inp.skill ?? inp.name ?? inp.notebook_path ?? inp.file_path ?? inp.path) ||
1285
+ (typeof raw === "string" ? raw : "") ||
1286
+ toolCall?.title ||
1287
+ "").trim();
1288
+ const always = toolCall?.kind === "execute" && text.includes(" ") ? `${text.split(/\s+/)[0]} *` : text || undefined;
1289
+ return { pattern: text || "*", always };
1290
+ }
1291
+ /** Emit a `question` tool-call to OpenCode (same deferred pattern as a real
1292
+ * tool-call): the native tool's request becomes a dialog — Allow once /
1293
+ * Always allow / Deny — and the answer arrives as the tool-result on the next
1294
+ * doStream. The agent itself only ever sees the ACP permission outcome. */
1295
+ emitPermissionCall(t, callId, toolCall, native, target) {
1296
+ const input = JSON.stringify({
1297
+ questions: [
1298
+ {
1299
+ question: `${native}: ${toolCall?.title ?? target.pattern}`,
1300
+ header: "Permission",
1301
+ options: [
1302
+ { label: ALLOW_ONCE, description: "Approve this action for this call only" },
1303
+ ...(target.always
1304
+ ? [{ label: ALWAYS_ALLOW, description: `Approve and stop asking for ${target.always}` }]
1305
+ : []),
1306
+ { label: DENY, description: "Block this action" },
1307
+ ],
1308
+ },
1309
+ ],
1310
+ });
1311
+ this.addStepItem(t, { id: callId, toolName: "question", input });
555
1312
  }
556
1313
  /** Fired by the ACP client on session/update. */
557
1314
  onSessionUpdate(params) {
@@ -579,6 +1336,10 @@ export class ACPOrchestratorModel {
579
1336
  return;
580
1337
  }
581
1338
  switch (update?.sessionUpdate) {
1339
+ case "usage_update":
1340
+ if (typeof update.used === "number")
1341
+ t.contextUsed = update.used;
1342
+ break;
582
1343
  case "agent_message_chunk":
583
1344
  if (update.content?.type === "text") {
584
1345
  if (!t.textId) {
@@ -597,10 +1358,63 @@ export class ACPOrchestratorModel {
597
1358
  this.emit(t, { type: "reasoning-delta", id: t.reasoningId, delta: update.content.text });
598
1359
  }
599
1360
  break;
1361
+ case "tool_call":
1362
+ case "tool_call_update":
1363
+ this.onNativeTool(t, update);
1364
+ break;
600
1365
  default:
601
- break; // tool_call/tool_call_update are informational; MCP host drives emission
1366
+ break;
602
1367
  }
603
1368
  }
1369
+ /** Native Claude Code tools run INSIDE the agent: OpenCode never sees them, so after a
1370
+ * switch to another model what Claude read, searched or delegated was simply gone.
1371
+ * Each one that completes is written into the answer as a short text block — plain
1372
+ * text, the only form every model accepts (tools marked provider-executed would be
1373
+ * replayed to other providers as calls they don't know). OpenCode's own tools
1374
+ * (mcp__opencode__*) are skipped: they're already in the history. */
1375
+ onNativeTool(t, u) {
1376
+ const mode = this.config.claudeCode?.nativeActivity ?? "text";
1377
+ if (mode === "off" || !u?.toolCallId)
1378
+ return;
1379
+ const meta = u._meta?.claudeCode ?? {};
1380
+ const prev = t.nativeCalls.get(u.toolCallId) ?? {};
1381
+ const call = {
1382
+ toolName: meta.toolName ?? prev.toolName,
1383
+ title: (typeof u.title === "string" && u.title) || prev.title,
1384
+ parent: meta.parentToolUseId ?? prev.parent,
1385
+ };
1386
+ t.nativeCalls.set(u.toolCallId, call);
1387
+ if (u.status !== "completed" && u.status !== "failed")
1388
+ return;
1389
+ t.nativeCalls.delete(u.toolCallId);
1390
+ const name = String(call.toolName ?? "");
1391
+ if (!name || name.startsWith("mcp__") || NATIVE_SILENT.has(name))
1392
+ return;
1393
+ const result = NATIVE_WITH_RESULT.has(name) ? this.nativeResultText(u) : "";
1394
+ const cap = this.config.claudeCode?.nativeActivityChars ?? NATIVE_RESULT_CHARS;
1395
+ const body = result.length > cap ? `${result.slice(0, cap)}…[truncated, ${result.length} chars]` : result;
1396
+ const head = `${call.parent ? " ↳ " : ""}⚙ ${name}${call.title && call.title !== name ? `: ${call.title}` : ""}${u.status === "failed" ? " — failed" : ""}`;
1397
+ const id = `n${++this.idSeq}`;
1398
+ this.closeBlocks(t);
1399
+ this.emit(t, { type: "text-start", id });
1400
+ this.emit(t, { type: "text-delta", id, delta: `\n${head}\n${body ? `\n\`\`\`text\n${body}\n\`\`\`\n` : ""}` });
1401
+ this.emit(t, { type: "text-end", id });
1402
+ }
1403
+ nativeResultText(u) {
1404
+ const content = Array.isArray(u.content) ? u.content : [];
1405
+ const text = content
1406
+ .map((c) => (c?.type === "content" && c.content?.type === "text" ? c.content.text : typeof c?.text === "string" ? c.text : ""))
1407
+ .filter(Boolean)
1408
+ .join("\n");
1409
+ if (text)
1410
+ return text.trim();
1411
+ const raw = u.rawOutput;
1412
+ if (typeof raw === "string")
1413
+ return raw.trim();
1414
+ if (Array.isArray(raw))
1415
+ return raw.map((x) => (typeof x?.text === "string" ? x.text : "")).join("\n").trim();
1416
+ return "";
1417
+ }
604
1418
  closeBlocks(t) {
605
1419
  if (t.textId) {
606
1420
  this.emit(t, { type: "text-end", id: t.textId });
@@ -612,7 +1426,6 @@ export class ACPOrchestratorModel {
612
1426
  }
613
1427
  }
614
1428
  endTurn(t) {
615
- this.clearCancelWatchdog(t);
616
1429
  // Settle any deferred permission requests (deny/cancel) so the agent never
617
1430
  // stays blocked awaiting a verdict that will no longer arrive.
618
1431
  this.drainPermissions(t);
@@ -622,6 +1435,9 @@ export class ACPOrchestratorModel {
622
1435
  }
623
1436
  catch { /* ignore */ }
624
1437
  t.host.stop();
1438
+ // Without this the agent keeps the session — and its `claude` process — forever.
1439
+ if (this.connection && t.sessionId)
1440
+ this.closeAcpSession(t.sessionId);
625
1441
  if (this.sessions.get(t.key) === t)
626
1442
  this.sessions.delete(t.key);
627
1443
  this.byAcpSession.delete(t.sessionId);
@@ -629,12 +1445,13 @@ export class ACPOrchestratorModel {
629
1445
  /** Keep at most MAX_LIVE_SESSIONS conversations alive; tear down the oldest idle ones
630
1446
  * (never one with work in flight) so hosts and agent sessions don't pile up. */
631
1447
  evictIdleSessions() {
632
- if (this.sessions.size <= MAX_LIVE_SESSIONS)
1448
+ const max = this.config.claudeCode?.maxLiveSessions ?? MAX_LIVE_SESSIONS;
1449
+ if (this.sessions.size <= max)
633
1450
  return;
634
1451
  const idle = [...this.sessions.values()]
635
1452
  .filter((s) => !s.controller && s.pendingTools.size === 0 && s.pendingPermissions.size === 0)
636
1453
  .sort((a, b) => a.lastActive - b.lastActive);
637
- while (this.sessions.size > MAX_LIVE_SESSIONS && idle.length) {
1454
+ while (this.sessions.size > max && idle.length) {
638
1455
  const victim = idle.shift();
639
1456
  dbg(`evicting idle session ${victim.sessionId} (LRU)`);
640
1457
  this.endTurn(victim);
@@ -644,18 +1461,46 @@ export class ACPOrchestratorModel {
644
1461
  drainPermissions(t) {
645
1462
  if (t.pendingPermissions.size === 0)
646
1463
  return;
1464
+ const abandoned = { type: "error-text", value: "Permission request abandoned" };
647
1465
  for (const resolve of [...t.pendingPermissions.values()]) {
648
1466
  try {
649
- resolve(false);
1467
+ resolve(abandoned);
650
1468
  }
651
1469
  catch { /* ignore */ }
652
1470
  }
653
1471
  t.pendingPermissions.clear();
654
1472
  }
1473
+ /** Per-call provider options: V2 nests them under `providerOptionKey(package,
1474
+ * providerID)` = the providerID. El fallback al primer objeto del mapa sería
1475
+ * voraz (podría tomar opciones de OTRO provider): solo se acepta si la key
1476
+ * contiene nuestro provider id (`acp`) o el objeto trae forma conocida
1477
+ * (ocSession/ocAgent/resumeId/…/mode/effort/native*); si no, como ausente. */
1478
+ providerOptions(options) {
1479
+ const all = (options.providerOptions ?? {});
1480
+ const own = all[this.provider];
1481
+ if (own && typeof own === "object")
1482
+ return own;
1483
+ const SHAPE_KEYS = new Set([
1484
+ "ocSession", "ocAgent", "resumeId", "resumeLen", "resumeConvKey", "resumeLastUsage", "resumeIdPrefixes",
1485
+ "requestKind", "hasQuestion",
1486
+ "mode", "effort", "thinking", "systemPromptMode", "forwardEnvContext",
1487
+ "tools", "allowedTools", "disallowedTools", "settingSources", "strictMcpConfig",
1488
+ "nativeTools", "resourceSearch", "nativeSubagents", "nativeSkills", "projectMemory", "skillShell",
1489
+ ]);
1490
+ for (const [key, value] of Object.entries(all)) {
1491
+ if (!value || typeof value !== "object" || Array.isArray(value))
1492
+ continue;
1493
+ if (String(key).toLowerCase().includes(this.provider))
1494
+ return value;
1495
+ if (Object.keys(value).some((k) => SHAPE_KEYS.has(k) || k.startsWith("native")))
1496
+ return value;
1497
+ }
1498
+ return {};
1499
+ }
655
1500
  /** Provider config overlaid with per-call `providerOptions.acp` (per-agent mode/effort/…). */
656
1501
  effectiveCtrl(options) {
657
1502
  const ctrl = { ...(this.config.claudeCode ?? {}) };
658
- const po = options.providerOptions?.[this.provider];
1503
+ const po = this.providerOptions(options);
659
1504
  if (po && typeof po === "object") {
660
1505
  // Per-agent overrides from `agent.<name>.options` (→ providerOptions.acp):
661
1506
  // mode/effort/reasoning plus the native-feature toggles.
@@ -669,18 +1514,34 @@ export class ACPOrchestratorModel {
669
1514
  ctrl[k] = po[k];
670
1515
  }
671
1516
  // OpenCode's modelId maps to Claude's model unless claudeCode.model overrides it.
672
- if (!ctrl.model && this.modelId && this.modelId !== "claude-code")
673
- ctrl.model = this.modelId;
1517
+ const modelId = this.callModel.get(options) ?? this.modelId;
1518
+ if (!ctrl.model && modelId && modelId !== "claude-code")
1519
+ ctrl.model = modelId;
674
1520
  return ctrl;
675
1521
  }
676
1522
  /** Apply runtime config (mode/effort) to a live ACP session via set_mode/set_config_option. */
677
1523
  async applySessionConfig(t, ctrl) {
1524
+ if (ctrl.model && ctrl.model !== t.appliedModel) {
1525
+ try {
1526
+ await this.connection.unstable_setSessionModel({ sessionId: t.sessionId, modelId: ctrl.model });
1527
+ t.appliedModel = ctrl.model;
1528
+ dbg(`model → ${ctrl.model}`);
1529
+ }
1530
+ catch (e) {
1531
+ note(`aviso: no se pudo aplicar el modelo ${ctrl.model} (${e instanceof Error ? e.message : String(e)})`);
1532
+ }
1533
+ }
678
1534
  // A CHANGED request (the user reselected the plan agent) overrides a mode the agent
679
1535
  // set for itself. Without this reset an ExitPlanMode would permanently pin the
680
1536
  // session out of plan mode, and going back to the plan agent would do nothing.
681
1537
  if (ctrl.mode !== t.requestedMode) {
682
1538
  t.requestedMode = ctrl.mode;
683
- t.modeChangedByAgent = false;
1539
+ // Leaving the plan agent for a non-plan one after the plan was approved keeps the
1540
+ // mode the user picked in that approval (acceptEdits, auto…) instead of downgrading
1541
+ // it to the new agent's default. Only (re)entering plan resets it.
1542
+ const keepApproved = t.modeChangedByAgent && ctrl.mode !== "plan" && t.appliedMode !== "plan";
1543
+ if (!keepApproved)
1544
+ t.modeChangedByAgent = false;
684
1545
  }
685
1546
  // Don't re-force the configured mode once the agent switched it itself (ExitPlanMode):
686
1547
  // the user approved leaving plan mode, so the next turn must not snap back to plan.
@@ -713,7 +1574,9 @@ export class ACPOrchestratorModel {
713
1574
  return Promise.resolve();
714
1575
  if (this.connecting)
715
1576
  return this.connecting;
716
- this.connecting = this.connect();
1577
+ // Si `connect()` lanza, `connecting` debe resetearse: si no, todos los
1578
+ // `ensureConnected()` futuros reutilizarían la promesa rechazada y colgarían.
1579
+ this.connecting = this.connect().then(() => undefined, (err) => { this.connecting = null; throw err; });
717
1580
  return this.connecting;
718
1581
  }
719
1582
  async connect() {
@@ -726,12 +1589,43 @@ export class ACPOrchestratorModel {
726
1589
  env.CLAUDE_CONFIG_DIR = configDir;
727
1590
  if (this.config.streamCloseTimeoutMs)
728
1591
  env.CLAUDE_CODE_STREAM_CLOSE_TIMEOUT = String(this.config.streamCloseTimeoutMs);
1592
+ // Claude compacts its own session before OpenCode's threshold (context − 32k), so
1593
+ // OpenCode's compaction — which forces a new session elsewhere — rarely triggers.
1594
+ const pct = ctrl.autoCompactPct ?? 75;
1595
+ if (pct && !env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE)
1596
+ env.CLAUDE_AUTOCOMPACT_PCT_OVERRIDE = String(pct);
729
1597
  // Model selection: the agent resolves the effective model from ANTHROPIC_MODEL
730
1598
  // (getAvailableModels overrides options.model otherwise). claudeCode.model wins,
731
1599
  // else the OpenCode modelId (unless the neutral "claude-code").
732
1600
  const model = ctrl.model ?? (this.modelId !== "claude-code" ? this.modelId : undefined);
733
1601
  if (model)
734
1602
  env.ANTHROPIC_MODEL = model;
1603
+ const stream = this.config.transport ? this.openTransport() : this.spawnAgent(env);
1604
+ const self = this;
1605
+ this.connection = new ClientSideConnection(() => ({
1606
+ // Keep the whole params object: `sessionId` is what routes the update to the
1607
+ // right conversation now that several can be live at once.
1608
+ async sessionUpdate(params) { self.onSessionUpdate(params); },
1609
+ async requestPermission(params) {
1610
+ return self.onRequestPermission(params);
1611
+ },
1612
+ async writeTextFile() { return {}; },
1613
+ async readTextFile() { return { content: "" }; },
1614
+ }), stream);
1615
+ const initResult = await this.connection.initialize({
1616
+ protocolVersion: PROTOCOL_VERSION,
1617
+ clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
1618
+ });
1619
+ this.promptCaps = (initResult?.agentCapabilities?.promptCapabilities ?? {});
1620
+ this.promptQueueing = !!initResult?.agentCapabilities?._meta?.claudeCode?.promptQueueing;
1621
+ dbg(`connected to agent — promptCapabilities: ${JSON.stringify(this.promptCaps)}`);
1622
+ }
1623
+ openTransport() {
1624
+ const t = this.config.transport();
1625
+ this.closeTransport = t.close ?? null;
1626
+ return ndJsonStream(t.input, t.output);
1627
+ }
1628
+ spawnAgent(env) {
735
1629
  this.agent = spawn(this.config.command, this.config.args ?? [], {
736
1630
  stdio: ["pipe", "pipe", "pipe"],
737
1631
  cwd: this.config.cwd ?? process.cwd(),
@@ -751,67 +1645,59 @@ export class ACPOrchestratorModel {
751
1645
  this.agent.stderr?.on("error", () => { });
752
1646
  this.agent.stderr?.on("data", (chunk) => { if (DEBUG)
753
1647
  process.stderr.write(chunk); });
754
- const stream = ndJsonStream(Writable.toWeb(this.agent.stdin), Readable.toWeb(this.agent.stdout));
755
- const self = this;
756
- this.connection = new ClientSideConnection(() => ({
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); },
760
- async requestPermission(params) {
761
- return self.onRequestPermission(params);
762
- },
763
- async writeTextFile() { return {}; },
764
- async readTextFile() { return { content: "" }; },
765
- }), stream);
766
- const initResult = await this.connection.initialize({
767
- protocolVersion: PROTOCOL_VERSION,
768
- clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
769
- });
770
- this.promptCaps = (initResult?.agentCapabilities?.promptCapabilities ?? {});
771
- dbg(`connected to agent — promptCapabilities: ${JSON.stringify(this.promptCaps)}`);
1648
+ return ndJsonStream(Writable.toWeb(this.agent.stdin), Readable.toWeb(this.agent.stdout));
772
1649
  }
1650
+ /** V2 reads every stream to its end; a cancel only comes from an error or the user
1651
+ * aborting (V1 also cancelled to PAUSE for a permission prompt — not anymore). So a
1652
+ * cancel ends the turn: the agent stops, deferred calls are released, leftovers are
1653
+ * dropped. The session itself — and its prompt cache — stays for the next message. */
773
1654
  onCancel(ref) {
774
1655
  const t = ref.t;
775
1656
  if (!t)
776
1657
  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);
1658
+ this.abortTurn(t, "stream cancelled");
796
1659
  }
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?.();
1660
+ sweeper = null;
1661
+ startSweeper() {
1662
+ if (this.sweeper)
1663
+ return;
1664
+ const c = this.config.claudeCode ?? {};
1665
+ const shortest = Math.min(c.idleSessionTtlMs ?? IDLE_TTL_MS, c.childSessionTtlMs ?? CHILD_TTL_MS);
1666
+ this.sweeper = setInterval(() => this.sweepIdle(), Math.max(20, Math.min(30_000, shortest / 2)));
1667
+ this.sweeper.unref?.();
807
1668
  }
808
- clearCancelWatchdog(t) {
809
- if (t.cancelWatchdog) {
810
- clearTimeout(t.cancelWatchdog);
811
- t.cancelWatchdog = null;
1669
+ /** Close sessions nobody is using. Only resumable ones (an OpenCode session id, so
1670
+ * the registry can bring them back without a replay); a turn left waiting on
1671
+ * OpenCode for hours is treated as abandoned. */
1672
+ sweepIdle() {
1673
+ const c = this.config.claudeCode ?? {};
1674
+ const now = Date.now();
1675
+ for (const t of [...this.sessions.values()]) {
1676
+ if (!t.ocSession)
1677
+ continue;
1678
+ const idle = now - t.lastActive;
1679
+ const waiting = t.pendingTools.size > 0 || t.pendingPermissions.size > 0 || t.queuedItems.length > 0;
1680
+ if (waiting) {
1681
+ if (idle > ABANDONED_TTL_MS) {
1682
+ this.abortTurn(t, "abandoned");
1683
+ this.endTurn(t);
1684
+ }
1685
+ continue;
1686
+ }
1687
+ if (t.controller || t.inflight)
1688
+ continue;
1689
+ const ttl = t.isChild ? c.childSessionTtlMs ?? CHILD_TTL_MS : c.idleSessionTtlMs ?? IDLE_TTL_MS;
1690
+ if (idle > ttl) {
1691
+ dbg(`closing idle session ${t.sessionId} (${Math.round(idle / 1000)}s)`);
1692
+ this.endTurn(t);
1693
+ }
812
1694
  }
813
1695
  }
814
1696
  cleanup() {
1697
+ if (this.sweeper) {
1698
+ clearInterval(this.sweeper);
1699
+ this.sweeper = null;
1700
+ }
815
1701
  for (const t of [...this.sessions.values()])
816
1702
  this.endTurn(t);
817
1703
  this.sessions.clear();
@@ -820,26 +1706,41 @@ export class ACPOrchestratorModel {
820
1706
  this.agent?.kill();
821
1707
  }
822
1708
  catch { /* ignore */ }
1709
+ try {
1710
+ this.closeTransport?.();
1711
+ }
1712
+ catch { /* ignore */ }
823
1713
  this.agent = null;
1714
+ this.closeTransport = null;
824
1715
  this.connection = null;
825
1716
  this.connecting = null;
826
1717
  }
1718
+ // ---- diagnostics ----------------------------------------------------------
1719
+ /** Conversation id for logs/recordings: OpenCode's sessionID, else the first-message hash. */
1720
+ convId(options) {
1721
+ const po = this.providerOptions(options);
1722
+ return typeof po.ocSession === "string" ? po.ocSession : `conv_${hashText(firstUserText(options.prompt))}`;
1723
+ }
1724
+ /** One line per turn decision (file log + recording): the evidence needed to tell a
1725
+ * genuine divergence from a false one after the fact. */
1726
+ decide(options, d) {
1727
+ const conv = this.convId(options);
1728
+ log.trace(`${conv} ${JSON.stringify(d)}`);
1729
+ record(conv, { kind: "decision", ...d });
1730
+ }
827
1731
  // ---- conversions ----------------------------------------------------------
828
1732
  convertTools(tools) {
829
1733
  if (!tools)
830
1734
  return [];
831
1735
  const out = [];
832
1736
  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;
838
1737
  if (t.type === "function") {
1738
+ const name = t.name;
839
1739
  out.push({
840
- name: t.name,
841
- description: this.toolDescription(t.name, t.description),
1740
+ name,
1741
+ description: this.toolDescription(name, t.description),
842
1742
  inputSchema: t.inputSchema ?? { type: "object", properties: {} },
1743
+ ...(this.parallelTools().includes(name) ? { annotations: { readOnlyHint: true } } : {}),
843
1744
  });
844
1745
  }
845
1746
  }
@@ -852,109 +1753,129 @@ export class ACPOrchestratorModel {
852
1753
  * agent silently assumes instead of asking. A tool description is NOT a system
853
1754
  * prompt, so this doesn't affect how Anthropic bills the session. */
854
1755
  toolDescription(name, description) {
1756
+ if (name === "subagent") {
1757
+ return `${description ?? ""}\n\nPrefer this tool for delegating substantial work: the child session is visible in OpenCode and any model can continue it, so its result stays part of the shared conversation. Use your native Task tool for your own specialised agents or quick self-contained lookups.`.trim();
1758
+ }
855
1759
  if (name === "question") {
856
1760
  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
1761
  }
858
1762
  return description;
859
1763
  }
860
- /** Text of the first user message — stable identifier for the conversation. */
861
- firstUserText(prompt) {
862
- for (const m of prompt) {
863
- if (m.role !== "user")
1764
+ /** Messages the agent hasn't seen, as prompt blocks.
1765
+ * - `tail` (live or resumed session): the user's messages verbatim; every run of
1766
+ * assistant/tool messages between them was produced by ANOTHER model or agent in
1767
+ * OpenCode (the agent's own output is dropped beforehand), and is labelled so —
1768
+ * as a bare "Assistant:" the agent took those actions for its own.
1769
+ * - `replay` (brand-new session): everything before the current request becomes a
1770
+ * bounded `<conversation_history>`; the request itself follows on its own. */
1771
+ blocksFor(msgs, t, mode = "tail") {
1772
+ if (mode === "replay")
1773
+ return this.replayBlocks(msgs, t);
1774
+ const blocks = [];
1775
+ for (let i = 0; i < msgs.length;) {
1776
+ if (msgs[i].role === "user") {
1777
+ const m = msgs[i++];
1778
+ if (isTransient(m) && t) {
1779
+ const k = msgKey(m);
1780
+ if (t.sentTransient.has(k))
1781
+ continue;
1782
+ t.sentTransient.add(k);
1783
+ }
1784
+ blocks.push(...this.messageToBlocks(m, false, t));
864
1785
  continue;
865
- if (typeof m.content === "string")
866
- return m.content;
867
- return m.content.filter((p) => p.type === "text").map((p) => p.text).join("");
868
- }
869
- return "";
870
- }
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}`;
1786
+ }
1787
+ const run = [];
1788
+ while (i < msgs.length && msgs[i].role !== "user")
1789
+ run.push(msgs[i++]);
1790
+ const inner = run.flatMap((m) => this.renderMessage(m, t));
1791
+ if (inner.length) {
1792
+ blocks.push({ type: "text", text: "<other_model_turn>\n(Another model or agent answered this part in OpenCode — you did not write it or run these tools.)" });
1793
+ blocks.push(...inner);
1794
+ blocks.push({ type: "text", text: "</other_model_turn>" });
895
1795
  }
896
1796
  }
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
1797
  return blocks;
919
1798
  }
920
- messageToBlocks(msg, withPrefix, t) {
921
- const prefixes = { system: "System: ", assistant: "Assistant: ", tool: "", user: "" };
922
- const prefix = withPrefix ? (prefixes[msg.role] ?? "") : "";
923
- if (typeof msg.content === "string")
924
- return [{ type: "text", text: `${prefix}${msg.content}` }];
1799
+ replayBlocks(msgs, t) {
1800
+ let cut = msgs.length;
1801
+ while (cut > 0 && msgs[cut - 1].role === "user")
1802
+ cut--;
1803
+ const current = msgs.slice(cut).flatMap((m) => this.messageToBlocks(m, false, t));
1804
+ let rendered = msgs.slice(0, cut).map((m) => this.renderMessage(m, t)).filter((b) => b.length);
1805
+ if (!rendered.length)
1806
+ return current;
1807
+ // Budget: keep the opening message (usually the task) and the most recent ones.
1808
+ let omitted = 0;
1809
+ while (rendered.length > 2 && rendered.reduce((n, b) => n + blocksChars(b), 0) > REPLAY_BUDGET_CHARS) {
1810
+ rendered.splice(1, 1);
1811
+ omitted++;
1812
+ }
1813
+ return [
1814
+ { type: "text", text: "<conversation_history>\n(Earlier turns of this conversation, replayed because the session was restarted. Context only: do not repeat or re-run anything from it.)" },
1815
+ ...rendered[0],
1816
+ ...(omitted ? [{ type: "text", text: `<omitted messages="${omitted}" reason="replay budget"/>` }] : []),
1817
+ ...rendered.slice(1).flat(),
1818
+ { type: "text", text: "</conversation_history>" },
1819
+ ...(current.length ? current : [{ type: "text", text: "(Continue the conversation above.)" }]),
1820
+ ];
1821
+ }
1822
+ /** One message as tagged blocks (for history and other models' turns). Reasoning and
1823
+ * the agent's own tool traffic are left out: neither is something to re-read. */
1824
+ renderMessage(msg, t) {
1825
+ const role = msg.role === "assistant" ? "assistant" : msg.role === "user" ? "user" : null;
1826
+ if (typeof msg.content === "string") {
1827
+ const text = stripInjected(msg.content).trim();
1828
+ return text && role ? [{ type: "text", text: `<${role}>\n${text}\n</${role}>` }] : [];
1829
+ }
925
1830
  const blocks = [];
926
- let first = true;
927
1831
  for (const part of msg.content) {
928
- const px = first ? prefix : "";
929
1832
  // OUR OWN tool traffic: the agent already holds these in its session (they came
930
1833
  // back over MCP). Replaying them as text duplicated whole file/shell outputs on
931
1834
  // 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))
1835
+ if ((part.type === "tool-call" || part.type === "tool-result") && t && this.isOwnId(t, part.toolCallId))
933
1836
  continue;
934
1837
  if (part.type === "text") {
935
- blocks.push({ type: "text", text: px + part.text });
936
- first = false;
1838
+ const text = stripInjected(String(part.text ?? "")).trim();
1839
+ if (text && role)
1840
+ blocks.push({ type: "text", text: `<${role}>\n${text}\n</${role}>` });
937
1841
  }
938
1842
  else if (part.type === "tool-call") {
939
- blocks.push({ type: "text", text: `${px}[Called tool ${part.toolName}(${JSON.stringify(part.input)})]` });
940
- first = false;
1843
+ const input = typeof part.input === "string" ? part.input : JSON.stringify(part.input ?? {});
1844
+ blocks.push({ type: "text", text: `<tool_call name="${part.toolName}">${input}</tool_call>` });
941
1845
  }
942
1846
  else if (part.type === "tool-result") {
943
- blocks.push({ type: "text", text: `${px}[Tool ${part.toolName} result: ${this.truncate(this.outputToText(part.output))}]` });
944
- first = false;
1847
+ blocks.push({ type: "text", text: `<tool_result name="${part.toolName}">${this.truncate(stripInjected(this.outputToText(part.output)))}</tool_result>` });
945
1848
  }
946
1849
  else if (part.type === "file") {
947
- const fb = this.fileToBlock(part);
948
- blocks.push(fb ?? { type: "text", text: `${px}[Attachment ${part.mediaType ?? "file"} not supported by the agent]` });
949
- first = false;
1850
+ blocks.push(this.fileToBlock(part) ?? { type: "text", text: `[Attachment ${part.mediaType ?? "file"} not supported by the agent]` });
950
1851
  }
951
1852
  }
952
1853
  return blocks;
953
1854
  }
1855
+ /** A user message verbatim (text + attachments), minus tags other plugins inject. */
1856
+ messageToBlocks(msg, _withPrefix, t) {
1857
+ if (typeof msg.content === "string")
1858
+ return [{ type: "text", text: stripInjected(msg.content) }];
1859
+ const blocks = [];
1860
+ for (const part of msg.content) {
1861
+ if ((part.type === "tool-call" || part.type === "tool-result") && t && this.isOwnId(t, part.toolCallId))
1862
+ continue;
1863
+ if (part.type === "text")
1864
+ blocks.push({ type: "text", text: stripInjected(String(part.text ?? "")) });
1865
+ else if (part.type === "tool-call")
1866
+ blocks.push({ type: "text", text: `<tool_call name="${part.toolName}">${JSON.stringify(part.input)}</tool_call>` });
1867
+ else if (part.type === "tool-result")
1868
+ blocks.push({ type: "text", text: `<tool_result name="${part.toolName}">${this.truncate(this.outputToText(part.output))}</tool_result>` });
1869
+ else if (part.type === "file")
1870
+ blocks.push(this.fileToBlock(part) ?? { type: "text", text: `[Attachment ${part.mediaType ?? "file"} not supported by the agent]` });
1871
+ }
1872
+ return blocks;
1873
+ }
954
1874
  /** A foreign tool-result is replayed only so the agent can follow the thread —
955
1875
  * the full payload isn't worth the tokens. */
956
1876
  truncate(s) {
957
- return s.length <= CATCHUP_RESULT_CHARS ? s : `${s.slice(0, CATCHUP_RESULT_CHARS)}…[truncado, ${s.length} chars]`;
1877
+ const cap = this.config.claudeCode?.catchupResultChars ?? CATCHUP_RESULT_CHARS;
1878
+ return s.length <= cap ? s : `${s.slice(0, cap)}…[truncated, ${s.length} chars]`;
958
1879
  }
959
1880
  /** Map an AI SDK file part to an ACP ContentBlock, honoring the agent's promptCapabilities. */
960
1881
  fileToBlock(part) {
@@ -986,22 +1907,11 @@ export class ACPOrchestratorModel {
986
1907
  buildSystemPromptMeta(prompt, mode) {
987
1908
  if (mode === "preset")
988
1909
  return undefined;
989
- const text = this.systemText(prompt);
1910
+ const text = systemText(prompt);
990
1911
  if (!text)
991
1912
  return undefined;
992
1913
  return mode === "replace" ? text : { append: text };
993
1914
  }
994
- systemText(prompt) {
995
- const parts = [];
996
- for (const m of prompt) {
997
- if (m.role !== "system")
998
- continue;
999
- parts.push(typeof m.content === "string"
1000
- ? m.content
1001
- : m.content.filter((p) => p.type === "text").map((p) => p.text).join(""));
1002
- }
1003
- return parts.join("\n").trim();
1004
- }
1005
1915
  /** The FACTUAL part of OpenCode's system prompt: where we are, what the workspace is,
1006
1916
  * what references exist. Under `preset` the system prompt itself never reaches the
1007
1917
  * agent (forwarding it would get the session billed as extra usage), but this
@@ -1010,7 +1920,7 @@ export class ACPOrchestratorModel {
1010
1920
  * AGENTS.md (the agent loads it itself via projectMemory), MCP/skill catalogues —
1011
1921
  * is deliberately left out. */
1012
1922
  extractContextBlock(prompt) {
1013
- const sys = this.systemText(prompt);
1923
+ const sys = systemText(prompt);
1014
1924
  if (!sys)
1015
1925
  return "";
1016
1926
  const out = [];
@@ -1035,9 +1945,14 @@ export class ACPOrchestratorModel {
1035
1945
  // The time is included only here: OpenCode's <env> is day-granular, and a
1036
1946
  // per-turn clock update would be pure noise.
1037
1947
  const now = new Date();
1948
+ // V2's Code Mode catalog lives in the system prompt (which `preset` never sends):
1949
+ // without it the agent sees an `execute` tool but not what it can call through it.
1950
+ // Sent once; V2 announces later changes itself as a `<system-update>` message.
1951
+ const catalog = codeModeSection(systemText(prompt));
1038
1952
  return [{
1039
1953
  type: "text",
1040
- text: `<opencode_context>\n${block}\n Session started: ${now.toLocaleString()} (${Intl.DateTimeFormat().resolvedOptions().timeZone})\n</opencode_context>`,
1954
+ text: `<opencode_context>\n${block}\n Session started: ${now.toLocaleString()} (${Intl.DateTimeFormat().resolvedOptions().timeZone})\n</opencode_context>`
1955
+ + (catalog ? `\n<code_mode_catalog>\n${catalog}\n</code_mode_catalog>` : ""),
1041
1956
  }];
1042
1957
  }
1043
1958
  const prev = new Set(t.lastContextBlock.split("\n").map((l) => l.trim()).filter(Boolean));
@@ -1048,6 +1963,32 @@ export class ACPOrchestratorModel {
1048
1963
  dbg(`context delta (${changed.length} line(s))`);
1049
1964
  return [{ type: "text", text: `<opencode_context_update>\n${changed.join("\n")}\n</opencode_context_update>` }];
1050
1965
  }
1966
+ /** What OpenCode appended after the results of a continuation, as prompt blocks:
1967
+ * user text verbatim (a steered message, a subagent result, a `<system-update>`), and
1968
+ * any assistant prefill (V2's max-steps notice) as an explicit notice. */
1969
+ midTurnBlocks(t, extras) {
1970
+ const blocks = [];
1971
+ for (const m of extras) {
1972
+ if (m.role === "user")
1973
+ blocks.push(...this.messageToBlocks(m, false, t));
1974
+ else if (m.role === "assistant") {
1975
+ const text = (Array.isArray(m.content) ? m.content : [{ type: "text", text: String(m.content ?? "") }])
1976
+ .filter((p) => p?.type === "text" && String(p.text ?? "").trim())
1977
+ .map((p) => p.text)
1978
+ .join("\n");
1979
+ if (text)
1980
+ blocks.push({ type: "text", text: `<opencode_notice>\n${text}\n</opencode_notice>` });
1981
+ }
1982
+ }
1983
+ return blocks;
1984
+ }
1985
+ /** Fallback when the agent can't queue a prompt: the extras ride on a tool result. */
1986
+ appendToResult(result, blocks) {
1987
+ const text = blocks.filter((b) => b.type === "text").map((b) => b.text).join("\n");
1988
+ const note = { type: "text", text: `<user_message_during_turn>\n${text}\n</user_message_during_turn>` };
1989
+ const content = Array.isArray(result?.content) ? result.content : [];
1990
+ return { ...(result ?? {}), content: [...content, note] };
1991
+ }
1051
1992
  /** Only the last user message (delta for a persistent session). */
1052
1993
  lastUserBlocks(prompt) {
1053
1994
  for (let i = prompt.length - 1; i >= 0; i--) {
@@ -1060,23 +2001,48 @@ export class ACPOrchestratorModel {
1060
2001
  return [{ type: "text", text: "" }];
1061
2002
  }
1062
2003
  /** Find the live conversation whose deferred tool-calls/permissions this prompt
1063
- * answers. Scoped per session, so two concurrent chats can't cross-resolve. */
1064
- detectContinuation(prompt) {
1065
- for (const t of this.sessions.values()) {
2004
+ * answers. Acotado a la conversación actual (`ocSession`/convKey de ESTA llamada):
2005
+ * iterar todas las sesiones cruzaba continuaciones de chats concurrentes. */
2006
+ detectContinuation(prompt, options) {
2007
+ let candidates;
2008
+ if (options) {
2009
+ const po = this.providerOptions(options);
2010
+ const baseKey = typeof po.ocSession === "string" ? po.ocSession : hashText(firstUserText(prompt));
2011
+ candidates = [this.sessions.get(baseKey), this.sessions.get(`${baseKey}:notools`)];
2012
+ }
2013
+ else {
2014
+ candidates = [...this.sessions.values()];
2015
+ }
2016
+ const hist = historyOf(prompt);
2017
+ for (const t of candidates) {
2018
+ if (!t)
2019
+ continue;
1066
2020
  if (t.pendingTools.size === 0 && t.pendingPermissions.size === 0)
1067
2021
  continue;
1068
- const results = [];
1069
- for (const msg of prompt) {
2022
+ // Last occurrence wins: ids are unique per session now, but a history can still
2023
+ // hold an older answer with the same id (pre-0.10 bare `perm_N`).
2024
+ const found = new Map();
2025
+ let lastResultAt = -1;
2026
+ hist.forEach((msg, idx) => {
1070
2027
  if (msg.role !== "tool" && msg.role !== "assistant")
1071
- continue;
2028
+ return;
1072
2029
  for (const part of msg.content) {
1073
2030
  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 });
2031
+ found.set(part.toolCallId, { toolCallId: part.toolCallId, result: this.toMcpResult(part.output), output: part.output });
2032
+ lastResultAt = idx;
1075
2033
  }
1076
2034
  }
1077
- }
1078
- if (results.length)
1079
- return { t, results };
2035
+ });
2036
+ if (!found.size)
2037
+ continue;
2038
+ const results = [...found.values()];
2039
+ return {
2040
+ t,
2041
+ results,
2042
+ lastResultAt,
2043
+ extras: hist.slice(lastResultAt + 1),
2044
+ aborted: results.some((r) => isInterrupted(r.output)),
2045
+ };
1080
2046
  }
1081
2047
  return null;
1082
2048
  }
@@ -1086,13 +2052,46 @@ export class ACPOrchestratorModel {
1086
2052
  const ty = output?.type;
1087
2053
  return ty === "error-text" || ty === "error-json" || ty === "error";
1088
2054
  }
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) {
2055
+ /** Approve a bridged permission ONLY on an explicit positive answer to the
2056
+ * `question` dialog. Errors, dismissals, and any ambiguous output (including
2057
+ * a typed-in answer) fail CLOSED so an unclear verdict never runs the tool.
2058
+ * Verificado: OpenCode V2 no expone identificador estable (sin schema de la tool
2059
+ * `question` en node_modules/@opencode-ai ni en /opt/OpenCode/resources; el shape
2060
+ * documentado es etiqueta en `{ answers: [["…"]] }` o texto renderizado) → match
2061
+ * por etiqueta normalizada (minúsculas, trim, "_" y espacios colapsados) con
2062
+ * fallback deny ante cualquier cosa no reconocida. Flujo de 3 opciones intacto. */
2063
+ questionVerdict(output) {
1093
2064
  if (this.isErrorOutput(output))
1094
- return false;
1095
- return this.outputToText(output).toLowerCase().includes("approved");
2065
+ return { approved: false, always: false };
2066
+ const answer = this.normalizeAnswer(this.answerLabel(output));
2067
+ if (answer.includes("always allow"))
2068
+ return { approved: true, always: true };
2069
+ if (answer.includes("allow once"))
2070
+ return { approved: true, always: false };
2071
+ return { approved: false, always: false };
2072
+ }
2073
+ /** Normaliza una etiqueta de respuesta para el match robusto. */
2074
+ normalizeAnswer(s) {
2075
+ return String(s ?? "").trim().toLowerCase().replace(/[_-]+/g, " ").replace(/\s+/g, " ");
2076
+ }
2077
+ /** The chosen label: typed output (`{ answers: [["Always allow"]] }`) first,
2078
+ * then the rendered text fallback (`"question"="Always allow"`). */
2079
+ answerLabel(output) {
2080
+ const answers = output?.value?.answers;
2081
+ if (Array.isArray(answers)) {
2082
+ const first = answers[0];
2083
+ const cand = Array.isArray(first) ? first[0] : first;
2084
+ if (typeof cand === "string")
2085
+ return cand;
2086
+ // Por si OpenCode V2 tipa la respuesta algún día (objeto con optionId/id
2087
+ // estable): preferir el identificador antes que el texto renderizado.
2088
+ if (cand && typeof cand === "object") {
2089
+ const stable = cand.label ?? cand.value ?? cand.text ?? cand.optionId ?? cand.id;
2090
+ if (typeof stable === "string")
2091
+ return stable;
2092
+ }
2093
+ }
2094
+ return this.outputToText(output);
1096
2095
  }
1097
2096
  outputToText(output) {
1098
2097
  if (!output)
@@ -1129,4 +2128,26 @@ export class ACPOrchestratorModel {
1129
2128
  return { content: [{ type: "text", text: this.outputToText(output) }], ...(isErr ? { isError: true } : {}) };
1130
2129
  }
1131
2130
  }
2131
+ /** One OpenCode model served by a shared orchestrator. Every model of the provider
2132
+ * talks to the SAME agent process and session map: switching opus ↔ sonnet mid-
2133
+ * conversation is a `session/set_model` on the live session, not a second process
2134
+ * resuming a session that is still open in the first one. */
2135
+ export class ACPModelView {
2136
+ core;
2137
+ modelId;
2138
+ specificationVersion = "v3";
2139
+ provider = "acp";
2140
+ supportedUrls = {};
2141
+ constructor(core, modelId) {
2142
+ this.core = core;
2143
+ this.modelId = modelId;
2144
+ }
2145
+ doStream(options) {
2146
+ return this.core.doStream(options, this.modelId);
2147
+ }
2148
+ async doGenerate(options) {
2149
+ const { stream } = await this.doStream(options);
2150
+ return collectGenerate(stream);
2151
+ }
2152
+ }
1132
2153
  //# sourceMappingURL=model.js.map