Skip to content

Commit 9cf0abd

Browse files
committed
fix(cursor): gate external continuation replay and rekey usage carry-forward
Address PR #318 review feedback: - retry invalid_argument only for external tool-result continuations with no committed output - track emitted non-heartbeat events to avoid duplicate text/tool replay - rekey Cursor context-usage carry-forward when conversation ids rotate - add regression coverage for both behaviors
1 parent 29cb2dc commit 9cf0abd

5 files changed

Lines changed: 104 additions & 5 deletions

File tree

‎src/adapters/cursor.ts‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,11 @@ import { isCursorExternalWireModel } from "./cursor/discovery";
66
import { createCursorKvStore, type CursorKvStore } from "./cursor/kv-store";
77
import { mapCursorServerMessage } from "./cursor/message-mapper";
88
import { createCursorRequest, generatedCursorConversationId } from "./cursor/request-builder";
9-
import { createLiveCursorTransport, CursorMissingCredentialError } from "./cursor/live-transport";
9+
import {
10+
createLiveCursorTransport,
11+
CursorMissingCredentialError,
12+
rekeyCursorContextUsage,
13+
} from "./cursor/live-transport";
1014
import { runCursorTurnWithRetry } from "./cursor/transport-retry";
1115
import {
1216
createDisabledCursorTransport,
@@ -71,10 +75,16 @@ export function createCursorAdapter(provider: OcxProviderConfig, deps: CursorAda
7175
const makeTransport = deps.createTransport ?? createLiveCursorTransport;
7276
const kv = deps.kv ?? createCursorKvStore();
7377
_parsed._cursorConversationId ??= generatedCursorConversationId();
78+
const previousConversationId = _parsed._cursorConversationId;
7479
let request = createCursorRequest(_parsed);
7580
// Keep remembered conversation id in sync when the request builder mints a fresh id
7681
// for external-model tool-result continuations (stateless replay).
82+
if (request.conversationId !== previousConversationId) {
83+
rekeyCursorContextUsage(previousConversationId, request.conversationId);
84+
}
7785
_parsed._cursorConversationId = request.conversationId;
86+
let emittedOutput = false;
87+
const lastRawIsToolResult = _parsed.context.messages.at(-1)?.role === "toolResult";
7888

7989
const runOnce = async (activeRequest: ReturnType<typeof createCursorRequest>) => {
8090
await runCursorTurnWithRetry(
@@ -97,26 +107,33 @@ export function createCursorAdapter(provider: OcxProviderConfig, deps: CursorAda
97107
void activeTransport.writeClient(clientMessage);
98108
},
99109
});
100-
for (const event of events) emit(event);
110+
for (const event of events) {
111+
if (event.type !== "heartbeat") emittedOutput = true;
112+
emit(event);
113+
}
101114
},
102115
);
103116
};
104117

105118
try {
106119
await runOnce(request);
107120
} catch (err) {
108-
// One-shot fallback: external Cursor models can reject resume/continuation on a
109-
// stale server-side conversation with Connect invalid_argument after stepCompleted.
110-
// Replay once with a fresh conversation id and full history.
121+
// One-shot fallback: only for external-model tool-result continuations that fail
122+
// with Connect invalid_argument before any non-heartbeat output was forwarded.
123+
// Replaying after text/tool events would duplicate output.
111124
if (
112125
!isCursorInvalidArgumentError(err)
113126
|| !isCursorExternalWireModel(request.modelId)
127+
|| !lastRawIsToolResult
128+
|| emittedOutput
114129
|| incoming.abortSignal?.aborted
115130
) {
116131
throw err;
117132
}
133+
const failedConversationId = request.conversationId;
118134
_parsed._cursorConversationId = undefined;
119135
request = createCursorRequest(_parsed, { forceFreshConversation: true });
136+
rekeyCursorContextUsage(failedConversationId, request.conversationId);
120137
_parsed._cursorConversationId = request.conversationId;
121138
await runOnce(request);
122139
}

‎src/adapters/cursor/live-transport.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,11 @@ const GENERIC_TOOL_COUNT_MAX_FINALIZE_GRACE_MS = 1_800;
7070
const GENERIC_TOOL_COUNT_PER_TOOL_GRACE_MS = 125;
7171
const cursorContextUsageTracker = createCursorContextUsageTracker();
7272

73+
/** Carry context-usage totals across conversation-id rotation for external-model replay. */
74+
export function rekeyCursorContextUsage(fromConversationId: string, toConversationId: string): void {
75+
cursorContextUsageTracker.rekey(fromConversationId, toConversationId);
76+
}
77+
7378
export class CursorMissingCredentialError extends Error {
7479
readonly code = "cursor_missing_credential";
7580

‎src/adapters/cursor/protobuf-events.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,8 @@ export interface CursorContextUsageTracker {
2222
controlsForConversation(conversationId: string, options?: { clearPrior?: boolean; storeCheckpoints?: boolean }): CursorContextUsageControls;
2323
get(conversationId: string): number | undefined;
2424
record(conversationId: string, tokens: number): void;
25+
/** Copy numeric carry-forward totals when a conversation id is rotated for replay. */
26+
rekey(fromConversationId: string, toConversationId: string): void;
2527
clear(conversationId: string): void;
2628
clearAll(): void;
2729
}
@@ -91,6 +93,18 @@ export function createCursorContextUsageTracker(options: { maxEntries?: number;
9193
},
9294
get,
9395
record,
96+
rekey(fromConversationId, toConversationId) {
97+
if (!fromConversationId || !toConversationId || fromConversationId === toConversationId) return;
98+
prune();
99+
const from = entries.get(fromConversationId);
100+
if (!from) return;
101+
const to = entries.get(toConversationId);
102+
const tokens = Math.max(from.tokens, to?.tokens ?? 0);
103+
entries.delete(fromConversationId);
104+
entries.delete(toConversationId);
105+
entries.set(toConversationId, { tokens, updatedAt: now() });
106+
prune();
107+
},
94108
clear(conversationId) {
95109
entries.delete(conversationId);
96110
},

‎tests/cursor-adapter.test.ts‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -203,3 +203,56 @@ describe("Cursor adapter live transport", () => {
203203
});
204204
});
205205

206+
test("does not replay invalid_argument after non-heartbeat output was already emitted", async () => {
207+
let attempts = 0;
208+
const adapter = createCursorAdapter({
209+
...provider,
210+
apiKey: "cursor-token",
211+
}, {
212+
createTransport: () => ({
213+
async *run() {
214+
attempts += 1;
215+
yield { type: "text", text: "partial output" } satisfies CursorServerMessage;
216+
throw Object.assign(
217+
new Error("Cursor invalid request: Cursor Connect error invalid_argument: Error"),
218+
{ code: "invalid_argument" },
219+
);
220+
},
221+
writeClient() {},
222+
}),
223+
});
224+
225+
const events: AdapterEvent[] = [];
226+
const body: OcxParsedRequest = {
227+
modelId: "cursor/gpt-5.6-sol",
228+
context: {
229+
messages: [
230+
{ role: "user", content: "read a file", timestamp: 1 },
231+
{
232+
role: "assistant",
233+
model: "cursor/gpt-5.6-sol",
234+
timestamp: 2,
235+
content: [{ type: "toolCall", id: "call_1", name: "read_file", namespace: "mcp__fs", arguments: { path: "a.txt" } }],
236+
},
237+
{
238+
role: "toolResult",
239+
toolCallId: "call_1",
240+
toolName: "read_file",
241+
toolNamespace: "mcp__fs",
242+
content: "FILE CONTENTS HERE",
243+
isError: false,
244+
timestamp: 3,
245+
},
246+
],
247+
},
248+
stream: false,
249+
options: { reasoning: "xhigh" },
250+
_cursorConversationId: "cursor_corrupt",
251+
};
252+
253+
await adapter.runTurn?.(body, { headers: new Headers() }, event => events.push(event));
254+
255+
expect(attempts).toBe(1);
256+
expect(events.some(event => event.type === "text_delta")).toBe(true);
257+
expect(events.some(event => event.type === "error")).toBe(true);
258+
});

‎tests/cursor-protobuf-events.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,16 @@ describe("Cursor protobuf tool-call events", () => {
589589
]);
590590
expect(tracker.get("cursor_conv_1")).toBeUndefined();
591591
});
592+
593+
test("rekey copies carry-forward totals onto a rotated conversation id", () => {
594+
const tracker = createCursorContextUsageTracker();
595+
tracker.record("cursor_old", 12_500);
596+
tracker.rekey("cursor_old", "cursor_new");
597+
598+
expect(tracker.get("cursor_old")).toBeUndefined();
599+
expect(tracker.get("cursor_new")).toBe(12_500);
600+
expect(tracker.controlsForConversation("cursor_new").carryForwardTokens).toBe(12_500);
601+
});
592602
});
593603

594604
describe("Cursor MCP display-name alias", () => {

0 commit comments

Comments
 (0)