Skip to content

Commit 29cb2dc

Browse files
committed
fix(cursor): replay external model tool continuations with fresh conversation ids
External Cursor models like gpt-5.6-sol can reject resumeAction on a stale server-side conversation with Connect invalid_argument after stepCompleted. Mint a fresh conversation id for external tool-result continuations, keep native composer resume unchanged, and retry once with full history replay.
1 parent af973e5 commit 29cb2dc

9 files changed

Lines changed: 278 additions & 25 deletions

‎src/adapters/cursor.ts‎

Lines changed: 51 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import type { AdapterEvent, OcxProviderConfig } from "../types";
22
import type { ProviderAdapter } from "./base";
33
import { cursorExecDeniedMessage, cursorRequestDeclaresFullAccess } from "./cursor/exec-policy";
4-
import { isCursorBenignCancelError, safeCursorErrorMessage } from "./cursor/cursor-errors";
4+
import { isCursorBenignCancelError, isCursorInvalidArgumentError, safeCursorErrorMessage } from "./cursor/cursor-errors";
5+
import { isCursorExternalWireModel } from "./cursor/discovery";
56
import { createCursorKvStore, type CursorKvStore } from "./cursor/kv-store";
67
import { mapCursorServerMessage } from "./cursor/message-mapper";
78
import { createCursorRequest, generatedCursorConversationId } from "./cursor/request-builder";
@@ -70,26 +71,55 @@ export function createCursorAdapter(provider: OcxProviderConfig, deps: CursorAda
7071
const makeTransport = deps.createTransport ?? createLiveCursorTransport;
7172
const kv = deps.kv ?? createCursorKvStore();
7273
_parsed._cursorConversationId ??= generatedCursorConversationId();
73-
const request = createCursorRequest(_parsed);
74-
await runCursorTurnWithRetry(
75-
makeTransport,
76-
{ provider, headers: incoming.headers, requestDeclaresFullAccess: cursorRequestDeclaresFullAccess(request) },
77-
request,
78-
incoming.abortSignal,
79-
(message, activeTransport) => {
80-
if (incoming.abortSignal?.aborted) {
81-
emit({ type: "error", message: "Cursor turn was aborted." });
82-
return;
83-
}
84-
const events = mapCursorServerMessage(message, {
85-
kv,
86-
writeClient: clientMessage => {
87-
void activeTransport.writeClient(clientMessage);
88-
},
89-
});
90-
for (const event of events) emit(event);
91-
},
92-
);
74+
let request = createCursorRequest(_parsed);
75+
// Keep remembered conversation id in sync when the request builder mints a fresh id
76+
// for external-model tool-result continuations (stateless replay).
77+
_parsed._cursorConversationId = request.conversationId;
78+
79+
const runOnce = async (activeRequest: ReturnType<typeof createCursorRequest>) => {
80+
await runCursorTurnWithRetry(
81+
makeTransport,
82+
{
83+
provider,
84+
headers: incoming.headers,
85+
requestDeclaresFullAccess: cursorRequestDeclaresFullAccess(activeRequest),
86+
},
87+
activeRequest,
88+
incoming.abortSignal,
89+
(message, activeTransport) => {
90+
if (incoming.abortSignal?.aborted) {
91+
emit({ type: "error", message: "Cursor turn was aborted." });
92+
return;
93+
}
94+
const events = mapCursorServerMessage(message, {
95+
kv,
96+
writeClient: clientMessage => {
97+
void activeTransport.writeClient(clientMessage);
98+
},
99+
});
100+
for (const event of events) emit(event);
101+
},
102+
);
103+
};
104+
105+
try {
106+
await runOnce(request);
107+
} 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.
111+
if (
112+
!isCursorInvalidArgumentError(err)
113+
|| !isCursorExternalWireModel(request.modelId)
114+
|| incoming.abortSignal?.aborted
115+
) {
116+
throw err;
117+
}
118+
_parsed._cursorConversationId = undefined;
119+
request = createCursorRequest(_parsed, { forceFreshConversation: true });
120+
_parsed._cursorConversationId = request.conversationId;
121+
await runOnce(request);
122+
}
93123
} catch (err) {
94124
if (isCursorBenignCancelError(err)) return;
95125
const partialUsage = (err as { partialUsage?: import("../types").OcxUsage }).partialUsage;

‎src/adapters/cursor/cursor-errors.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,17 @@ export function isCursorBenignCancelError(value: unknown): boolean {
3636
return false;
3737
}
3838

39+
/**
40+
* True when Cursor Connect rejected the turn with invalid_argument.
41+
* Seen after stepCompleted on brittle external-model continuations.
42+
*/
43+
export function isCursorInvalidArgumentError(value: unknown): boolean {
44+
const code = errorCode(value).toLowerCase();
45+
if (code === "invalid_argument") return true;
46+
const message = errorMessage(value).toLowerCase();
47+
return message.includes("invalid_argument");
48+
}
49+
3950
/**
4051
* Classify a Cursor transport/Connect/gRPC error message into an actionable category.
4152
* The returned prefix string is recognized by `src/lib/errors.ts` `classifyError` keywords,

‎src/adapters/cursor/discovery.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,6 +120,31 @@ export function cursorCodexToWireModelId(modelId: string): string {
120120
return cursorWireModelSelection(modelId).modelId;
121121
}
122122

123+
/**
124+
* Cursor-native wire models keep server-side conversation state reliably.
125+
* External models (gpt/claude/gemini/grok families and similar) are more brittle on resumeAction.
126+
*/
127+
export function isCursorNativeWireModel(modelId: string): boolean {
128+
const wire = cursorCodexToWireModelId(modelId).trim().toLowerCase();
129+
const bare = stripCursorEffortSuffix(wire);
130+
if (bare === CURSOR_AUTO_WIRE_MODEL_ID || bare === CURSOR_AUTO_MODEL_ID) return true;
131+
return bare.startsWith("composer-");
132+
}
133+
134+
/** Inverse of {@link isCursorNativeWireModel}. */
135+
export function isCursorExternalWireModel(modelId: string): boolean {
136+
return !isCursorNativeWireModel(modelId);
137+
}
138+
139+
function stripCursorEffortSuffix(wireModelId: string): string {
140+
const suffixes = [...CANONICAL_EFFORT_SUFFIXES].sort((a, b) => b.length - a.length);
141+
for (const suffix of suffixes) {
142+
const marker = `-${suffix}`;
143+
if (wireModelId.endsWith(marker)) return wireModelId.slice(0, -marker.length);
144+
}
145+
return wireModelId;
146+
}
147+
123148
export function isCursorRouterModelId(modelId: string): boolean {
124149
return (CURSOR_ROUTER_MODEL_IDS as readonly string[]).includes(modelId);
125150
}

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

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import { ValueSchema } from "@bufbuild/protobuf/wkt";
44
import type { OcxAssistantContentPart, OcxMessage, OcxToolResultMessage } from "../../types";
55
import { namespacedToolName } from "../../types";
66
import type { CursorRunRequest } from "./types";
7+
import { isCursorExternalWireModel } from "./discovery";
8+
import { debugProviderDiagnostic } from "../../lib/debug";
79
import { storeCursorBlob } from "./native-exec";
810
import {
911
AgentClientMessageSchema,
@@ -326,8 +328,9 @@ export function encodeCursorRunRequest(request: CursorRunRequest): Uint8Array {
326328
// would pollute the model input and double-deliver the result. Use ResumeAction so Cursor picks up
327329
// from the history we provided.
328330
const lastRawIsToolResult = request.rawMessages?.at(-1)?.role === "toolResult";
331+
const actionCase = !lastRawIsToolResult && text.trim().length > 0 ? "userMessageAction" : "resumeAction";
329332
const action = create(ConversationActionSchema, {
330-
action: !lastRawIsToolResult && text.trim().length > 0
333+
action: actionCase === "userMessageAction"
331334
? {
332335
case: "userMessageAction",
333336
value: create(UserMessageActionSchema, {
@@ -345,6 +348,13 @@ export function encodeCursorRunRequest(request: CursorRunRequest): Uint8Array {
345348
}),
346349
},
347350
});
351+
debugProviderDiagnostic("cursor", "run-request", {
352+
wireModel: request.modelId,
353+
action: actionCase,
354+
conversationId: request.conversationId,
355+
turnType: lastRawIsToolResult ? "tool-continuation" : "initial",
356+
externalModel: isCursorExternalWireModel(request.modelId),
357+
});
348358

349359
const runRequest = create(AgentRunRequestSchema, {
350360
conversationId: request.conversationId,

‎src/adapters/cursor/request-builder.ts‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import type {
88
} from "../../types";
99
import { isAllowedToolChoice, namespacedToolName, toolChoiceAliases, type OcxTool, type OcxToolChoice } from "../../types";
1010
import type { CursorRequestMessage, CursorRunRequest } from "./types";
11-
import { cursorWireModelSelection, type CursorRoutingLevel } from "./discovery";
11+
import { cursorWireModelSelection, isCursorExternalWireModel, type CursorRoutingLevel } from "./discovery";
1212
import { cursorEffortSuffix } from "./effort-map";
1313
import {
1414
cursorMcpToolEncodedSize,
@@ -159,7 +159,15 @@ export function generatedCursorConversationId(): string {
159159
return `cursor_${crypto.randomUUID().replace(/-/g, "")}`;
160160
}
161161

162-
export function createCursorRequest(parsed: OcxParsedRequest): CursorRunRequest {
162+
export interface CreateCursorRequestOptions {
163+
/** Force a brand-new Cursor conversation id even when remembered state exists. */
164+
forceFreshConversation?: boolean;
165+
}
166+
167+
export function createCursorRequest(
168+
parsed: OcxParsedRequest,
169+
options: CreateCursorRequestOptions = {},
170+
): CursorRunRequest {
163171
const messages = parsed.context.messages
164172
.map(requestMessage)
165173
.filter((message): message is CursorRequestMessage => !!message && message.content.length > 0);
@@ -168,14 +176,23 @@ export function createCursorRequest(parsed: OcxParsedRequest): CursorRunRequest
168176
const budget = applyCursorToolBudget(visibleTools, parsed.options.toolChoice);
169177
const limitNote = catalogLimitNote(budget.tools, budget.omitted);
170178
const model = normalizeCursorModelId(parsed.modelId, parsed.options.reasoning);
179+
const lastRaw = parsed.context.messages.at(-1);
180+
// External Cursor models (e.g. gpt-5.6-sol) can corrupt server-side conversation state across
181+
// tool-result continuations when ResumeAction reuses the same conversationId. Force a fresh id
182+
// so the full history is replayed without depending on that state.
183+
const forceFreshConversation =
184+
options.forceFreshConversation === true
185+
|| (lastRaw?.role === "toolResult" && isCursorExternalWireModel(model.modelId));
171186
return {
172187
modelId: model.modelId,
173188
...(model.routingLevel ? { routingLevel: model.routingLevel } : {}),
174189
// The Cursor conversation id comes ONLY from remembered state (_cursorConversationId). Do NOT fall
175190
// back to the OpenAI Responses previous_response_id (resp_*): that is a Responses-chain id in a
176191
// different namespace and would start an unrelated Cursor conversation, breaking tool-result
177192
// continuation. If we have no remembered Cursor conversation, start a fresh one.
178-
conversationId: parsed._cursorConversationId ?? generatedCursorConversationId(),
193+
conversationId: forceFreshConversation
194+
? generatedCursorConversationId()
195+
: (parsed._cursorConversationId ?? generatedCursorConversationId()),
179196
system: [...(parsed.context.systemPrompt ?? []), ...(limitNote ? [limitNote] : [])],
180197
messages,
181198
rawMessages: parsed.context.messages,

‎tests/cursor-adapter.test.ts‎

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,4 +140,66 @@ describe("Cursor adapter live transport", () => {
140140
expect(cursorExecDeniedMessage("shellArgs")).toContain("shellArgs");
141141
expect(cursorExecDeniedMessage("shellArgs")).toContain("legacy mock transport cannot execute");
142142
});
143+
144+
test("retries external-model invalid_argument once with a fresh conversation id", async () => {
145+
const seen: string[] = [];
146+
let attempts = 0;
147+
const adapter = createCursorAdapter({
148+
...provider,
149+
apiKey: "cursor-token",
150+
}, {
151+
createTransport: () => ({
152+
async *run(request) {
153+
attempts += 1;
154+
seen.push(request.conversationId);
155+
if (attempts === 1) {
156+
throw Object.assign(
157+
new Error("Cursor invalid request: Cursor Connect error invalid_argument: Error"),
158+
{ code: "invalid_argument" },
159+
);
160+
}
161+
yield { type: "done" } satisfies CursorServerMessage;
162+
},
163+
writeClient() {},
164+
}),
165+
});
166+
167+
const events: AdapterEvent[] = [];
168+
const body: OcxParsedRequest = {
169+
modelId: "cursor/gpt-5.6-sol",
170+
context: {
171+
messages: [
172+
{ role: "user", content: "read a file", timestamp: 1 },
173+
{
174+
role: "assistant",
175+
model: "cursor/gpt-5.6-sol",
176+
timestamp: 2,
177+
content: [{ type: "toolCall", id: "call_1", name: "read_file", namespace: "mcp__fs", arguments: { path: "a.txt" } }],
178+
},
179+
{
180+
role: "toolResult",
181+
toolCallId: "call_1",
182+
toolName: "read_file",
183+
toolNamespace: "mcp__fs",
184+
content: "FILE CONTENTS HERE",
185+
isError: false,
186+
timestamp: 3,
187+
},
188+
],
189+
},
190+
stream: false,
191+
options: { reasoning: "xhigh" },
192+
_cursorConversationId: "cursor_corrupt",
193+
};
194+
195+
await adapter.runTurn?.(body, { headers: new Headers() }, event => events.push(event));
196+
197+
expect(attempts).toBe(2);
198+
expect(seen).toHaveLength(2);
199+
expect(seen[0]).not.toBe("cursor_corrupt");
200+
expect(seen[1]).not.toBe(seen[0]);
201+
expect(body._cursorConversationId).toBe(seen[1]);
202+
expect(events.filter(event => event.type === "error")).toHaveLength(0);
203+
});
143204
});
205+

‎tests/cursor-discovery.test.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ import {
1414
cursorModelReasoningEfforts,
1515
cursorWireModelSelection,
1616
inferCursorContextWindow,
17+
isCursorExternalWireModel,
18+
isCursorNativeWireModel,
1719
normalizeCursorModels,
1820
} from "../src/adapters/cursor/discovery";
1921

@@ -145,4 +147,15 @@ describe("Cursor discovery metadata", () => {
145147
expect(efforts["unknown-reasoning-model"]).toEqual([]);
146148
expect(efforts["composer-2.5"]).toEqual([]);
147149
});
150+
151+
test("classifies native vs external Cursor wire models", () => {
152+
expect(isCursorNativeWireModel("default")).toBe(true);
153+
expect(isCursorNativeWireModel("auto")).toBe(true);
154+
expect(isCursorNativeWireModel("composer-2.5")).toBe(true);
155+
expect(isCursorNativeWireModel("composer-2.5-fast")).toBe(true);
156+
expect(isCursorExternalWireModel("gpt-5.6-sol")).toBe(true);
157+
expect(isCursorExternalWireModel("gpt-5.6-sol-xhigh")).toBe(true);
158+
expect(isCursorExternalWireModel("claude-4.6-sonnet-high")).toBe(true);
159+
expect(isCursorExternalWireModel("cursor/gpt-5.6-sol")).toBe(true);
160+
});
148161
});

‎tests/cursor-errors.test.ts‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
22
import {
33
classifyCursorError,
44
isCursorBenignCancelError,
5+
isCursorInvalidArgumentError,
56
safeCursorErrorMessage,
67
} from "../src/adapters/cursor/cursor-errors";
78

@@ -81,3 +82,12 @@ describe("safeCursorErrorMessage", () => {
8182
expect(msg).not.toContain("rate limit");
8283
});
8384
});
85+
86+
87+
describe("isCursorInvalidArgumentError", () => {
88+
test("matches Connect invalid_argument code and message", () => {
89+
expect(isCursorInvalidArgumentError({ code: "invalid_argument", message: "Cursor invalid request" })).toBe(true);
90+
expect(isCursorInvalidArgumentError(new Error("Cursor invalid request: Cursor Connect error invalid_argument: Error"))).toBe(true);
91+
expect(isCursorInvalidArgumentError(new Error("Cursor connection failed"))).toBe(false);
92+
});
93+
});

0 commit comments

Comments
 (0)