opencode-claude-code-acpbridge 0.11.0 → 0.11.2

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.
@@ -83,6 +83,9 @@ const COMPACT_WAIT_MS = 180_000;
83
83
  const CHECKPOINT_NOTE = "<context_update>\n(The conversation continued in OpenCode with another model and was then compacted. " +
84
84
  "OpenCode's checkpoint follows: it summarizes everything, including what happened after your last turn. " +
85
85
  "Keep what you remember; use it to catch up on what you did not see.)\n</context_update>";
86
+ /** Session updates only a turn that actually runs produces (not the command/config
87
+ * notices an agent sends on its own). */
88
+ const TURN_UPDATES = new Set(["agent_message_chunk", "agent_thought_chunk", "tool_call", "tool_call_update", "usage_update", "plan"]);
86
89
  /** How long a turn being replaced may take to wind down after a cancel. */
87
90
  const SETTLE_MS = 5000;
88
91
  /** The `# Code Mode` section of OpenCode's system prompt (up to the next top-level
@@ -176,6 +179,14 @@ function errorText(err) {
176
179
  const e = err;
177
180
  return [e.message, e.data !== undefined ? JSON.stringify(e.data) : ""].filter(Boolean).join(" ");
178
181
  }
182
+ /** The CLI's diagnostic for a cycle interrupted before Claude answered (the turn was
183
+ * stopped mid tool loop): `[ede_diagnostic] result_type=user last_content_type=n/a`.
184
+ * claude-agent-acp 0.31 fails the NEXT prompt with it, so it describes an earlier turn,
185
+ * not the prompt that receives it. (0.99 swallows only its `stop_reason=null` form.) */
186
+ export function isInterruptedCycle(err) {
187
+ const raw = errorText(err);
188
+ return /\[ede_diagnostic\]/.test(raw) && /\bresult_type=user\b/.test(raw) && /\blast_content_type=n\/a\b/.test(raw);
189
+ }
179
190
  /** Claude's usage/rate limit, rewritten so the user knows to switch models — and in
180
191
  * words OpenCode's retry classifier doesn't match ("try again", "overloaded"…), so it
181
192
  * isn't retried in a loop against an exhausted subscription. */
@@ -250,6 +261,8 @@ export class ACPOrchestratorModel {
250
261
  promptCaps = {};
251
262
  /** The agent merges a prompt sent mid-turn into the running turn (claude-agent-acp). */
252
263
  promptQueueing = false;
264
+ /** The agent has no session/set_model: models go through the `model` config option. */
265
+ modelByConfig = false;
253
266
  constructor(config) {
254
267
  this.config = config;
255
268
  this.modelId = config.modelId ?? "claude-code";
@@ -348,8 +361,12 @@ export class ACPOrchestratorModel {
348
361
  });
349
362
  if (extraBlocks.length && !piggyback)
350
363
  this.sendPrompt(t, extraBlocks);
364
+ // The prompt already failed (usage limit hit while OpenCode ran the step): nothing
365
+ // will continue this turn — fail it now instead of leaving OpenCode waiting.
366
+ if (t.doneErr)
367
+ this.failFromDone(t);
351
368
  // Calls that arrived while OpenCode ran the previous step go out now as the next one.
352
- if (t.queuedItems.length) {
369
+ else if (t.queuedItems.length) {
353
370
  t.stepItems.push(...t.queuedItems);
354
371
  t.queuedItems = [];
355
372
  this.closeStep(t);
@@ -452,6 +469,8 @@ export class ACPOrchestratorModel {
452
469
  // (2) Reuse the live session whenever we can — this is what keeps the cache warm.
453
470
  if (t) {
454
471
  let drop = null;
472
+ if (t.compacting)
473
+ await Promise.race([t.compacting, new Promise((r) => setTimeout(r, COMPACT_WAIT_MS))]);
455
474
  if (t.systemKey !== systemKey)
456
475
  drop = "system prompt changed";
457
476
  else if (t.cfgKey !== cfgKey) {
@@ -463,6 +482,11 @@ export class ACPOrchestratorModel {
463
482
  drop = "creation config changed";
464
483
  }
465
484
  }
485
+ // The previous prompt failed agent-side: talk to a new agent process, not to the one
486
+ // still holding that turn's leftovers (see `resync`).
487
+ if (!drop && t.resync && !(await this.reopenInPlace(t, ctrl, tools, systemMode, options.prompt, cfgKey, "recovering after an agent error"))) {
488
+ drop = "agent session out of sync";
489
+ }
466
490
  if (!drop) {
467
491
  // A changed tool set is applied to the LIVE session (MCP list_changed)
468
492
  // rather than forcing a new one.
@@ -472,8 +496,6 @@ export class ACPOrchestratorModel {
472
496
  t.toolsKey = toolsKey;
473
497
  dbg(`tools changed (${tools.length}) — refreshed in place, session kept`);
474
498
  }
475
- if (t.compacting)
476
- await Promise.race([t.compacting, new Promise((r) => setTimeout(r, COMPACT_WAIT_MS))]);
477
499
  let cls = this.classify(t, hist, keys, ctrl, options);
478
500
  // v2: OpenCode's checkpoint replaced the history. Keep the session: either it
479
501
  // compacted itself in step (adopt — only what follows the checkpoint is new), or
@@ -516,6 +538,8 @@ export class ACPOrchestratorModel {
516
538
  }
517
539
  live.pending = [];
518
540
  live.doneResp = null;
541
+ live.doneErr = null;
542
+ live.reopen = this.reopener(live, ctrl, tools, systemMode, options.prompt, cfgKey);
519
543
  live.controller = controller;
520
544
  live.lastActive = Date.now();
521
545
  live.isChild = isChildCall(options);
@@ -659,6 +683,10 @@ export class ACPOrchestratorModel {
659
683
  gen: 0,
660
684
  inflight: null,
661
685
  doneResp: null,
686
+ doneErr: null,
687
+ resync: false,
688
+ genEvents: 0,
689
+ reopen: null,
662
690
  aborted: false,
663
691
  stepItems: [],
664
692
  stepTimer: null,
@@ -672,6 +700,7 @@ export class ACPOrchestratorModel {
672
700
  lastActive: Date.now(),
673
701
  };
674
702
  ref.t = t;
703
+ t.reopen = this.reopener(t, ctrl, tools, systemMode, options.prompt, cfgKey);
675
704
  host.onToolCall((c) => this.onToolCall(t, c));
676
705
  host.onToolCancelled((id) => this.onToolCancelled(t, id));
677
706
  this.sessions.set(key, t);
@@ -732,6 +761,7 @@ export class ACPOrchestratorModel {
732
761
  t.appliedMode = undefined; // re-applied on the fork by applySessionConfig
733
762
  t.appliedEffort = undefined;
734
763
  t.appliedModel = undefined;
764
+ t.resync = false; // a fork is a new agent process: nothing of the old one is queued
735
765
  host.onToolCall((c) => this.onToolCall(t, c));
736
766
  host.onToolCancelled((id) => this.onToolCancelled(t, id));
737
767
  this.byAcpSession.set(t.sessionId, t);
@@ -746,6 +776,69 @@ export class ACPOrchestratorModel {
746
776
  return false;
747
777
  }
748
778
  }
779
+ /** `reopenInPlace` bound to the latest turn's profile, with its mode/model/effort
780
+ * re-applied — for a recovery that happens outside `startFresh`. */
781
+ reopener(t, ctrl, tools, systemMode, prompt, cfgKey) {
782
+ return async (why) => {
783
+ if (!(await this.reopenInPlace(t, ctrl, tools, systemMode, prompt, cfgKey, why)))
784
+ return false;
785
+ await this.applySessionConfig(t, ctrl);
786
+ return true;
787
+ };
788
+ }
789
+ /** Re-open `t`'s agent session in a NEW agent process under the same id: close it and
790
+ * resume it from its transcript. Whatever the old process still had queued is gone, and
791
+ * unlike a fork no transcript copy is written (a retry loop would write one per try).
792
+ * Falls back to a fork when the resume fails. */
793
+ async reopenInPlace(t, ctrl, tools, systemMode, prompt, cfgKey, why) {
794
+ if (t.inflight || t.pendingTools.size || t.pendingPermissions.size) {
795
+ this.abortTurn(t, why);
796
+ await this.settle(t);
797
+ }
798
+ const idPrefix = `acp_${randomBytes(5).toString("hex")}_`;
799
+ const host = new McpHost("opencode", idPrefix);
800
+ try {
801
+ await host.start();
802
+ host.setTools(tools);
803
+ // Awaited: resuming an id the agent still holds would hand back the same process.
804
+ let timer;
805
+ await Promise.race([
806
+ Promise.resolve(this.connection.extMethod?.("session/close", { sessionId: t.sessionId })).catch(() => { }),
807
+ new Promise((r) => { timer = setTimeout(r, SETTLE_MS); }),
808
+ ]);
809
+ clearTimeout(timer);
810
+ const meta = { claudeCode: { options: buildClaudeCodeOptions(ctrl) } };
811
+ const sysMeta = this.buildSystemPromptMeta(prompt, systemMode);
812
+ if (sysMeta !== undefined)
813
+ meta.systemPrompt = sysMeta;
814
+ const res = await this.connection.unstable_resumeSession({
815
+ sessionId: t.sessionId,
816
+ cwd: this.config.cwd ?? process.cwd(),
817
+ mcpServers: [host.getServerConfig()],
818
+ _meta: meta,
819
+ });
820
+ const oldHost = t.host;
821
+ t.host = host;
822
+ t.idPrefix = idPrefix;
823
+ t.ownPrefixes = [idPrefix, ...t.ownPrefixes].slice(0, 8);
824
+ t.cfgKey = cfgKey;
825
+ t.appliedMode = undefined; // re-applied on the new process by applySessionConfig
826
+ t.appliedEffort = undefined;
827
+ t.appliedModel = undefined;
828
+ t.defaultEffort = effortOption(res) ?? t.defaultEffort;
829
+ t.resync = false;
830
+ host.onToolCall((c) => this.onToolCall(t, c));
831
+ host.onToolCancelled((id) => this.onToolCancelled(t, id));
832
+ oldHost.stop();
833
+ note(`session ${t.sessionId} re-opened in a new agent process (${why}, context kept)`);
834
+ return true;
835
+ }
836
+ catch (e) {
837
+ host.stop();
838
+ dbg(`re-open of ${t.sessionId} failed (${e instanceof Error ? e.message : String(e)}) — forking instead`);
839
+ return this.forkInPlace(t, ctrl, tools, systemMode, prompt, cfgKey, undefined, why);
840
+ }
841
+ }
749
842
  /** Remember where this turn starts (index of its first user message) and Claude's
750
843
  * last transcript entry before it. */
751
844
  recordCheckpoint(t, hist, from) {
@@ -822,7 +915,10 @@ export class ACPOrchestratorModel {
822
915
  const done = this.connection
823
916
  .prompt({ sessionId: t.sessionId, prompt: [{ type: "text", text: "/compact" }] })
824
917
  .then(() => { if (gen === t.gen)
825
- t.adoptCheckpoint = true; }, (e) => dbg(`native /compact failed: ${errorText(e)}`))
918
+ t.adoptCheckpoint = true; }, (e) => {
919
+ note(`native /compact of ${t.sessionId} failed (${errorText(e)}) — the session is re-opened on the next turn`);
920
+ t.resync = true;
921
+ })
826
922
  .finally(() => {
827
923
  t.hidden = false;
828
924
  if (t.compacting === done)
@@ -937,27 +1033,72 @@ export class ACPOrchestratorModel {
937
1033
  /** Send a prompt as the session's newest generation. Completions of older ones — a
938
1034
  * cancelled turn, or the original prompt the agent resolves early when it merges a
939
1035
  * queued one — are ignored instead of closing the stream of the current turn. */
940
- sendPrompt(t, blocks) {
1036
+ sendPrompt(t, blocks, retry = true) {
1037
+ // An empty prompt (nothing new to say) may legitimately run nothing.
1038
+ if (!blocks.some((b) => b?.type !== "text" || b.text))
1039
+ retry = false;
941
1040
  const gen = ++t.gen;
942
1041
  t.aborted = false;
943
1042
  t.doneResp = null;
1043
+ t.doneErr = null;
1044
+ t.genEvents = 0;
944
1045
  const settled = this.connection
945
1046
  .prompt({ sessionId: t.sessionId, prompt: blocks })
946
1047
  .then((resp) => {
947
- if (gen === t.gen)
948
- this.onPromptDone(t, resp);
949
- else
1048
+ if (gen !== t.gen) {
950
1049
  dbg(`stale prompt completion ignored (gen ${gen} < ${t.gen}, ${resp?.stopReason})`);
1050
+ return;
1051
+ }
1052
+ if (retry && this.isStale(t, resp))
1053
+ return this.recoverStale(t, blocks);
1054
+ this.onPromptDone(t, resp);
951
1055
  }, (err) => {
952
- if (gen === t.gen)
953
- this.onPromptError(t, err);
954
- else
1056
+ if (gen !== t.gen) {
955
1057
  dbg(`stale prompt error ignored (gen ${gen} < ${t.gen})`);
1058
+ return;
1059
+ }
1060
+ if (retry && t.genEvents === 0 && isInterruptedCycle(err))
1061
+ return this.recoverStale(t, blocks);
1062
+ this.onPromptError(t, err);
956
1063
  })
957
1064
  .then(() => { if (t.inflight === settled)
958
1065
  t.inflight = null; });
959
1066
  t.inflight = settled;
960
1067
  }
1068
+ /** The agent ended the prompt on a turn-over left queued by an EARLIER turn (see
1069
+ * `resync`): `end_turn` with nothing streamed and a usage of exactly zero — a turn that
1070
+ * ran always bills a request. An agent that reports no usage is never flagged. */
1071
+ isStale(t, resp) {
1072
+ const u = resp?.usage;
1073
+ if (resp?.stopReason !== "end_turn" || t.genEvents > 0 || !u || typeof u !== "object")
1074
+ return false;
1075
+ return !(u.inputTokens || u.outputTokens || u.cachedReadTokens || u.cachedWriteTokens);
1076
+ }
1077
+ /** The prompt "finished" (or failed) without running and its real turn now runs unread.
1078
+ * Stop it, re-open the session and send the prompt again on the SAME stream, so OpenCode
1079
+ * only sees a slower answer instead of an empty one or an error. Once per prompt. */
1080
+ async recoverStale(t, blocks) {
1081
+ note(`session ${t.sessionId}: the agent ended a turn it never ran (leftover of an earlier turn) — re-opening the session`);
1082
+ // Stop the unread run (agent-side cancel, its calls released) but keep the stream.
1083
+ const controller = t.controller;
1084
+ this.abortTurn(t, "turn the agent never ran");
1085
+ t.aborted = false;
1086
+ // reopenInPlace checks for a busy turn synchronously, before its first await: hide
1087
+ // this one from that check only. Kept in flight otherwise, so a user turn arriving
1088
+ // meanwhile waits for the recovery (and cancels it) instead of racing it.
1089
+ const inflight = t.inflight;
1090
+ t.inflight = null;
1091
+ const reopening = t.reopen?.("recovering a turn the agent never ran");
1092
+ t.inflight = inflight;
1093
+ const ok = (await reopening) ?? false;
1094
+ if (this.sessions.get(t.key) !== t || t.aborted)
1095
+ return; // ended, or the user cancelled meanwhile
1096
+ t.controller = controller;
1097
+ if (ok)
1098
+ this.sendPrompt(t, blocks, false);
1099
+ else
1100
+ this.onPromptError(t, new Error("Claude Code: the agent session went out of sync and could not be re-opened. Send the message again."));
1101
+ }
961
1102
  /** Wait (bounded) for the running prompt to settle — e.g. after a cancel. */
962
1103
  async settle(t, ms = SETTLE_MS) {
963
1104
  const p = t.inflight;
@@ -986,6 +1127,7 @@ export class ACPOrchestratorModel {
986
1127
  t.textAcc.clear();
987
1128
  t.pending = [];
988
1129
  t.doneResp = null;
1130
+ t.doneErr = null;
989
1131
  if (t.stepTimer) {
990
1132
  clearTimeout(t.stepTimer);
991
1133
  t.stepTimer = null;
@@ -1062,9 +1204,17 @@ export class ACPOrchestratorModel {
1062
1204
  note(`session ${t.sessionId} lost agent-side — the next turn resumes it`);
1063
1205
  queueMicrotask(() => this.endTurn(t));
1064
1206
  }
1065
- if (!t.controller)
1066
- return;
1207
+ else {
1208
+ t.resync = true;
1209
+ }
1067
1210
  dbg(`prompt error: ${errorText(err)}`);
1211
+ // Failed while OpenCode runs a step (the stream is closed between a tool-call and its
1212
+ // continuation): kept for the continuation, which would otherwise wait forever.
1213
+ if (!t.controller) {
1214
+ if (!t.aborted)
1215
+ t.doneErr = err;
1216
+ return;
1217
+ }
1068
1218
  try {
1069
1219
  t.controller.enqueue({ type: "error", error: limitError(err) ?? err });
1070
1220
  t.controller.close();
@@ -1072,6 +1222,13 @@ export class ACPOrchestratorModel {
1072
1222
  catch { /* ignore */ }
1073
1223
  t.controller = null;
1074
1224
  }
1225
+ /** The prompt failed while no stream was attached: fail the current one with it. */
1226
+ failFromDone(t) {
1227
+ const err = t.doneErr;
1228
+ t.doneErr = null;
1229
+ this.flushPending(t);
1230
+ this.onPromptError(t, err);
1231
+ }
1075
1232
  /** Fired by the MCP host when the agent calls an OpenCode tool. The call is NOT
1076
1233
  * resolved here: it waits for OpenCode to run the tool and send the continuation. */
1077
1234
  onToolCall(t, call) {
@@ -1352,6 +1509,8 @@ export class ACPOrchestratorModel {
1352
1509
  if (!t)
1353
1510
  return;
1354
1511
  const update = params?.update;
1512
+ if (TURN_UPDATES.has(update?.sessionUpdate))
1513
+ t.genEvents++;
1355
1514
  // Mode switch (e.g. ExitPlanMode approved: plan → default). Track it even without a
1356
1515
  // live controller so the bridge stays in sync and won't re-force the agent's
1357
1516
  // configured mode on the next turn (which would undo the plan-exit).
@@ -1555,16 +1714,32 @@ export class ACPOrchestratorModel {
1555
1714
  ctrl.model = modelId;
1556
1715
  return ctrl;
1557
1716
  }
1717
+ /** session/set_model, or — claude-agent-acp ≥ 0.99 dropped it ("Method not found") —
1718
+ * the `model` config option, which takes the same ids. Learned once per connection. */
1719
+ async setModel(sessionId, modelId) {
1720
+ if (!this.modelByConfig) {
1721
+ try {
1722
+ await this.connection.unstable_setSessionModel({ sessionId, modelId });
1723
+ return;
1724
+ }
1725
+ catch (e) {
1726
+ if (e?.code !== -32601)
1727
+ throw e;
1728
+ this.modelByConfig = true;
1729
+ }
1730
+ }
1731
+ await this.connection.setSessionConfigOption({ sessionId, configId: "model", value: modelId });
1732
+ }
1558
1733
  /** Apply runtime config (mode/effort) to a live ACP session via set_mode/set_config_option. */
1559
1734
  async applySessionConfig(t, ctrl) {
1560
1735
  if (ctrl.model && ctrl.model !== t.appliedModel) {
1561
1736
  try {
1562
- await this.connection.unstable_setSessionModel({ sessionId: t.sessionId, modelId: ctrl.model });
1737
+ await this.setModel(t.sessionId, ctrl.model);
1563
1738
  t.appliedModel = ctrl.model;
1564
1739
  dbg(`model → ${ctrl.model}`);
1565
1740
  }
1566
1741
  catch (e) {
1567
- note(`warning: could not apply model ${ctrl.model} (${e instanceof Error ? e.message : String(e)})`);
1742
+ note(`warning: could not apply model ${ctrl.model} (${errorText(e)})`);
1568
1743
  }
1569
1744
  }
1570
1745
  // A CHANGED request (the user reselected the plan agent) overrides a mode the agent
@@ -1650,6 +1825,9 @@ export class ACPOrchestratorModel {
1650
1825
  },
1651
1826
  async writeTextFile() { return {}; },
1652
1827
  async readTextFile() { return { content: "" }; },
1828
+ // Agent notices (claude-agent-acp ≥ 0.99 sends `_auth/status_update`): not ours,
1829
+ // but unhandled they print an SDK error over OpenCode's output.
1830
+ async extNotification() { },
1653
1831
  }), stream);
1654
1832
  const initResult = await this.connection.initialize({
1655
1833
  protocolVersion: PROTOCOL_VERSION,