Open History to see the last commit
1import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
2import process from "node:process";
3import readline from "node:readline";
4
5type JsonPrimitive = null | boolean | number | string;
6type JsonValue = JsonPrimitive | JsonValue[] | { [key: string]: JsonValue };
7
8type JsonRpcId = number | string;
9
10type JsonRpcMessage = {
11 jsonrpc?: string;
12 id?: JsonRpcId;
13 method?: string;
14 params?: JsonValue;
15 result?: JsonValue;
16 error?: JsonValue;
17 headers?: JsonValue;
18};
19
20type SelectLeafOption = {
21 value: string;
22 label?: string;
23 name?: string;
24};
25
26type SelectGroupOption = {
27 label?: string;
28 name?: string;
29 options: SelectLeafOption[];
30};
31
32type SessionConfigOption = {
33 id: string;
34 name?: string;
35 category?: string;
36 type?: string;
37 options?: Array<SelectLeafOption | SelectGroupOption>;
38};
39
40type SessionNewResult = {
41 sessionId: string;
42 configOptions?: SessionConfigOption[];
43};
44
45type SetConfigResult = {
46 configOptions?: SessionConfigOption[];
47};
48
49type PendingRequest = {
50 method: string;
51 resolve: (value: JsonValue | undefined) => void;
52 reject: (error: Error) => void;
53};
54
55const targetCwd = process.argv[2] ?? process.cwd();
56const targetModel = process.argv[3] ?? "gpt-5.4";
57const promptText = process.argv[4] ?? "helo";
58const targetReasoning = process.env.CURSOR_REASONING ?? "";
59const targetContext = process.env.CURSOR_CONTEXT ?? "";
60const targetFast = process.env.CURSOR_FAST ?? "";
61const agentBin = process.env.CURSOR_AGENT_BIN ?? "agent";
62const promptWaitMs = Number(process.env.CURSOR_PROMPT_WAIT_MS ?? "4000");
63const requestTimeoutMs = Number(process.env.CURSOR_REQUEST_TIMEOUT_MS ?? "20000");
64
65function logSection(title: string, value: unknown) {
66 process.stdout.write(`\n=== ${title} ===\n`);
67 process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
68}
69
70function fail(message: string): never {
71 throw new Error(message);
72}
73
74function asString(value: JsonValue | undefined): string | null {
75 return typeof value === "string" ? value : null;
76}
77
78function flattenSelectValues(option: SessionConfigOption | undefined): string[] {
79 if (!option || option.type !== "select" || !Array.isArray(option.options)) {
80 return [];
81 }
82
83 const values: string[] = [];
84 for (const entry of option.options) {
85 if (!entry || typeof entry !== "object") {
86 continue;
87 }
88 if ("value" in entry && typeof entry.value === "string") {
89 values.push(entry.value);
90 continue;
91 }
92 if ("options" in entry && Array.isArray(entry.options)) {
93 for (const nested of entry.options) {
94 if (nested && typeof nested === "object" && typeof nested.value === "string") {
95 values.push(nested.value);
96 }
97 }
98 }
99 }
100 return values;
101}
102
103function findConfigOption(
104 configOptions: SessionConfigOption[],
105 predicate: (option: SessionConfigOption) => boolean,
106): SessionConfigOption | undefined {
107 return configOptions.find(predicate);
108}
109
110function matchesKeyword(option: SessionConfigOption, keyword: string): boolean {
111 const haystack = `${option.id} ${option.name ?? ""}`.toLowerCase();
112 return haystack.includes(keyword.toLowerCase());
113}
114
115function sleep(ms: number) {
116 return new Promise<void>((resolve) => {
117 setTimeout(resolve, ms);
118 });
119}
120
121class JsonRpcChild {
122 readonly child: ChildProcessWithoutNullStreams;
123 readonly pending = new Map<JsonRpcId, PendingRequest>();
124 nextId = 1;
125 closed = false;
126
127 constructor(bin: string, args: string[], cwd: string) {
128 this.child = spawn(bin, args, {
129 cwd,
130 shell: process.platform === "win32",
131 stdio: ["pipe", "pipe", "pipe"],
132 env: process.env,
133 });
134
135 this.child.on("exit", (code, signal) => {
136 this.closed = true;
137 const detail = `ACP process exited (code=${String(code)}, signal=${String(signal)})`;
138 for (const pending of this.pending.values()) {
139 pending.reject(new Error(`${detail} while waiting for ${pending.method}`));
140 }
141 this.pending.clear();
142 });
143
144 this.child.on("error", (error) => {
145 this.closed = true;
146 for (const pending of this.pending.values()) {
147 pending.reject(error);
148 }
149 this.pending.clear();
150 });
151
152 const stdout = readline.createInterface({ input: this.child.stdout });
153 stdout.on("line", (line) => {
154 void this.handleStdoutLine(line);
155 });
156
157 const stderr = readline.createInterface({ input: this.child.stderr });
158 stderr.on("line", (line) => {
159 process.stdout.write(`[stderr] ${line}\n`);
160 });
161 }
162
163 write(message: JsonRpcMessage) {
164 if (this.closed) {
165 fail("ACP process is already closed.");
166 }
167 const payload = JSON.stringify({
168 jsonrpc: "2.0",
169 headers: [],
170 ...message,
171 });
172 process.stdout.write(`>>> ${payload}\n`);
173 this.child.stdin.write(`${payload}\n`);
174 }
175
176 async request(method: string, params: JsonValue, timeoutMs = requestTimeoutMs) {
177 const id = this.nextId++;
178
179 const responsePromise = new Promise<JsonValue | undefined>((resolve, reject) => {
180 const timeout = setTimeout(() => {
181 this.pending.delete(id);
182 reject(new Error(`Timed out waiting for ${method} response after ${timeoutMs}ms.`));
183 }, timeoutMs);
184
185 this.pending.set(id, {
186 method,
187 resolve: (value) => {
188 clearTimeout(timeout);
189 resolve(value);
190 },
191 reject: (error) => {
192 clearTimeout(timeout);
193 reject(error);
194 },
195 });
196 });
197
198 this.write({
199 id,
200 method,
201 params,
202 });
203
204 return responsePromise;
205 }
206
207 notify(method: string, params: JsonValue) {
208 this.write({
209 method,
210 params,
211 });
212 }
213
214 respond(id: JsonRpcId, result: JsonValue) {
215 this.write({
216 id,
217 result,
218 });
219 }
220
221 respondError(id: JsonRpcId, code: number, message: string) {
222 this.write({
223 id,
224 error: {
225 code,
226 message,
227 },
228 });
229 }
230
231 async handleStdoutLine(line: string) {
232 if (line.trim().length === 0) {
233 return;
234 }
235
236 process.stdout.write(`<<< ${line}\n`);
237
238 let message: JsonRpcMessage;
239 try {
240 message = JSON.parse(line) as JsonRpcMessage;
241 } catch (error) {
242 process.stdout.write(`[parse-error] ${(error as Error).message}\n`);
243 return;
244 }
245
246 if (typeof message.id !== "undefined" && !message.method) {
247 const pending = this.pending.get(message.id);
248 if (!pending) {
249 return;
250 }
251 this.pending.delete(message.id);
252 if (typeof message.error !== "undefined") {
253 pending.reject(
254 new Error(`RPC ${pending.method} failed: ${JSON.stringify(message.error, null, 2)}`),
255 );
256 return;
257 }
258 pending.resolve(message.result);
259 return;
260 }
261
262 if (message.method === "session/request_permission" && typeof message.id !== "undefined") {
263 this.respond(message.id, {
264 outcome: {
265 outcome: "selected",
266 optionId: "allow",
267 },
268 });
269 return;
270 }
271
272 if (typeof message.id !== "undefined" && message.id !== "") {
273 this.respondError(
274 message.id,
275 -32601,
276 `Unhandled server request: ${message.method ?? "unknown"}`,
277 );
278 }
279 }
280
281 async close() {
282 if (this.closed) {
283 return;
284 }
285 this.child.kill("SIGTERM");
286 await sleep(250);
287 if (!this.closed) {
288 this.child.kill("SIGKILL");
289 }
290 }
291}
292
293async function setSelectOptionIfAdvertised(
294 rpc: JsonRpcChild,
295 sessionId: string,
296 configOptions: SessionConfigOption[],
297 predicate: (option: SessionConfigOption) => boolean,
298 value: string,
299 label: string,
300) {
301 if (value.length === 0) {
302 return configOptions;
303 }
304
305 const option = findConfigOption(configOptions, predicate);
306 const values = flattenSelectValues(option);
307 if (!option || !values.includes(value)) {
308 logSection(`SKIP_${label}`, {
309 requestedValue: value,
310 availableValues: values,
311 });
312 return configOptions;
313 }
314
315 const response = (await rpc.request("session/set_config_option", {
316 sessionId,
317 configId: option.id,
318 value,
319 })) as SetConfigResult | null | undefined;
320
321 logSection(`SET_${label}_RESPONSE`, response);
322 return response?.configOptions ?? configOptions;
323}
324
325async function main() {
326 const rpc = new JsonRpcChild(agentBin, ["acp"], targetCwd);
327
328 try {
329 const initializeResponse = await rpc.request("initialize", {
330 protocolVersion: 1,
331 clientCapabilities: {
332 fs: { readTextFile: false, writeTextFile: false },
333 terminal: false,
334 _meta: {
335 parameterizedModelPicker: true,
336 },
337 },
338 clientInfo: {
339 name: "cursor-acp-model-mismatch-probe",
340 version: "0.0.0",
341 },
342 });
343 logSection("INITIALIZE_RESPONSE", initializeResponse);
344
345 const authenticateResponse = await rpc.request("authenticate", {
346 methodId: "cursor_login",
347 });
348 logSection("AUTHENTICATE_RESPONSE", authenticateResponse);
349
350 const sessionResponse = (await rpc.request("session/new", {
351 cwd: targetCwd,
352 mcpServers: [],
353 })) as SessionNewResult;
354 logSection("SESSION_NEW_RESPONSE", sessionResponse);
355
356 const sessionId = asString(sessionResponse.sessionId);
357 if (!sessionId) {
358 fail("session/new did not return a sessionId.");
359 }
360
361 let configOptions = sessionResponse.configOptions ?? [];
362 const modelConfig = findConfigOption(configOptions, (option) => option.category === "model");
363 const advertisedModels = flattenSelectValues(modelConfig);
364 logSection("ADVERTISED_MODEL_VALUES", advertisedModels);
365
366 if (!modelConfig || modelConfig.type !== "select") {
367 fail("Cursor ACP did not expose a select-type model config option.");
368 }
369
370 if (!advertisedModels.includes(targetModel)) {
371 fail(
372 `Cursor ACP did not advertise model ${JSON.stringify(targetModel)}. Advertised values: ${advertisedModels.join(", ")}`,
373 );
374 }
375
376 const setModelResponse = (await rpc.request("session/set_config_option", {
377 sessionId,
378 configId: modelConfig.id,
379 value: targetModel,
380 })) as SetConfigResult | null | undefined;
381 logSection("SET_MODEL_RESPONSE", setModelResponse);
382
383 configOptions = setModelResponse?.configOptions ?? configOptions;
384
385 configOptions = await setSelectOptionIfAdvertised(
386 rpc,
387 sessionId,
388 configOptions,
389 (option) => option.category === "thought_level",
390 targetReasoning,
391 "REASONING",
392 );
393
394 configOptions = await setSelectOptionIfAdvertised(
395 rpc,
396 sessionId,
397 configOptions,
398 (option) => option.category === "model_config" && matchesKeyword(option, "context"),
399 targetContext,
400 "CONTEXT",
401 );
402
403 configOptions = await setSelectOptionIfAdvertised(
404 rpc,
405 sessionId,
406 configOptions,
407 (option) => option.category === "model_config" && matchesKeyword(option, "fast"),
408 targetFast,
409 "FAST",
410 );
411
412 const promptResponse = await rpc.request("session/prompt", {
413 sessionId,
414 prompt: [
415 {
416 type: "text",
417 text: promptText,
418 },
419 ],
420 });
421 logSection("PROMPT_RESPONSE", promptResponse);
422
423 await sleep(promptWaitMs);
424 rpc.notify("session/cancel", { sessionId });
425 } finally {
426 await rpc.close();
427 }
428}
429
430void main().catch((error: unknown) => {
431 process.stderr.write(
432 `${error instanceof Error ? (error.stack ?? error.message) : String(error)}\n`,
433 );
434 process.exitCode = 1;
435});