Skip to content

fix: keep Cursor conversations consistent across OpenCode 2.x subagents, model switches and host notes - #34

Merged
oakimov merged 12 commits into
oakimov:mainfrom
zcl0621:fix/opencode2-session-continuity
Oct 2, 2026
Merged

oakimov merged 12 commits into
oakimov:mainfrom
zcl0621:fix/opencode2-session-continuity

Conversation

@zcl0621

@zcl0621 zcl0621 commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor

Summary

This fixes Cursor API error (code=internal) after visible output or stateful server activity; automatic retry unsafe on 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:

  1. Subagents hijacked the parent's Cursor conversation. OpenCode 2.x sends X-Session-Id, x-session-affinity and x-opencode-session as the parent session (parentID ?? fork.sessionID ?? id) on every child-session request, for prompt-cache affinity. Only x-opencode-session-id names the requesting session. Because the provider keyed on x-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: prefer x-opencode-session-id; the old headers remain as fallbacks.

  2. 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.

  3. Host notes after tool results turned continuations into fresh turns. OpenCode 2.x appends messages right after a step's tool results:

    • a mid-turn system update (skills or MCP server instructions added, changed, removed or reconnected), lowered to a user message wrapping <system-update>…</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 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.

  4. A resumed checkpoint that Cursor cannot restore. Cursor sometimes asks for KV blobs the client does not have and then ends the Run with internal before 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

  • Unit tests: the new test files are turn-provenance.test.ts and checkpoint-unusable.test.ts, plus added cases in conversation-id.test.ts and continuation-session.test.ts. bun test 1240 pass / 0 fail; tsc --noEmit is clean.
  • Soak test on OpenCode 2.0.21 (@opencode/cli), using an isolated HOME and one long-lived opencode serve.
    • Cheap models: cursor/gpt-5-mini, cursor/gemini-3-flash, cursor/gpt-5.4-nano and deepseek/deepseek-flash.
    • 5 MCP servers: everything, memory, sequential-thinking, filesystem and remote context7.
    • Every phase ran 2 sessions concurrently. Build: this branch plus one debug trace line for end-stream error payloads.
Phase What varied Runs Result
Images & files User-attached image or text file (-f), image read through the read tool (tool-result media), subagent reading an image; parent alternates Cursor ↔ DeepSeek 24 all ok
Environment changes Between rounds: MCP disconnect/reconnect (/api/experimental/mcp/:server/*), skill add/modify/remove, opencode serve restart, then the same sessions continue. Parent alternates Cursor ↔ DeepSeek; subagents alternate on a different beat (all 4 combinations) 40 all ok
Auto compaction Context limit capped at 64K so the host auto-compacts (4 compactions, all on DeepSeek) 30 all ok
Manual compaction POST /api/session/:id/compact while on each Cursor model and on DeepSeek, then continue and switch (8 compactions) 16 all ok
Mixed rotation Parent rotates through 3 Cursor models and DeepSeek; general / Cursor / DeepSeek subagents 30 all ok
Long A different file each round, 0–150 s random idle to cross the 120 s semantic-idle lease. Ran alongside the manual-compaction phase (4 concurrent sessions) 40 all ok

180/180 runs exited 0, and no Cursor API error appeared in any output. Counts from the full debug log, captured with tail -F so the 10 MiB size cap did not truncate it:

Event Count
code=internal / Run end-stream error / replay suppressed 0 / 0 / 0
real blob miss (found=false echoed=false) / checkpoint unusable reseed 0 / 0
isolating in-session helper 0 (it was 10–15 per environment-change phase before fix 3)
superseded-by-new-run 0
conversation resets 76 foreign-history:model-switch and 12 compaction-related, all on parent sessions; 0 on child sessions
  • Before fix 1, the same setup reproduced the hijack: a child Run arrived with the parent's key, superseded the parent's Run and forced a reset.
  • Before fix 3, every isolation lined up with an OpenCode <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 as a83b819, 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.

Phase Runs Result
Images & files 8 all ok
Environment changes: one full cycle of MCP disconnect → reconnect + skill add → skill modify → skill remove → opencode serve restart. The model saw each skill change (the modified skill's new content, then its removal) 10 all ok
Auto compaction (64K cap; 2 compactions on DeepSeek) 8 all ok
Manual compaction on cursor/gpt-5-mini, then continue (2 compactions) 4 all ok
Mixed rotation 3 all ok
Long (2 sessions, random idle) 6 all ok

39/39 runs exited 0, and no Cursor API error appeared in any output. From the debug log of this run:

Event Count
code=internal / Run end-stream error / replay suppressed 0 / 0 / 0
real blob miss / checkpoint unusable reseed 0 / 0
isolating in-session helper / superseded-by-new-run 0 / 0
conversation resets 17 (13 foreign-history:model-switch, 2 compaction, 2 post-compaction-rebase), all on parent sessions; 0 on child sessions

The log also shows replay barrier: reason=unknown-or-malformed-frame at least once in each of the 81 Cursor sessions. That path is unchanged from main, 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-switch reset

The two runs above used builds that still had the model-switch reason, so their foreign-history:model-switch counts come from it. After ba6b697 removed it, I re-ran mixed rotation on the new build, plus a phase that switches directly between Cursor models:

Phase Models per round Runs Result
Mixed rotation gpt-5-mini → DeepSeek → gemini-3-flash → DeepSeek → gpt-5.4-nano, repeated 10 all ok
Direct Cursor switches (2 sessions concurrently) gpt-5-mini → gemini-3-flash → gpt-5.4-nano → gpt-5-mini → DeepSeek → gemini-3-flash → gpt-5-mini → gpt-5.4-nano 16 all ok
Event Count
code=internal / Run end-stream error 0 / 0
real blob miss / checkpoint unusable reseed 0 / 0
isolating in-session helper / superseded-by-new-run 0 / 0
conversation resets 6, all foreign-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 sessions

One replay suppressed appeared: 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-agent 2026.09.28-64d2043, --print --resume <chatId> --model <m>, ask mode): one chat started on gpt-5-mini, then 9 resumed turns, each on a different Cursor model from the previous one (gemini-3-flash, gpt-5.4-nano-medium and gpt-5-mini in turn). Each turn read a file and repeated a codeword given in the first turn. All 9 kept the same session_id, returned is_error=false and recalled the codeword. In the 8 turns recorded with stream-json, cacheReadTokens grew from 23,870 to 105,088. No internal error.

Notes

  • Out of scope, seen during testing: gemini-3-flash sometimes emits a write tool that OpenCode 2.x does not advertise.

Supersedes #32 and #33.

🤖 Generated with Claude Code

zcl0621 and others added 7 commits October 1, 2026 12:25
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]>
@zcl0621
zcl0621 marked this pull request as ready for review October 1, 2026 08:55
Copilot AI balanced review requested due to automatic review settings October 1, 2026 08:55

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Checkpoint recovery can override an unknown-frame replay barrier and potentially replay stateful activity.

Review effort: Balanced
Findings: 1 High severity

Open (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.

Comment thread src/language-model.ts Resolved
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]>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot review overview

🟡 Changes recommended

Control-frame classification can still override replay safety when a KV frame includes an unknown top-level field.

Review effort: Balanced
Findings: 1 Medium severity

Open (1)
Resolved since last review (1)

Comment thread src/language-model.ts Resolved
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]>

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 oakimov left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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, setCurrentModel in ACP) only updates the selection (src/models/index.ts, src/acp/agent-session.ts).
  • The next Run sends the same conversationId and checkpoint with the new model's details (src/ui.tsx, src/acp/agent-session.ts).
  • lastUsedModel only 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:

  1. Remove the modelId comparison from detectForeignHistory and the "model-switch" member of ForeignHistoryReason.
  2. 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.
  3. Add a test that Cursor A → foreign turn → Cursor B still returns "foreign-assistant".
  4. Update the README bullet: drop "or a different Cursor model".
  5. Verify against the Cursor CLI. Switch between the same Cursor models mid-session in cursor-agent and confirm it resumes on the same conversation without code=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.
  6. 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]>
@zcl0621

zcl0621 commented Oct 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for checking this against both OpenCode and the CLI. All six points are done in ba6b697:

  1. Removed the modelId comparison from detectForeignHistory, along with its now-unused modelId input, and dropped "model-switch" from ForeignHistoryReason. The provenance record still stores modelId, so the persisted snapshot format is unchanged.

  2. The test is now "resumes across a direct switch to another Cursor model when the last turn is ours". It asserts undefined, then records a step on the new model in the same conversation and asserts undefined again.

  3. Added "flags Cursor A, then a foreign turn, then Cursor B as foreign history". It expects "foreign-assistant". Detection no longer looks at the model, so this test exercises detectForeignHistory directly rather than a full Run on B.

  4. README: dropped "or a different Cursor model". I also updated the matching comments in turn-provenance.ts and language-model.ts.

  5. Cursor CLI 2026.09.28-64d2043: I started a --print chat on gpt-5-mini, then resumed it 9 times with --resume <chatId> --model <m>, changing the Cursor model each turn (gemini-3-flash, gpt-5.4-nano-medium, gpt-5-mini). Every turn kept the same session_id, returned is_error=false and recalled a codeword from the first turn. In the 8 turns recorded with stream-json, cacheReadTokens grew from 23,870 to 105,088. There was no internal error, so the CLI resumes across the switch, and the provider now does the same.

  6. Re-ran on the new build: mixed rotation (10 runs), plus a direct Cursor→Cursor switching phase with 2 concurrent sessions (16 runs). All 26 exited 0. The debug log shows:

    • code=internal: 0
    • checkpoint unusable reseeds: 0
    • real blob misses, isolations and supersedes: 0
    • conversation resets: 6, all foreign-history:foreign-assistant. Each was the first Cursor turn after a DeepSeek turn. There were none on the direct Cursor→Cursor switches and none on child sessions.

    One transport interruption (HTTP/2 ping timeout) was resumed from the checkpoint by the existing retry, and that run exited 0. Details are in the "Re-test after dropping the model-switch reset" section of the description.

Understood about the CLI being the reference. I'll check any future reset or remint path against it before proposing it.

bun test: 1241 pass / 0 fail; tsc --noEmit is clean.

- 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.
@oakimov
oakimov force-pushed the fix/opencode2-session-continuity branch from 352f399 to 631129b Compare October 1, 2026 12:26
@oakimov

oakimov commented Oct 1, 2026 •

Copy link
Copy Markdown
Owner

Thanks for the quick turnaround on ba6b697. Everything checks out. I pushed two follow-up commits so this can go in as a single merge: 631129b with the remaining cleanup, and 0762d1e with an OpenCode 1.x fix (below).

In 631129b:

  • Unused model id removed from turn provenance. Once the model-switch reason was gone, nothing read modelId. The persisted field you kept for format stability isn't needed either, since turn_provenance_json is new in this PR. recordRunModel is now trackTurnProvenance(sessionKey, conversationId). It's kept because it still starts an empty record when a conversation is reminted, and recovery Runs rely on that without calling beginEmittedStep. I dropped the "Cursor A → foreign turn → Cursor B" test: without a model input it duplicated "flags an assistant turn another model produced", as you noted.

  • Direct unit tests for isSoleControlFrame. They cover the three accepted control frames, extra fields inside a KV request (accepted), and rejection of non-heartbeat updates, extra or unknown top-level fields, two messages in one frame, malformed bytes and an empty payload.

  • AGENTS.md: four new rules:

    • Session key: read x-opencode-session-id first, and why the fallback headers point at the parent.
    • Foreign history: when another model's turn triggers a full reseed, plus an explicit note not to reintroduce a Cursor→Cursor model-switch remint, citing the CLI.
    • Unrestorable checkpoint: exactly when that reseed may bypass the replay barrier.
    • Host notes after tool results: tool-result media still reaches Cursor as history images on the next fresh Run.

    It also lists provenance in the snapshot contents, and the image-generation note now acknowledges the media-caption skip.

  • docs/cache-log-runbook.md: the foreign-history:foreign-assistant and checkpoint-unusable reset reasons, and how to read found=false echoed=true KV traces.

  • Unused clearFrozenRequestContext import removed from src/protocol/conversation-bind.ts. It predates this PR; strict tsc is now warning-free.

  • tasks/lessons.md: a review lesson on our side.

631129b changes no behavior beyond removing the unused model tracking.

0762d1e: OpenCode 1.x replays reasoning as text. After any model change, 1.x replays the previous model's reasoning as text parts (session/message-v2.ts, differentModel). Matching on text parts alone flagged our own turn as foreign after a Cursor→Cursor switch on 1.x, which brought back the reseed we just removed. Provenance now also records reasoning and text in emission order and accepts a host turn that matches it. A reasoning-only step counts as a recorded step. A turn with only typed reasoning still gives no opinion. The new tests fail without the fix.

On the current head, bun run typecheck, bun run build and bun test all pass (1246 pass / 0 fail), and strict tsc (--noUnusedLocals --noUnusedParameters --noImplicitReturns --noFallthroughCasesInSwitch) is clean.

Heads-up: I squashed my earlier follow-ups into 631129b, so the branch was force-pushed. If you have a local checkout, reset it to the current head, 0762d1e, before pushing again.

@oakimov

oakimov commented Oct 1, 2026

Copy link
Copy Markdown
Owner

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.
@zcl0621

zcl0621 commented Oct 1, 2026 •

Copy link
Copy Markdown
Contributor Author

Retested on 0762d1e. Short version: no regressions. Every run that finished exited 0, and there were no Cursor errors.

bun test gives 1246 pass / 0 fail. tsc --noEmit and bun run build are clean. The soak ran the built dist on OpenCode 2.0.21 (@opencode/cli), in the same isolated setup as before, with 2 sessions running concurrently in every phase.

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.

  • Images & files: 8 runs, all ok.
  • Environment changes: rounds 1–3 completed (MCP disconnect, then reconnect + skill add, then skill modify), giving 5 runs ok and 1 timeout.
    • In the timed-out run, a deepseek-flash subagent's stream stalled for 10 minutes.
    • Cursor then aborted the parent's held Run (the parent was waiting on that subagent's result). The provider reset with interrupted-run and continued.
    • The retried subagent never got a first token from DeepSeek, and the run hit my 900 s timeout. I attribute this to the incident.

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.

Phase What varied Runs Result
Environment changes MCP disconnect → reconnect + skill add → skill modify → skill remove → opencode serve restart. Cursor and DeepSeek alternate 10 all ok; the modified skill content was read
Auto compaction on Cursor gpt-5-mini context capped through provider.cursor.models (90K, then 45K, since 90K never filled). One compaction per session, then 1–2 more rounds 18 all ok
Manual compaction POST /api/session/:id/compact on gemini-3-flash, continue, then switch to gpt-5-mini 6 all ok
Direct Cursor switches gpt-5-mini → gemini-3-flash → gpt-5.4-nano → gpt-5-mini → DeepSeek → gemini-3-flash → gpt-5-mini → gpt-5.4-nano 16 all ok
Long Cursor model per round, random 0–150 s idle 6 all ok

Part 2 totals: 56/56 exited 0, with no Cursor API error in any output. From the debug log of part 2:

Event Count
code=internal / end-stream error / replay suppressed 0 / 0 / 0
real blob miss / checkpoint unusable reseed / isolation 0 / 0 / 0
conversation resets 6 foreign-history:foreign-assistant, each on the first Cursor turn after a DeepSeek turn, none on direct Cursor→Cursor switches. Also 4 compaction and 4 post-compaction-rebase. All were on parent sessions; there were 0 on child sessions
superseded-by-new-run 2, both in the same millisecond as a compaction reset. Each superseded the parent's idle held Run (pending=0) when the compaction Run started. This is the existing compaction path, not new behavior. Earlier soaks compacted on DeepSeek only, so there was no held Cursor Run to supersede

I did not exercise 0762d1e's OpenCode 1.x path: I have no 1.x setup, and 2.x keeps reasoning typed in the normal flow. On 2.x the reasoning-aware match left our own turns alone. No Cursor→Cursor switch reseeded.

@zcl0621
zcl0621 requested a review from oakimov October 1, 2026 22:59
@oakimov

oakimov commented Oct 2, 2026

Copy link
Copy Markdown
Owner

Merged. Thank you, @zcl0621, this was excellent work.

You tracked one vague symptom, code=internal … automatic retry unsafe, down to four separate causes:

  • subagents hijacking the parent's conversation through the affinity headers;
  • foreign turns hidden by a stale checkpoint;
  • host notes breaking continuations;
  • checkpoints Cursor couldn't restore.

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.

@oakimov
oakimov merged commit 47e3036 into oakimov:main Oct 2, 2026
oakimov added a commit that referenced this pull request Oct 2, 2026
…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]>
nkoynov added a commit to nkoynov/cursor-opencode-provider that referenced this pull request Oct 5, 2026
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.
oakimov pushed a commit to nkoynov/cursor-opencode-provider that referenced this pull request Oct 7, 2026
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.
oakimov pushed a commit to nkoynov/cursor-opencode-provider that referenced this pull request Oct 8, 2026
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.
oakimov added a commit that referenced this pull request Oct 8, 2026
* 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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants