Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

cursor-acp-model-mismatch-probe.ts

442 lines11.8 KB

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