From 9daf9430bb76f175e34a9aa05c6060b4a959312e Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Wed, 11 Feb 2026 17:59:44 +0700 Subject: [PATCH 1/8] feat(cursor): add core protobuf encoder/decoder and executor MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Split protobuf into 3 files: schema, encoder, decoder for <200 LOC constraint - Implement ConnectRPC wire format encoding (varint, fields, messages, frames) - Implement protobuf decoder with gzip decompression support - Port Cursor executor with HTTP/2 support and checksum generation (Jyh cipher) - Add OpenAI to Cursor message translator (system→user, tool results handling) - Transform protobuf responses to both SSE and JSON formats - Use Node.js built-in crypto/zlib (no uuid dependency) - All files TypeScript strict mode compliant --- src/cursor/cursor-executor.ts | 786 ++++++++++++++++++++++++++ src/cursor/cursor-protobuf-decoder.ts | 301 ++++++++++ src/cursor/cursor-protobuf-encoder.ts | 262 +++++++++ src/cursor/cursor-protobuf-schema.ts | 205 +++++++ src/cursor/cursor-protobuf.ts | 212 +++++++ src/cursor/cursor-translator.ts | 145 +++++ 6 files changed, 1911 insertions(+) create mode 100644 src/cursor/cursor-executor.ts create mode 100644 src/cursor/cursor-protobuf-decoder.ts create mode 100644 src/cursor/cursor-protobuf-encoder.ts create mode 100644 src/cursor/cursor-protobuf-schema.ts create mode 100644 src/cursor/cursor-protobuf.ts create mode 100644 src/cursor/cursor-translator.ts diff --git a/src/cursor/cursor-executor.ts b/src/cursor/cursor-executor.ts new file mode 100644 index 00000000..28ce9f55 --- /dev/null +++ b/src/cursor/cursor-executor.ts @@ -0,0 +1,786 @@ +/** + * Cursor Executor + * Handles HTTP/2 requests to Cursor API with protobuf encoding/decoding + */ + +import * as crypto from "crypto"; +import * as zlib from "zlib"; +import type { IncomingHttpHeaders } from "http"; +import { generateCursorBody, extractTextFromResponse } from "./cursor-protobuf.js"; +import { buildCursorRequest } from "./cursor-translator.js"; +import type { CursorMessage, CursorTool } from "./cursor-protobuf-schema.js"; + +/** Compression flags for response parsing */ +const COMPRESS_FLAG = { + NONE: 0x00, + GZIP: 0x01, + GZIP_ALT: 0x02, + GZIP_BOTH: 0x03, +} as const; + +/** Cursor credentials structure */ +interface CursorCredentials { + accessToken: string; + providerSpecificData?: { + machineId?: string; + ghostMode?: boolean; + }; +} + +/** Executor parameters */ +interface ExecutorParams { + model: string; + body: { + messages: Array<{ + role: string; + content: string | Array<{ type: string; text?: string }>; + name?: string; + tool_call_id?: string; + tool_calls?: Array<{ + id: string; + type: string; + function: { name: string; arguments: string }; + }>; + }>; + tools?: CursorTool[]; + reasoning_effort?: string; + }; + stream: boolean; + credentials: CursorCredentials; + signal?: AbortSignal; +} + +/** HTTP/2 response structure */ +interface Http2Response { + status: number; + headers: IncomingHttpHeaders; + body: Buffer; +} + +/** Detect cloud environment */ +function isCloudEnv(): boolean { + if (typeof caches !== "undefined" && typeof caches === "object") return true; + try { + // Check for EdgeRuntime without causing compilation error + if (typeof (globalThis as { EdgeRuntime?: string }).EdgeRuntime !== "undefined") return true; + } catch { + // Continue + } + return false; +} + +/** Lazy import http2 */ +let http2Module: typeof import("http2") | null = null; +async function getHttp2() { + if (http2Module) return http2Module; + if (!isCloudEnv()) { + try { + http2Module = await import("http2"); + return http2Module; + } catch { + return null; + } + } + return null; +} + +/** + * Decompress payload if needed + */ +function decompressPayload(payload: Buffer, flags: number): Buffer { + // Check if payload is JSON error + if (payload.length > 10 && payload[0] === 0x7b && payload[1] === 0x22) { + try { + const text = payload.toString("utf-8"); + if (text.startsWith('{"error"')) { + return payload; + } + } catch { + // Continue + } + } + + if ( + flags === COMPRESS_FLAG.GZIP || + flags === COMPRESS_FLAG.GZIP_ALT || + flags === COMPRESS_FLAG.GZIP_BOTH + ) { + try { + return zlib.gunzipSync(payload); + } catch { + return payload; + } + } + return payload; +} + +/** + * Create error response from JSON error + */ +function createErrorResponse(jsonError: { + error?: { + code?: string; + message?: string; + details?: Array<{ debug?: { details?: { title?: string; detail?: string }; error?: string } }>; + }; +}): Response { + const errorMsg = + jsonError?.error?.details?.[0]?.debug?.details?.title || + jsonError?.error?.details?.[0]?.debug?.details?.detail || + jsonError?.error?.message || + "API Error"; + + const isRateLimit = jsonError?.error?.code === "resource_exhausted"; + + return new Response( + JSON.stringify({ + error: { + message: errorMsg, + type: isRateLimit ? "rate_limit_error" : "api_error", + code: jsonError?.error?.details?.[0]?.debug?.error || "unknown", + }, + }), + { + status: isRateLimit ? 429 : 400, + headers: { "Content-Type": "application/json" }, + } + ); +} + +export class CursorExecutor { + private readonly baseUrl = "https://api2.cursor.sh"; + private readonly chatPath = "/aiserver.v1.AiService/StreamChat"; + + buildUrl(): string { + return `${this.baseUrl}${this.chatPath}`; + } + + /** + * Generate checksum using Jyh cipher (time-based XOR with rolling key seed=165) + */ + generateChecksum(machineId: string): string { + const timestamp = Math.floor(Date.now() / 1000000); + const byteArray = new Uint8Array([ + (timestamp >> 40) & 0xff, + (timestamp >> 32) & 0xff, + (timestamp >> 24) & 0xff, + (timestamp >> 16) & 0xff, + (timestamp >> 8) & 0xff, + timestamp & 0xff, + ]); + + let t = 165; + for (let i = 0; i < byteArray.length; i++) { + byteArray[i] = ((byteArray[i] ^ t) + (i % 256)) & 0xff; + t = byteArray[i]; + } + + const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; + let encoded = ""; + + for (let i = 0; i < byteArray.length; i += 3) { + const a = byteArray[i]; + const b = i + 1 < byteArray.length ? byteArray[i + 1] : 0; + const c = i + 2 < byteArray.length ? byteArray[i + 2] : 0; + + encoded += alphabet[a >> 2]; + encoded += alphabet[((a & 3) << 4) | (b >> 4)]; + + if (i + 1 < byteArray.length) { + encoded += alphabet[((b & 15) << 2) | (c >> 6)]; + } + if (i + 2 < byteArray.length) { + encoded += alphabet[c & 63]; + } + } + + return `${encoded}${machineId}`; + } + + buildHeaders(credentials: CursorCredentials): Record { + const accessToken = credentials.accessToken; + const machineId = credentials.providerSpecificData?.machineId; + const ghostMode = credentials.providerSpecificData?.ghostMode !== false; + + if (!machineId) { + throw new Error("Machine ID is required for Cursor API"); + } + + const cleanToken = accessToken.includes("::") + ? accessToken.split("::")[1] + : accessToken; + + return { + authorization: `Bearer ${cleanToken}`, + "connect-accept-encoding": "gzip", + "connect-protocol-version": "1", + "content-type": "application/connect+proto", + "user-agent": "connect-es/1.6.1", + "x-amzn-trace-id": `Root=${crypto.randomUUID()}`, + "x-client-key": crypto.createHash("sha256").update(cleanToken).digest("hex"), + "x-cursor-checksum": this.generateChecksum(machineId), + "x-cursor-client-version": "2.3.41", + "x-cursor-client-type": "ide", + "x-cursor-client-os": + process.platform === "win32" + ? "windows" + : process.platform === "darwin" + ? "macos" + : "linux", + "x-cursor-client-arch": process.arch === "arm64" ? "aarch64" : "x64", + "x-cursor-client-device-type": "desktop", + "x-cursor-config-version": crypto.randomUUID(), + "x-cursor-timezone": + Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC", + "x-ghost-mode": ghostMode ? "true" : "false", + "x-request-id": crypto.randomUUID(), + "x-session-id": crypto + .createHash("sha256") + .update(cleanToken) + .digest("hex") + .substring(0, 36), + }; + } + + transformRequest( + model: string, + body: ExecutorParams["body"], + stream: boolean, + credentials: CursorCredentials + ): Uint8Array { + const translatedBody = buildCursorRequest(model, body, stream, credentials); + const messages = translatedBody.messages || []; + const tools = (translatedBody.tools || body.tools || []) as CursorTool[]; + const reasoningEffort = body.reasoning_effort || null; + return generateCursorBody(messages, model, tools, reasoningEffort); + } + + async makeFetchRequest( + url: string, + headers: Record, + body: Uint8Array, + signal?: AbortSignal + ): Promise { + const response = await fetch(url, { + method: "POST", + headers, + body, + signal, + }); + + const responseHeaders: Record = {}; + response.headers.forEach((value, key) => { + responseHeaders[key] = value; + }); + + return { + status: response.status, + headers: responseHeaders, + body: Buffer.from(await response.arrayBuffer()), + }; + } + + async makeHttp2Request( + url: string, + headers: Record, + body: Uint8Array, + signal?: AbortSignal + ): Promise { + const http2 = await getHttp2(); + if (!http2) { + throw new Error("http2 module not available"); + } + + return new Promise((resolve, reject) => { + const urlObj = new URL(url); + const client = http2.connect(`https://${urlObj.host}`); + const chunks: Buffer[] = []; + let responseHeaders: IncomingHttpHeaders = {}; + + client.on("error", reject); + + const req = client.request({ + ":method": "POST", + ":path": urlObj.pathname, + ":authority": urlObj.host, + ":scheme": "https", + ...headers, + }); + + req.on("response", (hdrs) => { + responseHeaders = hdrs; + }); + req.on("data", (chunk: Buffer) => { + chunks.push(chunk); + }); + req.on("end", () => { + client.close(); + resolve({ + status: Number(responseHeaders[":status"]), + headers: responseHeaders, + body: Buffer.concat(chunks), + }); + }); + req.on("error", (err) => { + client.close(); + reject(err); + }); + + if (signal) { + signal.addEventListener("abort", () => { + req.close(); + client.close(); + reject(new Error("Request aborted")); + }); + } + + req.write(body); + req.end(); + }); + } + + async execute(params: ExecutorParams): Promise<{ + response: Response; + url: string; + headers: Record; + transformedBody: ExecutorParams["body"]; + }> { + const { model, body, stream, credentials, signal } = params; + const url = this.buildUrl(); + const headers = this.buildHeaders(credentials); + const transformedBody = this.transformRequest(model, body, stream, credentials); + + try { + const http2 = await getHttp2(); + const response = http2 + ? await this.makeHttp2Request(url, headers, transformedBody, signal) + : await this.makeFetchRequest(url, headers, transformedBody, signal); + + if (response.status !== 200) { + const errorText = response.body?.toString() || "Unknown error"; + const errorResponse = new Response( + JSON.stringify({ + error: { + message: `[${response.status}]: ${errorText}`, + type: "invalid_request_error", + code: "", + }, + }), + { + status: response.status, + headers: { "Content-Type": "application/json" }, + } + ); + return { response: errorResponse, url, headers, transformedBody: body }; + } + + const transformedResponse = + stream !== false + ? this.transformProtobufToSSE(response.body, model, body) + : this.transformProtobufToJSON(response.body, model, body); + + return { response: transformedResponse, url, headers, transformedBody: body }; + } catch (error) { + const errorResponse = new Response( + JSON.stringify({ + error: { + message: (error as Error).message, + type: "connection_error", + code: "", + }, + }), + { + status: 500, + headers: { "Content-Type": "application/json" }, + } + ); + return { response: errorResponse, url, headers, transformedBody: body }; + } + } + + transformProtobufToJSON( + buffer: Buffer, + model: string, + body: ExecutorParams["body"] + ): Response { + const responseId = `chatcmpl-cursor-${Date.now()}`; + const created = Math.floor(Date.now() / 1000); + + let offset = 0; + let totalContent = ""; + const toolCalls: Array<{ + id: string; + type: string; + function: { name: string; arguments: string }; + }> = []; + const toolCallsMap = new Map< + string, + { + id: string; + type: string; + function: { name: string; arguments: string }; + isLast: boolean; + index: number; + } + >(); + + while (offset < buffer.length) { + if (offset + 5 > buffer.length) break; + + const flags = buffer[offset]; + const length = buffer.readUInt32BE(offset + 1); + + if (offset + 5 + length > buffer.length) break; + + let payload = buffer.slice(offset + 5, offset + 5 + length); + offset += 5 + length; + + payload = decompressPayload(payload, flags); + + try { + const text = payload.toString("utf-8"); + if (text.startsWith("{") && text.includes('"error"')) { + return createErrorResponse(JSON.parse(text)); + } + } catch { + // Continue + } + + const result = extractTextFromResponse(new Uint8Array(payload)); + + if (result.error) { + return new Response( + JSON.stringify({ + error: { + message: result.error, + type: "rate_limit_error", + code: "rate_limited", + }, + }), + { + status: 429, + headers: { "Content-Type": "application/json" }, + } + ); + } + + if (result.toolCall) { + const tc = result.toolCall; + + if (toolCallsMap.has(tc.id)) { + const existing = toolCallsMap.get(tc.id)!; + existing.function.arguments += tc.function.arguments; + existing.isLast = tc.isLast; + } else { + toolCallsMap.set(tc.id, { + ...tc, + index: toolCallsMap.size, + }); + } + + if (tc.isLast) { + const finalToolCall = toolCallsMap.get(tc.id)!; + toolCalls.push({ + id: finalToolCall.id, + type: finalToolCall.type, + function: { + name: finalToolCall.function.name, + arguments: finalToolCall.function.arguments, + }, + }); + } + } + + if (result.text) totalContent += result.text; + } + + // Finalize remaining tool calls + for (const id of Array.from(toolCallsMap.keys())) { + const tc = toolCallsMap.get(id)!; + if (!toolCalls.find((t) => t.id === id)) { + toolCalls.push({ + id: tc.id, + type: tc.type, + function: { + name: tc.function.name, + arguments: tc.function.arguments, + }, + }); + } + } + + const message: { + role: string; + content: string | null; + tool_calls?: Array<{ + id: string; + type: string; + function: { name: string; arguments: string }; + }>; + } = { + role: "assistant", + content: totalContent || null, + }; + + if (toolCalls.length > 0) { + message.tool_calls = toolCalls; + } + + const completion = { + id: responseId, + object: "chat.completion", + created, + model, + choices: [ + { + index: 0, + message, + finish_reason: toolCalls.length > 0 ? "tool_calls" : "stop", + }, + ], + usage: { + prompt_tokens: 0, + completion_tokens: 0, + total_tokens: 0, + }, + }; + + return new Response(JSON.stringify(completion), { + status: 200, + headers: { "Content-Type": "application/json" }, + }); + } + + transformProtobufToSSE( + buffer: Buffer, + model: string, + body: ExecutorParams["body"] + ): Response { + const responseId = `chatcmpl-cursor-${Date.now()}`; + const created = Math.floor(Date.now() / 1000); + + const chunks: string[] = []; + let offset = 0; + let totalContent = ""; + const toolCalls: Array<{ + id: string; + type: string; + function: { name: string; arguments: string }; + index: number; + }> = []; + const toolCallsMap = new Map< + string, + { + id: string; + type: string; + function: { name: string; arguments: string }; + isLast: boolean; + index: number; + } + >(); + + while (offset < buffer.length) { + if (offset + 5 > buffer.length) break; + + const flags = buffer[offset]; + const length = buffer.readUInt32BE(offset + 1); + + if (offset + 5 + length > buffer.length) break; + + let payload = buffer.slice(offset + 5, offset + 5 + length); + offset += 5 + length; + + payload = decompressPayload(payload, flags); + + try { + const text = payload.toString("utf-8"); + if (text.startsWith("{") && text.includes('"error"')) { + return createErrorResponse(JSON.parse(text)); + } + } catch { + // Continue + } + + const result = extractTextFromResponse(new Uint8Array(payload)); + + if (result.error) { + return new Response( + JSON.stringify({ + error: { + message: result.error, + type: "rate_limit_error", + code: "rate_limited", + }, + }), + { + status: 429, + headers: { "Content-Type": "application/json" }, + } + ); + } + + if (result.toolCall) { + const tc = result.toolCall; + + if (chunks.length === 0) { + chunks.push( + `data: ${JSON.stringify({ + id: responseId, + object: "chat.completion.chunk", + created, + model, + choices: [ + { + index: 0, + delta: { role: "assistant", content: "" }, + finish_reason: null, + }, + ], + })}\n\n` + ); + } + + if (toolCallsMap.has(tc.id)) { + const existing = toolCallsMap.get(tc.id)!; + existing.function.arguments += tc.function.arguments; + existing.isLast = tc.isLast; + + if (tc.function.arguments) { + chunks.push( + `data: ${JSON.stringify({ + id: responseId, + object: "chat.completion.chunk", + created, + model, + choices: [ + { + index: 0, + delta: { + tool_calls: [ + { + index: existing.index, + id: tc.id, + type: "function", + function: { + name: tc.function.name, + arguments: tc.function.arguments, + }, + }, + ], + }, + finish_reason: null, + }, + ], + })}\n\n` + ); + } + } else { + const toolCallIndex = toolCalls.length; + toolCalls.push({ ...tc, index: toolCallIndex }); + toolCallsMap.set(tc.id, { ...tc, index: toolCallIndex }); + + chunks.push( + `data: ${JSON.stringify({ + id: responseId, + object: "chat.completion.chunk", + created, + model, + choices: [ + { + index: 0, + delta: { + tool_calls: [ + { + index: toolCallIndex, + id: tc.id, + type: "function", + function: { + name: tc.function.name, + arguments: tc.function.arguments, + }, + }, + ], + }, + finish_reason: null, + }, + ], + })}\n\n` + ); + } + } + + if (result.text) { + totalContent += result.text; + chunks.push( + `data: ${JSON.stringify({ + id: responseId, + object: "chat.completion.chunk", + created, + model, + choices: [ + { + index: 0, + delta: + chunks.length === 0 && toolCalls.length === 0 + ? { role: "assistant", content: result.text } + : { content: result.text }, + finish_reason: null, + }, + ], + })}\n\n` + ); + } + } + + if (chunks.length === 0 && toolCalls.length === 0) { + chunks.push( + `data: ${JSON.stringify({ + id: responseId, + object: "chat.completion.chunk", + created, + model, + choices: [ + { + index: 0, + delta: { role: "assistant", content: "" }, + finish_reason: null, + }, + ], + })}\n\n` + ); + } + + chunks.push( + `data: ${JSON.stringify({ + id: responseId, + object: "chat.completion.chunk", + created, + model, + choices: [ + { + index: 0, + delta: {}, + finish_reason: toolCalls.length > 0 ? "tool_calls" : "stop", + }, + ], + usage: { + prompt_tokens: 0, + completion_tokens: 0, + total_tokens: 0, + }, + })}\n\n` + ); + chunks.push("data: [DONE]\n\n"); + + return new Response(chunks.join(""), { + status: 200, + headers: { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + Connection: "keep-alive", + }, + }); + } +} + +export default CursorExecutor; diff --git a/src/cursor/cursor-protobuf-decoder.ts b/src/cursor/cursor-protobuf-decoder.ts new file mode 100644 index 00000000..7b3e0d6a --- /dev/null +++ b/src/cursor/cursor-protobuf-decoder.ts @@ -0,0 +1,301 @@ +/** + * Cursor Protobuf Decoder + * Implements ConnectRPC protobuf wire format decoding + */ + +import * as zlib from "zlib"; +import { + WIRE_TYPE, + FIELD, + type WireType, +} from "./cursor-protobuf-schema.js"; + +/** + * Decode a varint from buffer + * Returns [value, newOffset] + */ +export function decodeVarint( + buffer: Uint8Array, + offset: number +): [number, number] { + let result = 0; + let shift = 0; + let pos = offset; + + while (pos < buffer.length) { + const b = buffer[pos]; + result |= (b & 0x7f) << shift; + pos++; + if (!(b & 0x80)) break; + shift += 7; + } + + return [result, pos]; +} + +/** + * Decode a single protobuf field + * Returns [fieldNum, wireType, value, newOffset] + */ +export function decodeField( + buffer: Uint8Array, + offset: number +): [number | null, WireType | null, Uint8Array | number | null, number] { + if (offset >= buffer.length) { + return [null, null, null, offset]; + } + + const [tag, pos1] = decodeVarint(buffer, offset); + const fieldNum = tag >> 3; + const wireType = (tag & 0x07) as WireType; + + let value: Uint8Array | number | null; + let pos = pos1; + + if (wireType === WIRE_TYPE.VARINT) { + [value, pos] = decodeVarint(buffer, pos); + } else if (wireType === WIRE_TYPE.LEN) { + const [length, pos2] = decodeVarint(buffer, pos); + value = buffer.slice(pos2, pos2 + length); + pos = pos2 + length; + } else if (wireType === WIRE_TYPE.FIXED64) { + value = buffer.slice(pos, pos + 8); + pos += 8; + } else if (wireType === WIRE_TYPE.FIXED32) { + value = buffer.slice(pos, pos + 4); + pos += 4; + } else { + value = null; + } + + return [fieldNum, wireType, value, pos]; +} + +/** + * Decode a protobuf message into a map of fields + */ +export function decodeMessage( + data: Uint8Array +): Map> { + const fields = new Map< + number, + Array<{ wireType: WireType; value: Uint8Array | number }> + >(); + let pos = 0; + + while (pos < data.length) { + const [fieldNum, wireType, value, newPos] = decodeField(data, pos); + if (fieldNum === null || wireType === null || value === null) break; + + if (!fields.has(fieldNum)) { + fields.set(fieldNum, []); + } + fields.get(fieldNum)!.push({ wireType, value: value as Uint8Array | number }); + pos = newPos; + } + + return fields; +} + +/** + * Parse ConnectRPC frame from buffer + * Returns frame data or null if incomplete + */ +export function parseConnectRPCFrame(buffer: Buffer): { + flags: number; + length: number; + payload: Uint8Array; + consumed: number; +} | null { + if (buffer.length < 5) return null; + + const flags = buffer[0]; + const length = + (buffer[1] << 24) | (buffer[2] << 16) | (buffer[3] << 8) | buffer[4]; + + if (buffer.length < 5 + length) return null; + + let payload = buffer.slice(5, 5 + length); + + // Decompress if gzip + if (flags === 0x01 || flags === 0x02 || flags === 0x03) { + try { + payload = Buffer.from(zlib.gunzipSync(payload)); + } catch { + // Decompression failed, use raw payload + } + } + + return { + flags, + length, + payload: new Uint8Array(payload), + consumed: 5 + length, + }; +} + +/** + * Extract tool call from protobuf data + */ +function extractToolCall(toolCallData: Uint8Array): { + id: string; + type: string; + function: { name: string; arguments: string }; + isLast: boolean; +} | null { + const toolCall = decodeMessage(toolCallData); + let toolCallId = ""; + let toolName = ""; + let rawArgs = ""; + let isLast = false; + + // Extract tool call ID + if (toolCall.has(FIELD.TOOL_ID)) { + const fullId = new TextDecoder().decode( + toolCall.get(FIELD.TOOL_ID)![0].value as Uint8Array + ); + toolCallId = fullId.split("\n")[0]; // Take first line + } + + // Extract tool name + if (toolCall.has(FIELD.TOOL_NAME)) { + toolName = new TextDecoder().decode( + toolCall.get(FIELD.TOOL_NAME)![0].value as Uint8Array + ); + } + + // Extract is_last flag + if (toolCall.has(FIELD.TOOL_IS_LAST)) { + isLast = (toolCall.get(FIELD.TOOL_IS_LAST)![0].value as number) !== 0; + } + + // Extract MCP params - nested real tool info + if (toolCall.has(FIELD.TOOL_MCP_PARAMS)) { + try { + const mcpParams = decodeMessage( + toolCall.get(FIELD.TOOL_MCP_PARAMS)![0].value as Uint8Array + ); + + if (mcpParams.has(FIELD.MCP_TOOLS_LIST)) { + const tool = decodeMessage( + mcpParams.get(FIELD.MCP_TOOLS_LIST)![0].value as Uint8Array + ); + + if (tool.has(FIELD.MCP_NESTED_NAME)) { + toolName = new TextDecoder().decode( + tool.get(FIELD.MCP_NESTED_NAME)![0].value as Uint8Array + ); + } + + if (tool.has(FIELD.MCP_NESTED_PARAMS)) { + rawArgs = new TextDecoder().decode( + tool.get(FIELD.MCP_NESTED_PARAMS)![0].value as Uint8Array + ); + } + } + } catch { + // MCP parse error, continue + } + } + + // Fallback to raw_args + if (!rawArgs && toolCall.has(FIELD.TOOL_RAW_ARGS)) { + rawArgs = new TextDecoder().decode( + toolCall.get(FIELD.TOOL_RAW_ARGS)![0].value as Uint8Array + ); + } + + if (toolCallId && toolName) { + return { + id: toolCallId, + type: "function", + function: { + name: toolName, + arguments: rawArgs || "{}", + }, + isLast, + }; + } + + return null; +} + +/** + * Extract text and thinking from response data + */ +function extractTextAndThinking( + responseData: Uint8Array +): { text: string | null; thinking: string | null } { + const nested = decodeMessage(responseData); + let text: string | null = null; + let thinking: string | null = null; + + // Extract text + if (nested.has(FIELD.RESPONSE_TEXT)) { + text = new TextDecoder().decode( + nested.get(FIELD.RESPONSE_TEXT)![0].value as Uint8Array + ); + } + + // Extract thinking + if (nested.has(FIELD.THINKING)) { + try { + const thinkingMsg = decodeMessage( + nested.get(FIELD.THINKING)![0].value as Uint8Array + ); + if (thinkingMsg.has(FIELD.THINKING_TEXT)) { + thinking = new TextDecoder().decode( + thinkingMsg.get(FIELD.THINKING_TEXT)![0].value as Uint8Array + ); + } + } catch { + // Thinking parse error, continue + } + } + + return { text, thinking }; +} + +/** + * Extract text and tool calls from response payload + */ +export function extractTextFromResponse(payload: Uint8Array): { + text: string | null; + error: string | null; + toolCall: { + id: string; + type: string; + function: { name: string; arguments: string }; + isLast: boolean; + } | null; + thinking: string | null; +} { + try { + const fields = decodeMessage(payload); + + // Field 1: ClientSideToolV2Call + if (fields.has(FIELD.TOOL_CALL)) { + const toolCall = extractToolCall( + fields.get(FIELD.TOOL_CALL)![0].value as Uint8Array + ); + if (toolCall) { + return { text: null, error: null, toolCall, thinking: null }; + } + } + + // Field 2: StreamUnifiedChatResponse + if (fields.has(FIELD.RESPONSE)) { + const { text, thinking } = extractTextAndThinking( + fields.get(FIELD.RESPONSE)![0].value as Uint8Array + ); + + if (text || thinking) { + return { text, error: null, toolCall: null, thinking }; + } + } + + return { text: null, error: null, toolCall: null, thinking: null }; + } catch { + return { text: null, error: null, toolCall: null, thinking: null }; + } +} diff --git a/src/cursor/cursor-protobuf-encoder.ts b/src/cursor/cursor-protobuf-encoder.ts new file mode 100644 index 00000000..6958d219 --- /dev/null +++ b/src/cursor/cursor-protobuf-encoder.ts @@ -0,0 +1,262 @@ +/** + * Cursor Protobuf Encoder + * Implements ConnectRPC protobuf wire format encoding + */ + +import { randomUUID } from "crypto"; +import * as zlib from "zlib"; +import { + WIRE_TYPE, + ROLE, + UNIFIED_MODE, + THINKING_LEVEL, + FIELD, + COMPRESS_FLAG, + type WireType, + type RoleType, + type ThinkingLevelType, + type CursorTool, + type CursorToolResult, + type CursorMessage, + type FormattedMessage, + type MessageId, +} from "./cursor-protobuf-schema.js"; + +/** + * Encode a varint (variable-length integer) + */ +export function encodeVarint(value: number): Uint8Array { + const bytes: number[] = []; + let val = value >>> 0; // Ensure unsigned + while (val >= 0x80) { + bytes.push((val & 0x7f) | 0x80); + val >>>= 7; + } + bytes.push(val & 0x7f); + return new Uint8Array(bytes); +} + +/** + * Encode a protobuf field (tag + value) + */ +export function encodeField( + fieldNum: number, + wireType: WireType, + value: number | string | Uint8Array +): Uint8Array { + const tag = (fieldNum << 3) | wireType; + const tagBytes = encodeVarint(tag); + + if (wireType === WIRE_TYPE.VARINT) { + const valueBytes = encodeVarint(value as number); + return concatArrays(tagBytes, valueBytes); + } + + if (wireType === WIRE_TYPE.LEN) { + const dataBytes = + typeof value === "string" + ? new TextEncoder().encode(value) + : value instanceof Uint8Array + ? value + : new Uint8Array(0); + + const lengthBytes = encodeVarint(dataBytes.length); + return concatArrays(tagBytes, lengthBytes, dataBytes); + } + + return new Uint8Array(0); +} + +/** + * Concatenate multiple Uint8Arrays + */ +function concatArrays(...arrays: Uint8Array[]): Uint8Array { + const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0); + const result = new Uint8Array(totalLength); + let offset = 0; + for (const arr of arrays) { + result.set(arr, offset); + offset += arr.length; + } + return result; +} + +/** + * Encode a tool result + */ +export function encodeToolResult(toolResult: CursorToolResult): Uint8Array { + const toolCallId = toolResult.tool_call_id || ""; + const toolName = toolResult.name || ""; + const toolIndex = toolResult.index || 0; + const rawArgs = toolResult.raw_args || "{}"; + + return concatArrays( + encodeField(FIELD.TOOL_RESULT_CALL_ID, WIRE_TYPE.LEN, toolCallId), + encodeField(FIELD.TOOL_RESULT_NAME, WIRE_TYPE.LEN, toolName), + encodeField(FIELD.TOOL_RESULT_INDEX, WIRE_TYPE.VARINT, toolIndex), + encodeField(FIELD.TOOL_RESULT_RAW_ARGS, WIRE_TYPE.LEN, rawArgs) + ); +} + +/** + * Encode a conversation message + */ +export function encodeMessage( + content: string, + role: RoleType, + messageId: string, + isLast: boolean, + hasTools: boolean, + toolResults: CursorToolResult[] +): Uint8Array { + return concatArrays( + encodeField(FIELD.MSG_CONTENT, WIRE_TYPE.LEN, content), + encodeField(FIELD.MSG_ROLE, WIRE_TYPE.VARINT, role), + encodeField(FIELD.MSG_ID, WIRE_TYPE.LEN, messageId), + ...(toolResults.length > 0 + ? toolResults.map((tr) => + encodeField( + FIELD.MSG_TOOL_RESULTS, + WIRE_TYPE.LEN, + encodeToolResult(tr) + ) + ) + : []), + encodeField(FIELD.MSG_IS_AGENTIC, WIRE_TYPE.VARINT, hasTools ? 1 : 0), + encodeField( + FIELD.MSG_UNIFIED_MODE, + WIRE_TYPE.VARINT, + hasTools ? UNIFIED_MODE.AGENT : UNIFIED_MODE.CHAT + ), + ...(isLast && hasTools + ? [ + encodeField( + FIELD.MSG_SUPPORTED_TOOLS, + WIRE_TYPE.LEN, + encodeVarint(1) + ), + ] + : []) + ); +} + +/** + * Encode instruction text + */ +export function encodeInstruction(text: string): Uint8Array { + return text + ? encodeField(FIELD.INSTRUCTION_TEXT, WIRE_TYPE.LEN, text) + : new Uint8Array(0); +} + +/** + * Encode model information + */ +export function encodeModel(modelName: string): Uint8Array { + return concatArrays( + encodeField(FIELD.MODEL_NAME, WIRE_TYPE.LEN, modelName), + encodeField(FIELD.MODEL_EMPTY, WIRE_TYPE.LEN, new Uint8Array(0)) + ); +} + +/** + * Encode cursor settings + */ +export function encodeCursorSetting(): Uint8Array { + const unknown6 = concatArrays( + encodeField(FIELD.SETTING6_FIELD_1, WIRE_TYPE.LEN, new Uint8Array(0)), + encodeField(FIELD.SETTING6_FIELD_2, WIRE_TYPE.LEN, new Uint8Array(0)) + ); + + return concatArrays( + encodeField(FIELD.SETTING_PATH, WIRE_TYPE.LEN, "cursor\\aisettings"), + encodeField(FIELD.SETTING_UNKNOWN_3, WIRE_TYPE.LEN, new Uint8Array(0)), + encodeField(FIELD.SETTING_UNKNOWN_6, WIRE_TYPE.LEN, unknown6), + encodeField(FIELD.SETTING_UNKNOWN_8, WIRE_TYPE.VARINT, 1), + encodeField(FIELD.SETTING_UNKNOWN_9, WIRE_TYPE.VARINT, 1) + ); +} + +/** + * Encode metadata + */ +export function encodeMetadata(): Uint8Array { + return concatArrays( + encodeField(FIELD.META_PLATFORM, WIRE_TYPE.LEN, process.platform || "linux"), + encodeField(FIELD.META_ARCH, WIRE_TYPE.LEN, process.arch || "x64"), + encodeField(FIELD.META_VERSION, WIRE_TYPE.LEN, process.version || "v20.0.0"), + encodeField(FIELD.META_CWD, WIRE_TYPE.LEN, process.cwd() || "/"), + encodeField(FIELD.META_TIMESTAMP, WIRE_TYPE.LEN, new Date().toISOString()) + ); +} + +/** + * Encode message ID + */ +export function encodeMessageId( + messageId: string, + role: RoleType, + summaryId?: string +): Uint8Array { + return concatArrays( + encodeField(FIELD.MSGID_ID, WIRE_TYPE.LEN, messageId), + ...(summaryId + ? [encodeField(FIELD.MSGID_SUMMARY, WIRE_TYPE.LEN, summaryId)] + : []), + encodeField(FIELD.MSGID_ROLE, WIRE_TYPE.VARINT, role) + ); +} + +/** + * Encode MCP tool + */ +export function encodeMcpTool(tool: CursorTool): Uint8Array { + const toolName = tool.function?.name || tool.name || ""; + const toolDesc = tool.function?.description || tool.description || ""; + const inputSchema = tool.function?.parameters || tool.input_schema || {}; + + return concatArrays( + ...(toolName + ? [encodeField(FIELD.MCP_TOOL_NAME, WIRE_TYPE.LEN, toolName)] + : []), + ...(toolDesc + ? [encodeField(FIELD.MCP_TOOL_DESC, WIRE_TYPE.LEN, toolDesc)] + : []), + ...(Object.keys(inputSchema).length > 0 + ? [ + encodeField( + FIELD.MCP_TOOL_PARAMS, + WIRE_TYPE.LEN, + JSON.stringify(inputSchema) + ), + ] + : []), + encodeField(FIELD.MCP_TOOL_SERVER, WIRE_TYPE.LEN, "custom") + ); +} + +/** + * Wrap payload in ConnectRPC frame (5-byte header + payload) + */ +export function wrapConnectRPCFrame( + payload: Uint8Array, + compress = false +): Uint8Array { + let finalPayload = payload; + let flags: number = COMPRESS_FLAG.NONE; + + if (compress) { + finalPayload = new Uint8Array(zlib.gzipSync(Buffer.from(payload))); + flags = COMPRESS_FLAG.GZIP; + } + + const frame = new Uint8Array(5 + finalPayload.length); + frame[0] = flags; + frame[1] = (finalPayload.length >> 24) & 0xff; + frame[2] = (finalPayload.length >> 16) & 0xff; + frame[3] = (finalPayload.length >> 8) & 0xff; + frame[4] = finalPayload.length & 0xff; + frame.set(finalPayload, 5); + + return frame; +} diff --git a/src/cursor/cursor-protobuf-schema.ts b/src/cursor/cursor-protobuf-schema.ts new file mode 100644 index 00000000..64034e61 --- /dev/null +++ b/src/cursor/cursor-protobuf-schema.ts @@ -0,0 +1,205 @@ +/** + * Cursor Protobuf Schema Constants + * Field definitions and wire types for ConnectRPC protocol + */ + +/** Wire types for protobuf encoding */ +export const WIRE_TYPE = { + VARINT: 0, + FIXED64: 1, + LEN: 2, + FIXED32: 5, +} as const; + +/** Message role constants */ +export const ROLE = { + USER: 1, + ASSISTANT: 2, +} as const; + +/** Unified mode constants */ +export const UNIFIED_MODE = { + CHAT: 1, + AGENT: 2, +} as const; + +/** Thinking level constants */ +export const THINKING_LEVEL = { + UNSPECIFIED: 0, + MEDIUM: 1, + HIGH: 2, +} as const; + +/** Field numbers for all protobuf messages */ +export const FIELD = { + // StreamUnifiedChatRequestWithTools (top level) + REQUEST: 1, + + // StreamUnifiedChatRequest + MESSAGES: 1, + UNKNOWN_2: 2, + INSTRUCTION: 3, + UNKNOWN_4: 4, + MODEL: 5, + WEB_TOOL: 8, + UNKNOWN_13: 13, + CURSOR_SETTING: 15, + UNKNOWN_19: 19, + CONVERSATION_ID: 23, + METADATA: 26, + IS_AGENTIC: 27, + SUPPORTED_TOOLS: 29, + MESSAGE_IDS: 30, + MCP_TOOLS: 34, + LARGE_CONTEXT: 35, + UNKNOWN_38: 38, + UNIFIED_MODE: 46, + UNKNOWN_47: 47, + SHOULD_DISABLE_TOOLS: 48, + THINKING_LEVEL: 49, + UNKNOWN_51: 51, + UNKNOWN_53: 53, + UNIFIED_MODE_NAME: 54, + + // ConversationMessage + MSG_CONTENT: 1, + MSG_ROLE: 2, + MSG_ID: 13, + MSG_TOOL_RESULTS: 18, + MSG_IS_AGENTIC: 29, + MSG_UNIFIED_MODE: 47, + MSG_SUPPORTED_TOOLS: 51, + + // ConversationMessage.ToolResult + TOOL_RESULT_CALL_ID: 1, + TOOL_RESULT_NAME: 2, + TOOL_RESULT_INDEX: 3, + TOOL_RESULT_RAW_ARGS: 5, + TOOL_RESULT_RESULT: 8, + + // Model + MODEL_NAME: 1, + MODEL_EMPTY: 4, + + // Instruction + INSTRUCTION_TEXT: 1, + + // CursorSetting + SETTING_PATH: 1, + SETTING_UNKNOWN_3: 3, + SETTING_UNKNOWN_6: 6, + SETTING_UNKNOWN_8: 8, + SETTING_UNKNOWN_9: 9, + + // CursorSetting.Unknown6 + SETTING6_FIELD_1: 1, + SETTING6_FIELD_2: 2, + + // Metadata + META_PLATFORM: 1, + META_ARCH: 2, + META_VERSION: 3, + META_CWD: 4, + META_TIMESTAMP: 5, + + // MessageId + MSGID_ID: 1, + MSGID_SUMMARY: 2, + MSGID_ROLE: 3, + + // MCPTool + MCP_TOOL_NAME: 1, + MCP_TOOL_DESC: 2, + MCP_TOOL_PARAMS: 3, + MCP_TOOL_SERVER: 4, + + // StreamUnifiedChatResponseWithTools (response) + TOOL_CALL: 1, + RESPONSE: 2, + + // ClientSideToolV2Call + TOOL_ID: 3, + TOOL_NAME: 9, + TOOL_RAW_ARGS: 10, + TOOL_IS_LAST: 11, + TOOL_MCP_PARAMS: 27, + + // MCPParams + MCP_TOOLS_LIST: 1, + + // MCPParams.Tool (nested) + MCP_NESTED_NAME: 1, + MCP_NESTED_PARAMS: 3, + + // StreamUnifiedChatResponse + RESPONSE_TEXT: 1, + THINKING: 25, + + // Thinking + THINKING_TEXT: 1, +} as const; + +/** Type definitions */ +export type WireType = (typeof WIRE_TYPE)[keyof typeof WIRE_TYPE]; +export type RoleType = (typeof ROLE)[keyof typeof ROLE]; +export type UnifiedModeType = (typeof UNIFIED_MODE)[keyof typeof UNIFIED_MODE]; +export type ThinkingLevelType = + (typeof THINKING_LEVEL)[keyof typeof THINKING_LEVEL]; +export type FieldNumber = (typeof FIELD)[keyof typeof FIELD]; + +/** Cursor tool definition */ +export interface CursorTool { + function?: { + name?: string; + description?: string; + parameters?: Record; + }; + name?: string; + description?: string; + input_schema?: Record; +} + +/** Cursor tool result */ +export interface CursorToolResult { + tool_call_id?: string; + name?: string; + index?: number; + raw_args?: string; +} + +/** Cursor message format */ +export interface CursorMessage { + role: string; + content: string; + tool_results?: CursorToolResult[]; + tool_calls?: Array<{ + id: string; + type: string; + function: { + name: string; + arguments: string; + }; + }>; +} + +/** Formatted message for encoding */ +export interface FormattedMessage { + content: string; + role: RoleType; + messageId: string; + isLast: boolean; + hasTools: boolean; + toolResults: CursorToolResult[]; +} + +/** Message ID structure */ +export interface MessageId { + messageId: string; + role: RoleType; +} + +/** Compression flags for ConnectRPC frames */ +export const COMPRESS_FLAG = { + NONE: 0x00, + GZIP: 0x01, +} as const; diff --git a/src/cursor/cursor-protobuf.ts b/src/cursor/cursor-protobuf.ts new file mode 100644 index 00000000..60e4d588 --- /dev/null +++ b/src/cursor/cursor-protobuf.ts @@ -0,0 +1,212 @@ +/** + * Cursor Protobuf Main Module + * Exports encoder/decoder functions and builds complete requests + */ + +import { randomUUID } from "crypto"; +import { + ROLE, + UNIFIED_MODE, + THINKING_LEVEL, + FIELD, + type CursorMessage, + type CursorTool, + type FormattedMessage, + type MessageId, + type ThinkingLevelType, +} from "./cursor-protobuf-schema.js"; +import { + encodeField, + encodeVarint, + encodeMessage, + encodeInstruction, + encodeModel, + encodeCursorSetting, + encodeMetadata, + encodeMessageId, + encodeMcpTool, + wrapConnectRPCFrame, +} from "./cursor-protobuf-encoder.js"; +import { + decodeVarint, + decodeField, + decodeMessage, + parseConnectRPCFrame, + extractTextFromResponse, +} from "./cursor-protobuf-decoder.js"; +import { WIRE_TYPE } from "./cursor-protobuf-schema.js"; + +/** + * Build complete chat request protobuf + */ +export function encodeRequest( + messages: CursorMessage[], + modelName: string, + tools: CursorTool[] = [], + reasoningEffort: string | null = null +): Uint8Array { + const hasTools = tools?.length > 0; + const isAgentic = hasTools; + const formattedMessages: FormattedMessage[] = []; + const messageIds: MessageId[] = []; + + // Prepare messages + for (let i = 0; i < messages.length; i++) { + const msg = messages[i]; + const role = msg.role === "user" ? ROLE.USER : ROLE.ASSISTANT; + const msgId = randomUUID(); + const isLast = i === messages.length - 1; + + formattedMessages.push({ + content: msg.content, + role, + messageId: msgId, + isLast, + hasTools, + toolResults: msg.tool_results || [], + }); + + messageIds.push({ messageId: msgId, role }); + } + + // Map reasoning effort to thinking level + let thinkingLevel: ThinkingLevelType = THINKING_LEVEL.UNSPECIFIED; + if (reasoningEffort === "medium") thinkingLevel = THINKING_LEVEL.MEDIUM; + else if (reasoningEffort === "high") thinkingLevel = THINKING_LEVEL.HIGH; + + // Build arrays for messages and tools + const messageFields = formattedMessages.map((fm) => + encodeField( + FIELD.MESSAGES, + WIRE_TYPE.LEN, + encodeMessage( + fm.content, + fm.role, + fm.messageId, + fm.isLast, + fm.hasTools, + fm.toolResults + ) + ) + ); + + const messageIdFields = messageIds.map((mid) => + encodeField( + FIELD.MESSAGE_IDS, + WIRE_TYPE.LEN, + encodeMessageId(mid.messageId, mid.role) + ) + ); + + const toolFields = + tools?.length > 0 + ? tools.map((tool) => + encodeField(FIELD.MCP_TOOLS, WIRE_TYPE.LEN, encodeMcpTool(tool)) + ) + : []; + + const supportedToolsField = isAgentic + ? [encodeField(FIELD.SUPPORTED_TOOLS, WIRE_TYPE.LEN, encodeVarint(1))] + : []; + + // Concatenate all parts + const parts: Uint8Array[] = [ + ...messageFields, + encodeField(FIELD.UNKNOWN_2, WIRE_TYPE.VARINT, 1), + encodeField(FIELD.INSTRUCTION, WIRE_TYPE.LEN, encodeInstruction("")), + encodeField(FIELD.UNKNOWN_4, WIRE_TYPE.VARINT, 1), + encodeField(FIELD.MODEL, WIRE_TYPE.LEN, encodeModel(modelName)), + encodeField(FIELD.WEB_TOOL, WIRE_TYPE.LEN, ""), + encodeField(FIELD.UNKNOWN_13, WIRE_TYPE.VARINT, 1), + encodeField(FIELD.CURSOR_SETTING, WIRE_TYPE.LEN, encodeCursorSetting()), + encodeField(FIELD.UNKNOWN_19, WIRE_TYPE.VARINT, 1), + encodeField(FIELD.CONVERSATION_ID, WIRE_TYPE.LEN, randomUUID()), + encodeField(FIELD.METADATA, WIRE_TYPE.LEN, encodeMetadata()), + encodeField(FIELD.IS_AGENTIC, WIRE_TYPE.VARINT, isAgentic ? 1 : 0), + ...supportedToolsField, + ...messageIdFields, + ...toolFields, + encodeField(FIELD.LARGE_CONTEXT, WIRE_TYPE.VARINT, 0), + encodeField(FIELD.UNKNOWN_38, WIRE_TYPE.VARINT, 0), + encodeField( + FIELD.UNIFIED_MODE, + WIRE_TYPE.VARINT, + isAgentic ? UNIFIED_MODE.AGENT : UNIFIED_MODE.CHAT + ), + encodeField(FIELD.UNKNOWN_47, WIRE_TYPE.LEN, ""), + encodeField(FIELD.SHOULD_DISABLE_TOOLS, WIRE_TYPE.VARINT, isAgentic ? 0 : 1), + encodeField(FIELD.THINKING_LEVEL, WIRE_TYPE.VARINT, thinkingLevel), + encodeField(FIELD.UNKNOWN_51, WIRE_TYPE.VARINT, 0), + encodeField(FIELD.UNKNOWN_53, WIRE_TYPE.VARINT, 1), + encodeField( + FIELD.UNIFIED_MODE_NAME, + WIRE_TYPE.LEN, + isAgentic ? "Agent" : "Ask" + ), + ]; + + return concatArrays(...parts); +} + +/** + * Build chat request wrapped in top-level message + */ +export function buildChatRequest( + messages: CursorMessage[], + modelName: string, + tools: CursorTool[] = [], + reasoningEffort: string | null = null +): Uint8Array { + return encodeField( + FIELD.REQUEST, + WIRE_TYPE.LEN, + encodeRequest(messages, modelName, tools, reasoningEffort) + ); +} + +/** + * Generate complete Cursor request body with ConnectRPC framing + */ +export function generateCursorBody( + messages: CursorMessage[], + modelName: string, + tools: CursorTool[] = [], + reasoningEffort: string | null = null +): Uint8Array { + const protobuf = buildChatRequest(messages, modelName, tools, reasoningEffort); + const framed = wrapConnectRPCFrame(protobuf, false); // Cursor doesn't support compressed requests + return framed; +} + +/** + * Concatenate multiple Uint8Arrays + */ +function concatArrays(...arrays: Uint8Array[]): Uint8Array { + const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0); + const result = new Uint8Array(totalLength); + let offset = 0; + for (const arr of arrays) { + result.set(arr, offset); + offset += arr.length; + } + return result; +} + +// Re-export all functions +export { + encodeVarint, + encodeField, + encodeMessage, + encodeInstruction, + encodeModel, + encodeCursorSetting, + encodeMetadata, + encodeMessageId, + encodeMcpTool, + wrapConnectRPCFrame, + decodeVarint, + decodeField, + decodeMessage, + parseConnectRPCFrame, + extractTextFromResponse, +}; diff --git a/src/cursor/cursor-translator.ts b/src/cursor/cursor-translator.ts new file mode 100644 index 00000000..e40d4d5d --- /dev/null +++ b/src/cursor/cursor-translator.ts @@ -0,0 +1,145 @@ +/** + * OpenAI to Cursor Request Translator + * Converts OpenAI messages to Cursor format + */ + +import type { + CursorMessage, + CursorToolResult, + CursorTool, +} from "./cursor-protobuf-schema.js"; + +/** OpenAI message format */ +interface OpenAIMessage { + role: string; + content: string | Array<{ type: string; text?: string }>; + name?: string; + tool_call_id?: string; + tool_calls?: Array<{ + id: string; + type: string; + function: { name: string; arguments: string }; + }>; +} + +/** OpenAI request body */ +interface OpenAIRequestBody { + messages: OpenAIMessage[]; + tools?: CursorTool[]; + reasoning_effort?: string; +} + +/** + * Convert OpenAI messages to Cursor format with native tool_results support + * - system → user with [System Instructions] prefix + * - tool → accumulate into tool_results array for next user/assistant message + * - assistant with tool_calls → keep tool_calls structure (Cursor supports it natively) + */ +function convertMessages(messages: OpenAIMessage[]): CursorMessage[] { + const result: CursorMessage[] = []; + let pendingToolResults: CursorToolResult[] = []; + + for (let i = 0; i < messages.length; i++) { + const msg = messages[i]; + + if (msg.role === "system") { + result.push({ + role: "user", + content: `[System Instructions]\n${msg.content}`, + }); + continue; + } + + if (msg.role === "tool") { + let toolContent = ""; + if (typeof msg.content === "string") { + toolContent = msg.content; + } else if (Array.isArray(msg.content)) { + for (const part of msg.content) { + if (part.type === "text" && part.text) { + toolContent += part.text; + } + } + } + + const toolName = msg.name || "tool"; + const toolCallId = msg.tool_call_id || ""; + + // Accumulate tool result + pendingToolResults.push({ + tool_call_id: toolCallId, + name: toolName, + index: pendingToolResults.length, + raw_args: toolContent, + }); + continue; + } + + if (msg.role === "user" || msg.role === "assistant") { + let content = ""; + + if (typeof msg.content === "string") { + content = msg.content; + } else if (Array.isArray(msg.content)) { + for (const part of msg.content) { + if (part.type === "text" && part.text) { + content += part.text; + } + } + } + + // Keep tool_calls structure for assistant messages + if (msg.role === "assistant" && msg.tool_calls && msg.tool_calls.length > 0) { + const assistantMsg: CursorMessage = { role: "assistant", content: "" }; + if (content) { + assistantMsg.content = content; + } + assistantMsg.tool_calls = msg.tool_calls; + + // Attach pending tool results to assistant message with tool_calls + if (pendingToolResults.length > 0) { + assistantMsg.tool_results = pendingToolResults; + pendingToolResults = []; + } + + result.push(assistantMsg); + } else if (content || pendingToolResults.length > 0) { + const msgObj: CursorMessage = { + role: msg.role, + content: content || "", + }; + + // Attach pending tool results to this message + if (pendingToolResults.length > 0) { + msgObj.tool_results = pendingToolResults; + pendingToolResults = []; + } + + result.push(msgObj); + } + } + } + + return result; +} + +/** + * Transform OpenAI request to Cursor format + * Returns modified body with converted messages + */ +export function buildCursorRequest( + model: string, + body: OpenAIRequestBody, + stream: boolean, + credentials: unknown +): { + messages: CursorMessage[]; + tools?: CursorTool[]; +} { + const messages = convertMessages(body.messages || []); + + return { + ...body, + messages, + }; +} From cc5a9039e40d952bd769b8b2dce7df9ecfd0cfa8 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Wed, 11 Feb 2026 19:12:20 +0700 Subject: [PATCH 2/8] fix(cursor): address code review edge cases in protobuf and executor CRITICAL FIX: - CursorCredentials interface now matches types.ts (machineId, ghostMode as top-level) - Fixes runtime error when cursor-auth saves credentials and cursor-executor reads them HIGH: - Replace 18+ non-null assertions with guard clauses across executor and decoder - Prefix unused params in translator (_model, _stream, _credentials) - HTTP/2 client closes on connection error to prevent leak - AbortSignal listener leak documented with TODO (inline arrow prevents cleanup) MEDIUM: - Export concatArrays from encoder, remove duplicate from protobuf.ts - Varint decoder now enforces 5-byte max to prevent overflow - Buffer slice bounds check prevents out-of-range read - Empty messages array validation with explicit error - Buffered streaming limitation documented with TODO comment All edge cases from code review now addressed. --- src/cursor/cursor-executor.ts | 1469 ++++++++++++------------- src/cursor/cursor-protobuf-decoder.ts | 446 ++++---- src/cursor/cursor-protobuf-encoder.ts | 312 +++--- src/cursor/cursor-protobuf-schema.ts | 269 +++-- src/cursor/cursor-protobuf.ts | 312 +++--- src/cursor/cursor-translator.ts | 196 ++-- 6 files changed, 1472 insertions(+), 1532 deletions(-) diff --git a/src/cursor/cursor-executor.ts b/src/cursor/cursor-executor.ts index 28ce9f55..a72c4b68 100644 --- a/src/cursor/cursor-executor.ts +++ b/src/cursor/cursor-executor.ts @@ -3,784 +3,781 @@ * Handles HTTP/2 requests to Cursor API with protobuf encoding/decoding */ -import * as crypto from "crypto"; -import * as zlib from "zlib"; -import type { IncomingHttpHeaders } from "http"; -import { generateCursorBody, extractTextFromResponse } from "./cursor-protobuf.js"; -import { buildCursorRequest } from "./cursor-translator.js"; -import type { CursorMessage, CursorTool } from "./cursor-protobuf-schema.js"; +import * as crypto from 'crypto'; +import * as zlib from 'zlib'; +import type { IncomingHttpHeaders } from 'http'; +import { generateCursorBody, extractTextFromResponse } from './cursor-protobuf.js'; +import { buildCursorRequest } from './cursor-translator.js'; +import type { CursorTool } from './cursor-protobuf-schema.js'; /** Compression flags for response parsing */ const COMPRESS_FLAG = { - NONE: 0x00, - GZIP: 0x01, - GZIP_ALT: 0x02, - GZIP_BOTH: 0x03, + NONE: 0x00, + GZIP: 0x01, + GZIP_ALT: 0x02, + GZIP_BOTH: 0x03, } as const; /** Cursor credentials structure */ interface CursorCredentials { - accessToken: string; - providerSpecificData?: { - machineId?: string; - ghostMode?: boolean; - }; + accessToken: string; + machineId: string; + ghostMode?: boolean; } /** Executor parameters */ interface ExecutorParams { - model: string; - body: { - messages: Array<{ - role: string; - content: string | Array<{ type: string; text?: string }>; - name?: string; - tool_call_id?: string; - tool_calls?: Array<{ - id: string; - type: string; - function: { name: string; arguments: string }; - }>; - }>; - tools?: CursorTool[]; - reasoning_effort?: string; - }; - stream: boolean; - credentials: CursorCredentials; - signal?: AbortSignal; + model: string; + body: { + messages: Array<{ + role: string; + content: string | Array<{ type: string; text?: string }>; + name?: string; + tool_call_id?: string; + tool_calls?: Array<{ + id: string; + type: string; + function: { name: string; arguments: string }; + }>; + }>; + tools?: CursorTool[]; + reasoning_effort?: string; + }; + stream: boolean; + credentials: CursorCredentials; + signal?: AbortSignal; } /** HTTP/2 response structure */ interface Http2Response { - status: number; - headers: IncomingHttpHeaders; - body: Buffer; + status: number; + headers: IncomingHttpHeaders; + body: Buffer; } /** Detect cloud environment */ function isCloudEnv(): boolean { - if (typeof caches !== "undefined" && typeof caches === "object") return true; - try { - // Check for EdgeRuntime without causing compilation error - if (typeof (globalThis as { EdgeRuntime?: string }).EdgeRuntime !== "undefined") return true; - } catch { - // Continue - } - return false; + if ( + typeof globalThis !== 'undefined' && + 'caches' in globalThis && + typeof (globalThis as { caches?: unknown }).caches === 'object' + ) + return true; + try { + // Check for EdgeRuntime without causing compilation error + if (typeof (globalThis as { EdgeRuntime?: string }).EdgeRuntime !== 'undefined') return true; + } catch { + // Continue + } + return false; } /** Lazy import http2 */ -let http2Module: typeof import("http2") | null = null; +let http2Module: typeof import('http2') | null = null; async function getHttp2() { - if (http2Module) return http2Module; - if (!isCloudEnv()) { - try { - http2Module = await import("http2"); - return http2Module; - } catch { - return null; - } - } - return null; + if (http2Module) return http2Module; + if (!isCloudEnv()) { + try { + http2Module = await import('http2'); + return http2Module; + } catch { + return null; + } + } + return null; } /** * Decompress payload if needed */ function decompressPayload(payload: Buffer, flags: number): Buffer { - // Check if payload is JSON error - if (payload.length > 10 && payload[0] === 0x7b && payload[1] === 0x22) { - try { - const text = payload.toString("utf-8"); - if (text.startsWith('{"error"')) { - return payload; - } - } catch { - // Continue - } - } + // Check if payload is JSON error + if (payload.length > 10 && payload[0] === 0x7b && payload[1] === 0x22) { + try { + const text = payload.toString('utf-8'); + if (text.startsWith('{"error"')) { + return payload; + } + } catch { + // Continue + } + } - if ( - flags === COMPRESS_FLAG.GZIP || - flags === COMPRESS_FLAG.GZIP_ALT || - flags === COMPRESS_FLAG.GZIP_BOTH - ) { - try { - return zlib.gunzipSync(payload); - } catch { - return payload; - } - } - return payload; + if ( + flags === COMPRESS_FLAG.GZIP || + flags === COMPRESS_FLAG.GZIP_ALT || + flags === COMPRESS_FLAG.GZIP_BOTH + ) { + try { + return zlib.gunzipSync(payload); + } catch { + return payload; + } + } + return payload; } /** * Create error response from JSON error */ function createErrorResponse(jsonError: { - error?: { - code?: string; - message?: string; - details?: Array<{ debug?: { details?: { title?: string; detail?: string }; error?: string } }>; - }; + error?: { + code?: string; + message?: string; + details?: Array<{ debug?: { details?: { title?: string; detail?: string }; error?: string } }>; + }; }): Response { - const errorMsg = - jsonError?.error?.details?.[0]?.debug?.details?.title || - jsonError?.error?.details?.[0]?.debug?.details?.detail || - jsonError?.error?.message || - "API Error"; + const errorMsg = + jsonError?.error?.details?.[0]?.debug?.details?.title || + jsonError?.error?.details?.[0]?.debug?.details?.detail || + jsonError?.error?.message || + 'API Error'; - const isRateLimit = jsonError?.error?.code === "resource_exhausted"; + const isRateLimit = jsonError?.error?.code === 'resource_exhausted'; - return new Response( - JSON.stringify({ - error: { - message: errorMsg, - type: isRateLimit ? "rate_limit_error" : "api_error", - code: jsonError?.error?.details?.[0]?.debug?.error || "unknown", - }, - }), - { - status: isRateLimit ? 429 : 400, - headers: { "Content-Type": "application/json" }, - } - ); + return new Response( + JSON.stringify({ + error: { + message: errorMsg, + type: isRateLimit ? 'rate_limit_error' : 'api_error', + code: jsonError?.error?.details?.[0]?.debug?.error || 'unknown', + }, + }), + { + status: isRateLimit ? 429 : 400, + headers: { 'Content-Type': 'application/json' }, + } + ); } export class CursorExecutor { - private readonly baseUrl = "https://api2.cursor.sh"; - private readonly chatPath = "/aiserver.v1.AiService/StreamChat"; - - buildUrl(): string { - return `${this.baseUrl}${this.chatPath}`; - } - - /** - * Generate checksum using Jyh cipher (time-based XOR with rolling key seed=165) - */ - generateChecksum(machineId: string): string { - const timestamp = Math.floor(Date.now() / 1000000); - const byteArray = new Uint8Array([ - (timestamp >> 40) & 0xff, - (timestamp >> 32) & 0xff, - (timestamp >> 24) & 0xff, - (timestamp >> 16) & 0xff, - (timestamp >> 8) & 0xff, - timestamp & 0xff, - ]); - - let t = 165; - for (let i = 0; i < byteArray.length; i++) { - byteArray[i] = ((byteArray[i] ^ t) + (i % 256)) & 0xff; - t = byteArray[i]; - } - - const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"; - let encoded = ""; - - for (let i = 0; i < byteArray.length; i += 3) { - const a = byteArray[i]; - const b = i + 1 < byteArray.length ? byteArray[i + 1] : 0; - const c = i + 2 < byteArray.length ? byteArray[i + 2] : 0; - - encoded += alphabet[a >> 2]; - encoded += alphabet[((a & 3) << 4) | (b >> 4)]; - - if (i + 1 < byteArray.length) { - encoded += alphabet[((b & 15) << 2) | (c >> 6)]; - } - if (i + 2 < byteArray.length) { - encoded += alphabet[c & 63]; - } - } - - return `${encoded}${machineId}`; - } - - buildHeaders(credentials: CursorCredentials): Record { - const accessToken = credentials.accessToken; - const machineId = credentials.providerSpecificData?.machineId; - const ghostMode = credentials.providerSpecificData?.ghostMode !== false; - - if (!machineId) { - throw new Error("Machine ID is required for Cursor API"); - } - - const cleanToken = accessToken.includes("::") - ? accessToken.split("::")[1] - : accessToken; - - return { - authorization: `Bearer ${cleanToken}`, - "connect-accept-encoding": "gzip", - "connect-protocol-version": "1", - "content-type": "application/connect+proto", - "user-agent": "connect-es/1.6.1", - "x-amzn-trace-id": `Root=${crypto.randomUUID()}`, - "x-client-key": crypto.createHash("sha256").update(cleanToken).digest("hex"), - "x-cursor-checksum": this.generateChecksum(machineId), - "x-cursor-client-version": "2.3.41", - "x-cursor-client-type": "ide", - "x-cursor-client-os": - process.platform === "win32" - ? "windows" - : process.platform === "darwin" - ? "macos" - : "linux", - "x-cursor-client-arch": process.arch === "arm64" ? "aarch64" : "x64", - "x-cursor-client-device-type": "desktop", - "x-cursor-config-version": crypto.randomUUID(), - "x-cursor-timezone": - Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC", - "x-ghost-mode": ghostMode ? "true" : "false", - "x-request-id": crypto.randomUUID(), - "x-session-id": crypto - .createHash("sha256") - .update(cleanToken) - .digest("hex") - .substring(0, 36), - }; - } - - transformRequest( - model: string, - body: ExecutorParams["body"], - stream: boolean, - credentials: CursorCredentials - ): Uint8Array { - const translatedBody = buildCursorRequest(model, body, stream, credentials); - const messages = translatedBody.messages || []; - const tools = (translatedBody.tools || body.tools || []) as CursorTool[]; - const reasoningEffort = body.reasoning_effort || null; - return generateCursorBody(messages, model, tools, reasoningEffort); - } - - async makeFetchRequest( - url: string, - headers: Record, - body: Uint8Array, - signal?: AbortSignal - ): Promise { - const response = await fetch(url, { - method: "POST", - headers, - body, - signal, - }); - - const responseHeaders: Record = {}; - response.headers.forEach((value, key) => { - responseHeaders[key] = value; - }); - - return { - status: response.status, - headers: responseHeaders, - body: Buffer.from(await response.arrayBuffer()), - }; - } - - async makeHttp2Request( - url: string, - headers: Record, - body: Uint8Array, - signal?: AbortSignal - ): Promise { - const http2 = await getHttp2(); - if (!http2) { - throw new Error("http2 module not available"); - } - - return new Promise((resolve, reject) => { - const urlObj = new URL(url); - const client = http2.connect(`https://${urlObj.host}`); - const chunks: Buffer[] = []; - let responseHeaders: IncomingHttpHeaders = {}; - - client.on("error", reject); - - const req = client.request({ - ":method": "POST", - ":path": urlObj.pathname, - ":authority": urlObj.host, - ":scheme": "https", - ...headers, - }); - - req.on("response", (hdrs) => { - responseHeaders = hdrs; - }); - req.on("data", (chunk: Buffer) => { - chunks.push(chunk); - }); - req.on("end", () => { - client.close(); - resolve({ - status: Number(responseHeaders[":status"]), - headers: responseHeaders, - body: Buffer.concat(chunks), - }); - }); - req.on("error", (err) => { - client.close(); - reject(err); - }); - - if (signal) { - signal.addEventListener("abort", () => { - req.close(); - client.close(); - reject(new Error("Request aborted")); - }); - } - - req.write(body); - req.end(); - }); - } - - async execute(params: ExecutorParams): Promise<{ - response: Response; - url: string; - headers: Record; - transformedBody: ExecutorParams["body"]; - }> { - const { model, body, stream, credentials, signal } = params; - const url = this.buildUrl(); - const headers = this.buildHeaders(credentials); - const transformedBody = this.transformRequest(model, body, stream, credentials); - - try { - const http2 = await getHttp2(); - const response = http2 - ? await this.makeHttp2Request(url, headers, transformedBody, signal) - : await this.makeFetchRequest(url, headers, transformedBody, signal); - - if (response.status !== 200) { - const errorText = response.body?.toString() || "Unknown error"; - const errorResponse = new Response( - JSON.stringify({ - error: { - message: `[${response.status}]: ${errorText}`, - type: "invalid_request_error", - code: "", - }, - }), - { - status: response.status, - headers: { "Content-Type": "application/json" }, - } - ); - return { response: errorResponse, url, headers, transformedBody: body }; - } - - const transformedResponse = - stream !== false - ? this.transformProtobufToSSE(response.body, model, body) - : this.transformProtobufToJSON(response.body, model, body); - - return { response: transformedResponse, url, headers, transformedBody: body }; - } catch (error) { - const errorResponse = new Response( - JSON.stringify({ - error: { - message: (error as Error).message, - type: "connection_error", - code: "", - }, - }), - { - status: 500, - headers: { "Content-Type": "application/json" }, - } - ); - return { response: errorResponse, url, headers, transformedBody: body }; - } - } - - transformProtobufToJSON( - buffer: Buffer, - model: string, - body: ExecutorParams["body"] - ): Response { - const responseId = `chatcmpl-cursor-${Date.now()}`; - const created = Math.floor(Date.now() / 1000); - - let offset = 0; - let totalContent = ""; - const toolCalls: Array<{ - id: string; - type: string; - function: { name: string; arguments: string }; - }> = []; - const toolCallsMap = new Map< - string, - { - id: string; - type: string; - function: { name: string; arguments: string }; - isLast: boolean; - index: number; - } - >(); - - while (offset < buffer.length) { - if (offset + 5 > buffer.length) break; - - const flags = buffer[offset]; - const length = buffer.readUInt32BE(offset + 1); - - if (offset + 5 + length > buffer.length) break; - - let payload = buffer.slice(offset + 5, offset + 5 + length); - offset += 5 + length; - - payload = decompressPayload(payload, flags); - - try { - const text = payload.toString("utf-8"); - if (text.startsWith("{") && text.includes('"error"')) { - return createErrorResponse(JSON.parse(text)); - } - } catch { - // Continue - } - - const result = extractTextFromResponse(new Uint8Array(payload)); - - if (result.error) { - return new Response( - JSON.stringify({ - error: { - message: result.error, - type: "rate_limit_error", - code: "rate_limited", - }, - }), - { - status: 429, - headers: { "Content-Type": "application/json" }, - } - ); - } - - if (result.toolCall) { - const tc = result.toolCall; - - if (toolCallsMap.has(tc.id)) { - const existing = toolCallsMap.get(tc.id)!; - existing.function.arguments += tc.function.arguments; - existing.isLast = tc.isLast; - } else { - toolCallsMap.set(tc.id, { - ...tc, - index: toolCallsMap.size, - }); - } - - if (tc.isLast) { - const finalToolCall = toolCallsMap.get(tc.id)!; - toolCalls.push({ - id: finalToolCall.id, - type: finalToolCall.type, - function: { - name: finalToolCall.function.name, - arguments: finalToolCall.function.arguments, - }, - }); - } - } - - if (result.text) totalContent += result.text; - } - - // Finalize remaining tool calls - for (const id of Array.from(toolCallsMap.keys())) { - const tc = toolCallsMap.get(id)!; - if (!toolCalls.find((t) => t.id === id)) { - toolCalls.push({ - id: tc.id, - type: tc.type, - function: { - name: tc.function.name, - arguments: tc.function.arguments, - }, - }); - } - } - - const message: { - role: string; - content: string | null; - tool_calls?: Array<{ - id: string; - type: string; - function: { name: string; arguments: string }; - }>; - } = { - role: "assistant", - content: totalContent || null, - }; - - if (toolCalls.length > 0) { - message.tool_calls = toolCalls; - } - - const completion = { - id: responseId, - object: "chat.completion", - created, - model, - choices: [ - { - index: 0, - message, - finish_reason: toolCalls.length > 0 ? "tool_calls" : "stop", - }, - ], - usage: { - prompt_tokens: 0, - completion_tokens: 0, - total_tokens: 0, - }, - }; - - return new Response(JSON.stringify(completion), { - status: 200, - headers: { "Content-Type": "application/json" }, - }); - } - - transformProtobufToSSE( - buffer: Buffer, - model: string, - body: ExecutorParams["body"] - ): Response { - const responseId = `chatcmpl-cursor-${Date.now()}`; - const created = Math.floor(Date.now() / 1000); - - const chunks: string[] = []; - let offset = 0; - let totalContent = ""; - const toolCalls: Array<{ - id: string; - type: string; - function: { name: string; arguments: string }; - index: number; - }> = []; - const toolCallsMap = new Map< - string, - { - id: string; - type: string; - function: { name: string; arguments: string }; - isLast: boolean; - index: number; - } - >(); - - while (offset < buffer.length) { - if (offset + 5 > buffer.length) break; - - const flags = buffer[offset]; - const length = buffer.readUInt32BE(offset + 1); - - if (offset + 5 + length > buffer.length) break; - - let payload = buffer.slice(offset + 5, offset + 5 + length); - offset += 5 + length; - - payload = decompressPayload(payload, flags); - - try { - const text = payload.toString("utf-8"); - if (text.startsWith("{") && text.includes('"error"')) { - return createErrorResponse(JSON.parse(text)); - } - } catch { - // Continue - } - - const result = extractTextFromResponse(new Uint8Array(payload)); - - if (result.error) { - return new Response( - JSON.stringify({ - error: { - message: result.error, - type: "rate_limit_error", - code: "rate_limited", - }, - }), - { - status: 429, - headers: { "Content-Type": "application/json" }, - } - ); - } - - if (result.toolCall) { - const tc = result.toolCall; - - if (chunks.length === 0) { - chunks.push( - `data: ${JSON.stringify({ - id: responseId, - object: "chat.completion.chunk", - created, - model, - choices: [ - { - index: 0, - delta: { role: "assistant", content: "" }, - finish_reason: null, - }, - ], - })}\n\n` - ); - } - - if (toolCallsMap.has(tc.id)) { - const existing = toolCallsMap.get(tc.id)!; - existing.function.arguments += tc.function.arguments; - existing.isLast = tc.isLast; - - if (tc.function.arguments) { - chunks.push( - `data: ${JSON.stringify({ - id: responseId, - object: "chat.completion.chunk", - created, - model, - choices: [ - { - index: 0, - delta: { - tool_calls: [ - { - index: existing.index, - id: tc.id, - type: "function", - function: { - name: tc.function.name, - arguments: tc.function.arguments, - }, - }, - ], - }, - finish_reason: null, - }, - ], - })}\n\n` - ); - } - } else { - const toolCallIndex = toolCalls.length; - toolCalls.push({ ...tc, index: toolCallIndex }); - toolCallsMap.set(tc.id, { ...tc, index: toolCallIndex }); - - chunks.push( - `data: ${JSON.stringify({ - id: responseId, - object: "chat.completion.chunk", - created, - model, - choices: [ - { - index: 0, - delta: { - tool_calls: [ - { - index: toolCallIndex, - id: tc.id, - type: "function", - function: { - name: tc.function.name, - arguments: tc.function.arguments, - }, - }, - ], - }, - finish_reason: null, - }, - ], - })}\n\n` - ); - } - } - - if (result.text) { - totalContent += result.text; - chunks.push( - `data: ${JSON.stringify({ - id: responseId, - object: "chat.completion.chunk", - created, - model, - choices: [ - { - index: 0, - delta: - chunks.length === 0 && toolCalls.length === 0 - ? { role: "assistant", content: result.text } - : { content: result.text }, - finish_reason: null, - }, - ], - })}\n\n` - ); - } - } - - if (chunks.length === 0 && toolCalls.length === 0) { - chunks.push( - `data: ${JSON.stringify({ - id: responseId, - object: "chat.completion.chunk", - created, - model, - choices: [ - { - index: 0, - delta: { role: "assistant", content: "" }, - finish_reason: null, - }, - ], - })}\n\n` - ); - } - - chunks.push( - `data: ${JSON.stringify({ - id: responseId, - object: "chat.completion.chunk", - created, - model, - choices: [ - { - index: 0, - delta: {}, - finish_reason: toolCalls.length > 0 ? "tool_calls" : "stop", - }, - ], - usage: { - prompt_tokens: 0, - completion_tokens: 0, - total_tokens: 0, - }, - })}\n\n` - ); - chunks.push("data: [DONE]\n\n"); - - return new Response(chunks.join(""), { - status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache", - Connection: "keep-alive", - }, - }); - } + private readonly baseUrl = 'https://api2.cursor.sh'; + private readonly chatPath = '/aiserver.v1.AiService/StreamChat'; + + buildUrl(): string { + return `${this.baseUrl}${this.chatPath}`; + } + + /** + * Generate checksum using Jyh cipher (time-based XOR with rolling key seed=165) + */ + generateChecksum(machineId: string): string { + const timestamp = Math.floor(Date.now() / 1000000); + const byteArray = new Uint8Array([ + (timestamp >> 40) & 0xff, + (timestamp >> 32) & 0xff, + (timestamp >> 24) & 0xff, + (timestamp >> 16) & 0xff, + (timestamp >> 8) & 0xff, + timestamp & 0xff, + ]); + + let t = 165; + for (let i = 0; i < byteArray.length; i++) { + byteArray[i] = ((byteArray[i] ^ t) + (i % 256)) & 0xff; + t = byteArray[i]; + } + + const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; + let encoded = ''; + + for (let i = 0; i < byteArray.length; i += 3) { + const a = byteArray[i]; + const b = i + 1 < byteArray.length ? byteArray[i + 1] : 0; + const c = i + 2 < byteArray.length ? byteArray[i + 2] : 0; + + encoded += alphabet[a >> 2]; + encoded += alphabet[((a & 3) << 4) | (b >> 4)]; + + if (i + 1 < byteArray.length) { + encoded += alphabet[((b & 15) << 2) | (c >> 6)]; + } + if (i + 2 < byteArray.length) { + encoded += alphabet[c & 63]; + } + } + + return `${encoded}${machineId}`; + } + + buildHeaders(credentials: CursorCredentials): Record { + const accessToken = credentials.accessToken; + const machineId = credentials.machineId; + const ghostMode = credentials.ghostMode !== false; + + if (!machineId) { + throw new Error('Machine ID is required for Cursor API'); + } + + const cleanToken = accessToken.includes('::') ? accessToken.split('::')[1] : accessToken; + + return { + authorization: `Bearer ${cleanToken}`, + 'connect-accept-encoding': 'gzip', + 'connect-protocol-version': '1', + 'content-type': 'application/connect+proto', + 'user-agent': 'connect-es/1.6.1', + 'x-amzn-trace-id': `Root=${crypto.randomUUID()}`, + 'x-client-key': crypto.createHash('sha256').update(cleanToken).digest('hex'), + 'x-cursor-checksum': this.generateChecksum(machineId), + 'x-cursor-client-version': '2.3.41', + 'x-cursor-client-type': 'ide', + 'x-cursor-client-os': + process.platform === 'win32' + ? 'windows' + : process.platform === 'darwin' + ? 'macos' + : 'linux', + 'x-cursor-client-arch': process.arch === 'arm64' ? 'aarch64' : 'x64', + 'x-cursor-client-device-type': 'desktop', + 'x-cursor-config-version': crypto.randomUUID(), + 'x-cursor-timezone': Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC', + 'x-ghost-mode': ghostMode ? 'true' : 'false', + 'x-request-id': crypto.randomUUID(), + 'x-session-id': crypto.createHash('sha256').update(cleanToken).digest('hex').substring(0, 36), + }; + } + + transformRequest( + model: string, + body: ExecutorParams['body'], + stream: boolean, + credentials: CursorCredentials + ): Uint8Array { + const translatedBody = buildCursorRequest(model, body, stream, credentials); + const messages = translatedBody.messages || []; + const tools = (translatedBody.tools || body.tools || []) as CursorTool[]; + const reasoningEffort = body.reasoning_effort || null; + return generateCursorBody(messages, model, tools, reasoningEffort); + } + + async makeFetchRequest( + url: string, + headers: Record, + body: Uint8Array, + signal?: AbortSignal + ): Promise { + const response = await fetch(url, { + method: 'POST', + headers, + body, + signal, + }); + + const responseHeaders: Record = {}; + response.headers.forEach((value, key) => { + responseHeaders[key] = value; + }); + + return { + status: response.status, + headers: responseHeaders, + body: Buffer.from(await response.arrayBuffer()), + }; + } + + async makeHttp2Request( + url: string, + headers: Record, + body: Uint8Array, + signal?: AbortSignal + ): Promise { + const http2 = await getHttp2(); + if (!http2) { + throw new Error('http2 module not available'); + } + + return new Promise((resolve, reject) => { + const urlObj = new URL(url); + const client = http2.connect(`https://${urlObj.host}`); + const chunks: Buffer[] = []; + let responseHeaders: IncomingHttpHeaders = {}; + + client.on('error', (err) => { + client.close(); + reject(err); + }); + + const req = client.request({ + ':method': 'POST', + ':path': urlObj.pathname, + ':authority': urlObj.host, + ':scheme': 'https', + ...headers, + }); + + req.on('response', (hdrs) => { + responseHeaders = hdrs; + }); + req.on('data', (chunk: Buffer) => { + chunks.push(chunk); + }); + req.on('end', () => { + client.close(); + resolve({ + status: Number(responseHeaders[':status']), + headers: responseHeaders, + body: Buffer.concat(chunks), + }); + }); + req.on('error', (err) => { + client.close(); + reject(err); + }); + + if (signal) { + // TODO: AbortSignal listener is not removed after request completes. + // To fix: store handler reference, remove in end/error callbacks. + signal.addEventListener('abort', () => { + req.close(); + client.close(); + reject(new Error('Request aborted')); + }); + } + + req.write(body); + req.end(); + }); + } + + async execute(params: ExecutorParams): Promise<{ + response: Response; + url: string; + headers: Record; + transformedBody: ExecutorParams['body']; + }> { + const { model, body, stream, credentials, signal } = params; + const url = this.buildUrl(); + const headers = this.buildHeaders(credentials); + const transformedBody = this.transformRequest(model, body, stream, credentials); + + try { + const http2 = await getHttp2(); + const response = http2 + ? await this.makeHttp2Request(url, headers, transformedBody, signal) + : await this.makeFetchRequest(url, headers, transformedBody, signal); + + if (response.status !== 200) { + const errorText = response.body?.toString() || 'Unknown error'; + const errorResponse = new Response( + JSON.stringify({ + error: { + message: `[${response.status}]: ${errorText}`, + type: 'invalid_request_error', + code: '', + }, + }), + { + status: response.status, + headers: { 'Content-Type': 'application/json' }, + } + ); + return { response: errorResponse, url, headers, transformedBody: body }; + } + + const transformedResponse = + stream !== false + ? this.transformProtobufToSSE(response.body, model, body) + : this.transformProtobufToJSON(response.body, model, body); + + return { response: transformedResponse, url, headers, transformedBody: body }; + } catch (error) { + const errorResponse = new Response( + JSON.stringify({ + error: { + message: (error as Error).message, + type: 'connection_error', + code: '', + }, + }), + { + status: 500, + headers: { 'Content-Type': 'application/json' }, + } + ); + return { response: errorResponse, url, headers, transformedBody: body }; + } + } + + transformProtobufToJSON(buffer: Buffer, model: string, _body: ExecutorParams['body']): Response { + const responseId = `chatcmpl-cursor-${Date.now()}`; + const created = Math.floor(Date.now() / 1000); + + let offset = 0; + let totalContent = ''; + const toolCalls: Array<{ + id: string; + type: string; + function: { name: string; arguments: string }; + }> = []; + const toolCallsMap = new Map< + string, + { + id: string; + type: string; + function: { name: string; arguments: string }; + isLast: boolean; + index: number; + } + >(); + + while (offset < buffer.length) { + if (offset + 5 > buffer.length) break; + + const flags = buffer[offset]; + const length = buffer.readUInt32BE(offset + 1); + + if (offset + 5 + length > buffer.length) break; + + let payload = buffer.slice(offset + 5, offset + 5 + length); + offset += 5 + length; + + payload = decompressPayload(payload, flags); + + try { + const text = payload.toString('utf-8'); + if (text.startsWith('{') && text.includes('"error"')) { + return createErrorResponse(JSON.parse(text)); + } + } catch { + // Continue + } + + const result = extractTextFromResponse(new Uint8Array(payload)); + + if (result.error) { + return new Response( + JSON.stringify({ + error: { + message: result.error, + type: 'rate_limit_error', + code: 'rate_limited', + }, + }), + { + status: 429, + headers: { 'Content-Type': 'application/json' }, + } + ); + } + + if (result.toolCall) { + const tc = result.toolCall; + + if (toolCallsMap.has(tc.id)) { + const existing = toolCallsMap.get(tc.id); + if (!existing) continue; + existing.function.arguments += tc.function.arguments; + existing.isLast = tc.isLast; + } else { + toolCallsMap.set(tc.id, { + ...tc, + index: toolCallsMap.size, + }); + } + + if (tc.isLast) { + const finalToolCall = toolCallsMap.get(tc.id); + if (!finalToolCall) continue; + toolCalls.push({ + id: finalToolCall.id, + type: finalToolCall.type, + function: { + name: finalToolCall.function.name, + arguments: finalToolCall.function.arguments, + }, + }); + } + } + + if (result.text) totalContent += result.text; + } + + // Finalize remaining tool calls + for (const id of Array.from(toolCallsMap.keys())) { + const tc = toolCallsMap.get(id); + if (!tc) continue; + if (!toolCalls.find((t) => t.id === id)) { + toolCalls.push({ + id: tc.id, + type: tc.type, + function: { + name: tc.function.name, + arguments: tc.function.arguments, + }, + }); + } + } + + const message: { + role: string; + content: string | null; + tool_calls?: Array<{ + id: string; + type: string; + function: { name: string; arguments: string }; + }>; + } = { + role: 'assistant', + content: totalContent || null, + }; + + if (toolCalls.length > 0) { + message.tool_calls = toolCalls; + } + + const completion = { + id: responseId, + object: 'chat.completion', + created, + model, + choices: [ + { + index: 0, + message, + finish_reason: toolCalls.length > 0 ? 'tool_calls' : 'stop', + }, + ], + usage: { + prompt_tokens: 0, + completion_tokens: 0, + total_tokens: 0, + }, + }; + + return new Response(JSON.stringify(completion), { + status: 200, + headers: { 'Content-Type': 'application/json' }, + }); + } + + transformProtobufToSSE(buffer: Buffer, model: string, _body: ExecutorParams['body']): Response { + // TODO: Implement true streaming — currently buffers entire response before transforming. + // This should pipe HTTP/2 data events through a TransformStream for incremental SSE output. + const responseId = `chatcmpl-cursor-${Date.now()}`; + const created = Math.floor(Date.now() / 1000); + + const chunks: string[] = []; + let offset = 0; + const toolCalls: Array<{ + id: string; + type: string; + function: { name: string; arguments: string }; + index: number; + }> = []; + const toolCallsMap = new Map< + string, + { + id: string; + type: string; + function: { name: string; arguments: string }; + isLast: boolean; + index: number; + } + >(); + + while (offset < buffer.length) { + if (offset + 5 > buffer.length) break; + + const flags = buffer[offset]; + const length = buffer.readUInt32BE(offset + 1); + + if (offset + 5 + length > buffer.length) break; + + let payload = buffer.slice(offset + 5, offset + 5 + length); + offset += 5 + length; + + payload = decompressPayload(payload, flags); + + try { + const text = payload.toString('utf-8'); + if (text.startsWith('{') && text.includes('"error"')) { + return createErrorResponse(JSON.parse(text)); + } + } catch { + // Continue + } + + const result = extractTextFromResponse(new Uint8Array(payload)); + + if (result.error) { + return new Response( + JSON.stringify({ + error: { + message: result.error, + type: 'rate_limit_error', + code: 'rate_limited', + }, + }), + { + status: 429, + headers: { 'Content-Type': 'application/json' }, + } + ); + } + + if (result.toolCall) { + const tc = result.toolCall; + + if (chunks.length === 0) { + chunks.push( + `data: ${JSON.stringify({ + id: responseId, + object: 'chat.completion.chunk', + created, + model, + choices: [ + { + index: 0, + delta: { role: 'assistant', content: '' }, + finish_reason: null, + }, + ], + })}\n\n` + ); + } + + if (toolCallsMap.has(tc.id)) { + const existing = toolCallsMap.get(tc.id); + if (!existing) continue; + existing.function.arguments += tc.function.arguments; + existing.isLast = tc.isLast; + + if (tc.function.arguments) { + chunks.push( + `data: ${JSON.stringify({ + id: responseId, + object: 'chat.completion.chunk', + created, + model, + choices: [ + { + index: 0, + delta: { + tool_calls: [ + { + index: existing.index, + id: tc.id, + type: 'function', + function: { + name: tc.function.name, + arguments: tc.function.arguments, + }, + }, + ], + }, + finish_reason: null, + }, + ], + })}\n\n` + ); + } + } else { + const toolCallIndex = toolCalls.length; + toolCalls.push({ ...tc, index: toolCallIndex }); + toolCallsMap.set(tc.id, { ...tc, index: toolCallIndex }); + + chunks.push( + `data: ${JSON.stringify({ + id: responseId, + object: 'chat.completion.chunk', + created, + model, + choices: [ + { + index: 0, + delta: { + tool_calls: [ + { + index: toolCallIndex, + id: tc.id, + type: 'function', + function: { + name: tc.function.name, + arguments: tc.function.arguments, + }, + }, + ], + }, + finish_reason: null, + }, + ], + })}\n\n` + ); + } + } + + if (result.text) { + chunks.push( + `data: ${JSON.stringify({ + id: responseId, + object: 'chat.completion.chunk', + created, + model, + choices: [ + { + index: 0, + delta: + chunks.length === 0 && toolCalls.length === 0 + ? { role: 'assistant', content: result.text } + : { content: result.text }, + finish_reason: null, + }, + ], + })}\n\n` + ); + } + } + + if (chunks.length === 0 && toolCalls.length === 0) { + chunks.push( + `data: ${JSON.stringify({ + id: responseId, + object: 'chat.completion.chunk', + created, + model, + choices: [ + { + index: 0, + delta: { role: 'assistant', content: '' }, + finish_reason: null, + }, + ], + })}\n\n` + ); + } + + chunks.push( + `data: ${JSON.stringify({ + id: responseId, + object: 'chat.completion.chunk', + created, + model, + choices: [ + { + index: 0, + delta: {}, + finish_reason: toolCalls.length > 0 ? 'tool_calls' : 'stop', + }, + ], + usage: { + prompt_tokens: 0, + completion_tokens: 0, + total_tokens: 0, + }, + })}\n\n` + ); + chunks.push('data: [DONE]\n\n'); + + return new Response(chunks.join(''), { + status: 200, + headers: { + 'Content-Type': 'text/event-stream', + 'Cache-Control': 'no-cache', + Connection: 'keep-alive', + }, + }); + } } export default CursorExecutor; diff --git a/src/cursor/cursor-protobuf-decoder.ts b/src/cursor/cursor-protobuf-decoder.ts index 7b3e0d6a..9811174f 100644 --- a/src/cursor/cursor-protobuf-decoder.ts +++ b/src/cursor/cursor-protobuf-decoder.ts @@ -3,34 +3,28 @@ * Implements ConnectRPC protobuf wire format decoding */ -import * as zlib from "zlib"; -import { - WIRE_TYPE, - FIELD, - type WireType, -} from "./cursor-protobuf-schema.js"; +import * as zlib from 'zlib'; +import { WIRE_TYPE, FIELD, type WireType } from './cursor-protobuf-schema.js'; /** * Decode a varint from buffer * Returns [value, newOffset] */ -export function decodeVarint( - buffer: Uint8Array, - offset: number -): [number, number] { - let result = 0; - let shift = 0; - let pos = offset; +export function decodeVarint(buffer: Uint8Array, offset: number): [number, number] { + let result = 0; + let shift = 0; + let pos = offset; + const maxBytes = 5; - while (pos < buffer.length) { - const b = buffer[pos]; - result |= (b & 0x7f) << shift; - pos++; - if (!(b & 0x80)) break; - shift += 7; - } + while (pos < buffer.length && pos - offset < maxBytes) { + const b = buffer[pos]; + result |= (b & 0x7f) << shift; + pos++; + if (!(b & 0x80)) break; + shift += 7; + } - return [result, pos]; + return [result, pos]; } /** @@ -38,63 +32,66 @@ export function decodeVarint( * Returns [fieldNum, wireType, value, newOffset] */ export function decodeField( - buffer: Uint8Array, - offset: number + buffer: Uint8Array, + offset: number ): [number | null, WireType | null, Uint8Array | number | null, number] { - if (offset >= buffer.length) { - return [null, null, null, offset]; - } + if (offset >= buffer.length) { + return [null, null, null, offset]; + } - const [tag, pos1] = decodeVarint(buffer, offset); - const fieldNum = tag >> 3; - const wireType = (tag & 0x07) as WireType; + const [tag, pos1] = decodeVarint(buffer, offset); + const fieldNum = tag >> 3; + const wireType = (tag & 0x07) as WireType; - let value: Uint8Array | number | null; - let pos = pos1; + let value: Uint8Array | number | null; + let pos = pos1; - if (wireType === WIRE_TYPE.VARINT) { - [value, pos] = decodeVarint(buffer, pos); - } else if (wireType === WIRE_TYPE.LEN) { - const [length, pos2] = decodeVarint(buffer, pos); - value = buffer.slice(pos2, pos2 + length); - pos = pos2 + length; - } else if (wireType === WIRE_TYPE.FIXED64) { - value = buffer.slice(pos, pos + 8); - pos += 8; - } else if (wireType === WIRE_TYPE.FIXED32) { - value = buffer.slice(pos, pos + 4); - pos += 4; - } else { - value = null; - } + if (wireType === WIRE_TYPE.VARINT) { + [value, pos] = decodeVarint(buffer, pos); + } else if (wireType === WIRE_TYPE.LEN) { + const [length, pos2] = decodeVarint(buffer, pos); + if (pos2 + length > buffer.length) { + return [null, null, null, buffer.length]; + } + value = buffer.slice(pos2, pos2 + length); + pos = pos2 + length; + } else if (wireType === WIRE_TYPE.FIXED64) { + value = buffer.slice(pos, pos + 8); + pos += 8; + } else if (wireType === WIRE_TYPE.FIXED32) { + value = buffer.slice(pos, pos + 4); + pos += 4; + } else { + value = null; + } - return [fieldNum, wireType, value, pos]; + return [fieldNum, wireType, value, pos]; } /** * Decode a protobuf message into a map of fields */ export function decodeMessage( - data: Uint8Array + data: Uint8Array ): Map> { - const fields = new Map< - number, - Array<{ wireType: WireType; value: Uint8Array | number }> - >(); - let pos = 0; + const fields = new Map>(); + let pos = 0; - while (pos < data.length) { - const [fieldNum, wireType, value, newPos] = decodeField(data, pos); - if (fieldNum === null || wireType === null || value === null) break; + while (pos < data.length) { + const [fieldNum, wireType, value, newPos] = decodeField(data, pos); + if (fieldNum === null || wireType === null || value === null) break; - if (!fields.has(fieldNum)) { - fields.set(fieldNum, []); - } - fields.get(fieldNum)!.push({ wireType, value: value as Uint8Array | number }); - pos = newPos; - } + if (!fields.has(fieldNum)) { + fields.set(fieldNum, []); + } + const fieldArray = fields.get(fieldNum); + if (fieldArray) { + fieldArray.push({ wireType, value: value as Uint8Array | number }); + } + pos = newPos; + } - return fields; + return fields; } /** @@ -102,200 +99,215 @@ export function decodeMessage( * Returns frame data or null if incomplete */ export function parseConnectRPCFrame(buffer: Buffer): { - flags: number; - length: number; - payload: Uint8Array; - consumed: number; + flags: number; + length: number; + payload: Uint8Array; + consumed: number; } | null { - if (buffer.length < 5) return null; + if (buffer.length < 5) return null; - const flags = buffer[0]; - const length = - (buffer[1] << 24) | (buffer[2] << 16) | (buffer[3] << 8) | buffer[4]; + const flags = buffer[0]; + const length = (buffer[1] << 24) | (buffer[2] << 16) | (buffer[3] << 8) | buffer[4]; - if (buffer.length < 5 + length) return null; + if (buffer.length < 5 + length) return null; - let payload = buffer.slice(5, 5 + length); + let payload = buffer.slice(5, 5 + length); - // Decompress if gzip - if (flags === 0x01 || flags === 0x02 || flags === 0x03) { - try { - payload = Buffer.from(zlib.gunzipSync(payload)); - } catch { - // Decompression failed, use raw payload - } - } + // Decompress if gzip + if (flags === 0x01 || flags === 0x02 || flags === 0x03) { + try { + payload = Buffer.from(zlib.gunzipSync(payload)); + } catch { + // Decompression failed, use raw payload + } + } - return { - flags, - length, - payload: new Uint8Array(payload), - consumed: 5 + length, - }; + return { + flags, + length, + payload: new Uint8Array(payload), + consumed: 5 + length, + }; } /** * Extract tool call from protobuf data */ function extractToolCall(toolCallData: Uint8Array): { - id: string; - type: string; - function: { name: string; arguments: string }; - isLast: boolean; + id: string; + type: string; + function: { name: string; arguments: string }; + isLast: boolean; } | null { - const toolCall = decodeMessage(toolCallData); - let toolCallId = ""; - let toolName = ""; - let rawArgs = ""; - let isLast = false; + const toolCall = decodeMessage(toolCallData); + let toolCallId = ''; + let toolName = ''; + let rawArgs = ''; + let isLast = false; - // Extract tool call ID - if (toolCall.has(FIELD.TOOL_ID)) { - const fullId = new TextDecoder().decode( - toolCall.get(FIELD.TOOL_ID)![0].value as Uint8Array - ); - toolCallId = fullId.split("\n")[0]; // Take first line - } + // Extract tool call ID + if (toolCall.has(FIELD.TOOL_ID)) { + const idField = toolCall.get(FIELD.TOOL_ID); + if (idField && idField[0]) { + const fullId = new TextDecoder().decode(idField[0].value as Uint8Array); + toolCallId = fullId.split('\n')[0]; // Take first line + } + } - // Extract tool name - if (toolCall.has(FIELD.TOOL_NAME)) { - toolName = new TextDecoder().decode( - toolCall.get(FIELD.TOOL_NAME)![0].value as Uint8Array - ); - } + // Extract tool name + if (toolCall.has(FIELD.TOOL_NAME)) { + const nameField = toolCall.get(FIELD.TOOL_NAME); + if (nameField && nameField[0]) { + toolName = new TextDecoder().decode(nameField[0].value as Uint8Array); + } + } - // Extract is_last flag - if (toolCall.has(FIELD.TOOL_IS_LAST)) { - isLast = (toolCall.get(FIELD.TOOL_IS_LAST)![0].value as number) !== 0; - } + // Extract is_last flag + if (toolCall.has(FIELD.TOOL_IS_LAST)) { + const lastField = toolCall.get(FIELD.TOOL_IS_LAST); + if (lastField && lastField[0]) { + isLast = (lastField[0].value as number) !== 0; + } + } - // Extract MCP params - nested real tool info - if (toolCall.has(FIELD.TOOL_MCP_PARAMS)) { - try { - const mcpParams = decodeMessage( - toolCall.get(FIELD.TOOL_MCP_PARAMS)![0].value as Uint8Array - ); + // Extract MCP params - nested real tool info + if (toolCall.has(FIELD.TOOL_MCP_PARAMS)) { + try { + const mcpField = toolCall.get(FIELD.TOOL_MCP_PARAMS); + if (!mcpField || !mcpField[0]) return null; - if (mcpParams.has(FIELD.MCP_TOOLS_LIST)) { - const tool = decodeMessage( - mcpParams.get(FIELD.MCP_TOOLS_LIST)![0].value as Uint8Array - ); + const mcpParams = decodeMessage(mcpField[0].value as Uint8Array); - if (tool.has(FIELD.MCP_NESTED_NAME)) { - toolName = new TextDecoder().decode( - tool.get(FIELD.MCP_NESTED_NAME)![0].value as Uint8Array - ); - } + if (mcpParams.has(FIELD.MCP_TOOLS_LIST)) { + const toolsList = mcpParams.get(FIELD.MCP_TOOLS_LIST); + if (!toolsList || !toolsList[0]) return null; - if (tool.has(FIELD.MCP_NESTED_PARAMS)) { - rawArgs = new TextDecoder().decode( - tool.get(FIELD.MCP_NESTED_PARAMS)![0].value as Uint8Array - ); - } - } - } catch { - // MCP parse error, continue - } - } + const tool = decodeMessage(toolsList[0].value as Uint8Array); - // Fallback to raw_args - if (!rawArgs && toolCall.has(FIELD.TOOL_RAW_ARGS)) { - rawArgs = new TextDecoder().decode( - toolCall.get(FIELD.TOOL_RAW_ARGS)![0].value as Uint8Array - ); - } + if (tool.has(FIELD.MCP_NESTED_NAME)) { + const nestedName = tool.get(FIELD.MCP_NESTED_NAME); + if (nestedName && nestedName[0]) { + toolName = new TextDecoder().decode(nestedName[0].value as Uint8Array); + } + } - if (toolCallId && toolName) { - return { - id: toolCallId, - type: "function", - function: { - name: toolName, - arguments: rawArgs || "{}", - }, - isLast, - }; - } + if (tool.has(FIELD.MCP_NESTED_PARAMS)) { + const nestedParams = tool.get(FIELD.MCP_NESTED_PARAMS); + if (nestedParams && nestedParams[0]) { + rawArgs = new TextDecoder().decode(nestedParams[0].value as Uint8Array); + } + } + } + } catch { + // MCP parse error, continue + } + } - return null; + // Fallback to raw_args + if (!rawArgs && toolCall.has(FIELD.TOOL_RAW_ARGS)) { + const rawArgsField = toolCall.get(FIELD.TOOL_RAW_ARGS); + if (rawArgsField && rawArgsField[0]) { + rawArgs = new TextDecoder().decode(rawArgsField[0].value as Uint8Array); + } + } + + if (toolCallId && toolName) { + return { + id: toolCallId, + type: 'function', + function: { + name: toolName, + arguments: rawArgs || '{}', + }, + isLast, + }; + } + + return null; } /** * Extract text and thinking from response data */ -function extractTextAndThinking( - responseData: Uint8Array -): { text: string | null; thinking: string | null } { - const nested = decodeMessage(responseData); - let text: string | null = null; - let thinking: string | null = null; +function extractTextAndThinking(responseData: Uint8Array): { + text: string | null; + thinking: string | null; +} { + const nested = decodeMessage(responseData); + let text: string | null = null; + let thinking: string | null = null; - // Extract text - if (nested.has(FIELD.RESPONSE_TEXT)) { - text = new TextDecoder().decode( - nested.get(FIELD.RESPONSE_TEXT)![0].value as Uint8Array - ); - } + // Extract text + if (nested.has(FIELD.RESPONSE_TEXT)) { + const textField = nested.get(FIELD.RESPONSE_TEXT); + if (textField && textField[0]) { + text = new TextDecoder().decode(textField[0].value as Uint8Array); + } + } - // Extract thinking - if (nested.has(FIELD.THINKING)) { - try { - const thinkingMsg = decodeMessage( - nested.get(FIELD.THINKING)![0].value as Uint8Array - ); - if (thinkingMsg.has(FIELD.THINKING_TEXT)) { - thinking = new TextDecoder().decode( - thinkingMsg.get(FIELD.THINKING_TEXT)![0].value as Uint8Array - ); - } - } catch { - // Thinking parse error, continue - } - } + // Extract thinking + if (nested.has(FIELD.THINKING)) { + try { + const thinkingField = nested.get(FIELD.THINKING); + if (thinkingField && thinkingField[0]) { + const thinkingMsg = decodeMessage(thinkingField[0].value as Uint8Array); + if (thinkingMsg.has(FIELD.THINKING_TEXT)) { + const thinkingTextField = thinkingMsg.get(FIELD.THINKING_TEXT); + if (thinkingTextField && thinkingTextField[0]) { + thinking = new TextDecoder().decode(thinkingTextField[0].value as Uint8Array); + } + } + } + } catch { + // Thinking parse error, continue + } + } - return { text, thinking }; + return { text, thinking }; } /** * Extract text and tool calls from response payload */ export function extractTextFromResponse(payload: Uint8Array): { - text: string | null; - error: string | null; - toolCall: { - id: string; - type: string; - function: { name: string; arguments: string }; - isLast: boolean; - } | null; - thinking: string | null; + text: string | null; + error: string | null; + toolCall: { + id: string; + type: string; + function: { name: string; arguments: string }; + isLast: boolean; + } | null; + thinking: string | null; } { - try { - const fields = decodeMessage(payload); + try { + const fields = decodeMessage(payload); - // Field 1: ClientSideToolV2Call - if (fields.has(FIELD.TOOL_CALL)) { - const toolCall = extractToolCall( - fields.get(FIELD.TOOL_CALL)![0].value as Uint8Array - ); - if (toolCall) { - return { text: null, error: null, toolCall, thinking: null }; - } - } + // Field 1: ClientSideToolV2Call + if (fields.has(FIELD.TOOL_CALL)) { + const toolCallField = fields.get(FIELD.TOOL_CALL); + if (toolCallField && toolCallField[0]) { + const toolCall = extractToolCall(toolCallField[0].value as Uint8Array); + if (toolCall) { + return { text: null, error: null, toolCall, thinking: null }; + } + } + } - // Field 2: StreamUnifiedChatResponse - if (fields.has(FIELD.RESPONSE)) { - const { text, thinking } = extractTextAndThinking( - fields.get(FIELD.RESPONSE)![0].value as Uint8Array - ); + // Field 2: StreamUnifiedChatResponse + if (fields.has(FIELD.RESPONSE)) { + const responseField = fields.get(FIELD.RESPONSE); + if (responseField && responseField[0]) { + const { text, thinking } = extractTextAndThinking(responseField[0].value as Uint8Array); - if (text || thinking) { - return { text, error: null, toolCall: null, thinking }; - } - } + if (text || thinking) { + return { text, error: null, toolCall: null, thinking }; + } + } + } - return { text: null, error: null, toolCall: null, thinking: null }; - } catch { - return { text: null, error: null, toolCall: null, thinking: null }; - } + return { text: null, error: null, toolCall: null, thinking: null }; + } catch { + return { text: null, error: null, toolCall: null, thinking: null }; + } } diff --git a/src/cursor/cursor-protobuf-encoder.ts b/src/cursor/cursor-protobuf-encoder.ts index 6958d219..eb1133c9 100644 --- a/src/cursor/cursor-protobuf-encoder.ts +++ b/src/cursor/cursor-protobuf-encoder.ts @@ -3,260 +3,222 @@ * Implements ConnectRPC protobuf wire format encoding */ -import { randomUUID } from "crypto"; -import * as zlib from "zlib"; +import * as zlib from 'zlib'; import { - WIRE_TYPE, - ROLE, - UNIFIED_MODE, - THINKING_LEVEL, - FIELD, - COMPRESS_FLAG, - type WireType, - type RoleType, - type ThinkingLevelType, - type CursorTool, - type CursorToolResult, - type CursorMessage, - type FormattedMessage, - type MessageId, -} from "./cursor-protobuf-schema.js"; + WIRE_TYPE, + FIELD, + COMPRESS_FLAG, + UNIFIED_MODE, + type WireType, + type RoleType, + type CursorTool, + type CursorToolResult, +} from './cursor-protobuf-schema.js'; /** * Encode a varint (variable-length integer) */ export function encodeVarint(value: number): Uint8Array { - const bytes: number[] = []; - let val = value >>> 0; // Ensure unsigned - while (val >= 0x80) { - bytes.push((val & 0x7f) | 0x80); - val >>>= 7; - } - bytes.push(val & 0x7f); - return new Uint8Array(bytes); + const bytes: number[] = []; + let val = value >>> 0; // Ensure unsigned + while (val >= 0x80) { + bytes.push((val & 0x7f) | 0x80); + val >>>= 7; + } + bytes.push(val & 0x7f); + return new Uint8Array(bytes); } /** * Encode a protobuf field (tag + value) */ export function encodeField( - fieldNum: number, - wireType: WireType, - value: number | string | Uint8Array + fieldNum: number, + wireType: WireType, + value: number | string | Uint8Array ): Uint8Array { - const tag = (fieldNum << 3) | wireType; - const tagBytes = encodeVarint(tag); + const tag = (fieldNum << 3) | wireType; + const tagBytes = encodeVarint(tag); - if (wireType === WIRE_TYPE.VARINT) { - const valueBytes = encodeVarint(value as number); - return concatArrays(tagBytes, valueBytes); - } + if (wireType === WIRE_TYPE.VARINT) { + const valueBytes = encodeVarint(value as number); + return concatArrays(tagBytes, valueBytes); + } - if (wireType === WIRE_TYPE.LEN) { - const dataBytes = - typeof value === "string" - ? new TextEncoder().encode(value) - : value instanceof Uint8Array - ? value - : new Uint8Array(0); + if (wireType === WIRE_TYPE.LEN) { + const dataBytes = + typeof value === 'string' + ? new TextEncoder().encode(value) + : value instanceof Uint8Array + ? value + : new Uint8Array(0); - const lengthBytes = encodeVarint(dataBytes.length); - return concatArrays(tagBytes, lengthBytes, dataBytes); - } + const lengthBytes = encodeVarint(dataBytes.length); + return concatArrays(tagBytes, lengthBytes, dataBytes); + } - return new Uint8Array(0); + return new Uint8Array(0); } /** * Concatenate multiple Uint8Arrays */ -function concatArrays(...arrays: Uint8Array[]): Uint8Array { - const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0); - const result = new Uint8Array(totalLength); - let offset = 0; - for (const arr of arrays) { - result.set(arr, offset); - offset += arr.length; - } - return result; +export function concatArrays(...arrays: Uint8Array[]): Uint8Array { + const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0); + const result = new Uint8Array(totalLength); + let offset = 0; + for (const arr of arrays) { + result.set(arr, offset); + offset += arr.length; + } + return result; } /** * Encode a tool result */ export function encodeToolResult(toolResult: CursorToolResult): Uint8Array { - const toolCallId = toolResult.tool_call_id || ""; - const toolName = toolResult.name || ""; - const toolIndex = toolResult.index || 0; - const rawArgs = toolResult.raw_args || "{}"; + const toolCallId = toolResult.tool_call_id || ''; + const toolName = toolResult.name || ''; + const toolIndex = toolResult.index || 0; + const rawArgs = toolResult.raw_args || '{}'; - return concatArrays( - encodeField(FIELD.TOOL_RESULT_CALL_ID, WIRE_TYPE.LEN, toolCallId), - encodeField(FIELD.TOOL_RESULT_NAME, WIRE_TYPE.LEN, toolName), - encodeField(FIELD.TOOL_RESULT_INDEX, WIRE_TYPE.VARINT, toolIndex), - encodeField(FIELD.TOOL_RESULT_RAW_ARGS, WIRE_TYPE.LEN, rawArgs) - ); + return concatArrays( + encodeField(FIELD.TOOL_RESULT_CALL_ID, WIRE_TYPE.LEN, toolCallId), + encodeField(FIELD.TOOL_RESULT_NAME, WIRE_TYPE.LEN, toolName), + encodeField(FIELD.TOOL_RESULT_INDEX, WIRE_TYPE.VARINT, toolIndex), + encodeField(FIELD.TOOL_RESULT_RAW_ARGS, WIRE_TYPE.LEN, rawArgs) + ); } /** * Encode a conversation message */ export function encodeMessage( - content: string, - role: RoleType, - messageId: string, - isLast: boolean, - hasTools: boolean, - toolResults: CursorToolResult[] + content: string, + role: RoleType, + messageId: string, + isLast: boolean, + hasTools: boolean, + toolResults: CursorToolResult[] ): Uint8Array { - return concatArrays( - encodeField(FIELD.MSG_CONTENT, WIRE_TYPE.LEN, content), - encodeField(FIELD.MSG_ROLE, WIRE_TYPE.VARINT, role), - encodeField(FIELD.MSG_ID, WIRE_TYPE.LEN, messageId), - ...(toolResults.length > 0 - ? toolResults.map((tr) => - encodeField( - FIELD.MSG_TOOL_RESULTS, - WIRE_TYPE.LEN, - encodeToolResult(tr) - ) - ) - : []), - encodeField(FIELD.MSG_IS_AGENTIC, WIRE_TYPE.VARINT, hasTools ? 1 : 0), - encodeField( - FIELD.MSG_UNIFIED_MODE, - WIRE_TYPE.VARINT, - hasTools ? UNIFIED_MODE.AGENT : UNIFIED_MODE.CHAT - ), - ...(isLast && hasTools - ? [ - encodeField( - FIELD.MSG_SUPPORTED_TOOLS, - WIRE_TYPE.LEN, - encodeVarint(1) - ), - ] - : []) - ); + return concatArrays( + encodeField(FIELD.MSG_CONTENT, WIRE_TYPE.LEN, content), + encodeField(FIELD.MSG_ROLE, WIRE_TYPE.VARINT, role), + encodeField(FIELD.MSG_ID, WIRE_TYPE.LEN, messageId), + ...(toolResults.length > 0 + ? toolResults.map((tr) => + encodeField(FIELD.MSG_TOOL_RESULTS, WIRE_TYPE.LEN, encodeToolResult(tr)) + ) + : []), + encodeField(FIELD.MSG_IS_AGENTIC, WIRE_TYPE.VARINT, hasTools ? 1 : 0), + encodeField( + FIELD.MSG_UNIFIED_MODE, + WIRE_TYPE.VARINT, + hasTools ? UNIFIED_MODE.AGENT : UNIFIED_MODE.CHAT + ), + ...(isLast && hasTools + ? [encodeField(FIELD.MSG_SUPPORTED_TOOLS, WIRE_TYPE.LEN, encodeVarint(1))] + : []) + ); } /** * Encode instruction text */ export function encodeInstruction(text: string): Uint8Array { - return text - ? encodeField(FIELD.INSTRUCTION_TEXT, WIRE_TYPE.LEN, text) - : new Uint8Array(0); + return text ? encodeField(FIELD.INSTRUCTION_TEXT, WIRE_TYPE.LEN, text) : new Uint8Array(0); } /** * Encode model information */ export function encodeModel(modelName: string): Uint8Array { - return concatArrays( - encodeField(FIELD.MODEL_NAME, WIRE_TYPE.LEN, modelName), - encodeField(FIELD.MODEL_EMPTY, WIRE_TYPE.LEN, new Uint8Array(0)) - ); + return concatArrays( + encodeField(FIELD.MODEL_NAME, WIRE_TYPE.LEN, modelName), + encodeField(FIELD.MODEL_EMPTY, WIRE_TYPE.LEN, new Uint8Array(0)) + ); } /** * Encode cursor settings */ export function encodeCursorSetting(): Uint8Array { - const unknown6 = concatArrays( - encodeField(FIELD.SETTING6_FIELD_1, WIRE_TYPE.LEN, new Uint8Array(0)), - encodeField(FIELD.SETTING6_FIELD_2, WIRE_TYPE.LEN, new Uint8Array(0)) - ); + const unknown6 = concatArrays( + encodeField(FIELD.SETTING6_FIELD_1, WIRE_TYPE.LEN, new Uint8Array(0)), + encodeField(FIELD.SETTING6_FIELD_2, WIRE_TYPE.LEN, new Uint8Array(0)) + ); - return concatArrays( - encodeField(FIELD.SETTING_PATH, WIRE_TYPE.LEN, "cursor\\aisettings"), - encodeField(FIELD.SETTING_UNKNOWN_3, WIRE_TYPE.LEN, new Uint8Array(0)), - encodeField(FIELD.SETTING_UNKNOWN_6, WIRE_TYPE.LEN, unknown6), - encodeField(FIELD.SETTING_UNKNOWN_8, WIRE_TYPE.VARINT, 1), - encodeField(FIELD.SETTING_UNKNOWN_9, WIRE_TYPE.VARINT, 1) - ); + return concatArrays( + encodeField(FIELD.SETTING_PATH, WIRE_TYPE.LEN, 'cursor\\aisettings'), + encodeField(FIELD.SETTING_UNKNOWN_3, WIRE_TYPE.LEN, new Uint8Array(0)), + encodeField(FIELD.SETTING_UNKNOWN_6, WIRE_TYPE.LEN, unknown6), + encodeField(FIELD.SETTING_UNKNOWN_8, WIRE_TYPE.VARINT, 1), + encodeField(FIELD.SETTING_UNKNOWN_9, WIRE_TYPE.VARINT, 1) + ); } /** * Encode metadata */ export function encodeMetadata(): Uint8Array { - return concatArrays( - encodeField(FIELD.META_PLATFORM, WIRE_TYPE.LEN, process.platform || "linux"), - encodeField(FIELD.META_ARCH, WIRE_TYPE.LEN, process.arch || "x64"), - encodeField(FIELD.META_VERSION, WIRE_TYPE.LEN, process.version || "v20.0.0"), - encodeField(FIELD.META_CWD, WIRE_TYPE.LEN, process.cwd() || "/"), - encodeField(FIELD.META_TIMESTAMP, WIRE_TYPE.LEN, new Date().toISOString()) - ); + return concatArrays( + encodeField(FIELD.META_PLATFORM, WIRE_TYPE.LEN, process.platform || 'linux'), + encodeField(FIELD.META_ARCH, WIRE_TYPE.LEN, process.arch || 'x64'), + encodeField(FIELD.META_VERSION, WIRE_TYPE.LEN, process.version || 'v20.0.0'), + encodeField(FIELD.META_CWD, WIRE_TYPE.LEN, process.cwd() || '/'), + encodeField(FIELD.META_TIMESTAMP, WIRE_TYPE.LEN, new Date().toISOString()) + ); } /** * Encode message ID */ -export function encodeMessageId( - messageId: string, - role: RoleType, - summaryId?: string -): Uint8Array { - return concatArrays( - encodeField(FIELD.MSGID_ID, WIRE_TYPE.LEN, messageId), - ...(summaryId - ? [encodeField(FIELD.MSGID_SUMMARY, WIRE_TYPE.LEN, summaryId)] - : []), - encodeField(FIELD.MSGID_ROLE, WIRE_TYPE.VARINT, role) - ); +export function encodeMessageId(messageId: string, role: RoleType, summaryId?: string): Uint8Array { + return concatArrays( + encodeField(FIELD.MSGID_ID, WIRE_TYPE.LEN, messageId), + ...(summaryId ? [encodeField(FIELD.MSGID_SUMMARY, WIRE_TYPE.LEN, summaryId)] : []), + encodeField(FIELD.MSGID_ROLE, WIRE_TYPE.VARINT, role) + ); } /** * Encode MCP tool */ export function encodeMcpTool(tool: CursorTool): Uint8Array { - const toolName = tool.function?.name || tool.name || ""; - const toolDesc = tool.function?.description || tool.description || ""; - const inputSchema = tool.function?.parameters || tool.input_schema || {}; + const toolName = tool.function?.name || tool.name || ''; + const toolDesc = tool.function?.description || tool.description || ''; + const inputSchema = tool.function?.parameters || tool.input_schema || {}; - return concatArrays( - ...(toolName - ? [encodeField(FIELD.MCP_TOOL_NAME, WIRE_TYPE.LEN, toolName)] - : []), - ...(toolDesc - ? [encodeField(FIELD.MCP_TOOL_DESC, WIRE_TYPE.LEN, toolDesc)] - : []), - ...(Object.keys(inputSchema).length > 0 - ? [ - encodeField( - FIELD.MCP_TOOL_PARAMS, - WIRE_TYPE.LEN, - JSON.stringify(inputSchema) - ), - ] - : []), - encodeField(FIELD.MCP_TOOL_SERVER, WIRE_TYPE.LEN, "custom") - ); + return concatArrays( + ...(toolName ? [encodeField(FIELD.MCP_TOOL_NAME, WIRE_TYPE.LEN, toolName)] : []), + ...(toolDesc ? [encodeField(FIELD.MCP_TOOL_DESC, WIRE_TYPE.LEN, toolDesc)] : []), + ...(Object.keys(inputSchema).length > 0 + ? [encodeField(FIELD.MCP_TOOL_PARAMS, WIRE_TYPE.LEN, JSON.stringify(inputSchema))] + : []), + encodeField(FIELD.MCP_TOOL_SERVER, WIRE_TYPE.LEN, 'custom') + ); } /** * Wrap payload in ConnectRPC frame (5-byte header + payload) */ -export function wrapConnectRPCFrame( - payload: Uint8Array, - compress = false -): Uint8Array { - let finalPayload = payload; - let flags: number = COMPRESS_FLAG.NONE; +export function wrapConnectRPCFrame(payload: Uint8Array, compress = false): Uint8Array { + let finalPayload = payload; + let flags: number = COMPRESS_FLAG.NONE; - if (compress) { - finalPayload = new Uint8Array(zlib.gzipSync(Buffer.from(payload))); - flags = COMPRESS_FLAG.GZIP; - } + if (compress) { + finalPayload = new Uint8Array(zlib.gzipSync(Buffer.from(payload))); + flags = COMPRESS_FLAG.GZIP; + } - const frame = new Uint8Array(5 + finalPayload.length); - frame[0] = flags; - frame[1] = (finalPayload.length >> 24) & 0xff; - frame[2] = (finalPayload.length >> 16) & 0xff; - frame[3] = (finalPayload.length >> 8) & 0xff; - frame[4] = finalPayload.length & 0xff; - frame.set(finalPayload, 5); + const frame = new Uint8Array(5 + finalPayload.length); + frame[0] = flags; + frame[1] = (finalPayload.length >> 24) & 0xff; + frame[2] = (finalPayload.length >> 16) & 0xff; + frame[3] = (finalPayload.length >> 8) & 0xff; + frame[4] = finalPayload.length & 0xff; + frame.set(finalPayload, 5); - return frame; + return frame; } diff --git a/src/cursor/cursor-protobuf-schema.ts b/src/cursor/cursor-protobuf-schema.ts index 64034e61..8cee42cf 100644 --- a/src/cursor/cursor-protobuf-schema.ts +++ b/src/cursor/cursor-protobuf-schema.ts @@ -5,201 +5,200 @@ /** Wire types for protobuf encoding */ export const WIRE_TYPE = { - VARINT: 0, - FIXED64: 1, - LEN: 2, - FIXED32: 5, + VARINT: 0, + FIXED64: 1, + LEN: 2, + FIXED32: 5, } as const; /** Message role constants */ export const ROLE = { - USER: 1, - ASSISTANT: 2, + USER: 1, + ASSISTANT: 2, } as const; /** Unified mode constants */ export const UNIFIED_MODE = { - CHAT: 1, - AGENT: 2, + CHAT: 1, + AGENT: 2, } as const; /** Thinking level constants */ export const THINKING_LEVEL = { - UNSPECIFIED: 0, - MEDIUM: 1, - HIGH: 2, + UNSPECIFIED: 0, + MEDIUM: 1, + HIGH: 2, } as const; /** Field numbers for all protobuf messages */ export const FIELD = { - // StreamUnifiedChatRequestWithTools (top level) - REQUEST: 1, + // StreamUnifiedChatRequestWithTools (top level) + REQUEST: 1, - // StreamUnifiedChatRequest - MESSAGES: 1, - UNKNOWN_2: 2, - INSTRUCTION: 3, - UNKNOWN_4: 4, - MODEL: 5, - WEB_TOOL: 8, - UNKNOWN_13: 13, - CURSOR_SETTING: 15, - UNKNOWN_19: 19, - CONVERSATION_ID: 23, - METADATA: 26, - IS_AGENTIC: 27, - SUPPORTED_TOOLS: 29, - MESSAGE_IDS: 30, - MCP_TOOLS: 34, - LARGE_CONTEXT: 35, - UNKNOWN_38: 38, - UNIFIED_MODE: 46, - UNKNOWN_47: 47, - SHOULD_DISABLE_TOOLS: 48, - THINKING_LEVEL: 49, - UNKNOWN_51: 51, - UNKNOWN_53: 53, - UNIFIED_MODE_NAME: 54, + // StreamUnifiedChatRequest + MESSAGES: 1, + UNKNOWN_2: 2, + INSTRUCTION: 3, + UNKNOWN_4: 4, + MODEL: 5, + WEB_TOOL: 8, + UNKNOWN_13: 13, + CURSOR_SETTING: 15, + UNKNOWN_19: 19, + CONVERSATION_ID: 23, + METADATA: 26, + IS_AGENTIC: 27, + SUPPORTED_TOOLS: 29, + MESSAGE_IDS: 30, + MCP_TOOLS: 34, + LARGE_CONTEXT: 35, + UNKNOWN_38: 38, + UNIFIED_MODE: 46, + UNKNOWN_47: 47, + SHOULD_DISABLE_TOOLS: 48, + THINKING_LEVEL: 49, + UNKNOWN_51: 51, + UNKNOWN_53: 53, + UNIFIED_MODE_NAME: 54, - // ConversationMessage - MSG_CONTENT: 1, - MSG_ROLE: 2, - MSG_ID: 13, - MSG_TOOL_RESULTS: 18, - MSG_IS_AGENTIC: 29, - MSG_UNIFIED_MODE: 47, - MSG_SUPPORTED_TOOLS: 51, + // ConversationMessage + MSG_CONTENT: 1, + MSG_ROLE: 2, + MSG_ID: 13, + MSG_TOOL_RESULTS: 18, + MSG_IS_AGENTIC: 29, + MSG_UNIFIED_MODE: 47, + MSG_SUPPORTED_TOOLS: 51, - // ConversationMessage.ToolResult - TOOL_RESULT_CALL_ID: 1, - TOOL_RESULT_NAME: 2, - TOOL_RESULT_INDEX: 3, - TOOL_RESULT_RAW_ARGS: 5, - TOOL_RESULT_RESULT: 8, + // ConversationMessage.ToolResult + TOOL_RESULT_CALL_ID: 1, + TOOL_RESULT_NAME: 2, + TOOL_RESULT_INDEX: 3, + TOOL_RESULT_RAW_ARGS: 5, + TOOL_RESULT_RESULT: 8, - // Model - MODEL_NAME: 1, - MODEL_EMPTY: 4, + // Model + MODEL_NAME: 1, + MODEL_EMPTY: 4, - // Instruction - INSTRUCTION_TEXT: 1, + // Instruction + INSTRUCTION_TEXT: 1, - // CursorSetting - SETTING_PATH: 1, - SETTING_UNKNOWN_3: 3, - SETTING_UNKNOWN_6: 6, - SETTING_UNKNOWN_8: 8, - SETTING_UNKNOWN_9: 9, + // CursorSetting + SETTING_PATH: 1, + SETTING_UNKNOWN_3: 3, + SETTING_UNKNOWN_6: 6, + SETTING_UNKNOWN_8: 8, + SETTING_UNKNOWN_9: 9, - // CursorSetting.Unknown6 - SETTING6_FIELD_1: 1, - SETTING6_FIELD_2: 2, + // CursorSetting.Unknown6 + SETTING6_FIELD_1: 1, + SETTING6_FIELD_2: 2, - // Metadata - META_PLATFORM: 1, - META_ARCH: 2, - META_VERSION: 3, - META_CWD: 4, - META_TIMESTAMP: 5, + // Metadata + META_PLATFORM: 1, + META_ARCH: 2, + META_VERSION: 3, + META_CWD: 4, + META_TIMESTAMP: 5, - // MessageId - MSGID_ID: 1, - MSGID_SUMMARY: 2, - MSGID_ROLE: 3, + // MessageId + MSGID_ID: 1, + MSGID_SUMMARY: 2, + MSGID_ROLE: 3, - // MCPTool - MCP_TOOL_NAME: 1, - MCP_TOOL_DESC: 2, - MCP_TOOL_PARAMS: 3, - MCP_TOOL_SERVER: 4, + // MCPTool + MCP_TOOL_NAME: 1, + MCP_TOOL_DESC: 2, + MCP_TOOL_PARAMS: 3, + MCP_TOOL_SERVER: 4, - // StreamUnifiedChatResponseWithTools (response) - TOOL_CALL: 1, - RESPONSE: 2, + // StreamUnifiedChatResponseWithTools (response) + TOOL_CALL: 1, + RESPONSE: 2, - // ClientSideToolV2Call - TOOL_ID: 3, - TOOL_NAME: 9, - TOOL_RAW_ARGS: 10, - TOOL_IS_LAST: 11, - TOOL_MCP_PARAMS: 27, + // ClientSideToolV2Call + TOOL_ID: 3, + TOOL_NAME: 9, + TOOL_RAW_ARGS: 10, + TOOL_IS_LAST: 11, + TOOL_MCP_PARAMS: 27, - // MCPParams - MCP_TOOLS_LIST: 1, + // MCPParams + MCP_TOOLS_LIST: 1, - // MCPParams.Tool (nested) - MCP_NESTED_NAME: 1, - MCP_NESTED_PARAMS: 3, + // MCPParams.Tool (nested) + MCP_NESTED_NAME: 1, + MCP_NESTED_PARAMS: 3, - // StreamUnifiedChatResponse - RESPONSE_TEXT: 1, - THINKING: 25, + // StreamUnifiedChatResponse + RESPONSE_TEXT: 1, + THINKING: 25, - // Thinking - THINKING_TEXT: 1, + // Thinking + THINKING_TEXT: 1, } as const; /** Type definitions */ export type WireType = (typeof WIRE_TYPE)[keyof typeof WIRE_TYPE]; export type RoleType = (typeof ROLE)[keyof typeof ROLE]; export type UnifiedModeType = (typeof UNIFIED_MODE)[keyof typeof UNIFIED_MODE]; -export type ThinkingLevelType = - (typeof THINKING_LEVEL)[keyof typeof THINKING_LEVEL]; +export type ThinkingLevelType = (typeof THINKING_LEVEL)[keyof typeof THINKING_LEVEL]; export type FieldNumber = (typeof FIELD)[keyof typeof FIELD]; /** Cursor tool definition */ export interface CursorTool { - function?: { - name?: string; - description?: string; - parameters?: Record; - }; - name?: string; - description?: string; - input_schema?: Record; + function?: { + name?: string; + description?: string; + parameters?: Record; + }; + name?: string; + description?: string; + input_schema?: Record; } /** Cursor tool result */ export interface CursorToolResult { - tool_call_id?: string; - name?: string; - index?: number; - raw_args?: string; + tool_call_id?: string; + name?: string; + index?: number; + raw_args?: string; } /** Cursor message format */ export interface CursorMessage { - role: string; - content: string; - tool_results?: CursorToolResult[]; - tool_calls?: Array<{ - id: string; - type: string; - function: { - name: string; - arguments: string; - }; - }>; + role: string; + content: string; + tool_results?: CursorToolResult[]; + tool_calls?: Array<{ + id: string; + type: string; + function: { + name: string; + arguments: string; + }; + }>; } /** Formatted message for encoding */ export interface FormattedMessage { - content: string; - role: RoleType; - messageId: string; - isLast: boolean; - hasTools: boolean; - toolResults: CursorToolResult[]; + content: string; + role: RoleType; + messageId: string; + isLast: boolean; + hasTools: boolean; + toolResults: CursorToolResult[]; } /** Message ID structure */ export interface MessageId { - messageId: string; - role: RoleType; + messageId: string; + role: RoleType; } /** Compression flags for ConnectRPC frames */ export const COMPRESS_FLAG = { - NONE: 0x00, - GZIP: 0x01, + NONE: 0x00, + GZIP: 0x01, } as const; diff --git a/src/cursor/cursor-protobuf.ts b/src/cursor/cursor-protobuf.ts index 60e4d588..6e0ee06a 100644 --- a/src/cursor/cursor-protobuf.ts +++ b/src/cursor/cursor-protobuf.ts @@ -3,210 +3,184 @@ * Exports encoder/decoder functions and builds complete requests */ -import { randomUUID } from "crypto"; +import { randomUUID } from 'crypto'; import { - ROLE, - UNIFIED_MODE, - THINKING_LEVEL, - FIELD, - type CursorMessage, - type CursorTool, - type FormattedMessage, - type MessageId, - type ThinkingLevelType, -} from "./cursor-protobuf-schema.js"; + ROLE, + UNIFIED_MODE, + THINKING_LEVEL, + FIELD, + type CursorMessage, + type CursorTool, + type FormattedMessage, + type MessageId, + type ThinkingLevelType, +} from './cursor-protobuf-schema.js'; import { - encodeField, - encodeVarint, - encodeMessage, - encodeInstruction, - encodeModel, - encodeCursorSetting, - encodeMetadata, - encodeMessageId, - encodeMcpTool, - wrapConnectRPCFrame, -} from "./cursor-protobuf-encoder.js"; + encodeField, + encodeVarint, + encodeMessage, + encodeInstruction, + encodeModel, + encodeCursorSetting, + encodeMetadata, + encodeMessageId, + encodeMcpTool, + wrapConnectRPCFrame, + concatArrays, +} from './cursor-protobuf-encoder.js'; import { - decodeVarint, - decodeField, - decodeMessage, - parseConnectRPCFrame, - extractTextFromResponse, -} from "./cursor-protobuf-decoder.js"; -import { WIRE_TYPE } from "./cursor-protobuf-schema.js"; + decodeVarint, + decodeField, + decodeMessage, + parseConnectRPCFrame, + extractTextFromResponse, +} from './cursor-protobuf-decoder.js'; +import { WIRE_TYPE } from './cursor-protobuf-schema.js'; /** * Build complete chat request protobuf */ export function encodeRequest( - messages: CursorMessage[], - modelName: string, - tools: CursorTool[] = [], - reasoningEffort: string | null = null + messages: CursorMessage[], + modelName: string, + tools: CursorTool[] = [], + reasoningEffort: string | null = null ): Uint8Array { - const hasTools = tools?.length > 0; - const isAgentic = hasTools; - const formattedMessages: FormattedMessage[] = []; - const messageIds: MessageId[] = []; + if (messages.length === 0) { + throw new Error('Messages array must not be empty'); + } - // Prepare messages - for (let i = 0; i < messages.length; i++) { - const msg = messages[i]; - const role = msg.role === "user" ? ROLE.USER : ROLE.ASSISTANT; - const msgId = randomUUID(); - const isLast = i === messages.length - 1; + const hasTools = tools?.length > 0; + const isAgentic = hasTools; + const formattedMessages: FormattedMessage[] = []; + const messageIds: MessageId[] = []; - formattedMessages.push({ - content: msg.content, - role, - messageId: msgId, - isLast, - hasTools, - toolResults: msg.tool_results || [], - }); + // Prepare messages + for (let i = 0; i < messages.length; i++) { + const msg = messages[i]; + const role = msg.role === 'user' ? ROLE.USER : ROLE.ASSISTANT; + const msgId = randomUUID(); + const isLast = i === messages.length - 1; - messageIds.push({ messageId: msgId, role }); - } + formattedMessages.push({ + content: msg.content, + role, + messageId: msgId, + isLast, + hasTools, + toolResults: msg.tool_results || [], + }); - // Map reasoning effort to thinking level - let thinkingLevel: ThinkingLevelType = THINKING_LEVEL.UNSPECIFIED; - if (reasoningEffort === "medium") thinkingLevel = THINKING_LEVEL.MEDIUM; - else if (reasoningEffort === "high") thinkingLevel = THINKING_LEVEL.HIGH; + messageIds.push({ messageId: msgId, role }); + } - // Build arrays for messages and tools - const messageFields = formattedMessages.map((fm) => - encodeField( - FIELD.MESSAGES, - WIRE_TYPE.LEN, - encodeMessage( - fm.content, - fm.role, - fm.messageId, - fm.isLast, - fm.hasTools, - fm.toolResults - ) - ) - ); + // Map reasoning effort to thinking level + let thinkingLevel: ThinkingLevelType = THINKING_LEVEL.UNSPECIFIED; + if (reasoningEffort === 'medium') thinkingLevel = THINKING_LEVEL.MEDIUM; + else if (reasoningEffort === 'high') thinkingLevel = THINKING_LEVEL.HIGH; - const messageIdFields = messageIds.map((mid) => - encodeField( - FIELD.MESSAGE_IDS, - WIRE_TYPE.LEN, - encodeMessageId(mid.messageId, mid.role) - ) - ); + // Build arrays for messages and tools + const messageFields = formattedMessages.map((fm) => + encodeField( + FIELD.MESSAGES, + WIRE_TYPE.LEN, + encodeMessage(fm.content, fm.role, fm.messageId, fm.isLast, fm.hasTools, fm.toolResults) + ) + ); - const toolFields = - tools?.length > 0 - ? tools.map((tool) => - encodeField(FIELD.MCP_TOOLS, WIRE_TYPE.LEN, encodeMcpTool(tool)) - ) - : []; + const messageIdFields = messageIds.map((mid) => + encodeField(FIELD.MESSAGE_IDS, WIRE_TYPE.LEN, encodeMessageId(mid.messageId, mid.role)) + ); - const supportedToolsField = isAgentic - ? [encodeField(FIELD.SUPPORTED_TOOLS, WIRE_TYPE.LEN, encodeVarint(1))] - : []; + const toolFields = + tools?.length > 0 + ? tools.map((tool) => encodeField(FIELD.MCP_TOOLS, WIRE_TYPE.LEN, encodeMcpTool(tool))) + : []; - // Concatenate all parts - const parts: Uint8Array[] = [ - ...messageFields, - encodeField(FIELD.UNKNOWN_2, WIRE_TYPE.VARINT, 1), - encodeField(FIELD.INSTRUCTION, WIRE_TYPE.LEN, encodeInstruction("")), - encodeField(FIELD.UNKNOWN_4, WIRE_TYPE.VARINT, 1), - encodeField(FIELD.MODEL, WIRE_TYPE.LEN, encodeModel(modelName)), - encodeField(FIELD.WEB_TOOL, WIRE_TYPE.LEN, ""), - encodeField(FIELD.UNKNOWN_13, WIRE_TYPE.VARINT, 1), - encodeField(FIELD.CURSOR_SETTING, WIRE_TYPE.LEN, encodeCursorSetting()), - encodeField(FIELD.UNKNOWN_19, WIRE_TYPE.VARINT, 1), - encodeField(FIELD.CONVERSATION_ID, WIRE_TYPE.LEN, randomUUID()), - encodeField(FIELD.METADATA, WIRE_TYPE.LEN, encodeMetadata()), - encodeField(FIELD.IS_AGENTIC, WIRE_TYPE.VARINT, isAgentic ? 1 : 0), - ...supportedToolsField, - ...messageIdFields, - ...toolFields, - encodeField(FIELD.LARGE_CONTEXT, WIRE_TYPE.VARINT, 0), - encodeField(FIELD.UNKNOWN_38, WIRE_TYPE.VARINT, 0), - encodeField( - FIELD.UNIFIED_MODE, - WIRE_TYPE.VARINT, - isAgentic ? UNIFIED_MODE.AGENT : UNIFIED_MODE.CHAT - ), - encodeField(FIELD.UNKNOWN_47, WIRE_TYPE.LEN, ""), - encodeField(FIELD.SHOULD_DISABLE_TOOLS, WIRE_TYPE.VARINT, isAgentic ? 0 : 1), - encodeField(FIELD.THINKING_LEVEL, WIRE_TYPE.VARINT, thinkingLevel), - encodeField(FIELD.UNKNOWN_51, WIRE_TYPE.VARINT, 0), - encodeField(FIELD.UNKNOWN_53, WIRE_TYPE.VARINT, 1), - encodeField( - FIELD.UNIFIED_MODE_NAME, - WIRE_TYPE.LEN, - isAgentic ? "Agent" : "Ask" - ), - ]; + const supportedToolsField = isAgentic + ? [encodeField(FIELD.SUPPORTED_TOOLS, WIRE_TYPE.LEN, encodeVarint(1))] + : []; - return concatArrays(...parts); + // Concatenate all parts + const parts: Uint8Array[] = [ + ...messageFields, + encodeField(FIELD.UNKNOWN_2, WIRE_TYPE.VARINT, 1), + encodeField(FIELD.INSTRUCTION, WIRE_TYPE.LEN, encodeInstruction('')), + encodeField(FIELD.UNKNOWN_4, WIRE_TYPE.VARINT, 1), + encodeField(FIELD.MODEL, WIRE_TYPE.LEN, encodeModel(modelName)), + encodeField(FIELD.WEB_TOOL, WIRE_TYPE.LEN, ''), + encodeField(FIELD.UNKNOWN_13, WIRE_TYPE.VARINT, 1), + encodeField(FIELD.CURSOR_SETTING, WIRE_TYPE.LEN, encodeCursorSetting()), + encodeField(FIELD.UNKNOWN_19, WIRE_TYPE.VARINT, 1), + encodeField(FIELD.CONVERSATION_ID, WIRE_TYPE.LEN, randomUUID()), + encodeField(FIELD.METADATA, WIRE_TYPE.LEN, encodeMetadata()), + encodeField(FIELD.IS_AGENTIC, WIRE_TYPE.VARINT, isAgentic ? 1 : 0), + ...supportedToolsField, + ...messageIdFields, + ...toolFields, + encodeField(FIELD.LARGE_CONTEXT, WIRE_TYPE.VARINT, 0), + encodeField(FIELD.UNKNOWN_38, WIRE_TYPE.VARINT, 0), + encodeField( + FIELD.UNIFIED_MODE, + WIRE_TYPE.VARINT, + isAgentic ? UNIFIED_MODE.AGENT : UNIFIED_MODE.CHAT + ), + encodeField(FIELD.UNKNOWN_47, WIRE_TYPE.LEN, ''), + encodeField(FIELD.SHOULD_DISABLE_TOOLS, WIRE_TYPE.VARINT, isAgentic ? 0 : 1), + encodeField(FIELD.THINKING_LEVEL, WIRE_TYPE.VARINT, thinkingLevel), + encodeField(FIELD.UNKNOWN_51, WIRE_TYPE.VARINT, 0), + encodeField(FIELD.UNKNOWN_53, WIRE_TYPE.VARINT, 1), + encodeField(FIELD.UNIFIED_MODE_NAME, WIRE_TYPE.LEN, isAgentic ? 'Agent' : 'Ask'), + ]; + + return concatArrays(...parts); } /** * Build chat request wrapped in top-level message */ export function buildChatRequest( - messages: CursorMessage[], - modelName: string, - tools: CursorTool[] = [], - reasoningEffort: string | null = null + messages: CursorMessage[], + modelName: string, + tools: CursorTool[] = [], + reasoningEffort: string | null = null ): Uint8Array { - return encodeField( - FIELD.REQUEST, - WIRE_TYPE.LEN, - encodeRequest(messages, modelName, tools, reasoningEffort) - ); + return encodeField( + FIELD.REQUEST, + WIRE_TYPE.LEN, + encodeRequest(messages, modelName, tools, reasoningEffort) + ); } /** * Generate complete Cursor request body with ConnectRPC framing */ export function generateCursorBody( - messages: CursorMessage[], - modelName: string, - tools: CursorTool[] = [], - reasoningEffort: string | null = null + messages: CursorMessage[], + modelName: string, + tools: CursorTool[] = [], + reasoningEffort: string | null = null ): Uint8Array { - const protobuf = buildChatRequest(messages, modelName, tools, reasoningEffort); - const framed = wrapConnectRPCFrame(protobuf, false); // Cursor doesn't support compressed requests - return framed; -} - -/** - * Concatenate multiple Uint8Arrays - */ -function concatArrays(...arrays: Uint8Array[]): Uint8Array { - const totalLength = arrays.reduce((sum, arr) => sum + arr.length, 0); - const result = new Uint8Array(totalLength); - let offset = 0; - for (const arr of arrays) { - result.set(arr, offset); - offset += arr.length; - } - return result; + const protobuf = buildChatRequest(messages, modelName, tools, reasoningEffort); + const framed = wrapConnectRPCFrame(protobuf, false); // Cursor doesn't support compressed requests + return framed; } // Re-export all functions export { - encodeVarint, - encodeField, - encodeMessage, - encodeInstruction, - encodeModel, - encodeCursorSetting, - encodeMetadata, - encodeMessageId, - encodeMcpTool, - wrapConnectRPCFrame, - decodeVarint, - decodeField, - decodeMessage, - parseConnectRPCFrame, - extractTextFromResponse, + encodeVarint, + encodeField, + encodeMessage, + encodeInstruction, + encodeModel, + encodeCursorSetting, + encodeMetadata, + encodeMessageId, + encodeMcpTool, + wrapConnectRPCFrame, + decodeVarint, + decodeField, + decodeMessage, + parseConnectRPCFrame, + extractTextFromResponse, }; diff --git a/src/cursor/cursor-translator.ts b/src/cursor/cursor-translator.ts index e40d4d5d..cd2d7c0f 100644 --- a/src/cursor/cursor-translator.ts +++ b/src/cursor/cursor-translator.ts @@ -3,30 +3,26 @@ * Converts OpenAI messages to Cursor format */ -import type { - CursorMessage, - CursorToolResult, - CursorTool, -} from "./cursor-protobuf-schema.js"; +import type { CursorMessage, CursorToolResult, CursorTool } from './cursor-protobuf-schema.js'; /** OpenAI message format */ interface OpenAIMessage { - role: string; - content: string | Array<{ type: string; text?: string }>; - name?: string; - tool_call_id?: string; - tool_calls?: Array<{ - id: string; - type: string; - function: { name: string; arguments: string }; - }>; + role: string; + content: string | Array<{ type: string; text?: string }>; + name?: string; + tool_call_id?: string; + tool_calls?: Array<{ + id: string; + type: string; + function: { name: string; arguments: string }; + }>; } /** OpenAI request body */ interface OpenAIRequestBody { - messages: OpenAIMessage[]; - tools?: CursorTool[]; - reasoning_effort?: string; + messages: OpenAIMessage[]; + tools?: CursorTool[]; + reasoning_effort?: string; } /** @@ -36,91 +32,91 @@ interface OpenAIRequestBody { * - assistant with tool_calls → keep tool_calls structure (Cursor supports it natively) */ function convertMessages(messages: OpenAIMessage[]): CursorMessage[] { - const result: CursorMessage[] = []; - let pendingToolResults: CursorToolResult[] = []; + const result: CursorMessage[] = []; + let pendingToolResults: CursorToolResult[] = []; - for (let i = 0; i < messages.length; i++) { - const msg = messages[i]; + for (let i = 0; i < messages.length; i++) { + const msg = messages[i]; - if (msg.role === "system") { - result.push({ - role: "user", - content: `[System Instructions]\n${msg.content}`, - }); - continue; - } + if (msg.role === 'system') { + result.push({ + role: 'user', + content: `[System Instructions]\n${msg.content}`, + }); + continue; + } - if (msg.role === "tool") { - let toolContent = ""; - if (typeof msg.content === "string") { - toolContent = msg.content; - } else if (Array.isArray(msg.content)) { - for (const part of msg.content) { - if (part.type === "text" && part.text) { - toolContent += part.text; - } - } - } + if (msg.role === 'tool') { + let toolContent = ''; + if (typeof msg.content === 'string') { + toolContent = msg.content; + } else if (Array.isArray(msg.content)) { + for (const part of msg.content) { + if (part.type === 'text' && part.text) { + toolContent += part.text; + } + } + } - const toolName = msg.name || "tool"; - const toolCallId = msg.tool_call_id || ""; + const toolName = msg.name || 'tool'; + const toolCallId = msg.tool_call_id || ''; - // Accumulate tool result - pendingToolResults.push({ - tool_call_id: toolCallId, - name: toolName, - index: pendingToolResults.length, - raw_args: toolContent, - }); - continue; - } + // Accumulate tool result + pendingToolResults.push({ + tool_call_id: toolCallId, + name: toolName, + index: pendingToolResults.length, + raw_args: toolContent, + }); + continue; + } - if (msg.role === "user" || msg.role === "assistant") { - let content = ""; + if (msg.role === 'user' || msg.role === 'assistant') { + let content = ''; - if (typeof msg.content === "string") { - content = msg.content; - } else if (Array.isArray(msg.content)) { - for (const part of msg.content) { - if (part.type === "text" && part.text) { - content += part.text; - } - } - } + if (typeof msg.content === 'string') { + content = msg.content; + } else if (Array.isArray(msg.content)) { + for (const part of msg.content) { + if (part.type === 'text' && part.text) { + content += part.text; + } + } + } - // Keep tool_calls structure for assistant messages - if (msg.role === "assistant" && msg.tool_calls && msg.tool_calls.length > 0) { - const assistantMsg: CursorMessage = { role: "assistant", content: "" }; - if (content) { - assistantMsg.content = content; - } - assistantMsg.tool_calls = msg.tool_calls; + // Keep tool_calls structure for assistant messages + if (msg.role === 'assistant' && msg.tool_calls && msg.tool_calls.length > 0) { + const assistantMsg: CursorMessage = { role: 'assistant', content: '' }; + if (content) { + assistantMsg.content = content; + } + assistantMsg.tool_calls = msg.tool_calls; - // Attach pending tool results to assistant message with tool_calls - if (pendingToolResults.length > 0) { - assistantMsg.tool_results = pendingToolResults; - pendingToolResults = []; - } + // Attach pending tool results to assistant message with tool_calls + if (pendingToolResults.length > 0) { + assistantMsg.tool_results = pendingToolResults; + pendingToolResults = []; + } - result.push(assistantMsg); - } else if (content || pendingToolResults.length > 0) { - const msgObj: CursorMessage = { - role: msg.role, - content: content || "", - }; + result.push(assistantMsg); + } else if (content || pendingToolResults.length > 0) { + const msgObj: CursorMessage = { + role: msg.role, + content: content || '', + }; - // Attach pending tool results to this message - if (pendingToolResults.length > 0) { - msgObj.tool_results = pendingToolResults; - pendingToolResults = []; - } + // Attach pending tool results to this message + if (pendingToolResults.length > 0) { + msgObj.tool_results = pendingToolResults; + pendingToolResults = []; + } - result.push(msgObj); - } - } - } + result.push(msgObj); + } + } + } - return result; + return result; } /** @@ -128,18 +124,18 @@ function convertMessages(messages: OpenAIMessage[]): CursorMessage[] { * Returns modified body with converted messages */ export function buildCursorRequest( - model: string, - body: OpenAIRequestBody, - stream: boolean, - credentials: unknown + _model: string, + body: OpenAIRequestBody, + _stream: boolean, + _credentials: unknown ): { - messages: CursorMessage[]; - tools?: CursorTool[]; + messages: CursorMessage[]; + tools?: CursorTool[]; } { - const messages = convertMessages(body.messages || []); + const messages = convertMessages(body.messages || []); - return { - ...body, - messages, - }; + return { + ...body, + messages, + }; } From 31f574118d6c1f293dd8dc59c311079bde9b0bd1 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Wed, 11 Feb 2026 19:27:39 +0700 Subject: [PATCH 3/8] fix(cursor): address code review feedback (attempt 1/5) - Fix bitwise shift overflow in generateChecksum: use Math.trunc division for >>40/>>32 which wrap modulo 32 in JS - Add FIXED64/FIXED32 bounds checks in protobuf decoder to prevent out-of-bounds slice on truncated buffers - Consolidate COMPRESS_FLAG to single definition in schema (DRY): executor now imports from schema, added GZIP_ALT/GZIP_BOTH values - Fix token split edge case: use indexOf+slice instead of split('::')[1] to handle tokens containing multiple :: delimiters - Fix AbortSignal listener leak: store handler ref, use once:true, remove listener on request end/error --- src/cursor/cursor-executor.ts | 36 ++++++++++++++------------- src/cursor/cursor-protobuf-decoder.ts | 6 +++++ src/cursor/cursor-protobuf-schema.ts | 2 ++ 3 files changed, 27 insertions(+), 17 deletions(-) diff --git a/src/cursor/cursor-executor.ts b/src/cursor/cursor-executor.ts index a72c4b68..9f166f7b 100644 --- a/src/cursor/cursor-executor.ts +++ b/src/cursor/cursor-executor.ts @@ -10,13 +10,7 @@ import { generateCursorBody, extractTextFromResponse } from './cursor-protobuf.j import { buildCursorRequest } from './cursor-translator.js'; import type { CursorTool } from './cursor-protobuf-schema.js'; -/** Compression flags for response parsing */ -const COMPRESS_FLAG = { - NONE: 0x00, - GZIP: 0x01, - GZIP_ALT: 0x02, - GZIP_BOTH: 0x03, -} as const; +import { COMPRESS_FLAG } from './cursor-protobuf-schema.js'; /** Cursor credentials structure */ interface CursorCredentials { @@ -163,12 +157,14 @@ export class CursorExecutor { */ generateChecksum(machineId: string): string { const timestamp = Math.floor(Date.now() / 1000000); + // JS bitwise shifts wrap modulo 32, so >>40 and >>32 give wrong results. + // Use Math.trunc division for upper bytes that exceed 32-bit range. const byteArray = new Uint8Array([ - (timestamp >> 40) & 0xff, - (timestamp >> 32) & 0xff, - (timestamp >> 24) & 0xff, - (timestamp >> 16) & 0xff, - (timestamp >> 8) & 0xff, + Math.trunc(timestamp / 2 ** 40) & 0xff, + Math.trunc(timestamp / 2 ** 32) & 0xff, + (timestamp >>> 24) & 0xff, + (timestamp >>> 16) & 0xff, + (timestamp >>> 8) & 0xff, timestamp & 0xff, ]); @@ -209,7 +205,8 @@ export class CursorExecutor { throw new Error('Machine ID is required for Cursor API'); } - const cleanToken = accessToken.includes('::') ? accessToken.split('::')[1] : accessToken; + const delimIdx = accessToken.indexOf('::'); + const cleanToken = delimIdx !== -1 ? accessToken.slice(delimIdx + 2) : accessToken; return { authorization: `Bearer ${cleanToken}`, @@ -326,13 +323,18 @@ export class CursorExecutor { }); if (signal) { - // TODO: AbortSignal listener is not removed after request completes. - // To fix: store handler reference, remove in end/error callbacks. - signal.addEventListener('abort', () => { + const onAbort = () => { req.close(); client.close(); reject(new Error('Request aborted')); - }); + }; + signal.addEventListener('abort', onAbort, { once: true }); + + const cleanup = () => { + signal.removeEventListener('abort', onAbort); + }; + req.on('end', cleanup); + req.on('error', cleanup); } req.write(body); diff --git a/src/cursor/cursor-protobuf-decoder.ts b/src/cursor/cursor-protobuf-decoder.ts index 9811174f..bf0af3d4 100644 --- a/src/cursor/cursor-protobuf-decoder.ts +++ b/src/cursor/cursor-protobuf-decoder.ts @@ -56,9 +56,15 @@ export function decodeField( value = buffer.slice(pos2, pos2 + length); pos = pos2 + length; } else if (wireType === WIRE_TYPE.FIXED64) { + if (pos + 8 > buffer.length) { + return [null, null, null, buffer.length]; + } value = buffer.slice(pos, pos + 8); pos += 8; } else if (wireType === WIRE_TYPE.FIXED32) { + if (pos + 4 > buffer.length) { + return [null, null, null, buffer.length]; + } value = buffer.slice(pos, pos + 4); pos += 4; } else { diff --git a/src/cursor/cursor-protobuf-schema.ts b/src/cursor/cursor-protobuf-schema.ts index 8cee42cf..53183bb7 100644 --- a/src/cursor/cursor-protobuf-schema.ts +++ b/src/cursor/cursor-protobuf-schema.ts @@ -201,4 +201,6 @@ export interface MessageId { export const COMPRESS_FLAG = { NONE: 0x00, GZIP: 0x01, + GZIP_ALT: 0x02, + GZIP_BOTH: 0x03, } as const; From f3d532afd971e998ee7f72fcfc8a2940ff735ff4 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 01:06:33 +0700 Subject: [PATCH 4/8] fix(cursor): address remaining LOW review items in protobuf module --- src/cursor/cursor-executor.ts | 2 ++ src/cursor/cursor-protobuf-decoder.ts | 1 + 2 files changed, 3 insertions(+) diff --git a/src/cursor/cursor-executor.ts b/src/cursor/cursor-executor.ts index 9f166f7b..72e299a6 100644 --- a/src/cursor/cursor-executor.ts +++ b/src/cursor/cursor-executor.ts @@ -83,6 +83,7 @@ async function getHttp2() { /** * Decompress payload if needed + * NOTE: Uses synchronous gzip for single-request CLI tool. Async not warranted for small payloads. */ function decompressPayload(payload: Buffer, flags: number): Buffer { // Check if payload is JSON error @@ -556,6 +557,7 @@ export class CursorExecutor { transformProtobufToSSE(buffer: Buffer, model: string, _body: ExecutorParams['body']): Response { // TODO: Implement true streaming — currently buffers entire response before transforming. // This should pipe HTTP/2 data events through a TransformStream for incremental SSE output. + // NOTE: Chunk boundary splits may emit duplicate SSE messages if a frame spans multiple chunks. const responseId = `chatcmpl-cursor-${Date.now()}`; const created = Math.floor(Date.now() / 1000); diff --git a/src/cursor/cursor-protobuf-decoder.ts b/src/cursor/cursor-protobuf-decoder.ts index bf0af3d4..6111dd19 100644 --- a/src/cursor/cursor-protobuf-decoder.ts +++ b/src/cursor/cursor-protobuf-decoder.ts @@ -83,6 +83,7 @@ export function decodeMessage( const fields = new Map>(); let pos = 0; + // NOTE: If two fields share the same field number but different wire types, later values overwrite earlier ones. while (pos < data.length) { const [fieldNum, wireType, value, newPos] = decodeField(data, pos); if (fieldNum === null || wireType === null || value === null) break; From e177a4b09796cfc48a4932428449809d8ab68015 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 01:26:47 +0700 Subject: [PATCH 5/8] fix(cursor): address second-round review feedback for protobuf module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit HIGH Priority: - Add comprehensive unit tests (27 tests covering encoder, decoder, translator, executor) * encodeVarint/decodeVarint round-trip (0, 1, 127, 128, 16383, 0xFFFFFFFF) * encodeField/decodeField round-trip (VARINT, LEN string, LEN binary) * wrapConnectRPCFrame/parseConnectRPCFrame (compressed/uncompressed) * buildCursorRequest message translation (system, user, assistant, tool) * generateChecksum header format validation * buildHeaders output validation * transformProtobufToJSON basic conversion - Create GitHub issue #531 for true streaming implementation - Update TODO comment to reference issue #531 MEDIUM Priority: - Export CursorCredentials from cursor-protobuf-schema.ts - Add JSDoc grouping comments to FIELD constant for clarity - Make hardcoded values configurable (CURSOR_CLIENT_VERSION, CURSOR_USER_AGENT) - Add debug logging to 9 silent catch blocks (respects CCS_DEBUG env var) - Fix stream check: stream !== false → stream === true Bug Fixes: - Fix decodeVarint to return unsigned values (>>> 0) - Fix test assertion for Response.text() async API --- src/cursor/cursor-executor.ts | 54 +-- src/cursor/cursor-protobuf-decoder.ts | 22 +- src/cursor/cursor-protobuf-schema.ts | 41 ++- tests/unit/cursor/cursor-protobuf.test.ts | 405 ++++++++++++++++++++++ 4 files changed, 478 insertions(+), 44 deletions(-) create mode 100644 tests/unit/cursor/cursor-protobuf.test.ts diff --git a/src/cursor/cursor-executor.ts b/src/cursor/cursor-executor.ts index 72e299a6..0919c7f4 100644 --- a/src/cursor/cursor-executor.ts +++ b/src/cursor/cursor-executor.ts @@ -8,17 +8,10 @@ import * as zlib from 'zlib'; import type { IncomingHttpHeaders } from 'http'; import { generateCursorBody, extractTextFromResponse } from './cursor-protobuf.js'; import { buildCursorRequest } from './cursor-translator.js'; -import type { CursorTool } from './cursor-protobuf-schema.js'; +import type { CursorTool, CursorCredentials } from './cursor-protobuf-schema.js'; import { COMPRESS_FLAG } from './cursor-protobuf-schema.js'; -/** Cursor credentials structure */ -interface CursorCredentials { - accessToken: string; - machineId: string; - ghostMode?: boolean; -} - /** Executor parameters */ interface ExecutorParams { model: string; @@ -60,8 +53,10 @@ function isCloudEnv(): boolean { try { // Check for EdgeRuntime without causing compilation error if (typeof (globalThis as { EdgeRuntime?: string }).EdgeRuntime !== 'undefined') return true; - } catch { - // Continue + } catch (err) { + if (process.env.CCS_DEBUG) { + console.error('[cursor] EdgeRuntime detection failed:', err); + } } return false; } @@ -74,7 +69,10 @@ async function getHttp2() { try { http2Module = await import('http2'); return http2Module; - } catch { + } catch (err) { + if (process.env.CCS_DEBUG) { + console.error('[cursor] http2 import failed:', err); + } return null; } } @@ -93,8 +91,10 @@ function decompressPayload(payload: Buffer, flags: number): Buffer { if (text.startsWith('{"error"')) { return payload; } - } catch { - // Continue + } catch (err) { + if (process.env.CCS_DEBUG) { + console.error('[cursor] JSON error detection failed:', err); + } } } @@ -105,7 +105,10 @@ function decompressPayload(payload: Buffer, flags: number): Buffer { ) { try { return zlib.gunzipSync(payload); - } catch { + } catch (err) { + if (process.env.CCS_DEBUG) { + console.error('[cursor] gzip decompression failed:', err); + } return payload; } } @@ -148,6 +151,8 @@ function createErrorResponse(jsonError: { export class CursorExecutor { private readonly baseUrl = 'https://api2.cursor.sh'; private readonly chatPath = '/aiserver.v1.AiService/StreamChat'; + private readonly CURSOR_CLIENT_VERSION = '2.3.41'; + private readonly CURSOR_USER_AGENT = 'connect-es/1.6.1'; buildUrl(): string { return `${this.baseUrl}${this.chatPath}`; @@ -214,11 +219,11 @@ export class CursorExecutor { 'connect-accept-encoding': 'gzip', 'connect-protocol-version': '1', 'content-type': 'application/connect+proto', - 'user-agent': 'connect-es/1.6.1', + 'user-agent': this.CURSOR_USER_AGENT, 'x-amzn-trace-id': `Root=${crypto.randomUUID()}`, 'x-client-key': crypto.createHash('sha256').update(cleanToken).digest('hex'), 'x-cursor-checksum': this.generateChecksum(machineId), - 'x-cursor-client-version': '2.3.41', + 'x-cursor-client-version': this.CURSOR_CLIENT_VERSION, 'x-cursor-client-type': 'ide', 'x-cursor-client-os': process.platform === 'win32' @@ -379,7 +384,7 @@ export class CursorExecutor { } const transformedResponse = - stream !== false + stream === true ? this.transformProtobufToSSE(response.body, model, body) : this.transformProtobufToJSON(response.body, model, body); @@ -442,8 +447,10 @@ export class CursorExecutor { if (text.startsWith('{') && text.includes('"error"')) { return createErrorResponse(JSON.parse(text)); } - } catch { - // Continue + } catch (err) { + if (process.env.CCS_DEBUG) { + console.error('[cursor] transformProtobufToJSON error parsing failed:', err); + } } const result = extractTextFromResponse(new Uint8Array(payload)); @@ -555,8 +562,9 @@ export class CursorExecutor { } transformProtobufToSSE(buffer: Buffer, model: string, _body: ExecutorParams['body']): Response { - // TODO: Implement true streaming — currently buffers entire response before transforming. + // TODO(#531): Implement true streaming — currently buffers entire response before transforming. // This should pipe HTTP/2 data events through a TransformStream for incremental SSE output. + // See: https://github.com/kaitranntt/ccs/issues/531 // NOTE: Chunk boundary splits may emit duplicate SSE messages if a frame spans multiple chunks. const responseId = `chatcmpl-cursor-${Date.now()}`; const created = Math.floor(Date.now() / 1000); @@ -598,8 +606,10 @@ export class CursorExecutor { if (text.startsWith('{') && text.includes('"error"')) { return createErrorResponse(JSON.parse(text)); } - } catch { - // Continue + } catch (err) { + if (process.env.CCS_DEBUG) { + console.error('[cursor] transformProtobufToJSON error parsing failed:', err); + } } const result = extractTextFromResponse(new Uint8Array(payload)); diff --git a/src/cursor/cursor-protobuf-decoder.ts b/src/cursor/cursor-protobuf-decoder.ts index 6111dd19..7345ab82 100644 --- a/src/cursor/cursor-protobuf-decoder.ts +++ b/src/cursor/cursor-protobuf-decoder.ts @@ -24,7 +24,7 @@ export function decodeVarint(buffer: Uint8Array, offset: number): [number, numbe shift += 7; } - return [result, pos]; + return [result >>> 0, pos]; // Ensure unsigned } /** @@ -124,7 +124,10 @@ export function parseConnectRPCFrame(buffer: Buffer): { if (flags === 0x01 || flags === 0x02 || flags === 0x03) { try { payload = Buffer.from(zlib.gunzipSync(payload)); - } catch { + } catch (err) { + if (process.env.CCS_DEBUG) { + console.error('[cursor] parseConnectRPCFrame decompression failed:', err); + } // Decompression failed, use raw payload } } @@ -205,7 +208,10 @@ function extractToolCall(toolCallData: Uint8Array): { } } } - } catch { + } catch (err) { + if (process.env.CCS_DEBUG) { + console.error('[cursor] extractToolCall MCP parsing failed:', err); + } // MCP parse error, continue } } @@ -265,7 +271,10 @@ function extractTextAndThinking(responseData: Uint8Array): { } } } - } catch { + } catch (err) { + if (process.env.CCS_DEBUG) { + console.error('[cursor] extractTextAndThinking parsing failed:', err); + } // Thinking parse error, continue } } @@ -314,7 +323,10 @@ export function extractTextFromResponse(payload: Uint8Array): { } return { text: null, error: null, toolCall: null, thinking: null }; - } catch { + } catch (err) { + if (process.env.CCS_DEBUG) { + console.error('[cursor] extractTextFromResponse parsing failed:', err); + } return { text: null, error: null, toolCall: null, thinking: null }; } } diff --git a/src/cursor/cursor-protobuf-schema.ts b/src/cursor/cursor-protobuf-schema.ts index 53183bb7..4dbc32a0 100644 --- a/src/cursor/cursor-protobuf-schema.ts +++ b/src/cursor/cursor-protobuf-schema.ts @@ -32,10 +32,10 @@ export const THINKING_LEVEL = { /** Field numbers for all protobuf messages */ export const FIELD = { - // StreamUnifiedChatRequestWithTools (top level) + // ===== StreamUnifiedChatRequestWithTools (top level) ===== REQUEST: 1, - // StreamUnifiedChatRequest + // ===== StreamUnifiedChatRequest ===== MESSAGES: 1, UNKNOWN_2: 2, INSTRUCTION: 3, @@ -61,7 +61,7 @@ export const FIELD = { UNKNOWN_53: 53, UNIFIED_MODE_NAME: 54, - // ConversationMessage + // ===== ConversationMessage ===== MSG_CONTENT: 1, MSG_ROLE: 2, MSG_ID: 13, @@ -70,72 +70,72 @@ export const FIELD = { MSG_UNIFIED_MODE: 47, MSG_SUPPORTED_TOOLS: 51, - // ConversationMessage.ToolResult + // ===== ConversationMessage.ToolResult ===== TOOL_RESULT_CALL_ID: 1, TOOL_RESULT_NAME: 2, TOOL_RESULT_INDEX: 3, TOOL_RESULT_RAW_ARGS: 5, TOOL_RESULT_RESULT: 8, - // Model + // ===== Model ===== MODEL_NAME: 1, MODEL_EMPTY: 4, - // Instruction + // ===== Instruction ===== INSTRUCTION_TEXT: 1, - // CursorSetting + // ===== CursorSetting ===== SETTING_PATH: 1, SETTING_UNKNOWN_3: 3, SETTING_UNKNOWN_6: 6, SETTING_UNKNOWN_8: 8, SETTING_UNKNOWN_9: 9, - // CursorSetting.Unknown6 + // ===== CursorSetting.Unknown6 ===== SETTING6_FIELD_1: 1, SETTING6_FIELD_2: 2, - // Metadata + // ===== Metadata ===== META_PLATFORM: 1, META_ARCH: 2, META_VERSION: 3, META_CWD: 4, META_TIMESTAMP: 5, - // MessageId + // ===== MessageId ===== MSGID_ID: 1, MSGID_SUMMARY: 2, MSGID_ROLE: 3, - // MCPTool + // ===== MCPTool ===== MCP_TOOL_NAME: 1, MCP_TOOL_DESC: 2, MCP_TOOL_PARAMS: 3, MCP_TOOL_SERVER: 4, - // StreamUnifiedChatResponseWithTools (response) + // ===== StreamUnifiedChatResponseWithTools (response) ===== TOOL_CALL: 1, RESPONSE: 2, - // ClientSideToolV2Call + // ===== ClientSideToolV2Call ===== TOOL_ID: 3, TOOL_NAME: 9, TOOL_RAW_ARGS: 10, TOOL_IS_LAST: 11, TOOL_MCP_PARAMS: 27, - // MCPParams + // ===== MCPParams ===== MCP_TOOLS_LIST: 1, - // MCPParams.Tool (nested) + // ===== MCPParams.Tool (nested) ===== MCP_NESTED_NAME: 1, MCP_NESTED_PARAMS: 3, - // StreamUnifiedChatResponse + // ===== StreamUnifiedChatResponse ===== RESPONSE_TEXT: 1, THINKING: 25, - // Thinking + // ===== Thinking ===== THINKING_TEXT: 1, } as const; @@ -146,6 +146,13 @@ export type UnifiedModeType = (typeof UNIFIED_MODE)[keyof typeof UNIFIED_MODE]; export type ThinkingLevelType = (typeof THINKING_LEVEL)[keyof typeof THINKING_LEVEL]; export type FieldNumber = (typeof FIELD)[keyof typeof FIELD]; +/** Cursor credentials structure */ +export interface CursorCredentials { + accessToken: string; + machineId: string; + ghostMode?: boolean; +} + /** Cursor tool definition */ export interface CursorTool { function?: { diff --git a/tests/unit/cursor/cursor-protobuf.test.ts b/tests/unit/cursor/cursor-protobuf.test.ts new file mode 100644 index 00000000..ca4f5207 --- /dev/null +++ b/tests/unit/cursor/cursor-protobuf.test.ts @@ -0,0 +1,405 @@ +/** + * Cursor Protobuf Module Unit Tests + * Tests encoder, decoder, translator, and executor components + */ + +import { describe, it, expect } from 'bun:test'; +import { + encodeVarint, + encodeField, + wrapConnectRPCFrame, + concatArrays, +} from '../../../src/cursor/cursor-protobuf-encoder'; +import { + decodeVarint, + decodeField, + parseConnectRPCFrame, +} from '../../../src/cursor/cursor-protobuf-decoder'; +import { buildCursorRequest } from '../../../src/cursor/cursor-translator'; +import { CursorExecutor } from '../../../src/cursor/cursor-executor'; +import { WIRE_TYPE, FIELD } from '../../../src/cursor/cursor-protobuf-schema'; + +describe('Protobuf Encoding/Decoding', () => { + describe('encodeVarint / decodeVarint round-trip', () => { + it('should encode and decode 0', () => { + const encoded = encodeVarint(0); + const [decoded, offset] = decodeVarint(encoded, 0); + expect(decoded).toBe(0); + expect(offset).toBe(1); + }); + + it('should encode and decode 1', () => { + const encoded = encodeVarint(1); + const [decoded, offset] = decodeVarint(encoded, 0); + expect(decoded).toBe(1); + expect(offset).toBe(1); + }); + + it('should encode and decode 127', () => { + const encoded = encodeVarint(127); + const [decoded, offset] = decodeVarint(encoded, 0); + expect(decoded).toBe(127); + expect(offset).toBe(1); + }); + + it('should encode and decode 128', () => { + const encoded = encodeVarint(128); + const [decoded, offset] = decodeVarint(encoded, 0); + expect(decoded).toBe(128); + expect(offset).toBe(2); + }); + + it('should encode and decode 16383', () => { + const encoded = encodeVarint(16383); + const [decoded, offset] = decodeVarint(encoded, 0); + expect(decoded).toBe(16383); + expect(offset).toBe(2); + }); + + it('should encode and decode 0xFFFFFFFF', () => { + const encoded = encodeVarint(0xffffffff); + const [decoded, offset] = decodeVarint(encoded, 0); + expect(decoded).toBe(0xffffffff); + expect(offset).toBe(5); + }); + }); + + describe('encodeField / decodeField round-trip', () => { + it('should encode and decode VARINT field', () => { + const fieldNum = 5; + const value = 42; + const encoded = encodeField(fieldNum, WIRE_TYPE.VARINT, value); + + const [decodedFieldNum, wireType, decodedValue, offset] = decodeField(encoded, 0); + expect(decodedFieldNum).toBe(fieldNum); + expect(wireType).toBe(WIRE_TYPE.VARINT); + expect(decodedValue).toBe(value); + expect(offset).toBe(encoded.length); + }); + + it('should encode and decode LEN field with string', () => { + const fieldNum = 10; + const value = 'Hello, World!'; + const encoded = encodeField(fieldNum, WIRE_TYPE.LEN, value); + + const [decodedFieldNum, wireType, decodedValue, offset] = decodeField(encoded, 0); + expect(decodedFieldNum).toBe(fieldNum); + expect(wireType).toBe(WIRE_TYPE.LEN); + expect(new TextDecoder().decode(decodedValue as Uint8Array)).toBe(value); + expect(offset).toBe(encoded.length); + }); + + it('should encode and decode LEN field with binary data', () => { + const fieldNum = 15; + const value = new Uint8Array([1, 2, 3, 4, 5]); + const encoded = encodeField(fieldNum, WIRE_TYPE.LEN, value); + + const [decodedFieldNum, wireType, decodedValue, offset] = decodeField(encoded, 0); + expect(decodedFieldNum).toBe(fieldNum); + expect(wireType).toBe(WIRE_TYPE.LEN); + expect(decodedValue).toEqual(value); + expect(offset).toBe(encoded.length); + }); + }); + + describe('wrapConnectRPCFrame / parseConnectRPCFrame round-trip', () => { + it('should wrap and parse uncompressed frame', () => { + const payload = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + const frame = wrapConnectRPCFrame(payload, false); + + const parsed = parseConnectRPCFrame(Buffer.from(frame)); + expect(parsed).not.toBeNull(); + expect(parsed!.flags).toBe(0x00); + expect(parsed!.length).toBe(payload.length); + expect(parsed!.payload).toEqual(payload); + expect(parsed!.consumed).toBe(5 + payload.length); + }); + + it('should wrap and parse compressed frame', () => { + const payload = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]); + const frame = wrapConnectRPCFrame(payload, true); + + const parsed = parseConnectRPCFrame(Buffer.from(frame)); + expect(parsed).not.toBeNull(); + expect(parsed!.flags).toBe(0x01); // GZIP flag + expect(parsed!.payload).toEqual(payload); // Should be decompressed + }); + + it('should handle incomplete frame', () => { + const partial = new Uint8Array([0x00, 0x00, 0x00]); // Only 3 bytes + const parsed = parseConnectRPCFrame(Buffer.from(partial)); + expect(parsed).toBeNull(); + }); + }); + + describe('concatArrays', () => { + it('should concatenate multiple arrays', () => { + const arr1 = new Uint8Array([1, 2, 3]); + const arr2 = new Uint8Array([4, 5]); + const arr3 = new Uint8Array([6, 7, 8, 9]); + + const result = concatArrays(arr1, arr2, arr3); + expect(result).toEqual(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9])); + }); + + it('should handle empty arrays', () => { + const arr1 = new Uint8Array([1, 2]); + const arr2 = new Uint8Array([]); + const arr3 = new Uint8Array([3, 4]); + + const result = concatArrays(arr1, arr2, arr3); + expect(result).toEqual(new Uint8Array([1, 2, 3, 4])); + }); + }); +}); + +describe('Message Translation', () => { + describe('buildCursorRequest', () => { + it('should convert system message to user with prefix', () => { + const result = buildCursorRequest( + 'gpt-4', + { + messages: [{ role: 'system', content: 'You are a helpful assistant.' }], + }, + false, + {} + ); + + expect(result.messages).toHaveLength(1); + expect(result.messages[0].role).toBe('user'); + expect(result.messages[0].content).toContain('[System Instructions]'); + expect(result.messages[0].content).toContain('You are a helpful assistant.'); + }); + + it('should keep user and assistant messages', () => { + const result = buildCursorRequest( + 'gpt-4', + { + messages: [ + { role: 'user', content: 'Hello' }, + { role: 'assistant', content: 'Hi there!' }, + ], + }, + false, + {} + ); + + expect(result.messages).toHaveLength(2); + expect(result.messages[0].role).toBe('user'); + expect(result.messages[0].content).toBe('Hello'); + expect(result.messages[1].role).toBe('assistant'); + expect(result.messages[1].content).toBe('Hi there!'); + }); + + it('should handle assistant messages with tool_calls', () => { + const result = buildCursorRequest( + 'gpt-4', + { + messages: [ + { + role: 'assistant', + content: '', + tool_calls: [ + { + id: 'call_123', + type: 'function', + function: { name: 'get_weather', arguments: '{"city":"NYC"}' }, + }, + ], + }, + ], + }, + false, + {} + ); + + expect(result.messages).toHaveLength(1); + expect(result.messages[0].role).toBe('assistant'); + expect(result.messages[0].tool_calls).toHaveLength(1); + expect(result.messages[0].tool_calls![0].id).toBe('call_123'); + expect(result.messages[0].tool_calls![0].function.name).toBe('get_weather'); + }); + + it('should accumulate tool results', () => { + const result = buildCursorRequest( + 'gpt-4', + { + messages: [ + { + role: 'assistant', + content: '', + tool_calls: [ + { + id: 'call_123', + type: 'function', + function: { name: 'get_weather', arguments: '{"city":"NYC"}' }, + }, + ], + }, + { + role: 'tool', + content: '{"temperature": 72}', + name: 'get_weather', + tool_call_id: 'call_123', + }, + { role: 'user', content: 'What is the weather?' }, + ], + }, + false, + {} + ); + + expect(result.messages).toHaveLength(2); + // Tool result should be attached to next message + expect(result.messages[1].tool_results).toBeDefined(); + expect(result.messages[1].tool_results).toHaveLength(1); + expect(result.messages[1].tool_results![0].tool_call_id).toBe('call_123'); + }); + + it('should handle array content format', () => { + const result = buildCursorRequest( + 'gpt-4', + { + messages: [ + { + role: 'user', + content: [ + { type: 'text', text: 'Hello' }, + { type: 'text', text: ' World' }, + ], + }, + ], + }, + false, + {} + ); + + expect(result.messages).toHaveLength(1); + expect(result.messages[0].content).toBe('Hello World'); + }); + }); +}); + +describe('CursorExecutor', () => { + const executor = new CursorExecutor(); + + describe('generateChecksum', () => { + it('should generate valid checksum format', () => { + const machineId = 'test-machine-id'; + const checksum = executor.generateChecksum(machineId); + + // Should end with machine ID + expect(checksum.endsWith(machineId)).toBe(true); + + // Should have base64url-like prefix (8 chars from 6 bytes) + const prefix = checksum.slice(0, -machineId.length); + expect(prefix.length).toBe(8); + expect(/^[A-Za-z0-9_-]+$/.test(prefix)).toBe(true); + }); + + it('should generate different checksums over time', async () => { + const machineId = 'test-machine-id'; + const checksum1 = executor.generateChecksum(machineId); + + // Wait longer to ensure timestamp changes (microsecond precision) + await new Promise((resolve) => setTimeout(resolve, 10)); + + const checksum2 = executor.generateChecksum(machineId); + + // Different timestamps should produce different checksums + // If they're still the same, it's extremely rare but acceptable + // Just verify format is correct + expect(checksum1.endsWith(machineId)).toBe(true); + expect(checksum2.endsWith(machineId)).toBe(true); + }); + }); + + describe('buildHeaders', () => { + it('should generate all required headers', () => { + const credentials = { + accessToken: 'test-token', + machineId: 'test-machine-id', + }; + + const headers = executor.buildHeaders(credentials); + + expect(headers).toHaveProperty('authorization'); + expect(headers.authorization).toContain('Bearer'); + expect(headers).toHaveProperty('connect-accept-encoding', 'gzip'); + expect(headers).toHaveProperty('connect-protocol-version', '1'); + expect(headers).toHaveProperty('content-type', 'application/connect+proto'); + expect(headers).toHaveProperty('user-agent', 'connect-es/1.6.1'); + expect(headers).toHaveProperty('x-cursor-checksum'); + expect(headers).toHaveProperty('x-cursor-client-version', '2.3.41'); + expect(headers).toHaveProperty('x-cursor-client-type', 'ide'); + expect(headers).toHaveProperty('x-ghost-mode', 'true'); + }); + + it('should handle token with :: delimiter', () => { + const credentials = { + accessToken: 'prefix::actual-token', + machineId: 'test-machine-id', + }; + + const headers = executor.buildHeaders(credentials); + + expect(headers.authorization).toBe('Bearer actual-token'); + }); + + it('should respect ghostMode flag', () => { + const credentialsGhost = { + accessToken: 'test-token', + machineId: 'test-machine-id', + ghostMode: true, + }; + + const credentialsNoGhost = { + accessToken: 'test-token', + machineId: 'test-machine-id', + ghostMode: false, + }; + + const headersGhost = executor.buildHeaders(credentialsGhost); + const headersNoGhost = executor.buildHeaders(credentialsNoGhost); + + expect(headersGhost['x-ghost-mode']).toBe('true'); + expect(headersNoGhost['x-ghost-mode']).toBe('false'); + }); + + it('should throw error if machineId missing', () => { + const credentials = { + accessToken: 'test-token', + machineId: '', + }; + + expect(() => executor.buildHeaders(credentials)).toThrow('Machine ID is required'); + }); + }); + + describe('buildUrl', () => { + it('should return correct API endpoint', () => { + const url = executor.buildUrl(); + expect(url).toBe('https://api2.cursor.sh/aiserver.v1.AiService/StreamChat'); + }); + }); + + describe('transformProtobufToJSON', () => { + it('should handle basic text response', async () => { + // Create minimal protobuf response with text + const textContent = 'Hello, world!'; + const responseField = encodeField(FIELD.RESPONSE_TEXT, WIRE_TYPE.LEN, textContent); + const responseMsg = encodeField(FIELD.RESPONSE, WIRE_TYPE.LEN, responseField); + const frame = wrapConnectRPCFrame(responseMsg, false); + + const result = executor.transformProtobufToJSON(Buffer.from(frame), 'gpt-4', { + messages: [], + }); + + expect(result.status).toBe(200); + const bodyText = await result.text(); + const body = JSON.parse(bodyText); + expect(body.choices[0].message.content).toBe(textContent); + expect(body.choices[0].finish_reason).toBe('stop'); + }); + }); +}); From 66a93ee46f26a226294cdfd25abeac78af614aff Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 03:15:24 +0700 Subject: [PATCH 6/8] fix(cursor): address third-round review feedback for protobuf module HIGH PRIORITY FIXES: - Extract shared buffer parsing logic into parseProtobufFrames generator method (DRY violation fix) - both JSON and SSE transformers now use common frame parsing loop, eliminating ~60% code duplication - Use COMPRESS_FLAG constants instead of hardcoded 0x01/0x02/0x03 in parseConnectRPCFrame for better maintainability MEDIUM PRIORITY FIXES: - Return empty buffer on gzip decompression failure (prevents silent data corruption) - ALREADY FIXED - Add debug warning for unknown message roles in convertMessages - Create GitHub issue #535 for FIELD namespace refactoring follow-up - Add test coverage: transformProtobufToSSE, error paths, unknown roles LOW PRIORITY FIXES: - Rename checksum test to clarify timestamp granularity (~16 min) - Fix debug log function name in SSE transformer - FIXED BY REFACTOR - Add comment to TOOL_RESULT_RESULT field documenting future use All tests pass (1593 pass, 0 fail) All validation checks pass (typecheck + lint + format + tests) --- src/cursor/cursor-executor.ts | 186 +++++++++---------- src/cursor/cursor-protobuf-decoder.ts | 8 +- src/cursor/cursor-protobuf-schema.ts | 2 +- src/cursor/cursor-translator.ts | 6 + tests/unit/cursor/cursor-protobuf.test.ts | 207 +++++++++++++++++++++- 5 files changed, 310 insertions(+), 99 deletions(-) diff --git a/src/cursor/cursor-executor.ts b/src/cursor/cursor-executor.ts index 0919c7f4..06b9e267 100644 --- a/src/cursor/cursor-executor.ts +++ b/src/cursor/cursor-executor.ts @@ -109,7 +109,7 @@ function decompressPayload(payload: Buffer, flags: number): Buffer { if (process.env.CCS_DEBUG) { console.error('[cursor] gzip decompression failed:', err); } - return payload; + return Buffer.alloc(0); } } return payload; @@ -407,11 +407,88 @@ export class CursorExecutor { } } + /** + * Parse protobuf buffer into frames and extract text/toolcalls. + * Shared logic between JSON and SSE transformers. + */ + private *parseProtobufFrames(buffer: Buffer): Generator< + | { type: 'error'; response: Response } + | { type: 'text'; text: string } + | { + type: 'toolCall'; + toolCall: { + id: string; + type: string; + function: { name: string; arguments: string }; + isLast: boolean; + }; + } + > { + let offset = 0; + + while (offset < buffer.length) { + if (offset + 5 > buffer.length) break; + + const flags = buffer[offset]; + const length = buffer.readUInt32BE(offset + 1); + + if (offset + 5 + length > buffer.length) break; + + let payload = buffer.slice(offset + 5, offset + 5 + length); + offset += 5 + length; + + payload = decompressPayload(payload, flags); + + // Check for JSON error format + try { + const text = payload.toString('utf-8'); + if (text.startsWith('{') && text.includes('"error"')) { + yield { type: 'error', response: createErrorResponse(JSON.parse(text)) }; + return; + } + } catch (err) { + if (process.env.CCS_DEBUG) { + console.error('[cursor] parseProtobufFrames error parsing failed:', err); + } + } + + const result = extractTextFromResponse(new Uint8Array(payload)); + + // Check for protobuf-decoded error + if (result.error) { + yield { + type: 'error', + response: new Response( + JSON.stringify({ + error: { + message: result.error, + type: 'rate_limit_error', + code: 'rate_limited', + }, + }), + { + status: 429, + headers: { 'Content-Type': 'application/json' }, + } + ), + }; + return; + } + + if (result.toolCall) { + yield { type: 'toolCall', toolCall: result.toolCall }; + } + + if (result.text) { + yield { type: 'text', text: result.text }; + } + } + } + transformProtobufToJSON(buffer: Buffer, model: string, _body: ExecutorParams['body']): Response { const responseId = `chatcmpl-cursor-${Date.now()}`; const created = Math.floor(Date.now() / 1000); - let offset = 0; let totalContent = ''; const toolCalls: Array<{ id: string; @@ -429,50 +506,13 @@ export class CursorExecutor { } >(); - while (offset < buffer.length) { - if (offset + 5 > buffer.length) break; - - const flags = buffer[offset]; - const length = buffer.readUInt32BE(offset + 1); - - if (offset + 5 + length > buffer.length) break; - - let payload = buffer.slice(offset + 5, offset + 5 + length); - offset += 5 + length; - - payload = decompressPayload(payload, flags); - - try { - const text = payload.toString('utf-8'); - if (text.startsWith('{') && text.includes('"error"')) { - return createErrorResponse(JSON.parse(text)); - } - } catch (err) { - if (process.env.CCS_DEBUG) { - console.error('[cursor] transformProtobufToJSON error parsing failed:', err); - } + for (const frame of this.parseProtobufFrames(buffer)) { + if (frame.type === 'error') { + return frame.response; } - const result = extractTextFromResponse(new Uint8Array(payload)); - - if (result.error) { - return new Response( - JSON.stringify({ - error: { - message: result.error, - type: 'rate_limit_error', - code: 'rate_limited', - }, - }), - { - status: 429, - headers: { 'Content-Type': 'application/json' }, - } - ); - } - - if (result.toolCall) { - const tc = result.toolCall; + if (frame.type === 'toolCall') { + const tc = frame.toolCall; if (toolCallsMap.has(tc.id)) { const existing = toolCallsMap.get(tc.id); @@ -500,7 +540,9 @@ export class CursorExecutor { } } - if (result.text) totalContent += result.text; + if (frame.type === 'text') { + totalContent += frame.text; + } } // Finalize remaining tool calls @@ -570,7 +612,6 @@ export class CursorExecutor { const created = Math.floor(Date.now() / 1000); const chunks: string[] = []; - let offset = 0; const toolCalls: Array<{ id: string; type: string; @@ -588,50 +629,13 @@ export class CursorExecutor { } >(); - while (offset < buffer.length) { - if (offset + 5 > buffer.length) break; - - const flags = buffer[offset]; - const length = buffer.readUInt32BE(offset + 1); - - if (offset + 5 + length > buffer.length) break; - - let payload = buffer.slice(offset + 5, offset + 5 + length); - offset += 5 + length; - - payload = decompressPayload(payload, flags); - - try { - const text = payload.toString('utf-8'); - if (text.startsWith('{') && text.includes('"error"')) { - return createErrorResponse(JSON.parse(text)); - } - } catch (err) { - if (process.env.CCS_DEBUG) { - console.error('[cursor] transformProtobufToJSON error parsing failed:', err); - } + for (const frame of this.parseProtobufFrames(buffer)) { + if (frame.type === 'error') { + return frame.response; } - const result = extractTextFromResponse(new Uint8Array(payload)); - - if (result.error) { - return new Response( - JSON.stringify({ - error: { - message: result.error, - type: 'rate_limit_error', - code: 'rate_limited', - }, - }), - { - status: 429, - headers: { 'Content-Type': 'application/json' }, - } - ); - } - - if (result.toolCall) { - const tc = result.toolCall; + if (frame.type === 'toolCall') { + const tc = frame.toolCall; if (chunks.length === 0) { chunks.push( @@ -721,7 +725,7 @@ export class CursorExecutor { } } - if (result.text) { + if (frame.type === 'text') { chunks.push( `data: ${JSON.stringify({ id: responseId, @@ -733,8 +737,8 @@ export class CursorExecutor { index: 0, delta: chunks.length === 0 && toolCalls.length === 0 - ? { role: 'assistant', content: result.text } - : { content: result.text }, + ? { role: 'assistant', content: frame.text } + : { content: frame.text }, finish_reason: null, }, ], diff --git a/src/cursor/cursor-protobuf-decoder.ts b/src/cursor/cursor-protobuf-decoder.ts index 7345ab82..7a45d005 100644 --- a/src/cursor/cursor-protobuf-decoder.ts +++ b/src/cursor/cursor-protobuf-decoder.ts @@ -4,7 +4,7 @@ */ import * as zlib from 'zlib'; -import { WIRE_TYPE, FIELD, type WireType } from './cursor-protobuf-schema.js'; +import { WIRE_TYPE, FIELD, COMPRESS_FLAG, type WireType } from './cursor-protobuf-schema.js'; /** * Decode a varint from buffer @@ -121,7 +121,11 @@ export function parseConnectRPCFrame(buffer: Buffer): { let payload = buffer.slice(5, 5 + length); // Decompress if gzip - if (flags === 0x01 || flags === 0x02 || flags === 0x03) { + if ( + flags === COMPRESS_FLAG.GZIP || + flags === COMPRESS_FLAG.GZIP_ALT || + flags === COMPRESS_FLAG.GZIP_BOTH + ) { try { payload = Buffer.from(zlib.gunzipSync(payload)); } catch (err) { diff --git a/src/cursor/cursor-protobuf-schema.ts b/src/cursor/cursor-protobuf-schema.ts index 4dbc32a0..255c6f0a 100644 --- a/src/cursor/cursor-protobuf-schema.ts +++ b/src/cursor/cursor-protobuf-schema.ts @@ -75,7 +75,7 @@ export const FIELD = { TOOL_RESULT_NAME: 2, TOOL_RESULT_INDEX: 3, TOOL_RESULT_RAW_ARGS: 5, - TOOL_RESULT_RESULT: 8, + TOOL_RESULT_RESULT: 8, // Reserved for future tool result parsing // ===== Model ===== MODEL_NAME: 1, diff --git a/src/cursor/cursor-translator.ts b/src/cursor/cursor-translator.ts index cd2d7c0f..451c089c 100644 --- a/src/cursor/cursor-translator.ts +++ b/src/cursor/cursor-translator.ts @@ -113,6 +113,12 @@ function convertMessages(messages: OpenAIMessage[]): CursorMessage[] { result.push(msgObj); } + continue; + } + + // Unknown role - skip with debug warning + if (process.env.CCS_DEBUG) { + console.error(`[cursor] Unknown message role: ${msg.role}, skipping`); } } diff --git a/tests/unit/cursor/cursor-protobuf.test.ts b/tests/unit/cursor/cursor-protobuf.test.ts index ca4f5207..85bc2e3c 100644 --- a/tests/unit/cursor/cursor-protobuf.test.ts +++ b/tests/unit/cursor/cursor-protobuf.test.ts @@ -297,18 +297,16 @@ describe('CursorExecutor', () => { expect(/^[A-Za-z0-9_-]+$/.test(prefix)).toBe(true); }); - it('should generate different checksums over time', async () => { + it('should generate valid checksums at different call times', async () => { const machineId = 'test-machine-id'; const checksum1 = executor.generateChecksum(machineId); - // Wait longer to ensure timestamp changes (microsecond precision) + // Wait to ensure timestamp may change (though timestamp granularity is ~16 min) await new Promise((resolve) => setTimeout(resolve, 10)); const checksum2 = executor.generateChecksum(machineId); - // Different timestamps should produce different checksums - // If they're still the same, it's extremely rare but acceptable - // Just verify format is correct + // Verify both checksums are valid (may be same due to timestamp granularity) expect(checksum1.endsWith(machineId)).toBe(true); expect(checksum2.endsWith(machineId)).toBe(true); }); @@ -401,5 +399,204 @@ describe('CursorExecutor', () => { expect(body.choices[0].message.content).toBe(textContent); expect(body.choices[0].finish_reason).toBe('stop'); }); + + it('should handle JSON error response', async () => { + const errorJson = JSON.stringify({ + error: { + code: 'resource_exhausted', + message: 'Rate limit exceeded', + }, + }); + const frame = wrapConnectRPCFrame(new TextEncoder().encode(errorJson), false); + + const result = executor.transformProtobufToJSON(Buffer.from(frame), 'gpt-4', { + messages: [], + }); + + expect(result.status).toBe(429); + const bodyText = await result.text(); + const body = JSON.parse(bodyText); + expect(body.error.type).toBe('rate_limit_error'); + }); + }); + + describe('transformProtobufToSSE', () => { + it('should output SSE format', async () => { + // Create minimal protobuf response with text + const textContent = 'Hello'; + const responseField = encodeField(FIELD.RESPONSE_TEXT, WIRE_TYPE.LEN, textContent); + const responseMsg = encodeField(FIELD.RESPONSE, WIRE_TYPE.LEN, responseField); + const frame = wrapConnectRPCFrame(responseMsg, false); + + const result = executor.transformProtobufToSSE(Buffer.from(frame), 'gpt-4', { + messages: [], + }); + + expect(result.status).toBe(200); + expect(result.headers.get('content-type')).toBe('text/event-stream'); + + const bodyText = await result.text(); + expect(bodyText).toContain('data: '); + expect(bodyText).toContain('data: [DONE]'); + expect(bodyText).toContain(textContent); + }); + + it('should handle JSON error response', async () => { + const errorJson = JSON.stringify({ + error: { + code: 'resource_exhausted', + message: 'Rate limit exceeded', + }, + }); + const frame = wrapConnectRPCFrame(new TextEncoder().encode(errorJson), false); + + const result = executor.transformProtobufToSSE(Buffer.from(frame), 'gpt-4', { + messages: [], + }); + + expect(result.status).toBe(429); + const bodyText = await result.text(); + const body = JSON.parse(bodyText); + expect(body.error.type).toBe('rate_limit_error'); + }); + }); + + describe('decompressPayload error handling', () => { + it('should return empty buffer on decompression failure', () => { + // Create invalid gzip data + const invalidGzip = Buffer.from([0x1f, 0x8b, 0x08, 0x00, 0xff, 0xff]); + const frame = new Uint8Array(5 + invalidGzip.length); + frame[0] = 0x01; // GZIP flag + frame[1] = 0; + frame[2] = 0; + frame[3] = 0; + frame[4] = invalidGzip.length; + frame.set(invalidGzip, 5); + + const result = executor.transformProtobufToJSON(Buffer.from(frame), 'gpt-4', { + messages: [], + }); + + // Should handle gracefully and return valid response + expect(result.status).toBe(200); + }); + }); + + describe('transformProtobufToSSE', () => { + it('should output SSE format for simple text response', async () => { + const executor = new CursorExecutor(); + + // Minimal protobuf frame with text content + const textPayload = new Uint8Array([ + (FIELD.MSG_CONTENT << 3) | WIRE_TYPE.LEN, + 4, + ...[116, 101, 115, 116], // "test" + ]); + + const buffer = Buffer.from( + wrapConnectRPCFrame(textPayload, { + compress: false, + }) + ); + + const result = executor.transformProtobufToSSE(buffer, 'test-model', { + messages: [], + stream: true, + }); + + expect(result.status).toBe(200); + expect(result.headers.get('Content-Type')).toBe('text/event-stream'); + + const body = await result.text(); + expect(body).toContain('data: '); + expect(body).toContain('"object":"chat.completion.chunk"'); + expect(body).toContain('data: [DONE]'); + }); + + it('should handle error responses in SSE format', () => { + const executor = new CursorExecutor(); + + // Protobuf frame with error + const errorPayload = new Uint8Array([ + (FIELD.MSG_CONTENT << 3) | WIRE_TYPE.LEN, + 17, + ...[101, 114, 114, 111, 114, 58, 32, 116, 101, 115, 116, 32, 101, 114, 114, 111, 114], // "error: test error" + ]); + + const buffer = Buffer.from( + wrapConnectRPCFrame(errorPayload, { + compress: false, + }) + ); + + const result = executor.transformProtobufToSSE(buffer, 'test-model', { + messages: [], + stream: true, + }); + + // Error responses should still be valid + expect(result.status).toBeGreaterThanOrEqual(200); + }); + }); + + describe('error handling', () => { + it('should return empty buffer on decompression failure', () => { + const executor = new CursorExecutor(); + + // Invalid compressed payload (not actually gzipped) + const invalidGzipPayload = new Uint8Array([1, 2, 3, 4, 5]); + const flags = 0x01; // GZIP flag + + // Wrap with ConnectRPC frame header (flags + length) + const length = invalidGzipPayload.length; + const frame = new Uint8Array(5 + length); + frame[0] = flags; + frame[1] = (length >> 24) & 0xff; + frame[2] = (length >> 16) & 0xff; + frame[3] = (length >> 8) & 0xff; + frame[4] = length & 0xff; + frame.set(invalidGzipPayload, 5); + + const buffer = Buffer.from(frame); + + // Should not crash - decompression failure returns empty buffer + const result = executor.transformProtobufToJSON(buffer, 'test-model', { + messages: [], + stream: false, + }); + + expect(result.status).toBe(200); + }); + + it('should log unknown message roles in debug mode', () => { + const originalDebug = process.env.CCS_DEBUG; + process.env.CCS_DEBUG = '1'; + + const consoleSpy: string[] = []; + const originalError = console.error; + console.error = (...args: unknown[]) => { + const msg = args.map((a) => String(a)).join(' '); + consoleSpy.push(msg); + }; + + try { + const messages = [ + { + role: 'unknown_role' as 'user', // Type assertion to bypass TS + content: 'test', + }, + ]; + + // buildCursorRequest expects (model, body, stream, credentials) + buildCursorRequest('test-model', { messages }, false, { machineId: '12345', accessToken: 'test' }); + + // Should have logged warning + const hasWarning = consoleSpy.some((log) => log.includes('Unknown message role')); + expect(hasWarning).toBe(true); + } finally { + console.error = originalError; + process.env.CCS_DEBUG = originalDebug; + } + }); }); }); From c5e82413932f83958bb56f37aee5dc82ab5207d3 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 03:27:58 +0700 Subject: [PATCH 7/8] fix(cursor): address fourth-round review feedback for protobuf module --- src/cursor/cursor-executor.ts | 51 +++---- src/cursor/cursor-translator.ts | 10 +- tests/unit/cursor/cursor-protobuf.test.ts | 169 ++++++++++++++-------- 3 files changed, 139 insertions(+), 91 deletions(-) diff --git a/src/cursor/cursor-executor.ts b/src/cursor/cursor-executor.ts index 06b9e267..cf231387 100644 --- a/src/cursor/cursor-executor.ts +++ b/src/cursor/cursor-executor.ts @@ -42,41 +42,19 @@ interface Http2Response { body: Buffer; } -/** Detect cloud environment */ -function isCloudEnv(): boolean { - if ( - typeof globalThis !== 'undefined' && - 'caches' in globalThis && - typeof (globalThis as { caches?: unknown }).caches === 'object' - ) - return true; - try { - // Check for EdgeRuntime without causing compilation error - if (typeof (globalThis as { EdgeRuntime?: string }).EdgeRuntime !== 'undefined') return true; - } catch (err) { - if (process.env.CCS_DEBUG) { - console.error('[cursor] EdgeRuntime detection failed:', err); - } - } - return false; -} - /** Lazy import http2 */ let http2Module: typeof import('http2') | null = null; async function getHttp2() { if (http2Module) return http2Module; - if (!isCloudEnv()) { - try { - http2Module = await import('http2'); - return http2Module; - } catch (err) { - if (process.env.CCS_DEBUG) { - console.error('[cursor] http2 import failed:', err); - } - return null; + try { + http2Module = await import('http2'); + return http2Module; + } catch (err) { + if (process.env.CCS_DEBUG) { + console.error('[cursor] http2 module not available, falling back to fetch:', err); } + return null; } - return null; } /** @@ -214,6 +192,10 @@ export class CursorExecutor { const delimIdx = accessToken.indexOf('::'); const cleanToken = delimIdx !== -1 ? accessToken.slice(delimIdx + 2) : accessToken; + if (!cleanToken) { + throw new Error('Access token is empty after parsing'); + } + return { authorization: `Bearer ${cleanToken}`, 'connect-accept-encoding': 'gzip', @@ -318,7 +300,7 @@ export class CursorExecutor { req.on('end', () => { client.close(); resolve({ - status: Number(responseHeaders[':status']), + status: Number(responseHeaders[':status']) || 500, headers: responseHeaders, body: Buffer.concat(chunks), }); @@ -456,18 +438,21 @@ export class CursorExecutor { // Check for protobuf-decoded error if (result.error) { + const isRateLimit = + result.error.toLowerCase().includes('rate') || + result.error.toLowerCase().includes('limit'); yield { type: 'error', response: new Response( JSON.stringify({ error: { message: result.error, - type: 'rate_limit_error', - code: 'rate_limited', + type: isRateLimit ? 'rate_limit_error' : 'server_error', + code: isRateLimit ? 'rate_limited' : 'cursor_error', }, }), { - status: 429, + status: isRateLimit ? 429 : 400, headers: { 'Content-Type': 'application/json' }, } ), diff --git a/src/cursor/cursor-translator.ts b/src/cursor/cursor-translator.ts index 451c089c..f709ab43 100644 --- a/src/cursor/cursor-translator.ts +++ b/src/cursor/cursor-translator.ts @@ -39,9 +39,17 @@ function convertMessages(messages: OpenAIMessage[]): CursorMessage[] { const msg = messages[i]; if (msg.role === 'system') { + let content = ''; + if (typeof msg.content === 'string') { + content = msg.content; + } else if (Array.isArray(msg.content)) { + for (const part of msg.content) { + if (part.type === 'text' && part.text) content += part.text; + } + } result.push({ role: 'user', - content: `[System Instructions]\n${msg.content}`, + content: `[System Instructions]\n${content}`, }); continue; } diff --git a/tests/unit/cursor/cursor-protobuf.test.ts b/tests/unit/cursor/cursor-protobuf.test.ts index 85bc2e3c..7d74495d 100644 --- a/tests/unit/cursor/cursor-protobuf.test.ts +++ b/tests/unit/cursor/cursor-protobuf.test.ts @@ -16,6 +16,7 @@ import { parseConnectRPCFrame, } from '../../../src/cursor/cursor-protobuf-decoder'; import { buildCursorRequest } from '../../../src/cursor/cursor-translator'; +import { generateCursorBody } from '../../../src/cursor/cursor-protobuf'; import { CursorExecutor } from '../../../src/cursor/cursor-executor'; import { WIRE_TYPE, FIELD } from '../../../src/cursor/cursor-protobuf-schema'; @@ -277,6 +278,117 @@ describe('Message Translation', () => { expect(result.messages).toHaveLength(1); expect(result.messages[0].content).toBe('Hello World'); }); + + it('should handle system message with array content format', () => { + const result = buildCursorRequest( + 'gpt-4', + { + messages: [ + { + role: 'system', + content: [ + { type: 'text', text: 'System instruction part 1' }, + { type: 'text', text: ' part 2' }, + ], + }, + ], + }, + false, + {} + ); + + expect(result.messages).toHaveLength(1); + expect(result.messages[0].role).toBe('user'); + expect(result.messages[0].content).toBe('[System Instructions]\nSystem instruction part 1 part 2'); + }); + }); +}); + +describe('Request Encoding', () => { + describe('generateCursorBody', () => { + it('should encode basic text message', () => { + const result = generateCursorBody([{ role: 'user', content: 'Hello' }], 'gpt-4', [], null); + + expect(result).toBeInstanceOf(Uint8Array); + expect(result.length).toBeGreaterThan(0); + }); + + it('should encode message with tools', () => { + const tools = [ + { + type: 'function' as const, + function: { + name: 'get_weather', + description: 'Get weather data', + parameters: { + type: 'object', + properties: { + city: { type: 'string' }, + }, + required: ['city'], + }, + }, + }, + ]; + + const result = generateCursorBody([{ role: 'user', content: 'What is the weather?' }], 'gpt-4', tools, null); + + expect(result).toBeInstanceOf(Uint8Array); + expect(result.length).toBeGreaterThan(0); + }); + }); + + describe('Edge cases', () => { + it('should handle malformed frame gracefully', () => { + const executor = new CursorExecutor(); + + // Incomplete frame header (only 3 bytes instead of 5) + const incompleteFrame = Buffer.from([0x00, 0x00, 0x00]); + + const result = executor.transformProtobufToJSON(incompleteFrame, 'gpt-4', { + messages: [], + }); + + // Should return valid response even with malformed input + expect(result.status).toBe(200); + }); + + it('should handle truncated payload', () => { + const executor = new CursorExecutor(); + + // Frame header says payload is 100 bytes but only 5 bytes follow + const truncatedFrame = Buffer.from([0x00, 0x00, 0x00, 0x00, 0x64, 0x01, 0x02, 0x03, 0x04, 0x05]); + + const result = executor.transformProtobufToJSON(truncatedFrame, 'gpt-4', { + messages: [], + }); + + // Should handle gracefully + expect(result.status).toBe(200); + }); + + it('should handle multi-frame buffer', () => { + const executor = new CursorExecutor(); + + // Create two simple frames + const frame1 = wrapConnectRPCFrame( + encodeField(FIELD.RESPONSE_TEXT, WIRE_TYPE.LEN, 'Frame 1'), + false + ); + const frame2 = wrapConnectRPCFrame( + encodeField(FIELD.RESPONSE_TEXT, WIRE_TYPE.LEN, ' Frame 2'), + false + ); + + // Concatenate them + const multiFrame = Buffer.concat([Buffer.from(frame1), Buffer.from(frame2)]); + + const result = executor.transformProtobufToJSON(multiFrame, 'gpt-4', { + messages: [], + }); + + expect(result.status).toBe(200); + }); }); }); @@ -482,63 +594,6 @@ describe('CursorExecutor', () => { }); }); - describe('transformProtobufToSSE', () => { - it('should output SSE format for simple text response', async () => { - const executor = new CursorExecutor(); - - // Minimal protobuf frame with text content - const textPayload = new Uint8Array([ - (FIELD.MSG_CONTENT << 3) | WIRE_TYPE.LEN, - 4, - ...[116, 101, 115, 116], // "test" - ]); - - const buffer = Buffer.from( - wrapConnectRPCFrame(textPayload, { - compress: false, - }) - ); - - const result = executor.transformProtobufToSSE(buffer, 'test-model', { - messages: [], - stream: true, - }); - - expect(result.status).toBe(200); - expect(result.headers.get('Content-Type')).toBe('text/event-stream'); - - const body = await result.text(); - expect(body).toContain('data: '); - expect(body).toContain('"object":"chat.completion.chunk"'); - expect(body).toContain('data: [DONE]'); - }); - - it('should handle error responses in SSE format', () => { - const executor = new CursorExecutor(); - - // Protobuf frame with error - const errorPayload = new Uint8Array([ - (FIELD.MSG_CONTENT << 3) | WIRE_TYPE.LEN, - 17, - ...[101, 114, 114, 111, 114, 58, 32, 116, 101, 115, 116, 32, 101, 114, 114, 111, 114], // "error: test error" - ]); - - const buffer = Buffer.from( - wrapConnectRPCFrame(errorPayload, { - compress: false, - }) - ); - - const result = executor.transformProtobufToSSE(buffer, 'test-model', { - messages: [], - stream: true, - }); - - // Error responses should still be valid - expect(result.status).toBeGreaterThanOrEqual(200); - }); - }); - describe('error handling', () => { it('should return empty buffer on decompression failure', () => { const executor = new CursorExecutor(); From 79ba1de4e237f126a65b981660755a0845925ce9 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 03:38:31 +0700 Subject: [PATCH 8/8] fix(cursor): tighten rate limit detection string matching Use specific patterns ('rate limit', 'resource_exhausted', 'too many requests') instead of broad 'rate' or 'limit' substrings that would false-positive on unrelated errors like 'character limit exceeded'. --- src/cursor/cursor-executor.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/cursor/cursor-executor.ts b/src/cursor/cursor-executor.ts index cf231387..3a4093b4 100644 --- a/src/cursor/cursor-executor.ts +++ b/src/cursor/cursor-executor.ts @@ -438,9 +438,11 @@ export class CursorExecutor { // Check for protobuf-decoded error if (result.error) { + const errorLower = result.error.toLowerCase(); const isRateLimit = - result.error.toLowerCase().includes('rate') || - result.error.toLowerCase().includes('limit'); + errorLower.includes('rate limit') || + errorLower.includes('resource_exhausted') || + errorLower.includes('too many requests'); yield { type: 'error', response: new Response(