opencode-claude-code-acpbridge 0.9.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 (41) hide show
  1. package/CHANGELOG.md +83 -0
  2. package/README.md +73 -32
  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 +6 -2
  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 +21 -4
  12. package/dist/acp/mcp-runtime.js.map +1 -1
  13. package/dist/log.d.ts +11 -0
  14. package/dist/log.d.ts.map +1 -0
  15. package/dist/log.js +50 -0
  16. package/dist/log.js.map +1 -0
  17. package/dist/plugin/index.d.ts +3 -0
  18. package/dist/plugin/index.d.ts.map +1 -1
  19. package/dist/plugin/index.js +72 -12
  20. package/dist/plugin/index.js.map +1 -1
  21. package/dist/plugin/sessions.d.ts +11 -8
  22. package/dist/plugin/sessions.d.ts.map +1 -1
  23. package/dist/plugin/sessions.js +37 -4
  24. package/dist/plugin/sessions.js.map +1 -1
  25. package/dist/provider/factory.d.ts.map +1 -1
  26. package/dist/provider/factory.js +5 -3
  27. package/dist/provider/factory.js.map +1 -1
  28. package/dist/provider/history.d.ts +44 -0
  29. package/dist/provider/history.d.ts.map +1 -0
  30. package/dist/provider/history.js +145 -0
  31. package/dist/provider/history.js.map +1 -0
  32. package/dist/provider/model.d.ts +159 -23
  33. package/dist/provider/model.d.ts.map +1 -1
  34. package/dist/provider/model.js +1359 -477
  35. package/dist/provider/model.js.map +1 -1
  36. package/dist/provider/recorder.d.ts +5 -0
  37. package/dist/provider/recorder.d.ts.map +1 -0
  38. package/dist/provider/recorder.js +63 -0
  39. package/dist/provider/recorder.js.map +1 -0
  40. package/docs/DEVELOPMENT.md +15 -6
  41. package/package.json +3 -2
@@ -8,38 +8,104 @@
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
36
  import { addAlwaysRule, evaluate as evaluateBridge } from "../plugin/bridge-rules.js";
28
- const DEBUG = !!process.env.ACP_DEBUG;
29
- const dbg = (m) => { if (DEBUG)
30
- process.stderr.write(`[acp-orchestrator] ${m}\n`); };
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;
31
42
  /** Always-on notices (session lifecycle) — the user needs these without ACP_DEBUG. */
32
- const note = (m) => process.stderr.write(`[acp] ${m}\n`);
33
- /** Max live conversations kept per model instance (LRU); older idle ones are torn down. */
34
- const MAX_LIVE_SESSIONS = 8;
35
- /** Cap on a foreign tool-result replayed as text during catch-up. */
36
- const CATCHUP_RESULT_CHARS = 2000;
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;
37
60
  /** Tope del buffer `pending` (chunks emitidos sin controller vivo): sin cap un turno
38
61
  * largo con el stream cerrado lo haría crecer sin límite (OOM). */
39
62
  const MAX_PENDING_PARTS = 1000;
40
63
  /** System-prompt blocks worth forwarding to the agent as FACTUAL context (never as
41
64
  * a system prompt — that would make Anthropic bill the session as extra usage). */
42
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
+ }
43
109
  /** Dialog labels — also the strings the verdict parser looks for (see `questionVerdict`). */
44
110
  const ALLOW_ONCE = "Allow once";
45
111
  const ALWAYS_ALLOW = "Always allow";
@@ -63,26 +129,72 @@ function mapUsage(u) {
63
129
  outputTokens: { total: u.outputTokens ?? undefined, text: u.outputTokens ?? undefined },
64
130
  };
65
131
  }
66
- /** ACP usage is cumulative per session → subtract the previous snapshot to get this turn's. */
67
- function subtractUsage(acc, prev) {
68
- if (!acc || typeof acc !== "object")
69
- return acc;
70
- if (!prev)
71
- return acc;
72
- const d = (a, b) => Math.max(0, (a ?? 0) - (b ?? 0));
73
- return {
74
- inputTokens: d(acc.inputTokens, prev.inputTokens),
75
- outputTokens: d(acc.outputTokens, prev.outputTokens),
76
- cachedReadTokens: d(acc.cachedReadTokens, prev.cachedReadTokens),
77
- cachedWriteTokens: d(acc.cachedWriteTokens, prev.cachedWriteTokens),
78
- totalTokens: d(acc.totalTokens, prev.totalTokens),
79
- };
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(" ");
80
177
  }
81
- function hashText(s) {
82
- let h = 5381;
83
- for (let i = 0; i < s.length; i++)
84
- h = ((h << 5) + h) ^ s.charCodeAt(i);
85
- 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;
86
198
  }
87
199
  export class ACPOrchestratorModel {
88
200
  config;
@@ -91,6 +203,7 @@ export class ACPOrchestratorModel {
91
203
  modelId;
92
204
  supportedUrls = {};
93
205
  agent = null;
206
+ closeTransport = null;
94
207
  connection = null;
95
208
  connecting = null;
96
209
  /** Live conversations, keyed by OpenCode sessionID (or the conversation hash).
@@ -99,14 +212,38 @@ export class ACPOrchestratorModel {
99
212
  sessions = new Map();
100
213
  /** Same states indexed by ACP sessionId, to route agent-initiated callbacks. */
101
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();
102
219
  idSeq = 0;
103
220
  promptCaps = {};
221
+ /** The agent merges a prompt sent mid-turn into the running turn (claude-agent-acp). */
222
+ promptQueueing = false;
104
223
  constructor(config) {
105
224
  this.config = config;
106
225
  this.modelId = config.modelId ?? "claude-code";
107
226
  }
108
227
  // ---- LanguageModelV3 ------------------------------------------------------
109
- async doStream(options) {
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
+ }
110
247
  const continuation = this.detectContinuation(options.prompt, options);
111
248
  const ref = { t: continuation?.t ?? null };
112
249
  const stream = new ReadableStream({
@@ -117,27 +254,7 @@ export class ACPOrchestratorModel {
117
254
  }
118
255
  async doGenerate(options) {
119
256
  const { stream } = await this.doStream(options);
120
- const content = [];
121
- let text = "";
122
- let finishReason = { unified: "stop", raw: undefined };
123
- let usage = emptyUsage();
124
- const reader = stream.getReader();
125
- for (;;) {
126
- const { done, value } = await reader.read();
127
- if (done)
128
- break;
129
- if (value.type === "text-delta")
130
- text += value.delta;
131
- else if (value.type === "tool-call")
132
- content.push(value);
133
- else if (value.type === "finish") {
134
- finishReason = value.finishReason;
135
- usage = value.usage;
136
- }
137
- }
138
- if (text)
139
- content.unshift({ type: "text", text });
140
- return { content, finishReason, usage, warnings: [] };
257
+ return collectGenerate(stream);
141
258
  }
142
259
  // ---- turn lifecycle -------------------------------------------------------
143
260
  async onStart(controller, options, continuation, ref) {
@@ -145,231 +262,74 @@ export class ACPOrchestratorModel {
145
262
  controller.enqueue({ type: "stream-start", warnings: [] });
146
263
  // (1) Continuation of a deferred tool-call OR a bridged permission — resume
147
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
+ }
148
277
  if (continuation) {
149
278
  const t = continuation.t;
150
279
  ref.t = t;
151
- this.clearCancelWatchdog(t); // the turn DID continue — disarm the abort timer
152
280
  t.controller = controller;
153
281
  t.lastActive = Date.now();
154
- // Everything in this prompt is already known to the agent: its own tool-calls
155
- // and the results it will receive right now. Recording them here is what stops
156
- // the next turn from replaying whole file/shell outputs it already has.
157
- t.sentKeys = this.history(options.prompt).map((m) => this.msgKey(m));
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));
158
286
  // Text/thinking that arrived while the stream was closed goes out FIRST, in
159
287
  // order, so nothing the agent said before calling the tool is lost.
160
288
  this.flushPending(t);
161
- 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) => {
162
306
  const permResolve = t.pendingPermissions.get(toolCallId);
163
307
  if (permResolve) {
164
308
  // Permission bridge: the user's `question` answer came back as the
165
309
  // tool-result → resolve the deferred requestPermission.
166
310
  t.pendingPermissions.delete(toolCallId);
167
- permResolve(this.questionVerdict(output));
168
- }
169
- else {
170
- t.pendingTools.delete(toolCallId);
171
- t.host.resolveToolCall(toolCallId, result);
172
- }
173
- }
174
- return;
175
- }
176
- await this.ensureConnected();
177
- const tools = this.convertTools(options.tools);
178
- const ctrl = this.effectiveCtrl(options);
179
- const po = this.providerOptions(options);
180
- const ocSession = po.ocSession;
181
- const convKey = hashText(this.firstUserText(options.prompt));
182
- const toolsKey = tools.map((x) => x.name).sort().join(",");
183
- // The system prompt is part of the session identity ONLY when it actually
184
- // travels. Under the default `preset` mode OpenCode's system is never sent
185
- // (see buildSystemPromptMeta), so hashing it would tear the session down —
186
- // and replay the whole history — every time OpenCode swaps agents or its
187
- // dynamic blocks (date, AGENTS.md, skills) shift. The factual part of that
188
- // system is forwarded separately as user context (see contextBlocks).
189
- const systemMode = ctrl.systemPromptMode ?? "preset";
190
- const systemKey = systemMode === "preset" ? "preset" : hashText(this.systemText(options.prompt));
191
- // Params baked into newSession's _meta (thinking/systemPromptMode) can't change
192
- // mid-session → a change forces a fresh session. mode/effort are applied at
193
- // runtime via set_mode/set_config_option instead (no reset needed).
194
- const cfgKey = hashText(JSON.stringify({ t: ctrl.thinking, s: systemMode }));
195
- const hist = this.history(options.prompt);
196
- const keys = hist.map((m) => this.msgKey(m));
197
- // OpenCode's title/summary call arrives on the same model and session but with
198
- // NO tools. Give it a throwaway session instead of letting it evict the real
199
- // conversation. Only when the live conversation DOES have tools — a genuinely
200
- // tool-less conversation (programmatic use) must keep reusing its own session.
201
- const baseKey = ocSession ?? convKey;
202
- const live = this.sessions.get(baseKey);
203
- const key = tools.length === 0 && live && live.toolsKey !== "" ? `${baseKey}:notools` : baseKey;
204
- let t = this.sessions.get(key);
205
- if (t && t.convKey !== convKey) {
206
- this.endTurn(t);
207
- t = undefined;
208
- } // key reused for another conversation
209
- // (2) Reuse the live session whenever we can — this is what keeps the cache warm.
210
- if (t) {
211
- let drop = null;
212
- if (t.systemKey !== systemKey)
213
- drop = "system prompt changed";
214
- else if (t.cfgKey !== cfgKey)
215
- drop = "creation config changed";
216
- if (!drop) {
217
- // A changed tool set is applied to the LIVE session (MCP list_changed)
218
- // rather than forcing a new one.
219
- if (t.toolsKey !== toolsKey) {
220
- t.host.setTools(tools);
221
- t.host.notifyToolsChanged();
222
- t.toolsKey = toolsKey;
223
- dbg(`tools changed (${tools.length}) — refreshed in place, session kept`);
224
- }
225
- const cls = this.classifyHistory(t, keys);
226
- if (cls.kind !== "append") {
227
- drop = cls.kind === "revert" ? "history reverted" : "history diverged (compaction/rollback)";
228
- }
229
- else {
230
- const live = t;
231
- ref.t = live;
232
- dbg(`reuse session ${live.sessionId} — ${keys.length - cls.fromIndex} new msg(s) (cache-friendly)`);
233
- // A fresh user turn: drop any deferred state left by a prior turn that was
234
- // abandoned (continuation never arrived) so it can't hang or leak.
235
- this.clearCancelWatchdog(live);
236
- this.drainPermissions(live);
237
- live.pendingTools.clear();
238
- live.controller = controller;
239
- live.lastActive = Date.now();
240
- if (ocSession)
241
- live.ocSession = ocSession;
242
- if (po.ocAgent)
243
- live.ocAgent = String(po.ocAgent);
244
- this.flushPending(live);
245
- await this.applySessionConfig(live, ctrl);
246
- const tail = hist.slice(cls.fromIndex);
247
- const blocks = [
248
- ...this.contextBlocks(live, options.prompt, ctrl),
249
- ...(tail.length ? this.blocksFor(tail, live) : this.lastUserBlocks(options.prompt)),
250
- ];
251
- live.sentKeys = keys;
252
- if (ocSession)
253
- setLink(ocSession, live.sessionId, hist.length, convKey);
254
- this.connection
255
- .prompt({ sessionId: live.sessionId, prompt: blocks })
256
- .then((resp) => this.onPromptDone(live, resp))
257
- .catch((err) => this.onPromptError(live, err));
311
+ permResolve(output);
258
312
  return;
259
313
  }
260
- }
261
- dbg(`dropping session ${t.sessionId} — ${drop}`);
262
- this.endTurn(t);
263
- t = undefined;
264
- }
265
- // (3) Need a session: new conversation, or the history diverged, or a
266
- // resumable session from a new process. Set up the MCP host once.
267
- // Unique per-host prefix so minted toolCallIds NEVER collide with ids from a
268
- // previous session still present in OpenCode's replayed history (a fresh host is
269
- // created on every session reset). A random nonce is robust across resets, process
270
- // restarts and resume — unlike a per-host counter, which restarts at 0.
271
- const idPrefix = `acp_${randomBytes(5).toString("hex")}_`;
272
- const host = new McpHost("opencode", idPrefix);
273
- await host.start();
274
- host.setTools(tools);
275
- const serverConfig = host.getServerConfig();
276
- // Try to RESUME a registered Claude Code session (new process, no live state,
277
- // history grew rather than diverged) → no history replay (saves tokens). Else
278
- // create a fresh session and replay the full history.
279
- const resumeId = po.resumeId;
280
- const resumeLen = typeof po.resumeLen === "number" ? po.resumeLen : 0;
281
- let sessionId;
282
- let replayFull = true;
283
- if (DEBUG && po.resumeConvKey && po.resumeConvKey !== convKey) {
284
- dbg(`resumeConvKey mismatch (registry=${po.resumeConvKey} current=${convKey}) — resuming anyway`);
285
- }
286
- if (resumeId && resumeLen > 0 && hist.length > resumeLen) {
287
- try {
288
- await this.connection.unstable_resumeSession({
289
- sessionId: resumeId,
290
- cwd: this.config.cwd ?? process.cwd(),
291
- mcpServers: [serverConfig],
292
- // Re-apply the clean-brain options on resume too. Without this the agent
293
- // falls back to its defaults (--tools default, --setting-sources=user,
294
- // project,local, no --strict-mcp-config) and the resumed session regains
295
- // native tools + the claude.ai connectors.
296
- _meta: { claudeCode: { options: buildClaudeCodeOptions(ctrl) } },
297
- });
298
- sessionId = resumeId;
299
- replayFull = false;
300
- dbg(`resume ${resumeId} (oc=${ocSession ?? "?"}) — no history replay`);
301
- }
302
- catch (e) {
303
- dbg(`resume ${resumeId} failed (${e instanceof Error ? e.message : String(e)}) — fresh session`);
304
- }
305
- }
306
- if (!sessionId) {
307
- // OpenCode's system prompt → _meta.systemPrompt (preset/append/replace).
308
- const meta = { claudeCode: { options: buildClaudeCodeOptions(ctrl) } };
309
- const sysMeta = this.buildSystemPromptMeta(options.prompt, systemMode);
310
- if (sysMeta !== undefined)
311
- meta.systemPrompt = sysMeta;
312
- const session = await this.connection.newSession({
313
- cwd: this.config.cwd ?? process.cwd(),
314
- mcpServers: [serverConfig],
315
- _meta: meta,
314
+ t.pendingTools.delete(toolCallId);
315
+ t.host.resolveToolCall(toolCallId, piggyback && i === lastTool ? this.appendToResult(result, extraBlocks) : result);
316
316
  });
317
- sessionId = session.sessionId;
318
- 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;
319
328
  }
320
- if (!sessionId)
321
- throw new Error("failed to create or resume an ACP session");
322
- // The ACP sessionId IS the Claude Code session id: surfacing it lets the user
323
- // pick the conversation back up natively.
324
- note(`session ${sessionId}${replayFull ? "" : " (resumed)"} — retomable con: claude --resume ${sessionId}`);
325
- t = {
326
- key,
327
- host,
328
- idPrefix,
329
- sessionId,
330
- convKey,
331
- toolsKey,
332
- systemKey,
333
- cfgKey,
334
- ocSession,
335
- ocAgent: po.ocAgent ? String(po.ocAgent) : undefined,
336
- // Resume path: seed the cumulative usage snapshot from the persisted
337
- // registry so the first post-resume `subtractUsage` produces a real
338
- // turn delta instead of the full cumulative.
339
- lastUsage: replayFull ? undefined : po.resumeLastUsage,
340
- // Full replay covers the whole history; a bare resume only covers up to what
341
- // the registry last recorded — the rest still needs sending below.
342
- sentKeys: replayFull ? [] : keys.slice(0, resumeLen),
343
- controller,
344
- pending: [],
345
- pendingTools: new Set(),
346
- pendingPermissions: new Map(),
347
- textId: null,
348
- reasoningId: null,
349
- cancelWatchdogs: new Set(),
350
- lastActive: Date.now(),
351
- };
352
- ref.t = t;
353
- host.onToolCall((c) => this.onToolCall(t, c));
354
- this.sessions.set(key, t);
355
- this.byAcpSession.set(sessionId, t);
356
- this.evictIdleSessions();
357
- await this.applySessionConfig(t, ctrl);
358
- if (ocSession)
359
- setLink(ocSession, sessionId, hist.length, convKey);
360
- const tail = replayFull ? hist : hist.slice(resumeLen);
361
- if (DEBUG && !replayFull)
362
- dbg(`resume — catch-up ${tail.length} msg(s)`);
363
- const promptBlocks = [
364
- ...this.contextBlocks(t, options.prompt, ctrl),
365
- ...(tail.length ? this.blocksFor(tail, t) : [{ type: "text", text: "" }]),
366
- ];
367
- t.sentKeys = keys;
368
- const started = t;
369
- this.connection
370
- .prompt({ sessionId, prompt: promptBlocks })
371
- .then((resp) => this.onPromptDone(started, resp))
372
- .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));
373
333
  }
374
334
  catch (err) {
375
335
  dbg(`onStart error: ${err instanceof Error ? err.message : String(err)}`);
@@ -388,6 +348,9 @@ export class ACPOrchestratorModel {
388
348
  * (independent) ACP stdio channel meanwhile — dropping them truncated answers and
389
349
  * hid the reasoning block entirely. */
390
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);
391
354
  if (t.controller) {
392
355
  try {
393
356
  t.controller.enqueue(part);
@@ -403,6 +366,603 @@ export class ACPOrchestratorModel {
403
366
  dbg(`pending desbordado (>${MAX_PENDING_PARTS}) — descartados los más antiguos`);
404
367
  }
405
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);
965
+ }
406
966
  flushPending(t) {
407
967
  if (!t.controller || t.pending.length === 0)
408
968
  return;
@@ -417,46 +977,73 @@ export class ACPOrchestratorModel {
417
977
  }
418
978
  }
419
979
  onPromptDone(t, resp) {
420
- if (!t.controller)
421
- 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
+ }
422
992
  this.closeBlocks(t);
423
993
  this.flushPending(t);
424
- const turn = subtractUsage(resp?.usage, t.lastUsage); // ACP usage is cumulative per session
425
- if (resp?.usage) {
426
- t.lastUsage = resp.usage;
994
+ const turn = resp?.usage; // sum over the turn's requests (see usageNow)
995
+ if (turn) {
996
+ t.lastUsage = turn;
427
997
  if (t.ocSession)
428
- updateUsage(t.ocSession, resp.usage); // survive process restarts
998
+ updateUsage(t.ocSession, turn); // survive process restarts
429
999
  }
430
1000
  if (DEBUG && turn)
431
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);
432
1008
  try {
433
- t.controller.enqueue({
434
- type: "finish",
435
- usage: mapUsage(turn),
436
- finishReason: { unified: resp?.stopReason === "max_tokens" ? "length" : "stop", raw: resp?.stopReason },
437
- });
1009
+ t.controller.enqueue(finish);
438
1010
  t.controller.close();
439
1011
  }
440
1012
  catch { /* ignore */ }
441
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));
442
1021
  }
443
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
+ }
444
1029
  if (!t.controller)
445
1030
  return;
446
- dbg(`prompt error: ${err instanceof Error ? err.message : String(err)}`);
1031
+ dbg(`prompt error: ${errorText(err)}`);
447
1032
  try {
448
- t.controller.enqueue({ type: "error", error: err });
1033
+ t.controller.enqueue({ type: "error", error: limitError(err) ?? err });
449
1034
  t.controller.close();
450
1035
  }
451
1036
  catch { /* ignore */ }
452
1037
  t.controller = null;
453
1038
  }
454
- /** 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. */
455
1041
  onToolCall(t, call) {
456
- if (!t.controller)
1042
+ if (t.aborted) {
1043
+ t.host.rejectToolCall(call.toolCallId, "Turn aborted");
457
1044
  return;
1045
+ }
458
1046
  dbg(`agent → tool-call ${call.name} (${call.toolCallId}) → emit to OpenCode`);
459
- this.closeBlocks(t);
460
1047
  t.pendingTools.add(call.toolCallId);
461
1048
  // `call.args` puede traer refs circulares/BigInt → JSON.stringify lanzaría y
462
1049
  // tumbaría el turno: degradar a marcador en vez de crashear.
@@ -468,11 +1055,95 @@ export class ACPOrchestratorModel {
468
1055
  dbg(`tool-call ${call.name}: args no serializables (${e instanceof Error ? e.message : String(e)}) — input="<serialization error>"`);
469
1056
  inputJson = '"<serialization error>"';
470
1057
  }
471
- this.emit(t, { type: "tool-input-start", id: call.toolCallId, toolName: call.name });
472
- this.emit(t, { type: "tool-input-delta", id: call.toolCallId, delta: inputJson });
473
- this.emit(t, { type: "tool-input-end", id: call.toolCallId });
474
- this.emit(t, { type: "tool-call", toolCallId: call.toolCallId, toolName: call.name, input: inputJson });
475
- this.emit(t, { type: "finish", usage: emptyUsage(), finishReason: { unified: "tool-calls", raw: "tool_use" } });
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" } });
476
1147
  try {
477
1148
  t.controller?.close();
478
1149
  }
@@ -530,8 +1201,9 @@ export class ACPOrchestratorModel {
530
1201
  * the `question` tool-result (resolved in onStart's continuation branch). */
531
1202
  onRequestPermission(params) {
532
1203
  const t = this.byAcpSession.get(String(params?.sessionId ?? ""));
533
- // Sin turno vivo (crash/reinicio) — denegar es más seguro que aprobar a ciegas.
534
- 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)
535
1207
  return Promise.resolve(this.permOutcome(params, false));
536
1208
  const toolCall = params?.toolCall;
537
1209
  const native = this.permToolName(toolCall);
@@ -545,11 +1217,22 @@ export class ACPOrchestratorModel {
545
1217
  return Promise.resolve(this.permOutcome(params, true));
546
1218
  if (rules === "deny")
547
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
+ }
548
1226
  // (2) "ask": raise a `question` dialog and wait for its tool-result.
549
- const callId = `perm_${++this.idSeq}`;
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}`;
550
1230
  dbg(`requestPermission(${native}) → bridge as question (${callId})`);
1231
+ if (toolCall?.kind === "switch_mode")
1232
+ return this.askPlanApproval(t, callId, params);
551
1233
  return new Promise((resolve) => {
552
- t.pendingPermissions.set(callId, (verdict) => {
1234
+ t.pendingPermissions.set(callId, (output) => {
1235
+ const verdict = this.questionVerdict(output);
553
1236
  if (verdict.approved && verdict.always && target.always)
554
1237
  addAlwaysRule(agent, native, target.always);
555
1238
  resolve(this.permOutcome(params, verdict.approved));
@@ -557,6 +1240,40 @@ export class ACPOrchestratorModel {
557
1240
  this.emitPermissionCall(t, callId, toolCall, native, target);
558
1241
  });
559
1242
  }
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");
1250
+ const input = JSON.stringify({
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
+ }],
1259
+ });
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
+ }
560
1277
  /** Action target of a native request (command / skill / path), plus the glob an
561
1278
  * "Always allow" would persist. Shell commands collapse to their first token
562
1279
  * (`git status` → `git *`); a request with no real target persists nothing, so
@@ -576,21 +1293,6 @@ export class ACPOrchestratorModel {
576
1293
  * Always allow / Deny — and the answer arrives as the tool-result on the next
577
1294
  * doStream. The agent itself only ever sees the ACP permission outcome. */
578
1295
  emitPermissionCall(t, callId, toolCall, native, target) {
579
- if (!t.controller)
580
- return;
581
- this.closeBlocks(t);
582
- // ExitPlanMode (switch_mode): render the PLAN as visible assistant text before the
583
- // approval prompt — otherwise it's only buried in the permission metadata and the
584
- // user would approve blind. Presenting the plan for approval IS the point of the tool.
585
- if (toolCall?.kind === "switch_mode") {
586
- const plan = this.planText(toolCall);
587
- if (plan) {
588
- const id = `plan${++this.idSeq}`;
589
- this.emit(t, { type: "text-start", id });
590
- this.emit(t, { type: "text-delta", id, delta: plan });
591
- this.emit(t, { type: "text-end", id });
592
- }
593
- }
594
1296
  const input = JSON.stringify({
595
1297
  questions: [
596
1298
  {
@@ -606,16 +1308,7 @@ export class ACPOrchestratorModel {
606
1308
  },
607
1309
  ],
608
1310
  });
609
- this.emit(t, { type: "tool-input-start", id: callId, toolName: "question" });
610
- this.emit(t, { type: "tool-input-delta", id: callId, delta: input });
611
- this.emit(t, { type: "tool-input-end", id: callId });
612
- this.emit(t, { type: "tool-call", toolCallId: callId, toolName: "question", input });
613
- this.emit(t, { type: "finish", usage: emptyUsage(), finishReason: { unified: "tool-calls", raw: "tool_use" } });
614
- try {
615
- t.controller?.close();
616
- }
617
- catch { /* ignore */ }
618
- t.controller = null;
1311
+ this.addStepItem(t, { id: callId, toolName: "question", input });
619
1312
  }
620
1313
  /** Fired by the ACP client on session/update. */
621
1314
  onSessionUpdate(params) {
@@ -643,6 +1336,10 @@ export class ACPOrchestratorModel {
643
1336
  return;
644
1337
  }
645
1338
  switch (update?.sessionUpdate) {
1339
+ case "usage_update":
1340
+ if (typeof update.used === "number")
1341
+ t.contextUsed = update.used;
1342
+ break;
646
1343
  case "agent_message_chunk":
647
1344
  if (update.content?.type === "text") {
648
1345
  if (!t.textId) {
@@ -661,10 +1358,63 @@ export class ACPOrchestratorModel {
661
1358
  this.emit(t, { type: "reasoning-delta", id: t.reasoningId, delta: update.content.text });
662
1359
  }
663
1360
  break;
1361
+ case "tool_call":
1362
+ case "tool_call_update":
1363
+ this.onNativeTool(t, update);
1364
+ break;
664
1365
  default:
665
- break; // tool_call/tool_call_update are informational; MCP host drives emission
1366
+ break;
666
1367
  }
667
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
+ }
668
1418
  closeBlocks(t) {
669
1419
  if (t.textId) {
670
1420
  this.emit(t, { type: "text-end", id: t.textId });
@@ -676,7 +1426,6 @@ export class ACPOrchestratorModel {
676
1426
  }
677
1427
  }
678
1428
  endTurn(t) {
679
- this.clearCancelWatchdog(t);
680
1429
  // Settle any deferred permission requests (deny/cancel) so the agent never
681
1430
  // stays blocked awaiting a verdict that will no longer arrive.
682
1431
  this.drainPermissions(t);
@@ -686,6 +1435,9 @@ export class ACPOrchestratorModel {
686
1435
  }
687
1436
  catch { /* ignore */ }
688
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);
689
1441
  if (this.sessions.get(t.key) === t)
690
1442
  this.sessions.delete(t.key);
691
1443
  this.byAcpSession.delete(t.sessionId);
@@ -693,12 +1445,13 @@ export class ACPOrchestratorModel {
693
1445
  /** Keep at most MAX_LIVE_SESSIONS conversations alive; tear down the oldest idle ones
694
1446
  * (never one with work in flight) so hosts and agent sessions don't pile up. */
695
1447
  evictIdleSessions() {
696
- if (this.sessions.size <= MAX_LIVE_SESSIONS)
1448
+ const max = this.config.claudeCode?.maxLiveSessions ?? MAX_LIVE_SESSIONS;
1449
+ if (this.sessions.size <= max)
697
1450
  return;
698
1451
  const idle = [...this.sessions.values()]
699
1452
  .filter((s) => !s.controller && s.pendingTools.size === 0 && s.pendingPermissions.size === 0)
700
1453
  .sort((a, b) => a.lastActive - b.lastActive);
701
- while (this.sessions.size > MAX_LIVE_SESSIONS && idle.length) {
1454
+ while (this.sessions.size > max && idle.length) {
702
1455
  const victim = idle.shift();
703
1456
  dbg(`evicting idle session ${victim.sessionId} (LRU)`);
704
1457
  this.endTurn(victim);
@@ -708,10 +1461,10 @@ export class ACPOrchestratorModel {
708
1461
  drainPermissions(t) {
709
1462
  if (t.pendingPermissions.size === 0)
710
1463
  return;
711
- const denied = { approved: false, always: false };
1464
+ const abandoned = { type: "error-text", value: "Permission request abandoned" };
712
1465
  for (const resolve of [...t.pendingPermissions.values()]) {
713
1466
  try {
714
- resolve(denied);
1467
+ resolve(abandoned);
715
1468
  }
716
1469
  catch { /* ignore */ }
717
1470
  }
@@ -728,7 +1481,8 @@ export class ACPOrchestratorModel {
728
1481
  if (own && typeof own === "object")
729
1482
  return own;
730
1483
  const SHAPE_KEYS = new Set([
731
- "ocSession", "ocAgent", "resumeId", "resumeLen", "resumeConvKey", "resumeLastUsage",
1484
+ "ocSession", "ocAgent", "resumeId", "resumeLen", "resumeConvKey", "resumeLastUsage", "resumeIdPrefixes",
1485
+ "requestKind", "hasQuestion",
732
1486
  "mode", "effort", "thinking", "systemPromptMode", "forwardEnvContext",
733
1487
  "tools", "allowedTools", "disallowedTools", "settingSources", "strictMcpConfig",
734
1488
  "nativeTools", "resourceSearch", "nativeSubagents", "nativeSkills", "projectMemory", "skillShell",
@@ -760,18 +1514,34 @@ export class ACPOrchestratorModel {
760
1514
  ctrl[k] = po[k];
761
1515
  }
762
1516
  // OpenCode's modelId maps to Claude's model unless claudeCode.model overrides it.
763
- if (!ctrl.model && this.modelId && this.modelId !== "claude-code")
764
- 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;
765
1520
  return ctrl;
766
1521
  }
767
1522
  /** Apply runtime config (mode/effort) to a live ACP session via set_mode/set_config_option. */
768
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
+ }
769
1534
  // A CHANGED request (the user reselected the plan agent) overrides a mode the agent
770
1535
  // set for itself. Without this reset an ExitPlanMode would permanently pin the
771
1536
  // session out of plan mode, and going back to the plan agent would do nothing.
772
1537
  if (ctrl.mode !== t.requestedMode) {
773
1538
  t.requestedMode = ctrl.mode;
774
- 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;
775
1545
  }
776
1546
  // Don't re-force the configured mode once the agent switched it itself (ExitPlanMode):
777
1547
  // the user approved leaving plan mode, so the next turn must not snap back to plan.
@@ -819,12 +1589,43 @@ export class ACPOrchestratorModel {
819
1589
  env.CLAUDE_CONFIG_DIR = configDir;
820
1590
  if (this.config.streamCloseTimeoutMs)
821
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);
822
1597
  // Model selection: the agent resolves the effective model from ANTHROPIC_MODEL
823
1598
  // (getAvailableModels overrides options.model otherwise). claudeCode.model wins,
824
1599
  // else the OpenCode modelId (unless the neutral "claude-code").
825
1600
  const model = ctrl.model ?? (this.modelId !== "claude-code" ? this.modelId : undefined);
826
1601
  if (model)
827
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) {
828
1629
  this.agent = spawn(this.config.command, this.config.args ?? [], {
829
1630
  stdio: ["pipe", "pipe", "pipe"],
830
1631
  cwd: this.config.cwd ?? process.cwd(),
@@ -844,69 +1645,59 @@ export class ACPOrchestratorModel {
844
1645
  this.agent.stderr?.on("error", () => { });
845
1646
  this.agent.stderr?.on("data", (chunk) => { if (DEBUG)
846
1647
  process.stderr.write(chunk); });
847
- const stream = ndJsonStream(Writable.toWeb(this.agent.stdin), Readable.toWeb(this.agent.stdout));
848
- const self = this;
849
- this.connection = new ClientSideConnection(() => ({
850
- // Keep the whole params object: `sessionId` is what routes the update to the
851
- // right conversation now that several can be live at once.
852
- async sessionUpdate(params) { self.onSessionUpdate(params); },
853
- async requestPermission(params) {
854
- return self.onRequestPermission(params);
855
- },
856
- async writeTextFile() { return {}; },
857
- async readTextFile() { return { content: "" }; },
858
- }), stream);
859
- const initResult = await this.connection.initialize({
860
- protocolVersion: PROTOCOL_VERSION,
861
- clientCapabilities: { fs: { readTextFile: false, writeTextFile: false }, terminal: false },
862
- });
863
- this.promptCaps = (initResult?.agentCapabilities?.promptCapabilities ?? {});
864
- dbg(`connected to agent — promptCapabilities: ${JSON.stringify(this.promptCaps)}`);
1648
+ return ndJsonStream(Writable.toWeb(this.agent.stdin), Readable.toWeb(this.agent.stdout));
865
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. */
866
1654
  onCancel(ref) {
867
1655
  const t = ref.t;
868
1656
  if (!t)
869
1657
  return;
870
- // A stream cancel WHILE a tool-call or permission is deferred is OpenCode
871
- // PAUSING (e.g. to show a permission prompt), not a real abort — tearing the
872
- // host down here kills the pending tools/call with "host closed". Keep the
873
- // session/host alive; the continuation doStream resolves them. A WATCHDOG
874
- // guarantees teardown if the continuation never arrives (session truly aborted,
875
- // prompt dropped) so the agent can't hang forever.
876
- if (t.pendingTools.size > 0 || t.pendingPermissions.size > 0) {
877
- dbg("onCancel ignored — deferred tool-call/permission in flight (likely a permission pause)");
878
- this.armCancelWatchdog(t);
879
- return;
880
- }
881
- // A plain cancel ends the TURN, not the conversation: keep the session (and its
882
- // prompt cache) so the next message continues where this one stopped.
883
- try {
884
- this.connection?.cancel?.({ sessionId: t.sessionId });
885
- }
886
- catch { /* ignore */ }
887
- t.controller = null;
888
- this.closeBlocks(t);
1658
+ this.abortTurn(t, "stream cancelled");
889
1659
  }
890
- /** If a cancel was ignored (deferred work in flight) but no continuation comes,
891
- * force teardown so the agent doesn't stay blocked. Cleared by a continuation. */
892
- armCancelWatchdog(t) {
893
- this.clearCancelWatchdog(t);
894
- const timer = setTimeout(() => {
895
- t.cancelWatchdogs.delete(timer);
896
- dbg("cancel watchdog fired — no continuation arrived; tearing down");
897
- this.endTurn(t);
898
- }, this.config.streamCloseTimeoutMs ?? 600_000);
899
- timer.unref?.();
900
- t.cancelWatchdogs.add(timer);
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?.();
901
1668
  }
902
- /** Barre TODOS los watchdogs del turno (cada `onCancel` ignorado arma uno);
903
- * llamado desde endTurn/cleanup y al continuar el turno. */
904
- clearCancelWatchdog(t) {
905
- for (const timer of t.cancelWatchdogs)
906
- clearTimeout(timer);
907
- t.cancelWatchdogs.clear();
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
+ }
1694
+ }
908
1695
  }
909
1696
  cleanup() {
1697
+ if (this.sweeper) {
1698
+ clearInterval(this.sweeper);
1699
+ this.sweeper = null;
1700
+ }
910
1701
  for (const t of [...this.sessions.values()])
911
1702
  this.endTurn(t);
912
1703
  this.sessions.clear();
@@ -915,10 +1706,28 @@ export class ACPOrchestratorModel {
915
1706
  this.agent?.kill();
916
1707
  }
917
1708
  catch { /* ignore */ }
1709
+ try {
1710
+ this.closeTransport?.();
1711
+ }
1712
+ catch { /* ignore */ }
918
1713
  this.agent = null;
1714
+ this.closeTransport = null;
919
1715
  this.connection = null;
920
1716
  this.connecting = null;
921
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
+ }
922
1731
  // ---- conversions ----------------------------------------------------------
923
1732
  convertTools(tools) {
924
1733
  if (!tools)
@@ -926,10 +1735,12 @@ export class ACPOrchestratorModel {
926
1735
  const out = [];
927
1736
  for (const t of tools) {
928
1737
  if (t.type === "function") {
1738
+ const name = t.name;
929
1739
  out.push({
930
- name: t.name,
931
- description: this.toolDescription(t.name, t.description),
1740
+ name,
1741
+ description: this.toolDescription(name, t.description),
932
1742
  inputSchema: t.inputSchema ?? { type: "object", properties: {} },
1743
+ ...(this.parallelTools().includes(name) ? { annotations: { readOnlyHint: true } } : {}),
933
1744
  });
934
1745
  }
935
1746
  }
@@ -942,113 +1753,129 @@ export class ACPOrchestratorModel {
942
1753
  * agent silently assumes instead of asking. A tool description is NOT a system
943
1754
  * prompt, so this doesn't affect how Anthropic bills the session. */
944
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
+ }
945
1759
  if (name === "question") {
946
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();
947
1761
  }
948
1762
  return description;
949
1763
  }
950
- /** Text of the first user message — stable identifier for the conversation. */
951
- firstUserText(prompt) {
952
- for (const m of prompt) {
953
- 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));
954
1785
  continue;
955
- if (typeof m.content === "string")
956
- return m.content;
957
- return m.content.filter((p) => p.type === "text").map((p) => p.text).join("");
958
- }
959
- return "";
960
- }
961
- /** The conversation proper: system messages are excluded because they're forwarded
962
- * separately (or not at all) and OpenCode rewrites them every turn — including them
963
- * would make every history comparison look like a divergence. */
964
- history(prompt) {
965
- return prompt.filter((m) => m.role !== "system");
966
- }
967
- /** Cheap, stable per-message identity. Deliberately keyed on tool-call IDs rather
968
- * than payloads: it must survive re-serialization but change if the turn changes. */
969
- msgKey(msg) {
970
- let body = "";
971
- if (typeof msg.content === "string")
972
- body = msg.content;
973
- else if (Array.isArray(msg.content)) {
974
- for (const p of msg.content) {
975
- if (p?.type === "text")
976
- body += `t:${p.text}`;
977
- else if (p?.type === "tool-call")
978
- body += `c:${p.toolCallId}`;
979
- else if (p?.type === "tool-result")
980
- body += `r:${p.toolCallId}`;
981
- else if (p?.type === "file")
982
- body += `f:${p.filename ?? p.mediaType ?? ""}`;
983
- else
984
- body += `?${p?.type}`;
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>" });
985
1795
  }
986
1796
  }
987
- return `${msg.role}:${hashText(body)}`;
988
- }
989
- /** How the incoming history relates to what the agent already knows.
990
- * - append → normal turn (or another agent ran turns meanwhile): send the tail.
991
- * - revert → the user rewound: the agent can't unremember, so it needs a new session.
992
- * - diverged → compaction/rollback replaced the middle: same, a new session. */
993
- classifyHistory(t, keys) {
994
- const sent = t.sentKeys;
995
- let i = 0;
996
- while (i < sent.length && i < keys.length && sent[i] === keys[i])
997
- i++;
998
- if (i === sent.length)
999
- return { kind: "append", fromIndex: i };
1000
- // Prefijo estricto = revert SOLO si incoming es más corto; si son iguales no hay
1001
- // mensajes nuevos → append desde el final (evita falsos revert).
1002
- if (i === keys.length)
1003
- return keys.length < sent.length
1004
- ? { kind: "revert", fromIndex: i }
1005
- : { kind: "append", fromIndex: keys.length };
1006
- return { kind: "diverged", fromIndex: i };
1007
- }
1008
- blocksFor(msgs, t) {
1009
- const blocks = [];
1010
- for (const msg of msgs)
1011
- blocks.push(...this.messageToBlocks(msg, true, t));
1012
1797
  return blocks;
1013
1798
  }
1014
- messageToBlocks(msg, withPrefix, t) {
1015
- const prefixes = { system: "System: ", assistant: "Assistant: ", tool: "", user: "" };
1016
- const prefix = withPrefix ? (prefixes[msg.role] ?? "") : "";
1017
- if (typeof msg.content === "string")
1018
- 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
+ }
1019
1830
  const blocks = [];
1020
- let first = true;
1021
1831
  for (const part of msg.content) {
1022
- const px = first ? prefix : "";
1023
1832
  // OUR OWN tool traffic: the agent already holds these in its session (they came
1024
1833
  // back over MCP). Replaying them as text duplicated whole file/shell outputs on
1025
1834
  // every turn and blew the prompt cache — by far the biggest token sink.
1026
- if ((part.type === "tool-call" || part.type === "tool-result") && t && String(part.toolCallId ?? "").startsWith(t.idPrefix))
1835
+ if ((part.type === "tool-call" || part.type === "tool-result") && t && this.isOwnId(t, part.toolCallId))
1027
1836
  continue;
1028
1837
  if (part.type === "text") {
1029
- blocks.push({ type: "text", text: px + part.text });
1030
- 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}>` });
1031
1841
  }
1032
1842
  else if (part.type === "tool-call") {
1033
- blocks.push({ type: "text", text: `${px}[Called tool ${part.toolName}(${JSON.stringify(part.input)})]` });
1034
- 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>` });
1035
1845
  }
1036
1846
  else if (part.type === "tool-result") {
1037
- blocks.push({ type: "text", text: `${px}[Tool ${part.toolName} result: ${this.truncate(this.outputToText(part.output))}]` });
1038
- first = false;
1847
+ blocks.push({ type: "text", text: `<tool_result name="${part.toolName}">${this.truncate(stripInjected(this.outputToText(part.output)))}</tool_result>` });
1039
1848
  }
1040
1849
  else if (part.type === "file") {
1041
- const fb = this.fileToBlock(part);
1042
- blocks.push(fb ?? { type: "text", text: `${px}[Attachment ${part.mediaType ?? "file"} not supported by the agent]` });
1043
- first = false;
1850
+ blocks.push(this.fileToBlock(part) ?? { type: "text", text: `[Attachment ${part.mediaType ?? "file"} not supported by the agent]` });
1044
1851
  }
1045
1852
  }
1046
1853
  return blocks;
1047
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
+ }
1048
1874
  /** A foreign tool-result is replayed only so the agent can follow the thread —
1049
1875
  * the full payload isn't worth the tokens. */
1050
1876
  truncate(s) {
1051
- 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]`;
1052
1879
  }
1053
1880
  /** Map an AI SDK file part to an ACP ContentBlock, honoring the agent's promptCapabilities. */
1054
1881
  fileToBlock(part) {
@@ -1080,22 +1907,11 @@ export class ACPOrchestratorModel {
1080
1907
  buildSystemPromptMeta(prompt, mode) {
1081
1908
  if (mode === "preset")
1082
1909
  return undefined;
1083
- const text = this.systemText(prompt);
1910
+ const text = systemText(prompt);
1084
1911
  if (!text)
1085
1912
  return undefined;
1086
1913
  return mode === "replace" ? text : { append: text };
1087
1914
  }
1088
- systemText(prompt) {
1089
- const parts = [];
1090
- for (const m of prompt) {
1091
- if (m.role !== "system")
1092
- continue;
1093
- parts.push(typeof m.content === "string"
1094
- ? m.content
1095
- : m.content.filter((p) => p.type === "text").map((p) => p.text).join(""));
1096
- }
1097
- return parts.join("\n").trim();
1098
- }
1099
1915
  /** The FACTUAL part of OpenCode's system prompt: where we are, what the workspace is,
1100
1916
  * what references exist. Under `preset` the system prompt itself never reaches the
1101
1917
  * agent (forwarding it would get the session billed as extra usage), but this
@@ -1104,7 +1920,7 @@ export class ACPOrchestratorModel {
1104
1920
  * AGENTS.md (the agent loads it itself via projectMemory), MCP/skill catalogues —
1105
1921
  * is deliberately left out. */
1106
1922
  extractContextBlock(prompt) {
1107
- const sys = this.systemText(prompt);
1923
+ const sys = systemText(prompt);
1108
1924
  if (!sys)
1109
1925
  return "";
1110
1926
  const out = [];
@@ -1129,9 +1945,14 @@ export class ACPOrchestratorModel {
1129
1945
  // The time is included only here: OpenCode's <env> is day-granular, and a
1130
1946
  // per-turn clock update would be pure noise.
1131
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));
1132
1952
  return [{
1133
1953
  type: "text",
1134
- 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>` : ""),
1135
1956
  }];
1136
1957
  }
1137
1958
  const prev = new Set(t.lastContextBlock.split("\n").map((l) => l.trim()).filter(Boolean));
@@ -1142,6 +1963,32 @@ export class ACPOrchestratorModel {
1142
1963
  dbg(`context delta (${changed.length} line(s))`);
1143
1964
  return [{ type: "text", text: `<opencode_context_update>\n${changed.join("\n")}\n</opencode_context_update>` }];
1144
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
+ }
1145
1992
  /** Only the last user message (delta for a persistent session). */
1146
1993
  lastUserBlocks(prompt) {
1147
1994
  for (let i = prompt.length - 1; i >= 0; i--) {
@@ -1160,29 +2007,42 @@ export class ACPOrchestratorModel {
1160
2007
  let candidates;
1161
2008
  if (options) {
1162
2009
  const po = this.providerOptions(options);
1163
- const baseKey = typeof po.ocSession === "string" ? po.ocSession : hashText(this.firstUserText(prompt));
2010
+ const baseKey = typeof po.ocSession === "string" ? po.ocSession : hashText(firstUserText(prompt));
1164
2011
  candidates = [this.sessions.get(baseKey), this.sessions.get(`${baseKey}:notools`)];
1165
2012
  }
1166
2013
  else {
1167
2014
  candidates = [...this.sessions.values()];
1168
2015
  }
2016
+ const hist = historyOf(prompt);
1169
2017
  for (const t of candidates) {
1170
2018
  if (!t)
1171
2019
  continue;
1172
2020
  if (t.pendingTools.size === 0 && t.pendingPermissions.size === 0)
1173
2021
  continue;
1174
- const results = [];
1175
- 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) => {
1176
2027
  if (msg.role !== "tool" && msg.role !== "assistant")
1177
- continue;
2028
+ return;
1178
2029
  for (const part of msg.content) {
1179
2030
  if (part?.type === "tool-result" && (t.pendingTools.has(part.toolCallId) || t.pendingPermissions.has(part.toolCallId))) {
1180
- results.push({ toolCallId: part.toolCallId, result: this.toMcpResult(part.output), output: part.output });
2031
+ found.set(part.toolCallId, { toolCallId: part.toolCallId, result: this.toMcpResult(part.output), output: part.output });
2032
+ lastResultAt = idx;
1181
2033
  }
1182
2034
  }
1183
- }
1184
- if (results.length)
1185
- 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
+ };
1186
2046
  }
1187
2047
  return null;
1188
2048
  }
@@ -1268,4 +2128,26 @@ export class ACPOrchestratorModel {
1268
2128
  return { content: [{ type: "text", text: this.outputToText(output) }], ...(isErr ? { isError: true } : {}) };
1269
2129
  }
1270
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
+ }
1271
2153
  //# sourceMappingURL=model.js.map