opencode-claude-code-acpbridge 0.12.0 → 0.14.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.
@@ -26,7 +26,6 @@
26
26
  import { spawn } from "node:child_process";
27
27
  import { Writable, Readable } from "node:stream";
28
28
  import { randomBytes } from "node:crypto";
29
- import { closeSync, fstatSync, openSync, readSync } from "node:fs";
30
29
  import { homedir } from "node:os";
31
30
  import { join } from "node:path";
32
31
  import { ClientSideConnection, ndJsonStream, PROTOCOL_VERSION } from "@agentclientprotocol/sdk";
@@ -37,7 +36,8 @@ import { setLink, updateUsage } from "../plugin/sessions.js";
37
36
  import { addAlwaysRule, evaluate as evaluateBridge } from "../plugin/bridge-rules.js";
38
37
  import { DEBUG, logger } from "../log.js";
39
38
  import { record, recording, sanitizePrompt } from "./recorder.js";
40
- import { anchorsOf, classifyAnchors, classifyHistory, firstUserText, hashText, historyOf, isTransient, msgKey, stripInjected, systemText, } from "./history.js";
39
+ import { anchorsHash, anchorsOf, classifyAnchors, endsWithBridgeNotice, bridgeNoticeText, classifyHistory, firstUserText, hashText, historyOf, isTransient, msgKey, pickCheckpoint, prefixHash, sharedExtent, stripInjected, systemText, verifiedCheckpoint, } from "./history.js";
40
+ import { lastAssistantUuid, transcriptPath, userAfter } from "./transcript.js";
41
41
  const log = logger("acp-orchestrator");
42
42
  const dbg = log.dbg;
43
43
  /** Always-on notices (session lifecycle) — the user needs these without ACP_DEBUG. */
@@ -58,6 +58,10 @@ const CATCHUP_RESULT_CHARS = 8000;
58
58
  /** Ceiling for a full-history replay into a new session (~100k tokens): beyond it the
59
59
  * oldest turns are dropped — a 656k-char replay was seen in the wild. */
60
60
  const REPLAY_BUDGET_CHARS = 400_000;
61
+ /** A full replay smaller than this goes out in one prompt (re-replaying it is cheap). */
62
+ const SPLIT_REPLAY_MIN_CHARS = 20_000;
63
+ /** Longest a context-only replay turn may take before the replay is sent whole instead. */
64
+ const PRIME_TIMEOUT_MS = 5 * 60_000;
61
65
  /** Tope del buffer `pending` (chunks emitidos sin controller vivo): sin cap un turno
62
66
  * largo con el stream cerrado lo haría crecer sin límite (OOM). */
63
67
  const MAX_PENDING_PARTS = 1000;
@@ -107,6 +111,19 @@ function isInterrupted(output) {
107
111
  return true;
108
112
  return /^(Tool execution interrupted|Tool result missing)/.test(text.trim());
109
113
  }
114
+ /** Whether the agent cuts a fork at an ACP cursor (see `forkByCursor`). `auto` decides by the
115
+ * agent's version: the cursor fork arrived in claude-agent-acp 0.109; an agent that doesn't
116
+ * report one keeps the `resumeSessionAt` way. */
117
+ export function forkUsesCursor(setting, version) {
118
+ if (setting === "cursor")
119
+ return true;
120
+ if (setting === "resumeSessionAt")
121
+ return false;
122
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(String(version ?? ""));
123
+ if (!m)
124
+ return false;
125
+ return Number(m[1]) > 0 || Number(m[2]) >= 109;
126
+ }
110
127
  function ownTextKey(text) {
111
128
  return hashText(stripInjected(text).trim());
112
129
  }
@@ -261,6 +278,10 @@ export class ACPOrchestratorModel {
261
278
  promptCaps = {};
262
279
  /** The agent merges a prompt sent mid-turn into the running turn (claude-agent-acp). */
263
280
  promptQueueing = false;
281
+ /** How a fork is cut at a checkpoint: by ACP `cursorId` (claude-agent-acp ≥ 0.109: the fork
282
+ * copies the transcript with FRESH uuids, so `resumeSessionAt` of the source no longer
283
+ * exists in it) or by `resumeSessionAt` in the creation options (older agents). */
284
+ forkByCursor = false;
264
285
  /** The agent has no session/set_model: models go through the `model` config option. */
265
286
  modelByConfig = false;
266
287
  constructor(config) {
@@ -277,6 +298,28 @@ export class ACPOrchestratorModel {
277
298
  const po = this.providerOptions(options);
278
299
  if (po.pairedAgent === false)
279
300
  throw pairingError(po.ocAgent, this.callModel.get(options) ?? this.modelId);
301
+ // A turn woken only by a note the bridge posted for the user (`/sessions-acp`): answered
302
+ // here, empty, without calling the agent — the note is for the user, not for Claude.
303
+ if (endsWithBridgeNotice(options.prompt)) {
304
+ dbg(`bridge notice only — turn answered without the agent`);
305
+ const stream = new ReadableStream({
306
+ start: (controller) => {
307
+ controller.enqueue({ type: "stream-start", warnings: [] });
308
+ // The UIs show a synthetic message by its description only: the note goes out as
309
+ // this turn's answer (it starts with the marker too, so it never reaches Claude).
310
+ const text = bridgeNoticeText(options.prompt);
311
+ if (text) {
312
+ const id = `notice-${Date.now()}`;
313
+ controller.enqueue({ type: "text-start", id });
314
+ controller.enqueue({ type: "text-delta", id, delta: text });
315
+ controller.enqueue({ type: "text-end", id });
316
+ }
317
+ controller.enqueue({ type: "finish", usage: emptyUsage(), finishReason: { unified: "stop", raw: "bridge-notice" } });
318
+ controller.close();
319
+ },
320
+ });
321
+ return { stream, warnings: [] };
322
+ }
280
323
  if (recording()) {
281
324
  record(this.convId(options), {
282
325
  kind: "call",
@@ -341,8 +384,7 @@ export class ACPOrchestratorModel {
341
384
  // Without queueing it rides on the last tool result instead.
342
385
  // Keep the registry in step mid-turn too: a restart now resumes right here
343
386
  // instead of replaying every tool round-trip since the user's message.
344
- if (t.ocSession)
345
- setLink(t.ocSession, t.sessionId, t.sentKeys.length, t.convKey, t.ownPrefixes, t.cwd);
387
+ this.persistLink(t, t.sentKeys.length, t.sentAnchors);
346
388
  const extraBlocks = continuation.extras.length ? this.midTurnBlocks(t, continuation.extras) : [];
347
389
  const results = continuation.results;
348
390
  const lastTool = results.map((r) => !t.pendingPermissions.has(r.toolCallId)).lastIndexOf(true);
@@ -513,12 +555,20 @@ export class ACPOrchestratorModel {
513
555
  // fork the session at Claude's state right before it. Nothing is replayed and the
514
556
  // shared prefix stays cached; anything unexpected falls back to a new session.
515
557
  if (cls.kind !== "append" && ctrl.smartRevert !== false) {
516
- const at = classifyHistory(t.sentKeys, keys).fromIndex;
517
- const cp = t.checkpoints.find((c) => c.at === at);
518
- if (cp && (await this.forkInPlace(t, ctrl, tools, systemMode, options.prompt, cfgKey, { resumeSessionAt: cp.uuid }, "revert"))) {
558
+ // Anchors (not the legacy per-message keys) locate the rewind point in v2/shadow-v2:
559
+ // the legacy key of an old, re-rendered message would put it far too early.
560
+ const cur = t;
561
+ const legacyAt = classifyHistory(cur.sentKeys, keys).fromIndex;
562
+ const cp = mode === "v2"
563
+ ? pickCheckpoint(cur.checkpoints, sharedExtent(cur.sentAnchors, hist))
564
+ : cur.checkpoints.find((c) => c.at === legacyAt);
565
+ if (!cp)
566
+ dbg(`smartRevert: no checkpoint for the rewind (extent ${mode === "v2" ? sharedExtent(cur.sentAnchors, hist) : legacyAt}, hist ${hist.length}, checkpoints [${cur.checkpoints.map((c) => c.at).join(",")}])`);
567
+ if (cp && (await this.forkInPlace(t, ctrl, tools, systemMode, options.prompt, cfgKey, undefined, "revert", cp))) {
568
+ const at = cp.at;
519
569
  this.markKnown(t, hist.slice(0, at));
520
570
  t.checkpoints = t.checkpoints.filter((c) => c.at < at);
521
- this.decide(options, { decision: "smart-revert", session: t.sessionId, at, uuid: cp.uuid });
571
+ this.decide(options, { decision: "smart-revert", session: t.sessionId, at, uuid: cp.uuid, from: cp.sid });
522
572
  cls = { kind: "append", fromIndex: at };
523
573
  }
524
574
  }
@@ -565,8 +615,7 @@ export class ACPOrchestratorModel {
565
615
  if (ctrl.smartRevert !== false)
566
616
  this.recordCheckpoint(live, hist, cls.fromIndex);
567
617
  this.markKnown(live, hist);
568
- if (ocSession)
569
- setLink(ocSession, live.sessionId, hist.length, convKey, live.ownPrefixes, live.cwd);
618
+ this.persistLink(live, hist.length, live.sentAnchors);
570
619
  this.sendPrompt(live, blocks.length ? blocks : [{ type: "text", text: "" }]);
571
620
  return;
572
621
  }
@@ -597,11 +646,15 @@ export class ACPOrchestratorModel {
597
646
  // history grew rather than diverged) → no history replay (saves tokens). Else
598
647
  // create a fresh session and replay the full history.
599
648
  const resumeId = po.resumeId;
600
- const resumeLen = typeof po.resumeLen === "number" ? po.resumeLen : 0;
649
+ let resumeLen = typeof po.resumeLen === "number" ? po.resumeLen : 0;
601
650
  const resumePrefixes = Array.isArray(po.resumeIdPrefixes) ? po.resumeIdPrefixes.map(String) : [];
651
+ const resumeCps = Array.isArray(po.resumeCheckpoints)
652
+ ? po.resumeCheckpoints.filter((c) => c && typeof c.uuid === "string" && typeof c.sid === "string" && typeof c.at === "number")
653
+ : [];
602
654
  let sessionId;
603
655
  let replayFull = true;
604
656
  let defaultEffort;
657
+ let carriedCps = [];
605
658
  // A registry entry for a DIFFERENT conversation (first message changed: compaction,
606
659
  // or a reused id) must not be resumed — the agent would carry the wrong context.
607
660
  const sameConv = !po.resumeConvKey || po.resumeConvKey === convKey;
@@ -611,27 +664,69 @@ export class ACPOrchestratorModel {
611
664
  // resumed where it was created: its transcript lives under that directory's slug, and
612
665
  // entries from before the registry kept one were all created in the default.
613
666
  let cwd = this.sessionCwd(po);
614
- if (resumeId && sameConv && resumeLen > 0 && hist.length > resumeLen) {
667
+ if (resumeId && sameConv && resumeLen > 0) {
615
668
  const resumeCwd = typeof po.resumeCwd === "string" && po.resumeCwd ? po.resumeCwd : this.defaultCwd();
616
- try {
617
- const resumed = await this.connection.unstable_resumeSession({
618
- sessionId: resumeId,
619
- cwd: resumeCwd,
620
- mcpServers: [serverConfig],
621
- // Re-apply the clean-brain options on resume too. Without this the agent
622
- // falls back to its defaults (--tools default, --setting-sources=user,
623
- // project,local, no --strict-mcp-config) and the resumed session regains
624
- // native tools + the claude.ai connectors.
625
- _meta: { claudeCode: { options: buildClaudeCodeOptions(ctrl) } },
626
- });
627
- sessionId = resumeId;
628
- replayFull = false;
629
- cwd = resumeCwd;
630
- defaultEffort = effortOption(resumed);
631
- dbg(`resume ${resumeId} (oc=${ocSession ?? "?"}) — no history replay`);
669
+ // The registry proves what the agent session holds (`sentHash`): a history that no
670
+ // longer starts with it was rewound, and resuming would bring the undone turns back.
671
+ const rewound = typeof po.resumeSentHash === "string" && prefixHash(hist, resumeLen) !== po.resumeSentHash;
672
+ if (!rewound && hist.length > resumeLen) {
673
+ try {
674
+ const resumed = await this.connection.unstable_resumeSession({
675
+ sessionId: resumeId,
676
+ cwd: resumeCwd,
677
+ mcpServers: [serverConfig],
678
+ // Re-apply the clean-brain options on resume too. Without this the agent
679
+ // falls back to its defaults (--tools default, --setting-sources=user,
680
+ // project,local, no --strict-mcp-config) and the resumed session regains
681
+ // native tools + the claude.ai connectors.
682
+ _meta: { claudeCode: { options: buildClaudeCodeOptions(ctrl) } },
683
+ });
684
+ sessionId = resumeId;
685
+ replayFull = false;
686
+ cwd = resumeCwd;
687
+ carriedCps = resumeCps;
688
+ defaultEffort = effortOption(resumed);
689
+ dbg(`resume ${resumeId} (oc=${ocSession ?? "?"}) — no history replay`);
690
+ }
691
+ catch (e) {
692
+ dbg(`resume ${resumeId} failed (${e instanceof Error ? e.message : String(e)}) — fresh session`);
693
+ }
632
694
  }
633
- catch (e) {
634
- dbg(`resume ${resumeId} failed (${e instanceof Error ? e.message : String(e)}) — fresh session`);
695
+ else if (rewound && ctrl.smartRevert !== false) {
696
+ // Rewound while no process held the session (restart, idle eviction): fork the
697
+ // transcript at the newest rewind point the history still matches.
698
+ const cp = verifiedCheckpoint(resumeCps, hist);
699
+ if (!cp) {
700
+ // Why no rewind point matched: each checkpoint's recorded prefix hash against the incoming one.
701
+ const anchors = anchorsOf(hist);
702
+ const seen = resumeCps.map((c) => {
703
+ const n = anchors.filter((x) => x.at < c.at).length;
704
+ return `${c.at}:${c.h ?? "-"}→${anchorsHash(anchors.slice(0, n).map((x) => x.key))}`;
705
+ });
706
+ dbg(`smartRevert: no registry checkpoint matches (hist ${hist.length}, sent ${resumeLen}, ${po.resumeSentHash}→${prefixHash(hist, resumeLen)}; checkpoints ${seen.join(" ") || "none"})`);
707
+ }
708
+ if (cp) {
709
+ const meta = { claudeCode: { options: buildClaudeCodeOptions(ctrl) } };
710
+ const sysMeta = this.buildSystemPromptMeta(options.prompt, systemMode);
711
+ if (sysMeta !== undefined)
712
+ meta.systemPrompt = sysMeta;
713
+ try {
714
+ const forked = await this.forkSessionAt(resumeId, resumeCwd, [serverConfig], meta, cp);
715
+ if (!forked?.sessionId)
716
+ throw new Error("fork returned no sessionId");
717
+ sessionId = forked.sessionId;
718
+ replayFull = false;
719
+ cwd = resumeCwd;
720
+ resumeLen = cp.at;
721
+ carriedCps = resumeCps.filter((c) => c.at < cp.at);
722
+ defaultEffort = effortOption(forked);
723
+ this.decide(options, { decision: "smart-revert", session: sessionId, at: cp.at, uuid: cp.uuid, from: cp.sid, source: "registry" });
724
+ note(`session ${cp.sid} → fork ${sessionId} (revert after a restart, context kept) — resumable with: claude --resume ${sessionId}`);
725
+ }
726
+ catch (e) {
727
+ dbg(`fork of ${cp.sid} at ${cp.uuid} failed (${e instanceof Error ? e.message : String(e)}) — fresh session`);
728
+ }
729
+ }
635
730
  }
636
731
  }
637
732
  if (!sessionId) {
@@ -699,7 +794,7 @@ export class ACPOrchestratorModel {
699
794
  stepTimer: null,
700
795
  queuedItems: [],
701
796
  nativeCalls: new Map(),
702
- checkpoints: [],
797
+ checkpoints: carriedCps,
703
798
  compacting: null,
704
799
  hidden: false,
705
800
  adoptCheckpoint: false,
@@ -715,17 +810,44 @@ export class ACPOrchestratorModel {
715
810
  this.evictIdleSessions();
716
811
  this.startSweeper();
717
812
  await this.applySessionConfig(t, ctrl);
718
- if (ocSession)
719
- setLink(ocSession, sessionId, hist.length, convKey, t.ownPrefixes, t.cwd);
813
+ // The state of the agent before the tail goes out: where a later revert can rewind to.
814
+ if (!replayFull && ctrl.smartRevert !== false)
815
+ this.recordCheckpoint(t, hist, resumeLen);
816
+ this.persistLink(t, hist.length, anchorsOf(hist).map((a) => a.key));
720
817
  // Resume: the registry may lag behind (process died mid-turn), and the agent's own
721
818
  // last answer follows the recorded point — the resumed session already has it.
722
819
  const tail = replayFull ? hist : this.dropOwnLead(t, hist.slice(resumeLen));
723
820
  if (DEBUG && !replayFull)
724
821
  dbg(`resume — catch-up ${tail.length} msg(s)`);
822
+ const ctxBlocks = this.contextBlocks(t, options.prompt, ctrl);
725
823
  const promptBlocks = [
726
- ...this.contextBlocks(t, options.prompt, ctrl),
824
+ ...ctxBlocks,
727
825
  ...(tail.length ? this.blocksFor(tail, t, replayFull ? "replay" : "tail") : [{ type: "text", text: "" }]),
728
826
  ];
827
+ // Split replay: a replayed history is ONE transcript entry, so a later revert to the
828
+ // prompt that came with it had nowhere to fork and replayed everything again (and again).
829
+ // The history goes first as a hidden, context-only turn; the prompt follows as a normal
830
+ // turn, with a checkpoint right before it.
831
+ const split = replayFull ? this.replaySplit(hist, ctrl, promptBlocks) : -1;
832
+ if (split > 0) {
833
+ const histBlocks = [...ctxBlocks, ...this.replayBlocks(hist.slice(0, split), t, true)];
834
+ this.decide(options, {
835
+ decision: "new", session: sessionId, keys: keys.length, tail: tail.length,
836
+ chars: blocksChars(promptBlocks), split, primeChars: blocksChars(histBlocks),
837
+ });
838
+ this.markKnown(t, hist);
839
+ if (await this.primeReplay(t, histBlocks)) {
840
+ this.recordCheckpoint(t, hist, split);
841
+ this.persistLink(t, hist.length, anchorsOf(hist).map((a) => a.key));
842
+ this.sendPrompt(t, this.blocksFor(hist.slice(split), t, "tail"));
843
+ return;
844
+ }
845
+ if (t.aborted)
846
+ return;
847
+ note(`session ${sessionId}: context-only replay turn failed — sending the whole replay at once`);
848
+ this.sendPrompt(t, promptBlocks);
849
+ return;
850
+ }
729
851
  this.decide(options, {
730
852
  decision: replayFull ? "new" : "resume", session: sessionId, keys: keys.length,
731
853
  tail: tail.length, chars: blocksChars(promptBlocks),
@@ -733,10 +855,75 @@ export class ACPOrchestratorModel {
733
855
  this.markKnown(t, hist);
734
856
  this.sendPrompt(t, promptBlocks);
735
857
  }
858
+ /** Where a full replay is split (index of the trailing user messages = the new prompt), or
859
+ * -1: only when smartRevert is on, the history ends with the user's prompt and what comes
860
+ * before it is worth a fork point (`splitReplayMinChars`, default 20 000). */
861
+ replaySplit(hist, ctrl, blocks) {
862
+ if (ctrl.smartRevert === false || ctrl.splitReplay === false)
863
+ return -1;
864
+ let cut = hist.length;
865
+ while (cut > 0 && hist[cut - 1].role === "user")
866
+ cut--;
867
+ if (cut === 0 || cut === hist.length)
868
+ return -1;
869
+ return blocksChars(blocks) >= (ctrl.splitReplayMinChars ?? SPLIT_REPLAY_MIN_CHARS) ? cut : -1;
870
+ }
871
+ /** Context-only turn (output hidden, tools refused): the replayed history lands in the
872
+ * agent's session as a turn of its own. False when it didn't end normally in time. */
873
+ async primeReplay(t, blocks) {
874
+ t.hidden = true;
875
+ t.priming = true;
876
+ let timer;
877
+ try {
878
+ const timeout = new Promise((r) => { timer = setTimeout(() => r("timeout"), PRIME_TIMEOUT_MS); });
879
+ const resp = await Promise.race([this.connection.prompt({ sessionId: t.sessionId, prompt: blocks }), timeout]);
880
+ if (resp === "timeout") {
881
+ try {
882
+ await this.connection.cancel({ sessionId: t.sessionId });
883
+ }
884
+ catch { /* ignore */ }
885
+ return false;
886
+ }
887
+ dbg(`context-only replay turn of ${t.sessionId}: ${resp?.stopReason}`);
888
+ return resp?.stopReason === "end_turn";
889
+ }
890
+ catch (e) {
891
+ dbg(`context-only replay turn of ${t.sessionId} failed (${errorText(e)})`);
892
+ return false;
893
+ }
894
+ finally {
895
+ if (timer)
896
+ clearTimeout(timer);
897
+ t.hidden = false;
898
+ t.priming = false;
899
+ }
900
+ }
901
+ /** Directory Claude Code keeps its projects (and transcripts) in. */
902
+ claudeConfigDir() {
903
+ return resolveConfigDir(this.config.claudeCode ?? {}) ?? join(homedir(), ".claude");
904
+ }
905
+ /** `session/fork`. Without `at`: the whole session of `sessionId`. With a checkpoint: the
906
+ * session the checkpoint was taken in (`at.sid`), cut right before the turn that followed it.
907
+ * Throws when the point can't be located (the caller falls back to a new session). */
908
+ async forkSessionAt(sessionId, cwd, mcpServers, meta, at) {
909
+ const params = { sessionId: at?.sid ?? sessionId, cwd, mcpServers, _meta: meta };
910
+ if (at) {
911
+ if (this.forkByCursor) {
912
+ const user = userAfter(transcriptPath(this.claudeConfigDir(), cwd, at.sid), at.uuid);
913
+ if (!user)
914
+ throw new Error(`no prompt after transcript entry ${at.uuid} of ${at.sid}`);
915
+ params.cursorId = `before:${user}`;
916
+ }
917
+ else {
918
+ meta.claudeCode = { ...meta.claudeCode, options: { ...meta.claudeCode?.options, resumeSessionAt: at.uuid } };
919
+ }
920
+ }
921
+ return this.connection.unstable_forkSession(params);
922
+ }
736
923
  /** Swap `t` onto a fork of its ACP session created with the current profile. The
737
924
  * fork carries the whole transcript, so what `t` knows (sentKeys, own output) still
738
925
  * holds; it gets its own MCP host. The old session is closed. */
739
- async forkInPlace(t, ctrl, tools, systemMode, prompt, cfgKey, extra, why = "agent profile changed") {
926
+ async forkInPlace(t, ctrl, tools, systemMode, prompt, cfgKey, extra, why = "agent profile changed", at) {
740
927
  if (t.inflight || t.pendingTools.size || t.pendingPermissions.size) {
741
928
  this.abortTurn(t, why);
742
929
  await this.settle(t);
@@ -750,12 +937,7 @@ export class ACPOrchestratorModel {
750
937
  const sysMeta = this.buildSystemPromptMeta(prompt, systemMode);
751
938
  if (sysMeta !== undefined)
752
939
  meta.systemPrompt = sysMeta;
753
- const res = await this.connection.unstable_forkSession({
754
- sessionId: t.sessionId,
755
- cwd: t.cwd, // the source transcript is found under its own directory's slug
756
- mcpServers: [host.getServerConfig()],
757
- _meta: meta,
758
- });
940
+ const res = await this.forkSessionAt(t.sessionId, t.cwd, [host.getServerConfig()], meta, at);
759
941
  if (!res?.sessionId)
760
942
  throw new Error("fork returned no sessionId");
761
943
  const old = { id: t.sessionId, host: t.host };
@@ -854,39 +1036,19 @@ export class ACPOrchestratorModel {
854
1036
  at++;
855
1037
  if (at >= hist.length || t.checkpoints.some((c) => c.at === at))
856
1038
  return;
857
- const uuid = this.lastAssistantUuid(t);
1039
+ const uuid = lastAssistantUuid(transcriptPath(this.claudeConfigDir(), t.cwd, t.sessionId));
858
1040
  if (uuid)
859
- t.checkpoints.push({ at, uuid });
1041
+ t.checkpoints.push({ at, uuid, sid: t.sessionId, h: prefixHash(hist, at) });
860
1042
  }
861
- /** uuid of the last main-thread assistant entry in the session's transcript
862
- * (`<configDir>/projects/<cwd as slug>/<sessionId>.jsonl`), read from its tail. */
863
- lastAssistantUuid(t) {
864
- try {
865
- const dir = resolveConfigDir(this.config.claudeCode ?? {}) ?? join(homedir(), ".claude");
866
- const slug = t.cwd.replace(/[^a-zA-Z0-9]/g, "-");
867
- const file = join(dir, "projects", slug, `${t.sessionId}.jsonl`);
868
- const fd = openSync(file, "r");
869
- try {
870
- const size = fstatSync(fd).size;
871
- const len = Math.min(size, 256 * 1024);
872
- const buf = Buffer.alloc(len);
873
- readSync(fd, buf, 0, len, size - len);
874
- const lines = buf.toString("utf8").split("\n");
875
- for (let i = lines.length - 1; i >= 0; i--) {
876
- try {
877
- const e = JSON.parse(lines[i]);
878
- if (e?.type === "assistant" && typeof e.uuid === "string" && !e.isSidechain)
879
- return e.uuid;
880
- }
881
- catch { /* partial first line */ }
882
- }
883
- }
884
- finally {
885
- closeSync(fd);
886
- }
887
- }
888
- catch { /* no transcript (other configDir, agent not writing one) */ }
889
- return undefined;
1043
+ /** Keep the registry in step: where the agent session is up to (length + proof) and its
1044
+ * rewind points, so a new process can resume it — or fork it at a revert. */
1045
+ persistLink(t, len, anchorKeys) {
1046
+ if (!t.ocSession)
1047
+ return;
1048
+ setLink(t.ocSession, t.sessionId, len, t.convKey, t.ownPrefixes, t.cwd, {
1049
+ sentHash: anchorsHash(anchorKeys),
1050
+ checkpoints: t.checkpoints.slice(-48),
1051
+ });
890
1052
  }
891
1053
  /** Free the agent-side session (its Claude Code process and MCP servers). The client
892
1054
  * SDK has no method for it; the agent implements `session/close`. */
@@ -915,6 +1077,26 @@ export class ACPOrchestratorModel {
915
1077
  this.sendPrompt(t, this.lastUserBlocks(options.prompt));
916
1078
  return true;
917
1079
  }
1080
+ /** Claude Code compacts at `autoCompactPct` on its own — except in a fork (it ignores
1081
+ * CLAUDE_AUTOCOMPACT_PCT_OVERRIDE there) and in a few other cases where it waits for the
1082
+ * model's whole window. Every request re-reads the context, so a session left to grow
1083
+ * to ~1M is the most expensive kind. After a turn whose context is past the threshold,
1084
+ * the session is compacted here (hidden `/compact`; the next turn waits for it). */
1085
+ selfCompact(t) {
1086
+ const ctrl = this.config.claudeCode ?? {};
1087
+ const pct = ctrl.autoCompactPct ?? 75;
1088
+ const used = t.contextUsed, size = t.contextSize;
1089
+ if (!pct || ctrl.selfCompact === false || !used || !size || t.compacting || t.hidden)
1090
+ return;
1091
+ if (used < (size * pct) / 100)
1092
+ return;
1093
+ // Didn't shrink last time: try again only once it has grown another 10 %.
1094
+ if (t.selfCompactedAt && used < t.selfCompactedAt * 1.1)
1095
+ return;
1096
+ t.selfCompactedAt = used;
1097
+ note(`session ${t.sessionId}: context ${used}/${size} past ${pct}% — compacting it (native /compact)`);
1098
+ this.nativeCompact(t);
1099
+ }
918
1100
  /** Native `/compact` of the live session, output hidden. */
919
1101
  nativeCompact(t) {
920
1102
  t.hidden = true;
@@ -1200,6 +1382,8 @@ export class ACPOrchestratorModel {
1200
1382
  const after = t.afterTurn;
1201
1383
  t.afterTurn = null;
1202
1384
  after?.();
1385
+ if (!after)
1386
+ this.selfCompact(t);
1203
1387
  // A tool-less side call (title/summary in programmatic use) never continues.
1204
1388
  if (t.key.endsWith(":notools"))
1205
1389
  queueMicrotask(() => this.endTurn(t));
@@ -1243,6 +1427,10 @@ export class ACPOrchestratorModel {
1243
1427
  t.host.rejectToolCall(call.toolCallId, "Turn aborted");
1244
1428
  return;
1245
1429
  }
1430
+ if (t.priming) {
1431
+ t.host.rejectToolCall(call.toolCallId, "Context-only turn: no tools now. Reply with exactly: OK");
1432
+ return;
1433
+ }
1246
1434
  dbg(`agent → tool-call ${call.name} (${call.toolCallId}) → emit to OpenCode`);
1247
1435
  t.pendingTools.add(call.toolCallId);
1248
1436
  // `call.args` puede traer refs circulares/BigInt → JSON.stringify lanzaría y
@@ -1541,6 +1729,8 @@ export class ACPOrchestratorModel {
1541
1729
  case "usage_update":
1542
1730
  if (typeof update.used === "number")
1543
1731
  t.contextUsed = update.used;
1732
+ if (typeof update.size === "number" && update.size > 0)
1733
+ t.contextSize = update.size;
1544
1734
  break;
1545
1735
  case "agent_message_chunk":
1546
1736
  if (update.content?.type === "text") {
@@ -1853,6 +2043,7 @@ export class ACPOrchestratorModel {
1853
2043
  });
1854
2044
  this.promptCaps = (initResult?.agentCapabilities?.promptCapabilities ?? {});
1855
2045
  this.promptQueueing = !!initResult?.agentCapabilities?._meta?.claudeCode?.promptQueueing;
2046
+ this.forkByCursor = forkUsesCursor(this.config.claudeCode?.smartRevertFork, initResult?.agentInfo?.version);
1856
2047
  dbg(`connected to agent — promptCapabilities: ${JSON.stringify(this.promptCaps)}`);
1857
2048
  }
1858
2049
  openTransport() {
@@ -2031,10 +2222,11 @@ export class ACPOrchestratorModel {
2031
2222
  }
2032
2223
  return blocks;
2033
2224
  }
2034
- replayBlocks(msgs, t) {
2225
+ replayBlocks(msgs, t, contextOnly = false) {
2035
2226
  let cut = msgs.length;
2036
- while (cut > 0 && msgs[cut - 1].role === "user")
2037
- cut--;
2227
+ if (!contextOnly)
2228
+ while (cut > 0 && msgs[cut - 1].role === "user")
2229
+ cut--;
2038
2230
  const current = msgs.slice(cut).flatMap((m) => this.messageToBlocks(m, false, t));
2039
2231
  let rendered = msgs.slice(0, cut).map((m) => this.renderMessage(m, t)).filter((b) => b.length);
2040
2232
  if (!rendered.length)
@@ -2051,7 +2243,9 @@ export class ACPOrchestratorModel {
2051
2243
  ...(omitted ? [{ type: "text", text: `<omitted messages="${omitted}" reason="replay budget"/>` }] : []),
2052
2244
  ...rendered.slice(1).flat(),
2053
2245
  { type: "text", text: "</conversation_history>" },
2054
- ...(current.length ? current : [{ type: "text", text: "(Continue the conversation above.)" }]),
2246
+ ...(contextOnly
2247
+ ? [{ type: "text", text: "(This turn only restores context; the user's next message follows. Do not run any tool and do not act on the history. Reply with exactly: OK)" }]
2248
+ : current.length ? current : [{ type: "text", text: "(Continue the conversation above.)" }]),
2055
2249
  ];
2056
2250
  }
2057
2251
  /** One message as tagged blocks (for history and other models' turns). Reasoning and