Skip to content

Commit b980c4d

Browse files
committed
fix(server): honor Cursor long-context selections
1 parent a1d9d72 commit b980c4d

2 files changed

Lines changed: 194 additions & 8 deletions

File tree

‎apps/server/src/provider/cursorSdk.test.ts‎

Lines changed: 158 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -4,17 +4,27 @@ import { describe, expect, it } from "vite-plus/test";
44

55
const cursorSdkUrl = new URL("./cursorSdk.ts", import.meta.url).href;
66

7-
// Loads cursorSdk.ts in a fresh process. @cursor/sdk is stubbed so the guard
8-
// can be tested without the real package. The vitest worker already has its
9-
// own unhandledRejection listener, which would hide the process-exit behavior.
7+
// Loads cursorSdk.ts in a fresh process. The send probe uses the real SDK;
8+
// shell guard probes stub it. The worker's own unhandledRejection listener
9+
// would hide the process-exit behavior.
1010
const probeProgram = `
1111
import { mkdtempSync, writeFileSync } from "node:fs";
1212
import { tmpdir } from "node:os";
1313
import { join } from "node:path";
14-
import { registerHooks } from "node:module";
14+
import { createRequire, registerHooks } from "node:module";
1515
import { pathToFileURL } from "node:url";
1616
import { spawn } from "node:child_process";
1717
18+
const sdkRequire = createRequire(createRequire(${JSON.stringify(cursorSdkUrl)}).resolve("@cursor/sdk"));
19+
const protobufUrl = pathToFileURL(sdkRequire.resolve("@bufbuild/protobuf")).href;
20+
const { proto3, ScalarType } = sdkRequire("@bufbuild/protobuf");
21+
const mode = process.argv[1];
22+
if (mode === "sdk-model-requests") {
23+
process.on("uncaughtException", error => {
24+
console.error(error.stack);
25+
process.exit(1);
26+
});
27+
}
1828
const dir = mkdtempSync(join(tmpdir(), "cursor-sdk-stub-"));
1929
const stub = join(dir, "stub.cjs");
2030
writeFileSync(
@@ -23,17 +33,110 @@ writeFileSync(
2333
);
2434
registerHooks({
2535
resolve(specifier, context, next) {
26-
if (specifier === "@cursor/sdk") {
36+
if (specifier === "@cursor/sdk" && mode !== "sdk-model-requests") {
2737
return { url: pathToFileURL(stub).href, shortCircuit: true };
2838
}
39+
if (specifier === "@bufbuild/protobuf") {
40+
return { url: protobufUrl, shortCircuit: true };
41+
}
2942
return next(specifier, context);
3043
},
3144
});
3245
33-
const { isCursorShellSpawnFailure } = await import(${JSON.stringify(cursorSdkUrl)});
34-
const mode = process.argv[1];
46+
const { isCursorShellSpawnFailure, createAgentPlatform } = await import(${JSON.stringify(cursorSdkUrl)});
3547
const missingCwd = join(tmpdir(), "t3-missing-cwd-" + process.pid);
3648
49+
if (mode === "sdk-model-requests") {
50+
const { JsonlLocalAgentStore } = sdkRequire("@cursor/sdk");
51+
const store = new JsonlLocalAgentStore(join(dir, "store"));
52+
const platform = await createAgentPlatform({ localStore: store, workspaceRef: dir });
53+
// Catalog validation is an external dependency; the SDK's send path and
54+
// generated RequestedModel constructor stay real. Stop before transport.
55+
platform.resolveLocalModelSelection = async selection => selection;
56+
globalThis.fetch = async () => { throw new Error("Unexpected network request"); };
57+
const requests = [];
58+
const initPartial = proto3.util.initPartial;
59+
const captured = new Error("model request captured before transport");
60+
proto3.util.initPartial = function(source, target) {
61+
initPartial.call(this, source, target);
62+
if (target.getType().typeName !== "agent.v1.RequestedModel" || !target.modelId) return;
63+
const decoded = target.getType().fromBinary(target.toBinary());
64+
requests.push({ model: decoded.modelId, maxMode: decoded.maxMode,
65+
context: decoded.parameters.find(parameter => parameter.id === "context")?.value });
66+
throw captured;
67+
};
68+
for (const [id, context] of [
69+
["grok-4.7", "500k"], ["grok-4.7", "256k"],
70+
["claude-opus-5-5", "1m"], ["claude-opus-5-5", "300k"],
71+
]) {
72+
const agent = await platform.createAgent({
73+
apiKey: "t3-offline-test-key", model: { id, params: [{ id: "context", value: context }] },
74+
mode: "plan", tools: [], local: { cwd: dir, store, autoReview: false,
75+
settingSources: [], sandboxOptions: { enabled: false }, enableAgentRetries: false },
76+
});
77+
try {
78+
await agent.send("Reply with exactly: pong");
79+
throw new Error("SDK did not construct a model request");
80+
} catch (error) {
81+
if (error !== captured && error.cause !== captured) throw error;
82+
} finally {
83+
await agent[Symbol.asyncDispose]();
84+
}
85+
}
86+
console.log(JSON.stringify(requests));
87+
process.exit(0);
88+
}
89+
90+
if (mode === "model-requests") {
91+
const Parameter = proto3.makeMessageType("agent.v1.ModelParameter", [
92+
{ no: 1, name: "id", kind: "scalar", T: ScalarType.STRING },
93+
{ no: 2, name: "value", kind: "scalar", T: ScalarType.STRING },
94+
]);
95+
const fields = [
96+
{ no: 1, name: "model_id", kind: "scalar", T: ScalarType.STRING },
97+
{ no: 2, name: "max_mode", kind: "scalar", T: ScalarType.BOOL },
98+
{ no: 3, name: "parameters", kind: "message", T: Parameter, repeated: true },
99+
];
100+
const RequestedModel = proto3.makeMessageType("agent.v1.RequestedModel", fields);
101+
const OtherMessage = proto3.makeMessageType("other.RequestedModel", fields);
102+
const cases = [
103+
{ modelId: "claude-opus-5-5", context: "1m" },
104+
{ modelId: "grok-4.7", context: "500k" },
105+
{ modelId: "gpt-5.6-sol", context: "1M" },
106+
{ modelId: "claude-opus-5-5", context: "0.5m" },
107+
{ modelId: "claude-opus-5-5", context: "300k" },
108+
{ modelId: "grok-4.7", context: "256k" },
109+
{ modelId: "gpt-5.6-sol", context: "272k" },
110+
{ modelId: "claude-sonnet-4-6", context: "200k" },
111+
{ modelId: "claude-opus-5-5", context: "0.3m" },
112+
{ modelId: "default" },
113+
{ modelId: "custom", context: "unknown" },
114+
{ modelId: "claude-opus-5-5", context: "300k", maxMode: true },
115+
];
116+
const requests = cases.map(({ context, ...selection }) => {
117+
const source = {
118+
...selection,
119+
parameters: [
120+
{ id: "reasoning_effort", value: "high" },
121+
...(context === undefined ? [] : [{ id: "context", value: context }]),
122+
{ id: "fast", value: "true" },
123+
],
124+
};
125+
const sourceBefore = JSON.stringify(source);
126+
const request = new RequestedModel(source);
127+
const decoded = RequestedModel.fromBinary(request.toBinary());
128+
return {
129+
maxMode: decoded.maxMode,
130+
modelId: decoded.modelId,
131+
parameters: decoded.parameters.map(({ id, value }) => ({ id, value })),
132+
sourceUnchanged: sourceBefore === JSON.stringify(source),
133+
};
134+
});
135+
const unrelated = new OtherMessage({ parameters: [{ id: "context", value: "1m" }] });
136+
console.log(JSON.stringify({ requests, unrelatedMaxMode: unrelated.maxMode }));
137+
process.exit(0);
138+
}
139+
37140
if (mode === "predicate") {
38141
const cursorShell = Object.assign(new Error("spawn /bin/zsh ENOENT"), {
39142
code: "ENOENT",
@@ -139,7 +242,7 @@ function runProbe(mode: string): Promise<{ code: number | null; stdout: string;
139242
reject(new Error(`probe ${mode} timed out`));
140243
}, 5_000);
141244
child.on("error", reject);
142-
child.on("exit", (code) => {
245+
child.on("close", (code) => {
143246
clearTimeout(timer);
144247
resolve({ code, stdout, stderr });
145248
});
@@ -163,6 +266,53 @@ describe("isCursorShellSpawnFailure", () => {
163266
});
164267
});
165268

269+
describe("Cursor long-context requests", () => {
270+
it("sets Max Mode in real SDK sends for the reported context tiers", async () => {
271+
const result = await runProbe("sdk-model-requests");
272+
expect(result.code, result.stderr.slice(-2_000)).toBe(0);
273+
expect(JSON.parse(result.stdout)).toEqual([
274+
{ model: "grok-4.7", context: "500k", maxMode: true },
275+
{ model: "grok-4.7", context: "256k", maxMode: false },
276+
{ model: "claude-opus-5-5", context: "1m", maxMode: true },
277+
{ model: "claude-opus-5-5", context: "300k", maxMode: false },
278+
]);
279+
});
280+
281+
it("serializes Max Mode for long tiers and preserves standard requests", async () => {
282+
const result = await runProbe("model-requests");
283+
expect(result.code).toBe(0);
284+
const { requests, unrelatedMaxMode } = JSON.parse(result.stdout);
285+
expect(requests.map((request: { maxMode: boolean }) => request.maxMode)).toEqual([
286+
true,
287+
true,
288+
true,
289+
true,
290+
false,
291+
false,
292+
false,
293+
false,
294+
false,
295+
false,
296+
false,
297+
true,
298+
]);
299+
expect(requests[0]).toEqual({
300+
maxMode: true,
301+
modelId: "claude-opus-5-5",
302+
parameters: [
303+
{ id: "reasoning_effort", value: "high" },
304+
{ id: "context", value: "1m" },
305+
{ id: "fast", value: "true" },
306+
],
307+
sourceUnchanged: true,
308+
});
309+
expect(requests.every((request: { sourceUnchanged: boolean }) => request.sourceUnchanged)).toBe(
310+
true,
311+
);
312+
expect(unrelatedMaxMode).toBe(false);
313+
});
314+
});
315+
166316
describe("Cursor shell spawn guard", () => {
167317
it("keeps the process alive when Cursor's shell spawn rejects", async () => {
168318
const result = await runProbe("cursor-shell");

‎apps/server/src/provider/cursorSdk.ts‎

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,42 @@ installCursorShellSpawnGuard();
6767
// Cursor's Webpack chunks and local helpers must stay beside the SDK entry.
6868
// createRequire also loads that disk-backed package from a Node SEA executable.
6969
const requireCursorSdk = NodeModule.createRequire(import.meta.url);
70+
71+
// The SDK omits RequestedModel.maxMode and exposes no way to set it. Cursor's
72+
// current context tiers above 300K require Max Mode, as in its CLI. Patch only
73+
// that message in the SDK's own disk-backed protobuf runtime, before loading
74+
// the SDK. Remove this workaround when ModelSelection supports Max Mode.
75+
// https://github.com/pingdotgg/t3code/issues/15788
76+
const requireCursorSdkDependency = NodeModule.createRequire(
77+
requireCursorSdk.resolve("@cursor/sdk"),
78+
);
79+
const { proto3 } = requireCursorSdkDependency("@bufbuild/protobuf") as {
80+
proto3: {
81+
util: {
82+
initPartial: (
83+
source: unknown,
84+
target: {
85+
getType: () => { typeName: string };
86+
maxMode?: boolean;
87+
parameters?: ReadonlyArray<{ id: string; value: string }>;
88+
},
89+
) => void;
90+
};
91+
};
92+
};
93+
const initPartial = proto3.util.initPartial;
94+
proto3.util.initPartial = function (source, target) {
95+
initPartial.call(this, source, target);
96+
if (target.getType().typeName !== "agent.v1.RequestedModel" || target.maxMode) {
97+
return;
98+
}
99+
const context = target.parameters?.find((parameter) => parameter.id === "context")?.value ?? "";
100+
const tier = /^(\d+(?:\.\d+)?)([km])$/i.exec(context);
101+
if (tier && Number(tier[1]) * (tier[2]?.toLowerCase() === "m" ? 1_000_000 : 1_000) > 300_000) {
102+
target.maxMode = true;
103+
}
104+
};
105+
70106
export const {
71107
Agent,
72108
AuthenticationError,

0 commit comments

Comments
 (0)