Skip to content

Commit a0b9688

Browse files
authored
Merge pull request #318 from Wibias/codex/fix-cursor-sol-continuation
fix(cursor): replay external model tool continuations with fresh conversation ids
2 parents 82af651 + 9cf0abd commit a0b9688

12 files changed

Lines changed: 378 additions & 26 deletions

‎src/adapters/cursor.ts‎

Lines changed: 69 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,16 @@
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";
8-
import { createLiveCursorTransport, CursorMissingCredentialError } from "./cursor/live-transport";
9+
import {
10+
createLiveCursorTransport,
11+
CursorMissingCredentialError,
12+
rekeyCursorContextUsage,
13+
} from "./cursor/live-transport";
914
import { runCursorTurnWithRetry } from "./cursor/transport-retry";
1015
import {
1116
createDisabledCursorTransport,
@@ -70,26 +75,68 @@ export function createCursorAdapter(provider: OcxProviderConfig, deps: CursorAda
7075
const makeTransport = deps.createTransport ?? createLiveCursorTransport;
7176
const kv = deps.kv ?? createCursorKvStore();
7277
_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-
);
78+
const previousConversationId = _parsed._cursorConversationId;
79+
let request = createCursorRequest(_parsed);
80+
// Keep remembered conversation id in sync when the request builder mints a fresh id
81+
// for external-model tool-result continuations (stateless replay).
82+
if (request.conversationId !== previousConversationId) {
83+
rekeyCursorContextUsage(previousConversationId, request.conversationId);
84+
}
85+
_parsed._cursorConversationId = request.conversationId;
86+
let emittedOutput = false;
87+
const lastRawIsToolResult = _parsed.context.messages.at(-1)?.role === "toolResult";
88+
89+
const runOnce = async (activeRequest: ReturnType<typeof createCursorRequest>) => {
90+
await runCursorTurnWithRetry(
91+
makeTransport,
92+
{
93+
provider,
94+
headers: incoming.headers,
95+
requestDeclaresFullAccess: cursorRequestDeclaresFullAccess(activeRequest),
96+
},
97+
activeRequest,
98+
incoming.abortSignal,
99+
(message, activeTransport) => {
100+
if (incoming.abortSignal?.aborted) {
101+
emit({ type: "error", message: "Cursor turn was aborted." });
102+
return;
103+
}
104+
const events = mapCursorServerMessage(message, {
105+
kv,
106+
writeClient: clientMessage => {
107+
void activeTransport.writeClient(clientMessage);
108+
},
109+
});
110+
for (const event of events) {
111+
if (event.type !== "heartbeat") emittedOutput = true;
112+
emit(event);
113+
}
114+
},
115+
);
116+
};
117+
118+
try {
119+
await runOnce(request);
120+
} catch (err) {
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.
124+
if (
125+
!isCursorInvalidArgumentError(err)
126+
|| !isCursorExternalWireModel(request.modelId)
127+
|| !lastRawIsToolResult
128+
|| emittedOutput
129+
|| incoming.abortSignal?.aborted
130+
) {
131+
throw err;
132+
}
133+
const failedConversationId = request.conversationId;
134+
_parsed._cursorConversationId = undefined;
135+
request = createCursorRequest(_parsed, { forceFreshConversation: true });
136+
rekeyCursorContextUsage(failedConversationId, request.conversationId);
137+
_parsed._cursorConversationId = request.conversationId;
138+
await runOnce(request);
139+
}
93140
} catch (err) {
94141
if (isCursorBenignCancelError(err)) return;
95142
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/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
},

‎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,

0 commit comments

Comments
 (0)