Repository navigation
fix: keep Cursor conversations consistent across OpenCode 2.x subagents, model switches and host notes - #34
Conversation
A Cursor conversation only contains what Cursor produced. When a session switches to another provider, a local model, or a different Cursor model and then back, resuming the old checkpoint hides that work from Cursor and has been observed to end Runs with `Cursor API error (code=internal)` after visible output, where automatic retry is unsafe. Record the text and tool call ids this provider emits per OpenCode session (persisted with the conversation cache). Before a fresh Run, compare them with the host's latest assistant turn; on a model switch or a foreign turn, start a new Cursor conversation seeded with the full host history including tool results. If that history would exceed 80% of the model context, raise a 413 "prompt is too long" APICallError before opening the Run so the host compacts. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Record only the latest non-empty host step and require an exact match, so a foreign "Done." no longer matches an older Cursor turn's text. - Cap tracked sessions at MAX_PROVENANCE_SESSIONS (LRU, mirrors MAX_TURN_STATE_SESSIONS) and re-hydrate an evicted entry from the persisted conversation cache. - A foreign-history reseed resends history images like a recovery rebase. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Identify a step by its first 64 tool call ids and first 4 KiB of text, so the LRU-bounded map holds at most ~1 MiB instead of ~16 MiB. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A fresh turn resumed from a stored checkpoint can fail with `Cursor API error (code=internal)` right after Cursor requests KV blobs the client does not hold (`found=false`), before any output. The KV request frames also set the replay barrier, so the failure surfaced as "automatic retry unsafe" although nothing was shown. When the first pass of such a Run sees a blob miss and fails transiently with only control frames (KV, heartbeat, checkpoint) received, mark the checkpoint unusable and recover by rotating to a new conversation seeded from the full host history (all tool results, the real user message), with the same context-size guard as the foreign-history rebase. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Cursor sometimes sends inline content (e.g. `{"role":...`) as a blob id; the
client echoes it back and reports found=false/echoed=true. That is normal
and happens on most turns, so counting it as a missing blob made any
no-output transient failure reseed the whole history. Only an unserved
32-byte hash means the resumed checkpoint references state we lost.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
OpenCode 2.x sends x-session-id, x-session-affinity and x-opencode-session as the parent (or fork source) session for every child session, so subagents share prompt-cache affinity with their parent. Only x-opencode-session-id names the requesting session. Keying on the affinity ids made every subagent Run bind to its parent's Cursor conversation: it superseded the parent's held Run and left the parent resuming a checkpoint that now held the subagent's turns. Co-Authored-By: Claude Opus 5.5 <[email protected]>
OpenCode 2.x appends messages after the tool results of a step: - a mid-turn system update (skills or MCP server instructions added, changed, removed, reconnected), lowered to a user message wrapping <system-update>; - tool-result media re-sent as a user message captioned "Attached media from tool result:". The prompt then no longer ended with tool messages, so the provider treated the call as a fresh turn: the held Run never got its tool result and the request either superseded the parent Run (forcing an interrupted-run reset) or ran as an isolated helper conversation that is never persisted. Skip these trailing host notes when locating the live tool-result tail, and append system-update text to the last delivered result so Cursor still sees it (a Run continuation only carries exec results). Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Copilot review overview
🟡 Changes recommended
Checkpoint recovery can override an unknown-frame replay barrier and potentially replay stateful activity.
Review effort: Balanced
Findings: 1
What changed in this PR
This PR improves Cursor conversation consistency across OpenCode 2.x subagents, model changes, host notes, and unusable checkpoints.
Changes:
- Keys subagents by their requesting session.
- Detects foreign model history and reseeds with full history.
- Preserves continuations through host notes and recovers from missing checkpoint blobs.
| File | Description |
|---|---|
README.md |
Documents model-switch reseeding. |
src/errors.ts |
Marks unusable-checkpoint failures. |
src/language-model.ts |
Implements reseeding, provenance, host-note handling, and recovery. |
src/session.ts |
Tracks checkpoint-rebase eligibility. |
src/protocol/turn-provenance.ts |
Records and compares emitted turns. |
src/protocol/conversation-state.ts |
Hydrates and persists provenance. |
src/protocol/conversation-persistence.ts |
Adds provenance to cached snapshots. |
test/checkpoint-unusable.test.ts |
Tests missing-blob recovery. |
test/continuation-session.test.ts |
Tests continuations with host notes. |
test/conversation-id.test.ts |
Tests child-session identity. |
test/turn-provenance.test.ts |
Tests provenance, rebasing, and persistence. |
💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.
The missing-blob reseed overrode the replay barrier whenever no frame had looked like output. A frame that failed to gunzip or decode, or that carried only an unknown top-level field, left that state untouched, so a skipped frame that may have held visible output or stateful activity could still be replayed. Track control-only state with a positive list instead: KV messages, checkpoint updates and heartbeats keep it; anything else, including undecodable frames, clears it and the normal replay barrier applies. KV reads that decode but fail the strict wire check (seen live) still count as control frames, so that recovery keeps working. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A frame holding a decodable KV request plus an unknown top-level field still counted as a control frame, because only the decoded fields were checked. Check the raw envelope instead: exactly one top-level field, and it must be a KV request, a checkpoint update, or an interaction update that is only a heartbeat. Extra fields inside a KV request are still tolerated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
There was a problem hiding this comment.
Copilot review overview
🔵 Needs a closer look
The changes alter checkpoint recovery and held-run conversation semantics across several stateful protocol paths, warranting final human review despite strong coverage.
Review effort: Balanced
Findings: None
Resolved since last review (1)
oakimov
left a comment
There was a problem hiding this comment.
Thanks for consolidating these. Fixes 1 and 3 check out against OpenCode v2.0.21: X-Session-Id is the parent/fork-source id (core/src/session/model-request.ts, session/affinity.ts), and both host notes are OpenCode's own (core/src/aisdk.ts, ai/src/protocols/shared.ts).
The model-switch reset should go; foreign-assistant stays. Switching to a non-Cursor model and back is already handled by foreign-assistant: A → other → A and A → other → B both still reseed. model-switch decides the outcome on its own only for a direct switch between two Cursor models. For that case I verified the current Cursor CLI (2026.09.28-64d2043), and it keeps one conversation:
- A model change (Ctrl+/ in the TUI,
setCurrentModelin ACP) only updates the selection (src/models/index.ts,src/acp/agent-session.ts). - The next Run sends the same
conversationIdand checkpoint with the new model's details (src/ui.tsx,src/acp/agent-session.ts). lastUsedModelonly restores the model picker on resume. Nothing resets on a model change.
Since #32 never pinned down which switches caused code=internal, fixes 1 and 3 likely explain what you saw.
Please:
- Remove the
modelIdcomparison fromdetectForeignHistoryand the"model-switch"member ofForeignHistoryReason. - Turn the test "flags a switch to another Cursor model even when the last turn is ours" around: it should assert
undefined, so Cursor→Cursor resumes. - Add a test that Cursor A → foreign turn → Cursor B still returns
"foreign-assistant". - Update the README bullet: drop "or a different Cursor model".
- Verify against the Cursor CLI. Switch between the same Cursor models mid-session in
cursor-agentand confirm it resumes on the same conversation withoutcode=internal. If the CLI fails the same way, that's a Cursor backend issue and the trace is worth sharing. If the CLI succeeds and the provider doesn't, the cause is on our side, not in the checkpoint. - Re-run the mixed-rotation soak phase and post the
code=internal/checkpoint unusable/ reset counts.
We treat Cursor CLI behavior as the reference for protocol and conversation lifecycle. Any new reset or remint path should be checked against what the CLI does before it lands.
Drop the model-switch foreign-history reason. The Cursor CLI keeps one conversation when the model changes and sends the next Run with the same conversationId and checkpoint, so a direct switch between two Cursor models now resumes. A turn answered by another provider still reseeds through foreign-assistant. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks for checking this against both OpenCode and the CLI. All six points are done in
Understood about the CLI being the reference. I'll check any future reset or remint path against it before proposing it.
|
- Remove the Cursor model id from turn provenance. Nothing reads it since the model-switch reason was dropped; recordRunModel becomes trackTurnProvenance, which still starts a fresh record when the conversation is reminted. Drop the Cursor A -> foreign -> Cursor B test: without a model input it duplicated the foreign-assistant test. - Add direct unit tests for isSoleControlFrame. - AGENTS.md: session-key header precedence, foreign-history reseed (and why a Cursor-to-Cursor switch must not remint), unrestorable-checkpoint reseed, host notes after tool results, provenance in the snapshot. - Cache runbook: foreign-history and checkpoint-unusable reset reasons. - Remove the unused clearFrozenRequestContext import. - tasks/lessons.md: trace the whole feature path before calling a gap.
352f399 to
631129b
Compare
|
Thanks for the quick turnaround on In
On the current head, Heads-up: I squashed my earlier follow-ups into |
|
It would be great if you could retest before I merge |
After any model change, OpenCode 1.x replays the previous model's reasoning as text parts (session/message-v2.ts differentModel). Turn provenance compared only text parts against the text this provider emitted, so after a Cursor-to-Cursor switch on 1.x a turn with reasoning looked foreign and forced a full-history reseed, the reset the CLI never does. Also record reasoning and text in emission order, and accept a host turn whose text and reasoning parts, in order, match it. Reasoning deltas now start a recorded step, so a reasoning-only step replayed as text still matches. A turn with only typed reasoning still gives no opinion. This also covers OpenCode 2 replaying an errored message's reasoning as text.
|
Retested on
DeepSeek had an incident during the run ("V4.1 Flash API degraded performance" on status.deepseek.com, more than an hour), so the run is in two parts. Part 1, before the outage. I ran the original phases until DeepSeek stopped responding.
Part 2, after DeepSeek recovered. I re-ran the remaining phases. DeepSeek was limited to short, tool-free "foreign" turns, and all subagents ran on Cursor.
Part 2 totals: 56/56 exited 0, with no
I did not exercise |
|
Merged. Thank you, @zcl0621, this was excellent work. You tracked one vague symptom,
Each fix came with a clear explanation and tests, and the soak testing gave us real evidence to review against. Thanks as well for turning the review feedback around quickly, checking the Cursor→Cursor behavior against the CLI yourself, and retesting the final head through a DeepSeek outage. Much appreciated. Contributions like this make the provider better for everyone. |
…ts, model switches and host notes (#34) Fixes `Cursor API error (code=internal) … automatic retry unsafe` on OpenCode 2.x across subagents, model switches and host notes: - Key Cursor conversations on x-opencode-session-id. OpenCode 2.x sends X-Session-Id / x-session-affinity as the parent (or fork source), so subagents took over their parent's conversation. - Reseed with full history when another provider or a local model answered since the last checkpoint (turn provenance). A direct Cursor-to-Cursor switch resumes the same conversation, as the Cursor CLI does. Provenance also matches OpenCode 1.x replaying reasoning as text after a model switch. Oversized reseeds raise a 413 so the host compacts first. - Keep continuations when OpenCode appends <system-update> notes or the tool-result media caption after tool results. - Reseed when Cursor cannot restore a resumed checkpoint (missing KV blobs before any non-control frame). - Docs: AGENTS.md rules and cache-runbook reset reasons. Co-authored-by: zcl0621 <[email protected]> Co-authored-by: oakimov <[email protected]>
OpenCode moves the images an MCP tool returns into a trailing `Attached media from tool result:` user message. Since oakimov#34 that message no longer forces a fresh Run, so the held Run got the MCP result as text only and the model saw the image at the earliest after the next user message. The README gave the reason as "Cursor's exec-result channel has no image field", but agent.v1 has one: Cursor CLI 2026.10.01 declares `McpImageContent|1 data 12|2 mime_type 9` and `McpToolResultContentItem|1 text #0 content|2 image oakimov#1 content` in `agent/v1/mcp_exec_pb.js`, and its MCP executor appends every MCP `image` item as `{content: {case: "image", value: McpImageContent{data, mimeType}}}`. Declare the type and the oneof case, and append the images attributed to an `mcp_result` (the trailing-media path from the read-image change) as image items after the text, as the CLI does. Update the README and AGENTS.md: only results without an image field (shell, write) still wait for the history path.
OpenCode moves the images an MCP tool returns into a trailing `Attached media from tool result:` user message. Since oakimov#34 that message no longer forces a fresh Run, so the held Run got the MCP result as text only and the model saw the image at the earliest after the next user message. The README gave the reason as "Cursor's exec-result channel has no image field", but agent.v1 has one: Cursor CLI 2026.10.01 declares `McpImageContent|1 data 12|2 mime_type 9` and `McpToolResultContentItem|1 text #0 content|2 image oakimov#1 content` in `agent/v1/mcp_exec_pb.js`, and its MCP executor appends every MCP `image` item as `{content: {case: "image", value: McpImageContent{data, mimeType}}}`. Declare the type and the oneof case, and append the images attributed to an `mcp_result` (the trailing-media path from the read-image change) as image items after the text, as the CLI does. Update the README and AGENTS.md: only results without an image field (shell, write) still wait for the history path.
OpenCode moves the images an MCP tool returns into a trailing `Attached media from tool result:` user message. Since oakimov#34 that message no longer forces a fresh Run, so the held Run got the MCP result as text only and the model saw the image at the earliest after the next user message. The README gave the reason as "Cursor's exec-result channel has no image field", but agent.v1 has one: Cursor CLI 2026.10.01 declares `McpImageContent|1 data 12|2 mime_type 9` and `McpToolResultContentItem|1 text #0 content|2 image oakimov#1 content` in `agent/v1/mcp_exec_pb.js`, and its MCP executor appends every MCP `image` item as `{content: {case: "image", value: McpImageContent{data, mimeType}}}`. Declare the type and the oneof case, and append the images attributed to an `mcp_result` (the trailing-media path from the read-image change) as image items after the text, as the CLI does. Update the README and AGENTS.md: only results without an image field (shell, write) still wait for the history path.
* fix: deliver MCP tool images on the held Run as McpImageContent OpenCode moves the images an MCP tool returns into a trailing `Attached media from tool result:` user message. Since #34 that message no longer forces a fresh Run, so the held Run got the MCP result as text only and the model saw the image at the earliest after the next user message. The README gave the reason as "Cursor's exec-result channel has no image field", but agent.v1 has one: Cursor CLI 2026.10.01 declares `McpImageContent|1 data 12|2 mime_type 9` and `McpToolResultContentItem|1 text #0 content|2 image #1 content` in `agent/v1/mcp_exec_pb.js`, and its MCP executor appends every MCP `image` item as `{content: {case: "image", value: McpImageContent{data, mimeType}}}`. Declare the type and the oneof case, and append the images attributed to an `mcp_result` (the trailing-media path from the read-image change) as image items after the text, as the CLI does. Update the README and AGENTS.md: only results without an image field (shell, write) still wait for the history path. * fix: recognize OpenCode MCP media part shapes on held Runs Normalize host mime/uri and OpenCode 1 type:media tool parts before ReadSuccess/McpImageContent decode, and log continuation prompt-tail media counts for cache/live diagnosis. * fix: harden held-Run image attribution and result delivery --------- Co-authored-by: oakimov <[email protected]>


Summary
This fixes
Cursor API error (code=internal) after visible output or stateful server activity; automatic retry unsafeon OpenCode 2.x when a session switches models or spawns subagents. It combines and supersedes #32 and #33 and adds two more causes I found while soak testing. There are four independent causes:Subagents hijacked the parent's Cursor conversation. OpenCode 2.x sends
X-Session-Id,x-session-affinityandx-opencode-sessionas the parent session (parentID ?? fork.sessionID ?? id) on every child-session request, for prompt-cache affinity. Onlyx-opencode-session-idnames the requesting session. Because the provider keyed onx-session-id, every Cursor subagent bound to its parent's conversation, superseded the parent's held Run, and wrote its turns into the parent's checkpoint. Fix: preferx-opencode-session-id; the old headers remain as fallbacks.Another model answered in between (another provider or a local model). Resuming the old checkpoint hides that work from Cursor. A direct switch between two Cursor models is not treated as foreign history: like the Cursor CLI, the next Run resumes the same conversation with the new model. Fix: record what this provider emitted in its latest step (tool-call ids plus the first 4 KiB of text, LRU-bounded and persisted with the conversation snapshot). When the host's latest assistant turn is not ours, reseed a fresh conversation with full history (
toolResults: "all"). If that history would exceed 80% of the model context, throw a 413 "prompt is too long" so the host compacts first.Host notes after tool results turned continuations into fresh turns. OpenCode 2.x appends messages right after a step's tool results:
<system-update>…</system-update>;Attached media from tool result:.The prompt then no longer ended with tool messages, so the held Run never received its tool result. The new request either superseded the parent Run or ran as an isolated helper conversation that is never persisted. Fix: skip these trailing notes when locating the live tool-result tail, and append the system-update text to the last delivered result so Cursor still sees it.
A resumed checkpoint that Cursor cannot restore. Cursor sometimes asks for KV blobs the client does not have and then ends the Run with
internalbefore any output. Fix: when a resumed fresh turn fails that way before any output, reseed with full history instead of surfacing a non-retryable error. Content-as-id reads (echoed=true) are normal and happen on most turns, so they are not counted as misses.Test plan
turn-provenance.test.tsandcheckpoint-unusable.test.ts, plus added cases inconversation-id.test.tsandcontinuation-session.test.ts.bun test1240 pass / 0 fail;tsc --noEmitis clean.@opencode/cli), using an isolatedHOMEand one long-livedopencode serve.cursor/gpt-5-mini,cursor/gemini-3-flash,cursor/gpt-5.4-nanoanddeepseek/deepseek-flash.everything,memory,sequential-thinking,filesystemand remotecontext7.-f), image read through the read tool (tool-result media), subagent reading an image; parent alternates Cursor ↔ DeepSeek/api/experimental/mcp/:server/*), skill add/modify/remove,opencode serverestart, then the same sessions continue. Parent alternates Cursor ↔ DeepSeek; subagents alternate on a different beat (all 4 combinations)POST /api/session/:id/compactwhile on each Cursor model and on DeepSeek, then continue and switch (8 compactions)general/ Cursor / DeepSeek subagents180/180 runs exited 0, and no
Cursor API errorappeared in any output. Counts from the full debug log, captured withtail -Fso the 10 MiB size cap did not truncate it:code=internal/ Run end-stream error /replay suppressedfound=false echoed=false) /checkpoint unusablereseedisolating in-session helpersuperseded-by-new-runforeign-history:model-switchand 12 compaction-related, all on parent sessions; 0 on child sessions<system-update>notice or a tool-media caption appended after a tool result.Re-test after the review fixes
After the two review fixes (
ffba820,a83b819) I ran a shorter regression of every phase above. It used the packaged build of this branch's code (the same code asa83b819, with no extra trace line), on a fresh isolated OpenCode 2.0.21 with the same models and MCP servers. Each phase again ran 2 sessions concurrently, except mixed rotation.opencode serverestart. The model saw each skill change (the modified skill's new content, then its removal)cursor/gpt-5-mini, then continue (2 compactions)39/39 runs exited 0, and no
Cursor API errorappeared in any output. From the debug log of this run:code=internal/ Run end-stream error /replay suppressedcheckpoint unusablereseedisolating in-session helper/superseded-by-new-runforeign-history:model-switch, 2compaction, 2post-compaction-rebase), all on parent sessions; 0 on child sessionsThe log also shows
replay barrier: reason=unknown-or-malformed-frameat least once in each of the 81 Cursor sessions. That path is unchanged frommain, and it only decides whether an attempt may be retried after an error, so it had no effect here. It does mean automatic retry is effectively unavailable on current Cursor streams. I left it out of scope for this PR.Re-test after dropping the
model-switchresetThe two runs above used builds that still had the
model-switchreason, so theirforeign-history:model-switchcounts come from it. Afterba6b697removed it, I re-ran mixed rotation on the new build, plus a phase that switches directly between Cursor models:gpt-5-mini→ DeepSeek →gemini-3-flash→ DeepSeek →gpt-5.4-nano, repeatedgpt-5-mini→gemini-3-flash→gpt-5.4-nano→gpt-5-mini→ DeepSeek →gemini-3-flash→gpt-5-mini→gpt-5.4-nanocode=internal/ Run end-stream errorcheckpoint unusablereseedisolating in-session helper/superseded-by-new-runforeign-history:foreign-assistant, each on the first Cursor turn after a DeepSeek turn (4 in mixed rotation, 1 per direct-switch session). None on the direct Cursor→Cursor switches, and none on child sessionsOne
replay suppressedappeared: an HTTP/2 cached-session ping timed out and the pending stream was canceled. The existing transport retry resumed from the checkpoint on attempt 1/2, and that run exited 0.Cursor CLI reference (
cursor-agent2026.09.28-64d2043,--print --resume <chatId> --model <m>, ask mode): one chat started ongpt-5-mini, then 9 resumed turns, each on a different Cursor model from the previous one (gemini-3-flash,gpt-5.4-nano-mediumandgpt-5-miniin turn). Each turn read a file and repeated a codeword given in the first turn. All 9 kept the samesession_id, returnedis_error=falseand recalled the codeword. In the 8 turns recorded withstream-json,cacheReadTokensgrew from 23,870 to 105,088. Nointernalerror.Notes
gemini-3-flashsometimes emits awritetool that OpenCode 2.x does not advertise.Supersedes #32 and #33.
🤖 Generated with Claude Code