Skip to content

Commit c11480f

Browse files
committed
fix(recovery): rebuild a dropped Run when nothing of the interrupted step ran on the host, and send a cut Run upload again
Only execs handed to a host tool need a result in history; the provider's own answers (refusals, its runtime files, placeholders) no longer block the completed-tool-results rebuild, anywhere in the Run. The interrupted pump pass is judged on its own: its text, reasoning, announced calls and provider-answered execs do not bar the rebuild, and its shown text goes to the rebuilt Run to be continued. A host exec, a bridge or a stateful or unknown frame in it still does. A new Run's request upload that the stream cuts off is replay-safe unless Cursor's own refusal ended the stream. Final retry-unsafe errors say to send "continue". CB-10.
1 parent 05a1969 commit c11480f

13 files changed

Lines changed: 341 additions & 44 deletions

‎AGENTS.md‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,10 @@ The **1.18 v2** API and **OpenCode 2.0** are source-incompatible:
124124
once per process in memory, validate HTTPS `*.cursor.sh`, and fail closed;
125125
no disk memo or legacy-host fallback. GetServerConfig telemetry defaults off.
126126
- Serialize every response-required write and await drain. A buffered failure
127-
is ambiguous delivery and cannot be replayed. There is no upload deadline;
127+
is ambiguous delivery and cannot be replayed. Fork: a new Run's own request
128+
upload is the exception: nothing reads that stream before it is sent, so a
129+
cut upload is transient and replay-safe unless the stream's terminal error is
130+
Cursor's final verdict (`runUploadFailure`). There is no upload deadline;
128131
errors, Run termination and the 120 s inbound read-idle watchdog settle waits.
129132
- Initial and replacement uploads own temporary abort/host-Stop listeners;
130133
continuation delivery and the active pump use their current call's signal.
@@ -303,6 +306,13 @@ The **1.18 v2** API and **OpenCode 2.0** are source-incompatible:
303306
exec has a completed result and no opaque activity occurred. Include all
304307
completed tool steps; never resume their earlier checkpoint. Other barriers
305308
stay final.
309+
- Fork (CB-10): only execs handed to a host tool (`recordHostExec`) need a
310+
result in history; the provider's own answers change nothing outside it. The
311+
interrupted pump pass (`ReplaySafetyState.attempt`) does not bar the rebuild
312+
with its output, its announced calls nothing claimed or completed, or its
313+
provider-answered execs; it does with a host exec, a bridge or a stateful or
314+
unknown frame. Its shown text goes to the rebuilt Run as `<interrupted_reply>`
315+
to be continued. A final retry-unsafe error tells the user to send "continue".
306316
Missing-blob recovery is limited to the initial control-only checkpoint path
307317
(`isSoleControlFrame`); unknown/mixed frames keep the normal replay barrier.
308318
- Carry an uncheckpointed request only on its unchanged checkpoint; persist it

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
### Fixed
2727

2828
- An early edit row no longer shows "Cursor did not finish this tool call." for a call that did finish. When Cursor ends an edit itself without a write (for example a string it could not find), the row now shows Cursor's own result, the one the model saw, and fails only if that result is an error. When another call of the step runs first, the row completes with a note that Cursor runs this call afterwards, and the call shows up again when it runs. A row still fails as unfinished when its Run ends without the call or its exec is refused. An edit Cursor fails after its permission-checked read, which opens no early row, now shows as a failed edit with Cursor's error instead of only the read. A turn rebuilt from OpenCode's history leaves these closed rows (empty input) out of the transcript.
29+
- A Cursor connection that dies mid-turn no longer ends the turn with "Cursor Run sent no frames for 30000ms after visible output or stateful server activity; automatic retry unsafe" when nothing would run twice. After OpenCode's tool results reach Cursor and before Cursor saves a checkpoint, the turn is rebuilt from OpenCode's history even if the interrupted step had already streamed text or reasoning, announced its next tool call, or had the provider answer an exec itself (a read of the provider's own terminal records, a refusal). Before, any of those, or such a provider answer anywhere earlier in the Run, made the failure final. The rebuilt step is shown the text it already wrote so it continues instead of repeating it. A host tool started in the interrupted step, a call Cursor ran itself and stateful interactions still end the turn, and that error now says to send a message such as "continue". A new Run whose request upload is cut off ("Cursor initial Run request backpressure drain failed while opening the replacement Run; automatic retry unsafe") is sent again within the retry budget, since nothing was read from it, unless Cursor's own refusal ended the stream
2930
- A shell command Cursor runs with a foreground window (most of them) now ends with its own exit code in OpenCode, not 0. The provider's wrapper printed the code for Cursor and then exited 0, so OpenCode stored every such command as a success, T3 and other clients showed no failure, and a turn rebuilt from OpenCode's history lost the code. A hard timeout exits 124 after its timeout notice; a command handed off to the background still exits 0. On OpenCode 2 the stored result of a failed command now ends with OpenCode's own `Exited with code N` line, which a rebuilt turn keeps on its own line after the output; the live result leaves it out of Cursor's stdout, which gets the code as its exit code. OpenCode 1.x keeps a command's exit only in its metadata, so the provider now adds the same line to the model's copy of a failed shell result there too, and a rebuilt turn keeps every command's code.
3031
- Image-heavy sessions no longer decode every earlier image on every step when OpenCode keeps tool-result images out of its stored history (agent-stack's OpenCode patch stores them as `tool-media/<sha256>.<ext>` files). The provider declares `file:` URLs for images in `supportedUrls`, so OpenCode hands it the stored file instead of the bytes; an image Cursor's conversation already holds is recognised by the hash in its name and skipped without reading the file, and one that has to be sent is read and checked against that hash (a missing or changed file is left out like other unreadable tool media). Hosts that send image bytes are unchanged.
3132
- A plan the user declines, or approves for the build agent, ends its Run with the plan's own cancellation even when Cursor switched models during that turn, instead of the model-switch stop.

‎README.md‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -345,12 +345,18 @@ transport retry budget and the 180-second consecutive-stall window. The separate
345345
120-second transport read-idle watchdog remains a backstop. Direct SDK callers
346346
can override `continuation.semanticIdleMs` (or its `softHealthMs` alias).
347347

348-
If a Run drops immediately after completed tool results, before new output,
349-
the provider can rebuild from host history containing every observed exec's
350-
result. It sends the completed results once and asks Cursor to continue. A
351-
checkpoint predating those results is never resumed. Missing results, unknown
352-
activity, a tool call Cursor ran itself or a new interaction keep the failure
353-
final. If the rebuilt history would fill more than 80% of the model's context,
348+
If a Run drops after completed tool results, before Cursor saves a checkpoint,
349+
the provider can rebuild from host history containing the result of every exec
350+
a host tool ran. It sends the completed results once and asks Cursor to
351+
continue. A checkpoint predating those results is never resumed. The step that
352+
was interrupted does not stop the rebuild while nothing of it ran on the host:
353+
its text (which the rebuilt step is told it already wrote, so it continues
354+
rather than repeats), its reasoning, calls it had only announced, and execs the
355+
provider answered itself (refusals, its own runtime files). Missing results,
356+
unknown activity, a tool call Cursor ran itself, a host tool started in the
357+
interrupted step or a stateful interaction keep the failure final, and the
358+
error says to send a message such as "continue". A Run whose request upload is
359+
cut off had nothing read from it, so it is sent again within the retry budget. If the rebuilt history would fill more than 80% of the model's context,
354360
the provider reports a context overflow so the host compacts first.
355361
A checkpoint received while the completed result drains remains eligible.
356362
History recovery retains completed results from earlier resumed Runs too.

‎docs/opencode-1.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -174,9 +174,12 @@ if no exec or started tool lifecycle arrived; it closes without execution.
174174
Stateful activity stays a replay barrier. Like Cursor CLI, an active Run with no
175175
pending host work fails after 30 s without an inbound frame; heartbeats and
176176
partial inputs renew that deadline, while client heartbeats do not. The 120 s
177-
transport read-idle watchdog remains a backstop. A drop immediately after
178-
completed tool results can rebuild from complete host history
179-
before new output; missing results or unrepresented activity remain final.
177+
transport read-idle watchdog remains a backstop. A drop after completed tool
178+
results, before a new checkpoint, can rebuild from complete host history; the
179+
interrupted step's output, announced calls and provider-answered execs do not
180+
prevent it, and its shown text is passed on to be continued. Missing results,
181+
a host tool started in that step or unrepresented activity remain final. A Run
182+
whose request upload is cut off is sent again.
180183
A rebuild too large for the model's context is reported as a context overflow
181184
(413) so the host can compact. Recovery retains the latest eligible checkpoint across token renewal, including
182185
a rejected credential on an untouched resumed attempt. Checkpoints received

‎docs/opencode-2.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -217,9 +217,12 @@ if no exec or started tool lifecycle arrived; it closes without execution.
217217
Stateful activity stays a replay barrier. Like Cursor CLI, an active Run with no
218218
pending host work fails after 30 s without an inbound frame; heartbeats and
219219
partial inputs renew that deadline, while client heartbeats do not. The 120 s
220-
transport read-idle watchdog remains a backstop. A drop immediately after
221-
completed tool results can rebuild from complete host history
222-
before new output; missing results or unrepresented activity remain final.
220+
transport read-idle watchdog remains a backstop. A drop after completed tool
221+
results, before a new checkpoint, can rebuild from complete host history; the
222+
interrupted step's output, announced calls and provider-answered execs do not
223+
prevent it, and its shown text is passed on to be continued. Missing results,
224+
a host tool started in that step or unrepresented activity remain final. A Run
225+
whose request upload is cut off is sent again.
223226
A rebuild too large for the model's context is reported as a context overflow
224227
(413), so OpenCode compacts instead of retrying. Recovery retains the latest eligible checkpoint across token renewal, including
225228
a rejected credential on an untouched resumed attempt. Checkpoints received

‎src/errors.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -631,7 +631,8 @@ export function retrySuppressedError(
631631
cause.message.replace(/^Cursor Run stream /, "Cursor stream "),
632632
)
633633
return new CursorProviderError(
634-
`${subject} ${reason}; automatic retry unsafe (attempt ${attempt}/${maxAttempts})`,
634+
`${subject} ${reason}; automatic retry unsafe (attempt ${attempt}/${maxAttempts}). ` +
635+
`Send a message such as "continue" to resume from the last saved state`,
635636
{
636637
origin: cause.origin,
637638
transient: false,

‎src/language-model.ts‎

Lines changed: 56 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -369,7 +369,7 @@ import {
369369
hostNoteText,
370370
wrapHostNotesForCursor,
371371
} from "./protocol/host-notes.js"
372-
import { analyzeReplayFrame, announcedCallsClaimed, AttemptReplaySafety, describeFrameLayout } from "./replay-safety.js"
372+
import { analyzeReplayFrame, announcedCallsClaimed, AttemptReplaySafety, describeFrameLayout, hostExecs } from "./replay-safety.js"
373373
import { noteCursorWaitEnded, noteCursorWaitStarted } from "./cursor-waits.js"
374374
import {
375375
deferToolExec,
@@ -1338,14 +1338,15 @@ async function doStreamImpl(
13381338
retryPolicy,
13391339
retryBudget,
13401340
canRebaseFromHistory: (failed) => {
1341+
const replay = failed.replaySafety
13411342
if (failed !== session || trailingToolResults.length === 0
13421343
|| !failed.checkpointRevokedByHostResult || failed.pending.size > 0
1343-
|| failed.replaySafety?.historyRebaseUnsafe
1344-
|| !announcedCallsClaimed(failed.replaySafety)) return false
1344+
|| replay?.historyRebaseUnsafe || replay?.attempt?.unrepresentable
1345+
|| !announcedCallsClaimed(replay, replay?.attempt?.announcedCalls)) return false
13451346
const completed = new Set(extractToolResults(prompt)
13461347
.map(result => `${result.sessionId}:${result.execId}`))
1347-
const execs = failed.replaySafety?.execs ?? []
1348-
if (!execs.length && !failed.replaySafety?.bridgedCalls?.length) return false
1348+
const execs = hostExecs(replay)
1349+
if (!execs.length && !replay?.bridgedCalls?.length) return false
13491350
return execs.every(exec => completed.has(`${exec.sessionId}:${exec.id}`))
13501351
},
13511352
recover: (recovery) => openSession({ recovery }),
@@ -1479,6 +1480,8 @@ export async function pumpWithRecovery(input: {
14791480
checkpoint: Uint8Array | undefined,
14801481
) => {
14811482
const toolCallIds = pumpedSession.resultsAfterCheckpoint?.toolCallIds
1483+
const fromHistory = !failure.checkpointUnusable && !checkpoint && !!input.canRebaseFromHistory?.(pumpedSession)
1484+
const shownText = fromHistory ? pumpedSession.replaySafety?.attempt?.shownText?.trim() : undefined
14821485
const recovery: CursorRunRecovery = failure.checkpointUnusable
14831486
? { kind: "rebase", reason: "checkpoint-unusable" }
14841487
: checkpoint
@@ -1489,7 +1492,8 @@ export async function pumpWithRecovery(input: {
14891492
}
14901493
: {
14911494
kind: "rebase",
1492-
...(input.canRebaseFromHistory?.(pumpedSession) ? { reason: "completed-tool-results" as const } : {}),
1495+
...(fromHistory ? { reason: "completed-tool-results" as const } : {}),
1496+
...(shownText ? { shownText } : {}),
14931497
...(input.steer ? { steer: true } : {}),
14941498
...(toolCallIds?.size ? { toolCallIds: new Set(toolCallIds) } : {}),
14951499
}
@@ -1687,7 +1691,8 @@ export async function pumpWithRecovery(input: {
16871691
throw noProgressResumeError(failure, noProgressResumes)
16881692
}
16891693
}
1690-
const historyRecovery = failure.replayBarrier === undefined && input.canRebaseFromHistory?.(pumpedSession)
1694+
// The interrupted step's own output and provider-answered execs do not bar it: the rebuild generates them again.
1695+
const historyRecovery = input.canRebaseFromHistory?.(pumpedSession)
16911696
if (!failure.replaySafe && !checkpoint && !historyRecovery) {
16921697
// Cursor CLI sends the same action again. Shown output keeps the
16931698
// provider from doing so; the host can, unless a side effect would repeat.
@@ -1755,7 +1760,7 @@ export async function sendRunRequest(
17551760
await writeWithBackpressure(stream, request, operation)
17561761
return stream
17571762
} catch (error) {
1758-
if (!stream.compressionRejected?.()) throw error
1763+
if (!stream.compressionRejected?.()) throw runUploadFailure(error, operation)
17591764
}
17601765
try { stream.destroy() } catch { /* already closed */ }
17611766
trace(`Run compression: ${operation} refused while uploading — sending it once more uncompressed`)
@@ -1765,10 +1770,33 @@ export async function sendRunRequest(
17651770
return next
17661771
} catch (error) {
17671772
try { next.destroy() } catch { /* already closed */ }
1768-
throw error
1773+
throw runUploadFailure(error, operation)
17691774
}
17701775
}
17711776

1777+
/**
1778+
* Fork: nothing reads a new Run's stream before its request is uploaded, so a cut upload ran no tool and answered
1779+
* nothing, and the Run can go again. A failure Cursor sent keeps its own verdict.
1780+
*/
1781+
export function runUploadFailure(error: unknown, operation: string): CursorProviderError {
1782+
const failure = toCursorProviderError(error, { replaySafe: false, fallback: `Cursor ${operation} write failed` })
1783+
const terminal = failure instanceof StreamWriteDrainError && failure.cause instanceof CursorProviderError
1784+
? failure.cause
1785+
: undefined
1786+
if (terminal) {
1787+
if (terminal.transient) terminal.replaySafe = true
1788+
trace(`Run upload cut off: ${operation} err=${failure.message} terminal=${terminal.message} transient=${terminal.transient}`)
1789+
return terminal
1790+
}
1791+
trace(`Run upload cut off: ${operation} err=${failure.message}`)
1792+
return new CursorTransportError(failure.message, {
1793+
transient: true,
1794+
replaySafe: true,
1795+
code: failure.code ?? "CURSOR_RUN_UPLOAD_FAILED",
1796+
cause: error,
1797+
})
1798+
}
1799+
17721800
/** A recovery Run continues the same turn: same request, same tools run so far, same acceptance of a switch. */
17731801
function carryModelSwitchState(from: CursorSession, to: CursorSession): void {
17741802
if (from.allowModelSwitch) to.allowModelSwitch = true
@@ -1824,15 +1852,30 @@ export type CursorRunRecovery =
18241852
/**
18251853
* `steer`: the prompt ends with mid-turn user messages after the step's results.
18261854
* `toolCallIds`: earlier results of this step that no checkpoint holds.
1855+
* `shownText`: what the interrupted step already showed, for a rebuild to continue.
18271856
*/
18281857
| {
18291858
kind: "rebase"
18301859
reason?: "checkpoint-unusable" | "unfinished-prior-run" | "completed-tool-results"
18311860
steer?: boolean
18321861
toolCallIds?: ReadonlySet<string>
1862+
shownText?: string
18331863
}
18341864
| { kind: "resume"; conversationId: string; checkpoint: Uint8Array }
18351865

1866+
const INTERRUPTED_REPLY_MAX_CHARS = 16_000
1867+
1868+
/** A rebuilt step continues the reply the user already sees instead of writing it again. */
1869+
export function interruptedReplyNote(shownText: string): string {
1870+
const shown = shownText.length > INTERRUPTED_REPLY_MAX_CHARS
1871+
? `[…]${shownText.slice(-INTERRUPTED_REPLY_MAX_CHARS)}`
1872+
: shownText
1873+
return "\n\nThe connection dropped while you were replying. The user already sees this part of your reply:\n"
1874+
+ `<interrupted_reply>\n${shown}\n</interrupted_reply>\n`
1875+
+ "Continue from where it ends without repeating it. A tool call you had started after it did not complete; "
1876+
+ "make it again if you still need it."
1877+
}
1878+
18361879
const heartbeatWritePendingBySession = new WeakMap<CursorSession, boolean>()
18371880
/** Runs whose first current category breakdown was checked for missing rules. */
18381881
const rulesCategoryChecked = new WeakSet<CursorSession>()
@@ -2201,6 +2244,7 @@ async function startSession(
22012244
const liveTurn = allowTools && !isCompaction && !isolateHelper ? liveUserTurn(prompt) : undefined
22022245
let userText = recovery?.kind === "rebase" && !checkpointUnusable && !unfinishedPriorRun
22032246
? "Continue the interrupted turn from the conversation history above. Do not repeat completed work."
2247+
+ (recovery.shownText ? interruptedReplyNote(recovery.shownText) : "")
22042248
: ((liveTurn ? liveTurn.text : extractUserText(lastUser)) || ".")
22052249
// The reply to a turn stopped on a model switch. That stop already bound the
22062250
// conversation to the checkpoint before the switch, so only the request changes.
@@ -5344,6 +5388,7 @@ export async function pump(
53445388
textSeparator = ""
53455389
assistantText += text
53465390
replaySafety.markBarrier("visible-text")
5391+
replaySafety.recordShownText(text)
53475392
// Close reasoning before text (hosts expect reasoning-end before text-start).
53485393
if (reasoningStarted && !textStarted) {
53495394
safeEnqueue({ type: "reasoning-end", id: reasoningId } as V3Part)
@@ -6665,6 +6710,7 @@ export async function pump(
66656710
continue
66666711
}
66676712
if (displayCallId) session.displayToolCalls.delete(displayCallId)
6713+
replaySafety.recordHostExec(parsed.id)
66686714
sessionManager.registerPending(
66696715
parsed.id,
66706716
session,
@@ -6810,6 +6856,7 @@ export async function pump(
68106856
registerCursorShellCall(tc.toolCallId, parsed.resultMetadata)
68116857
}
68126858
// Keep the stream open; the result arrives on the next doStream call.
6859+
replaySafety.recordHostExec(parsed.id)
68136860
sessionManager.registerPending(
68146861
parsed.id,
68156862
session,

0 commit comments

Comments
 (0)