Skip to content

Commit c6b8d7e

Browse files
committed
Merge branch 'vpr-1990' into codex/land-1990
# Conflicts: # tests/cursor-blob.test.ts
2 parents 891c828 + e3c9965 commit c6b8d7e

8 files changed

Lines changed: 171 additions & 17 deletions

File tree

‎src/adapters/cursor.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,7 @@ export function createCursorAdapter(provider: OcxProviderConfig, deps: CursorAda
121121
headers: incoming.headers,
122122
translatorBudget: incoming.translatorBudget,
123123
requestDeclaresFullAccess: cursorRequestDeclaresFullAccess(activeRequest),
124+
sessionId: activeRequest.conversationId,
124125
},
125126
activeRequest,
126127
incoming.abortSignal,

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

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -438,9 +438,12 @@ class LiveCursorTransport implements CursorTransport {
438438
private firstFrameAt?: number;
439439
private firstFrameLogged = false;
440440
/** Stable session identifier sent as x-session-id; mirrors IDE session semantics. */
441-
private readonly sessionId = crypto.randomUUID();
441+
private readonly sessionId: string;
442+
/** Per-transport owner for native-exec / background shells. Must not share conversationId. */
443+
private readonly shellOwnerId = crypto.randomUUID();
442444

443445
constructor(private readonly input: CursorTransportFactoryInput) {
446+
this.sessionId = input.sessionId?.trim() || crypto.randomUUID();
444447
this.translatorBudget = input.translatorBudget;
445448
this.token = resolveCursorToken(input.provider, input.headers);
446449
// Grace window before a drained client-tool turn is finalized. Small enough not to look like a
@@ -452,7 +455,7 @@ class LiveCursorTransport implements CursorTransport {
452455
this.desktopDeps = desktopDepsFromConfig(input.provider.desktopExecutor);
453456
this.execContext = {
454457
...this.desktopDeps,
455-
sessionId: this.sessionId,
458+
sessionId: this.shellOwnerId,
456459
unsafeAllowNativeLocalExec: effectiveCursorNativeExecAllow(input.provider, input.requestDeclaresFullAccess === true),
457460
};
458461
const servers = resolveMcpServers(input.provider);
@@ -487,7 +490,7 @@ class LiveCursorTransport implements CursorTransport {
487490
...this.desktopDeps,
488491
...mcpDepsFromManager(this.mcpManager!),
489492
mcpToolDefs,
490-
sessionId: this.sessionId,
493+
sessionId: this.shellOwnerId,
491494
unsafeAllowNativeLocalExec: effectiveCursorNativeExecAllow(this.input.provider, this.input.requestDeclaresFullAccess === true),
492495
};
493496
} catch (err) {
@@ -700,7 +703,7 @@ class LiveCursorTransport implements CursorTransport {
700703
}
701704

702705
private startShellCleanup(): Promise<BackgroundShellTerminationReport> {
703-
return this.shellCleanup ??= terminateBackgroundShellsForSession(this.sessionId);
706+
return this.shellCleanup ??= terminateBackgroundShellsForSession(this.shellOwnerId);
704707
}
705708

706709
async close(): Promise<void> {

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

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,14 @@ export const CURSOR_EXTERNAL_ROOT_BLOB_LIMIT = 192;
6868
/** Approximate prompt-size guard; tool schemas and protocol framing consume context separately. */
6969
export const CURSOR_EXTERNAL_ROOT_BYTE_LIMIT = 512 * 1024;
7070

71+
/**
72+
* Action text for external-model tool-result continuations. Native models keep
73+
* resumeAction; external wire models continue as userMessageAction so the
74+
* results already stored in history blobs are visible without a ResumeAction.
75+
*/
76+
export const CURSOR_EXTERNAL_TOOL_CONTINUATION_TEXT =
77+
"Continue: the requested tool results are provided in the conversation history above.";
78+
7179
/** Runtime timezone for protobuf RequestContextEnv (dynamic, never hardcoded). */
7280
function runtimeTimeZone(): string {
7381
try {
@@ -731,18 +739,24 @@ function buildPreparedCursorRunRequest(
731739
const text = lastRole === "user" || lastRole === "developer"
732740
? appendCursorGenericToolUseHint(request.tools, rawText)
733741
: rawText;
734-
// Tool-result-only turns resume the remembered Cursor conversation with results in history.
735742
const lastRawIsToolResult = request.rawMessages?.at(-1)?.role === "toolResult";
736-
const actionCase = !lastRawIsToolResult && text.trim().length > 0
743+
// Native models resume the remembered Cursor conversation. External wire
744+
// models continue as userMessageAction so history-blob tool results stay
745+
// visible without a ResumeAction.
746+
const externalToolContinuation = lastRawIsToolResult && isCursorExternalWireModel(request.modelId);
747+
const actionCase = (externalToolContinuation || (!lastRawIsToolResult && text.trim().length > 0))
737748
? "userMessageAction"
738749
: "resumeAction";
750+
const actionText = externalToolContinuation
751+
? CURSOR_EXTERNAL_TOOL_CONTINUATION_TEXT
752+
: text;
739753
const action = create(ConversationActionSchema, {
740754
action: actionCase === "userMessageAction"
741755
? {
742756
case: "userMessageAction",
743757
value: create(UserMessageActionSchema, {
744758
userMessage: create(UserMessageSchema, {
745-
text,
759+
text: actionText,
746760
messageId: crypto.randomUUID(),
747761
}),
748762
requestContext: buildRequestContext(),
@@ -842,7 +856,7 @@ function buildPreparedCursorRunRequest(
842856
// tools the payload dropped — the defect that blocked PR #376.
843857
const modelVisibleParts = [
844858
...rootPromptMessagesState.serialized,
845-
...(actionCase === "userMessageAction" ? [text] : []),
859+
...(actionCase === "userMessageAction" ? [actionText] : []),
846860
...mcpToolDefs.map(modelVisibleToolText),
847861
];
848862
return {

‎src/adapters/cursor/transport.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ export interface CursorTransportFactoryInput {
3333
* native local exec authorization because the text is caller-controlled.
3434
*/
3535
requestDeclaresFullAccess?: boolean;
36+
/**
37+
* Stable Cursor Connect `x-session-id` across transport rebuilds for the same
38+
* client thread. Distinct from the per-transport native-exec/shell owner.
39+
*/
40+
sessionId?: string;
3641
}
3742

3843
export type CursorTransportFactory = (input: CursorTransportFactoryInput) => CursorTransport;

‎tests/cursor-adapter.test.ts‎

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import {
99
} from "../src/adapters/cursor/thread-continuity";
1010
import type { AdapterEvent, OcxParsedRequest, OcxProviderConfig } from "../src/types";
1111
import type { CursorClientMessage, CursorRunRequest, CursorServerMessage } from "../src/adapters/cursor/types";
12+
import type { CursorTransportFactoryInput } from "../src/adapters/cursor/transport";
1213
import { withTestTranslatorBudget } from "./helpers/translator-budget";
1314

1415
const createCursorAdapter = (...args: Parameters<typeof createCursorAdapterProduction>) =>
@@ -162,6 +163,47 @@ describe("Cursor adapter live transport", () => {
162163
expect(ids).toHaveLength(2);
163164
expect(ids[0]).not.toBe(ids[1]);
164165
});
166+
test("passes conversationId as Connect sessionId and isolates helper turns", async () => {
167+
const captured: CursorTransportFactoryInput[] = [];
168+
const adapter = createCursorAdapter({ ...provider, apiKey: "cursor-token" }, {
169+
createTransport(input) {
170+
captured.push(input);
171+
return {
172+
async *run() {
173+
yield { type: "done" } satisfies CursorServerMessage;
174+
},
175+
writeClient() {},
176+
};
177+
},
178+
});
179+
180+
const parent: OcxParsedRequest = {
181+
modelId: "cursor/auto",
182+
context: { messages: [{ role: "user", content: "hi", timestamp: 1 }] },
183+
stream: false,
184+
options: {},
185+
_clientThreadId: "parent-thread-session-id",
186+
};
187+
await adapter.runTurn?.(parent, { headers: new Headers() }, () => {});
188+
expect(captured).toHaveLength(1);
189+
expect(captured[0]?.sessionId).toBeTruthy();
190+
expect(captured[0]?.sessionId).toBe(parent._cursorConversationId);
191+
192+
const helper: OcxParsedRequest = {
193+
modelId: "cursor/auto",
194+
context: { messages: [{ role: "user", content: "summarize", timestamp: 1 }] },
195+
stream: false,
196+
options: {},
197+
_clientThreadId: "parent-thread-session-id",
198+
_cursorConversationId: parent._cursorConversationId,
199+
_cursorIsolateConversation: true,
200+
};
201+
await adapter.runTurn?.(helper, { headers: new Headers() }, () => {});
202+
expect(captured).toHaveLength(2);
203+
expect(captured[1]?.sessionId).toBeTruthy();
204+
expect(captured[1]?.sessionId).not.toBe(captured[0]?.sessionId);
205+
expect(captured[1]?.sessionId).toBe(helper._cursorConversationId);
206+
});
165207

166208
test("parseStream reports that the fetch path is disabled", async () => {
167209
const adapter = createCursorAdapter(provider);

‎tests/cursor-blob.test.ts‎

Lines changed: 33 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
} from "../src/lib/app-owned-memory";
2424
import {
2525
CURSOR_EXTERNAL_ROOT_BYTE_LIMIT,
26+
CURSOR_EXTERNAL_TOOL_CONTINUATION_TEXT,
2627
CURSOR_EXTERNAL_ROOT_BLOB_LIMIT,
2728
CURSOR_ROUTING_LEVEL_PARAMETER_ID,
2829
encodeCursorRunRequest,
@@ -246,7 +247,7 @@ describe("Cursor blob handshake", () => {
246247
const rootBytes = (run?.conversationState?.rootPromptMessagesJson ?? [])
247248
.reduce((sum, id) => sum + blobData(id).byteLength, 0);
248249

249-
expect(run?.action?.action.case).toBe("resumeAction");
250+
expect(run?.action?.action.case).toBe("userMessageAction");
250251
expect(rootBytes).toBeLessThanOrEqual(CURSOR_EXTERNAL_ROOT_BYTE_LIMIT);
251252
expect(JSON.stringify(roots)).toContain("[Tool Result]");
252253
expect(JSON.stringify(roots)).toContain("truncated for Cursor external replay budget");
@@ -594,7 +595,7 @@ describe("Cursor blob handshake", () => {
594595
expect(historicalUser?.content).toEqual([{ type: "text", text: "read a file" }]);
595596
const toolResultRoot = roots.find(root => JSON.stringify(root).includes("[Tool Result]"));
596597
expect(toolResultRoot?.role).toBe("assistant");
597-
expect(run?.action?.action.case).toBe("resumeAction");
598+
expect(run?.action?.action.case).toBe("userMessageAction");
598599
expect(JSON.stringify(roots)).toContain("contents");
599600
expect(JSON.stringify(roots)).not.toContain("hidden reasoning");
600601
});
@@ -621,6 +622,36 @@ describe("Cursor blob handshake", () => {
621622

622623
expect(run?.action?.action.case).toBe("resumeAction");
623624
});
625+
626+
test("drives external-model tool-result continuations as userMessageAction", () => {
627+
// External wire models encode tool-result hops as userMessageAction; native
628+
// models keep resumeAction. Tool results stay in the history blobs.
629+
const bytes = encodeCursorRunRequest({
630+
modelId: "claude-fable-5",
631+
conversationId: "c-ext-cont",
632+
system: ["You are helpful."],
633+
messages: [{ role: "tool", content: "[tool_result]\ncall_id: call_1\nname: read_file\nis_error: false\noutput:\ncontents" }],
634+
rawMessages: [
635+
{ role: "user", content: "read a file", timestamp: 1 },
636+
{
637+
role: "assistant",
638+
model: "cursor/claude-fable-5",
639+
timestamp: 2,
640+
content: [{ type: "toolCall", id: "call_1", name: "read_file", arguments: { path: "a.txt" } }],
641+
},
642+
{ role: "toolResult", toolCallId: "call_1", toolName: "read_file", content: "contents", isError: false, timestamp: 3 },
643+
],
644+
});
645+
const msg = fromBinary(AgentClientMessageSchema, bytes);
646+
const run = msg.message.case === "runRequest" ? msg.message.value : undefined;
647+
648+
expect(run?.action?.action.case).toBe("userMessageAction");
649+
const value = run?.action?.action.case === "userMessageAction" ? run.action.action.value : undefined;
650+
expect(value?.userMessage?.text).toBe(CURSOR_EXTERNAL_TOOL_CONTINUATION_TEXT);
651+
// Tool results are still replayed via history blobs.
652+
const roots = decodeRootMessages(bytes) as Array<{ role?: string }>;
653+
expect(JSON.stringify(roots)).toContain("contents");
654+
});
624655
});
625656

626657
describe("Cursor AgentRunRequest.mcp_tools channel", () => {

‎tests/cursor-hardening.test.ts‎

Lines changed: 30 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,11 @@ import { clearModelCache, getProviderDiscoveryStatus } from "../src/codex/model-
2525
import { handleManagementAPI } from "../src/server/management-api";
2626

2727
async function withDiscoveryServer<T>(
28-
handler: (stream: http2.ServerHttp2Stream) => void,
28+
handler: (stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders) => void,
2929
run: (baseUrl: string) => Promise<T>,
3030
): Promise<T> {
3131
const server = http2.createServer();
32-
server.on("stream", handler);
32+
server.on("stream", (stream, headers) => handler(stream, headers));
3333
await new Promise<void>((resolve, reject) => {
3434
const onError = (error: Error) => reject(error);
3535
server.once("error", onError);
@@ -443,6 +443,34 @@ describe("Cursor live transport unexpected EOF", () => {
443443
expect(messages.at(-1)).toMatchObject({ type: "done" });
444444
});
445445
});
446+
test("sends the injected session id as Connect x-session-id", async () => {
447+
let seenSessionId: string | undefined;
448+
await withDiscoveryServer((stream, headers) => {
449+
const raw = headers["x-session-id"];
450+
seenSessionId = Array.isArray(raw) ? raw[0] : raw;
451+
stream.respond({ ":status": 200, "content-type": "application/connect+proto" });
452+
stream.end();
453+
}, async baseUrl => {
454+
const transport = createLiveCursorTransport({
455+
provider: { adapter: "cursor", baseUrl, apiKey: "test-token" },
456+
translatorBudget: createTestTranslatorBudget(),
457+
firstFrameTimeoutMs: 2_000,
458+
sessionId: "cursor_from_gjc_session",
459+
});
460+
try {
461+
for await (const _ of transport.run({
462+
modelId: "composer-2",
463+
conversationId: "cursor_header_test",
464+
system: [],
465+
messages: [{ role: "user", content: "hello" }],
466+
})) { /* drain */ }
467+
} catch { /* fixture closes immediately */ }
468+
finally {
469+
await transport.close?.();
470+
}
471+
});
472+
expect(seenSessionId).toBe("cursor_from_gjc_session");
473+
});
446474

447475
test("synthesizes done after createPlanRequestQuery text on clean Connect EOF", async () => {
448476
const planFrame = encodeConnectFrame(toBinary(AgentServerMessageSchema, create(AgentServerMessageSchema, {

‎tests/cursor-live-transport.test.ts‎

Lines changed: 35 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -55,7 +55,7 @@ describe("Cursor live transport", () => {
5555
translatorBudget: createTestTranslatorBudget(),
5656
headers: new Headers(),
5757
});
58-
const sessionId = (transport as unknown as { sessionId: string }).sessionId;
58+
const sessionId = (transport as unknown as { shellOwnerId: string }).shellOwnerId;
5959
const fake = spawnTransportOwnedShell(sessionId);
6060
let closed = false;
6161
const closing = Promise.resolve(transport.close?.()).then(() => { closed = true; });
@@ -73,8 +73,8 @@ describe("Cursor live transport", () => {
7373
translatorBudget: createTestTranslatorBudget(),
7474
headers: new Headers(),
7575
});
76-
const internals = transport as unknown as { sessionId: string; cancelCursorRun(): void };
77-
const fake = spawnTransportOwnedShell(internals.sessionId);
76+
const internals = transport as unknown as { shellOwnerId: string; cancelCursorRun(): void };
77+
const fake = spawnTransportOwnedShell(internals.shellOwnerId);
7878
internals.cancelCursorRun();
7979
const closing = Promise.resolve(transport.close?.());
8080
await Promise.resolve();
@@ -92,19 +92,49 @@ describe("Cursor live transport", () => {
9292
});
9393
const internals = transport as unknown as {
9494
sessionId: string;
95+
shellOwnerId: string;
9596
execContext: { sessionId?: string };
9697
mcpManager?: { listToolHandles(): Promise<unknown[]>; dispose(): Promise<void> };
9798
prepareMcp(): Promise<void>;
9899
};
99-
expect(internals.execContext.sessionId).toBe(internals.sessionId);
100+
expect(internals.execContext.sessionId).toBe(internals.shellOwnerId);
101+
expect(internals.execContext.sessionId).not.toBe(internals.sessionId);
100102
internals.mcpManager = {
101103
listToolHandles: async () => [],
102104
dispose: async () => {},
103105
};
104106
await internals.prepareMcp();
105-
expect(internals.execContext.sessionId).toBe(internals.sessionId);
107+
expect(internals.execContext.sessionId).toBe(internals.shellOwnerId);
106108
await transport.close?.();
107109
});
110+
test("honors an injected session id for Cursor Connect x-session-id", () => {
111+
const transport = createLiveCursorTransport({
112+
provider: { adapter: "cursor", baseUrl: "https://api2.cursor.sh", apiKey: "test-token" },
113+
translatorBudget: createTestTranslatorBudget(),
114+
headers: new Headers(),
115+
sessionId: "cursor_from_gjc_session",
116+
});
117+
const internals = transport as unknown as {
118+
sessionId: string;
119+
shellOwnerId: string;
120+
execContext: { sessionId?: string };
121+
};
122+
expect(internals.sessionId).toBe("cursor_from_gjc_session");
123+
expect(internals.execContext.sessionId).toBe(internals.shellOwnerId);
124+
expect(internals.execContext.sessionId).not.toBe("cursor_from_gjc_session");
125+
});
126+
test("keeps a blank injected session id from becoming the Connect x-session-id", () => {
127+
const transport = createLiveCursorTransport({
128+
provider: { adapter: "cursor", baseUrl: "https://api2.cursor.sh", apiKey: "test-token" },
129+
translatorBudget: createTestTranslatorBudget(),
130+
headers: new Headers(),
131+
sessionId: " ",
132+
});
133+
const internals = transport as unknown as { sessionId: string };
134+
expect(internals.sessionId.length).toBeGreaterThan(0);
135+
expect(internals.sessionId.trim()).toBe(internals.sessionId);
136+
expect(internals.sessionId).not.toBe(" ");
137+
});
108138

109139
test("fails before network when no Cursor credential is configured", () => {
110140
const prev = process.env.OPENCODEX_CURSOR_TEST_TOKEN;

0 commit comments

Comments
 (0)