From 75095bde1b7f8044fbd96ec409257b7e4dea213e Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Wed, 11 Feb 2026 18:01:20 +0700 Subject: [PATCH 01/17] chore: merge cursor core (#518) and auth (#519) as base for daemon+CLI --- src/cursor/cursor-auth.ts | 246 ++++++++ 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 +++++ src/cursor/types.ts | 141 +++++ 8 files changed, 2298 insertions(+) create mode 100644 src/cursor/cursor-auth.ts 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 create mode 100644 src/cursor/types.ts diff --git a/src/cursor/cursor-auth.ts b/src/cursor/cursor-auth.ts new file mode 100644 index 00000000..a7a62c53 --- /dev/null +++ b/src/cursor/cursor-auth.ts @@ -0,0 +1,246 @@ +/** + * Cursor IDE Authentication Handler + * + * Handles token import and authentication for Cursor IDE integration. + * Supports auto-detection from Cursor's SQLite database. + * + * Token Location: + * - Linux: ~/.config/Cursor/User/globalStorage/state.vscdb + * - macOS: ~/Library/Application Support/Cursor/User/globalStorage/state.vscdb + * - Windows: %APPDATA%\Cursor\User\globalStorage\state.vscdb + * + * Database Keys: + * - cursorAuth/accessToken: Access token + * - storage.serviceMachineId: Machine ID for checksum + */ + +import { execSync } from 'child_process'; +import * as fs from 'fs'; +import * as path from 'path'; +import * as os from 'os'; +import type { CursorCredentials, CursorAuthStatus, AutoDetectResult } from './types'; +import { getCcsDir } from '../utils/config-manager'; + +/** + * Get platform-specific path to Cursor's state.vscdb + */ +export function getTokenStoragePath(): string { + const platform = process.platform; + const home = os.homedir(); + + if (platform === 'win32') { + const appData = process.env.APPDATA || path.join(home, 'AppData', 'Roaming'); + return path.join(appData, 'Cursor', 'User', 'globalStorage', 'state.vscdb'); + } else if (platform === 'darwin') { + return path.join( + home, + 'Library', + 'Application Support', + 'Cursor', + 'User', + 'globalStorage', + 'state.vscdb' + ); + } else { + // Linux + return path.join(home, '.config', 'Cursor', 'User', 'globalStorage', 'state.vscdb'); + } +} + +/** + * Query Cursor's SQLite database using sqlite3 CLI + */ +function queryStateDb(dbPath: string, key: string): string | null { + try { + const result = execSync( + `sqlite3 "${dbPath}" "SELECT value FROM itemTable WHERE key='${key}'" 2>/dev/null`, + { encoding: 'utf8', timeout: 5000 } + ).trim(); + return result || null; + } catch { + return null; + } +} + +/** + * Auto-detect tokens from Cursor's SQLite database + */ +export function autoDetectTokens(): AutoDetectResult { + const dbPath = getTokenStoragePath(); + + // Check if database exists + if (!fs.existsSync(dbPath)) { + return { + found: false, + error: + 'Cursor state database not found. Make sure Cursor IDE is installed and you are logged in.', + }; + } + + // Try to query access token + const accessToken = queryStateDb(dbPath, 'cursorAuth/accessToken'); + if (!accessToken) { + return { + found: false, + error: 'Access token not found in database. Please log in to Cursor IDE first.', + }; + } + + // Try to query machine ID + const machineId = queryStateDb(dbPath, 'storage.serviceMachineId'); + if (!machineId) { + return { + found: false, + error: 'Machine ID not found in database.', + }; + } + + return { + found: true, + accessToken, + machineId, + }; +} + +/** + * Validate token and machine ID format + */ +export function validateToken(accessToken: string, machineId: string): boolean { + // Basic validation + if (!accessToken || typeof accessToken !== 'string') { + return false; + } + + if (!machineId || typeof machineId !== 'string') { + return false; + } + + // Token format validation (Cursor tokens are typically long strings) + if (accessToken.length < 50) { + return false; + } + + // Machine ID format validation (should be UUID-like) + const uuidRegex = /^[a-f0-9-]{32,}$/i; + if (!uuidRegex.test(machineId.replace(/-/g, ''))) { + return false; + } + + return true; +} + +/** + * Extract user info from token if possible + * Cursor tokens may contain encoded user info as JWT + */ +export function extractUserInfo(accessToken: string): { email?: string; userId?: string } | null { + try { + // Try to decode as JWT + const parts = accessToken.split('.'); + if (parts.length === 3) { + let payload = parts[1]; + // Add padding if needed + while (payload.length % 4) { + payload += '='; + } + const decoded = JSON.parse( + Buffer.from(payload.replace(/-/g, '+').replace(/_/g, '/'), 'base64').toString() + ); + return { + email: decoded.email || decoded.sub, + userId: decoded.sub || decoded.user_id, + }; + } + } catch { + // Token is not a JWT, that's okay + } + + return null; +} + +/** + * Get path to credentials file + */ +export function getCredentialsPath(): string { + return path.join(getCcsDir(), 'cursor', 'credentials.json'); +} + +/** + * Save credentials to CCS config directory + */ +export function saveCredentials(credentials: CursorCredentials): void { + const credPath = getCredentialsPath(); + const dir = path.dirname(credPath); + + // Ensure directory exists + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true }); + } + + // Write credentials + fs.writeFileSync(credPath, JSON.stringify(credentials, null, 2), 'utf8'); +} + +/** + * Load credentials from CCS config directory + */ +export function loadCredentials(): CursorCredentials | null { + const credPath = getCredentialsPath(); + + if (!fs.existsSync(credPath)) { + return null; + } + + try { + const raw = fs.readFileSync(credPath, 'utf8'); + const parsed: unknown = JSON.parse(raw); + + // Basic validation + if ( + typeof parsed === 'object' && + parsed !== null && + 'accessToken' in parsed && + 'machineId' in parsed && + 'authMethod' in parsed && + 'importedAt' in parsed + ) { + return parsed as CursorCredentials; + } + + return null; + } catch { + return null; + } +} + +/** + * Check authentication status + */ +export function checkAuthStatus(): CursorAuthStatus { + const credentials = loadCredentials(); + + if (!credentials) { + return { authenticated: false }; + } + + // Validate credentials are still valid format + if (!validateToken(credentials.accessToken, credentials.machineId)) { + return { authenticated: false }; + } + + // Calculate token age in hours + let tokenAge: number | undefined; + try { + const importedDate = new Date(credentials.importedAt); + const now = new Date(); + tokenAge = Math.floor((now.getTime() - importedDate.getTime()) / (1000 * 60 * 60)); + } catch { + // Invalid date format + } + + return { + authenticated: true, + credentials, + tokenAge, + }; +} 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, + }; +} diff --git a/src/cursor/types.ts b/src/cursor/types.ts new file mode 100644 index 00000000..e22c37ae --- /dev/null +++ b/src/cursor/types.ts @@ -0,0 +1,141 @@ +/** + * Cursor IDE Type Definitions + * + * TypeScript interfaces for the Cursor module. + */ + +/** + * Cursor authentication credentials + */ +export interface CursorCredentials { + /** Access token from Cursor IDE */ + accessToken: string; + /** Machine ID for checksum generation */ + machineId: string; + /** User email (if available from token) */ + email?: string; + /** User ID (if available from token) */ + userId?: string; + /** How credentials were obtained */ + authMethod: 'auto-detect' | 'manual'; + /** ISO datetime when credentials were imported */ + importedAt: string; +} + +/** + * Cursor authentication status + */ +export interface CursorAuthStatus { + /** Whether user is authenticated */ + authenticated: boolean; + /** Current credentials (if authenticated) */ + credentials?: CursorCredentials; + /** Hours since credentials were imported (if available) */ + tokenAge?: number; +} + +/** + * Cursor daemon/process status + */ +export interface CursorDaemonStatus { + /** Whether daemon is running */ + running: boolean; + /** Port number daemon is listening on */ + port: number; + /** Process ID (if available) */ + pid?: number; +} + +/** + * Cursor AI model + */ +export interface CursorModel { + /** Model ID */ + id: string; + /** Display name */ + name: string; + /** Provider (e.g., 'openai', 'anthropic') */ + provider: string; + /** Whether this is the default model */ + isDefault?: boolean; +} + +/** + * Message role + */ +export type MessageRole = 'user' | 'assistant'; + +/** + * Cursor message for protobuf + */ +export interface CursorMessage { + /** Message role */ + role: MessageRole; + /** Message content */ + content: string; + /** Tool calls (if any) */ + tool_calls?: CursorToolCall[]; + /** Tool results (if any) */ + tool_results?: CursorToolResult[]; +} + +/** + * Cursor tool call + */ +export interface CursorToolCall { + /** Unique ID for this tool call */ + id: string; + /** Type of tool call */ + type: 'function'; + /** Function details */ + function: { + /** Function name */ + name: string; + /** JSON-encoded arguments */ + arguments: string; + }; + /** Whether this is the last tool call in sequence */ + isLast?: boolean; +} + +/** + * Cursor tool result + */ +export interface CursorToolResult { + /** ID of the tool call this result is for */ + tool_call_id: string; + /** Tool name */ + name: string; + /** Result index */ + index: number; + /** Raw arguments */ + raw_args: string; +} + +/** + * Result from protobuf extraction + */ +export interface ProtobufExtractResult { + /** Extracted text content */ + text: string | null; + /** Error message (if extraction failed) */ + error: string | null; + /** Extracted tool call (if any) */ + toolCall: CursorToolCall | null; + /** Thinking/reasoning content (if any) */ + thinking: string | null; +} + +/** + * Auto-detection result + */ +export interface AutoDetectResult { + /** Whether tokens were found */ + found: boolean; + /** Access token (if found) */ + accessToken?: string; + /** Machine ID (if found) */ + machineId?: string; + /** Error message (if detection failed) */ + error?: string; +} From aaa31c64270d0e718ad82d584c8c76692e39dbf4 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Wed, 11 Feb 2026 18:06:46 +0700 Subject: [PATCH 02/17] feat(cursor): add daemon lifecycle, models catalog, and CLI commands Implements #520 - Cursor IDE daemon, models catalog, module index, and CLI. Files created: - src/cursor/cursor-daemon.ts (~230 LOC) - Lifecycle management (start/stop/status) - src/cursor/cursor-models.ts (~145 LOC) - Model catalog with Anthropic/OpenAI/Google/Cursor models - src/cursor/index.ts (~30 LOC) - Module barrel exports - src/commands/cursor-command.ts (~230 LOC) - CLI commands (auth/status/models/start/stop) Key features: - Daemon health checks via HTTP /health endpoint - PID file management in ~/.ccs/cursor/daemon.pid - Model catalog with fetchModelsFromDaemon() and fallback defaults - CLI subcommand routing following copilot-command.ts pattern - ASCII-only output ([OK], [X], [i] markers) Temporary defaults for config (port: 4242, model: gpt-4.1) until #521 adds cursor to unified config schema. Note: Actual daemon server implementation (CursorExecutor integration) deferred to #522 - this creates the lifecycle structure only. --- src/commands/cursor-command.ts | 238 +++++++++++++++++++++++++++++++ src/cursor/cursor-daemon.ts | 253 +++++++++++++++++++++++++++++++++ src/cursor/cursor-models.ts | 166 +++++++++++++++++++++ src/cursor/index.ts | 30 ++++ 4 files changed, 687 insertions(+) create mode 100644 src/commands/cursor-command.ts create mode 100644 src/cursor/cursor-daemon.ts create mode 100644 src/cursor/cursor-models.ts create mode 100644 src/cursor/index.ts diff --git a/src/commands/cursor-command.ts b/src/commands/cursor-command.ts new file mode 100644 index 00000000..ecbb6602 --- /dev/null +++ b/src/commands/cursor-command.ts @@ -0,0 +1,238 @@ +/** + * Cursor CLI Command + * + * Handles `ccs cursor ` commands. + */ + +import { + autoDetectTokens, + checkAuthStatus, + startDaemon, + stopDaemon, + getDaemonStatus, + getAvailableModels, +} from '../cursor'; +import { ok, fail, info, color } from '../utils/ui'; + +// Temporary default config until #521 adds cursor to unified config +const DEFAULT_CURSOR_CONFIG = { + port: 4242, + model: 'gpt-4.1', +}; + +/** + * Handle cursor subcommand. + */ +export async function handleCursorCommand(args: string[]): Promise { + const subcommand = args[0]; + + switch (subcommand) { + case 'auth': + return handleAuth(); + case 'status': + return handleStatus(); + case 'models': + return handleModels(); + case 'start': + return handleStart(); + case 'stop': + return handleStop(); + case undefined: + case 'help': + case '--help': + case '-h': + return handleHelp(); + default: + console.error(fail(`Unknown subcommand: ${subcommand}`)); + console.error(''); + return handleHelp(); + } +} + +/** + * Show help for cursor commands. + */ +function handleHelp(): number { + console.log('Cursor IDE Integration'); + console.log(''); + console.log('Usage: ccs cursor '); + console.log(''); + console.log('Subcommands:'); + console.log(' auth Import Cursor IDE authentication token'); + console.log(' status Show authentication and daemon status'); + console.log(' models List available models'); + console.log(' start Start cursor daemon'); + console.log(' stop Stop cursor daemon'); + console.log(' help Show this help message'); + console.log(''); + console.log('Quick start:'); + console.log(' 1. ccs cursor auth # Import Cursor IDE token'); + console.log(' 2. ccs cursor start # Start daemon'); + console.log(' 3. Use cursor models # Via daemon on configured port'); + console.log(''); + console.log('Or use the web UI: ccs config → Cursor tab'); + console.log(''); + return 0; +} + +/** + * Handle auth subcommand. + */ +async function handleAuth(): Promise { + console.log(info('Importing Cursor IDE authentication...')); + console.log(''); + + // Try auto-detection first + console.log(info('Attempting auto-detection...')); + const autoResult = await autoDetectTokens(); + + if (autoResult.found && autoResult.accessToken && autoResult.machineId) { + console.log(ok('Auto-detected Cursor credentials')); + console.log(''); + console.log('Next steps:'); + console.log(' 1. Start daemon: ccs cursor start'); + console.log(' 2. Check status: ccs cursor status'); + return 0; + } + + // Fall back to manual import + console.log(''); + console.log('Auto-detection failed. Please provide credentials manually.'); + console.log(''); + console.log('To find your Cursor credentials:'); + console.log(' 1. Open Cursor IDE'); + console.log(' 2. Check application data directory'); + console.log(' 3. Look for access token and machine ID'); + console.log(''); + + // For now, just show instructions + // Manual import flow will be implemented when needed + console.error(fail('Manual import not yet implemented')); + console.error(''); + console.error('Use auto-detection for now or wait for manual import feature.'); + + return 1; +} + +/** + * Handle status subcommand. + */ +async function handleStatus(): Promise { + // TODO: Load from unified config when #521 is complete + const cursorConfig = DEFAULT_CURSOR_CONFIG; + + const authStatus = await checkAuthStatus(); + const daemonStatus = await getDaemonStatus(cursorConfig.port); + + console.log('Cursor IDE Status'); + console.log('─────────────────'); + console.log(''); + + // Auth status + const authIcon = authStatus.authenticated ? color('[OK]', 'success') : color('[X]', 'error'); + const authText = authStatus.authenticated ? 'Authenticated' : 'Not authenticated'; + console.log(`Authentication: ${authIcon} ${authText}`); + + if (authStatus.authenticated && authStatus.tokenAge !== undefined) { + console.log(` Token age: ${authStatus.tokenAge.toFixed(1)} hours`); + } + + // Daemon status + const daemonIcon = daemonStatus.running ? color('[OK]', 'success') : color('[X]', 'error'); + const daemonText = daemonStatus.running ? 'Running' : 'Not running'; + console.log(`Daemon: ${daemonIcon} ${daemonText}`); + + if (daemonStatus.pid) { + console.log(` PID: ${daemonStatus.pid}`); + } + + console.log(''); + console.log('Configuration:'); + console.log(` Port: ${cursorConfig.port}`); + console.log(` Model: ${cursorConfig.model}`); + + console.log(''); + + // Show next steps if not fully configured + if (!authStatus.authenticated || !daemonStatus.running) { + console.log('Next steps:'); + if (!authStatus.authenticated) { + console.log(' - Auth: ccs cursor auth'); + } + if (!daemonStatus.running) { + console.log(' - Start: ccs cursor start'); + } + } + + return 0; +} + +/** + * Handle models subcommand. + */ +async function handleModels(): Promise { + // TODO: Load from unified config when #521 is complete + const cursorConfig = DEFAULT_CURSOR_CONFIG; + + console.log('Available Cursor Models'); + console.log('───────────────────────'); + console.log(''); + + const models = await getAvailableModels(cursorConfig.port); + + for (const model of models) { + const current = model.id === cursorConfig.model ? ' [CURRENT]' : ''; + const defaultMark = model.isDefault ? ' (default)' : ''; + console.log(` ${model.id}${current}${defaultMark}`); + console.log(` Provider: ${model.provider}`); + } + + console.log(''); + console.log('To change model: ccs config (Cursor section)'); + + return 0; +} + +/** + * Handle start subcommand. + */ +async function handleStart(): Promise { + // TODO: Load from unified config when #521 is complete + const cursorConfig = DEFAULT_CURSOR_CONFIG; + + // Check auth first + const authStatus = await checkAuthStatus(); + if (!authStatus.authenticated) { + console.error(fail('Not authenticated. Run: ccs cursor auth')); + return 1; + } + + console.log(info(`Starting cursor daemon on port ${cursorConfig.port}...`)); + + const result = await startDaemon(cursorConfig); + + if (result.success) { + console.log(ok(`Daemon started (PID: ${result.pid})`)); + return 0; + } else { + console.error(fail(result.error || 'Failed to start daemon')); + return 1; + } +} + +/** + * Handle stop subcommand. + */ +async function handleStop(): Promise { + console.log(info('Stopping cursor daemon...')); + + const result = await stopDaemon(); + + if (result.success) { + console.log(ok('Daemon stopped')); + return 0; + } else { + console.error(fail(result.error || 'Failed to stop daemon')); + return 1; + } +} diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts new file mode 100644 index 00000000..0166be41 --- /dev/null +++ b/src/cursor/cursor-daemon.ts @@ -0,0 +1,253 @@ +/** + * Cursor Daemon Manager + * + * Manages the cursor daemon lifecycle (start/stop/status). + * Uses CursorExecutor for OpenAI-compatible API proxy to Cursor backend. + */ + +import { spawn, ChildProcess } from 'child_process'; +import * as fs from 'fs'; +import * as path from 'path'; +import * as http from 'http'; +import type { CursorDaemonStatus } from './types'; +import { getCcsDir } from '../utils/config-manager'; + +// Temporary interface until #521 adds cursor to unified config +interface CursorConfig { + port: number; + model: string; +} + +/** + * Get Cursor directory path. + */ +function getCursorDir(): string { + return path.join(getCcsDir(), 'cursor'); +} + +const PID_FILE = path.join(getCursorDir(), 'daemon.pid'); + +/** + * Check if cursor daemon is running on the specified port. + * Uses 127.0.0.1 instead of localhost for more reliable local connections. + */ +export async function isDaemonRunning(port: number): Promise { + return new Promise((resolve) => { + const req = http.request( + { + hostname: '127.0.0.1', + port, + path: '/health', + method: 'GET', + timeout: 3000, + }, + (res) => { + resolve(res.statusCode === 200); + } + ); + + req.on('error', () => { + resolve(false); + }); + + req.on('timeout', () => { + req.destroy(); + resolve(false); + }); + + req.end(); + }); +} + +/** + * Get daemon status. + */ +export async function getDaemonStatus(port: number): Promise { + const running = await isDaemonRunning(port); + const pid = getPidFromFile(); + + return { + running, + port, + pid: running ? (pid ?? undefined) : undefined, + }; +} + +/** + * Read PID from file. + */ +function getPidFromFile(): number | null { + try { + if (fs.existsSync(PID_FILE)) { + const content = fs.readFileSync(PID_FILE, 'utf8').trim(); + const pid = parseInt(content, 10); + return isNaN(pid) ? null : pid; + } + } catch { + // Ignore errors + } + return null; +} + +/** + * Write PID to file. + */ +function writePidToFile(pid: number): void { + try { + const dir = path.dirname(PID_FILE); + if (!fs.existsSync(dir)) { + fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); + } + fs.writeFileSync(PID_FILE, pid.toString(), { mode: 0o600 }); + } catch { + // Ignore errors + } +} + +/** + * Remove PID file. + */ +function removePidFile(): void { + try { + if (fs.existsSync(PID_FILE)) { + fs.unlinkSync(PID_FILE); + } + } catch { + // Ignore errors + } +} + +/** + * Start the cursor daemon. + * + * @param config Cursor configuration + * @returns Promise that resolves when daemon is ready + */ +export async function startDaemon( + config: CursorConfig +): Promise<{ success: boolean; pid?: number; error?: string }> { + // Check if already running + if (await isDaemonRunning(config.port)) { + return { success: true, pid: getPidFromFile() ?? undefined }; + } + + // For now, create a simple structure that will be filled in later + // The actual server implementation will be added in a separate task + return new Promise((resolve) => { + let proc: ChildProcess; + + try { + // Spawn a placeholder Node.js process + // TODO: Replace with actual CursorExecutor-based server + const args = [ + '-e', + ` + const http = require('http'); + const server = http.createServer((req, res) => { + if (req.url === '/health') { + res.writeHead(200); + res.end('OK'); + } else if (req.url === '/v1/models') { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ data: [] })); + } else { + res.writeHead(404); + res.end('Not found'); + } + }); + server.listen(${config.port}, '127.0.0.1'); + `, + ]; + + proc = spawn('node', args, { + stdio: ['ignore', 'pipe', 'pipe'], + detached: true, + shell: process.platform === 'win32', + }); + + // Unref so parent can exit + proc.unref(); + + if (proc.pid) { + writePidToFile(proc.pid); + } + + // Wait for daemon to be ready (poll for up to 30 seconds) + let attempts = 0; + const maxAttempts = 30; + const checkInterval = setInterval(async () => { + attempts++; + + if (await isDaemonRunning(config.port)) { + clearInterval(checkInterval); + resolve({ success: true, pid: proc.pid }); + } else if (attempts >= maxAttempts) { + clearInterval(checkInterval); + resolve({ + success: false, + error: 'Daemon did not start within 30 seconds', + }); + } + }, 1000); + + proc.on('error', (err) => { + clearInterval(checkInterval); + resolve({ + success: false, + error: `Failed to start daemon: ${err.message}`, + }); + }); + } catch (err) { + resolve({ + success: false, + error: `Failed to spawn daemon: ${(err as Error).message}`, + }); + } + }); +} + +/** + * Stop the cursor daemon. + */ +export async function stopDaemon(): Promise<{ success: boolean; error?: string }> { + const pid = getPidFromFile(); + + if (!pid) { + // No PID file, try to find by port + removePidFile(); + return { success: true }; + } + + try { + // Send SIGTERM to the process + process.kill(pid, 'SIGTERM'); + + // Wait for process to exit (up to 5 seconds) + let attempts = 0; + while (attempts < 10) { + await new Promise((resolve) => setTimeout(resolve, 500)); + try { + // Check if process still exists (kill(pid, 0) throws if not) + process.kill(pid, 0); + attempts++; + } catch { + // Process no longer exists + break; + } + } + + removePidFile(); + return { success: true }; + } catch (err) { + const error = err as NodeJS.ErrnoException; + if (error.code === 'ESRCH') { + // Process doesn't exist + removePidFile(); + return { success: true }; + } + return { + success: false, + error: `Failed to stop daemon: ${error.message}`, + }; + } +} diff --git a/src/cursor/cursor-models.ts b/src/cursor/cursor-models.ts new file mode 100644 index 00000000..4735e4c5 --- /dev/null +++ b/src/cursor/cursor-models.ts @@ -0,0 +1,166 @@ +/** + * Cursor Model Catalog + * + * Manages available models from Cursor IDE. + * Based on Cursor's supported models as of Feb 2025. + */ + +import * as http from 'http'; +import type { CursorModel } from './types'; + +/** + * Default models available through Cursor IDE. + * Used as fallback when daemon is not reachable. + * Source: Cursor IDE supported models (Feb 2025) + */ +export const DEFAULT_CURSOR_MODELS: CursorModel[] = [ + // Anthropic Models + { + id: 'claude-sonnet-4', + name: 'Claude Sonnet 4', + provider: 'anthropic', + }, + { + id: 'claude-sonnet-4.5', + name: 'Claude Sonnet 4.5', + provider: 'anthropic', + }, + { + id: 'claude-opus-4', + name: 'Claude Opus 4', + provider: 'anthropic', + }, + + // OpenAI Models + { + id: 'gpt-4.1', + name: 'GPT-4.1', + provider: 'openai', + isDefault: true, + }, + { + id: 'gpt-5-mini', + name: 'GPT-5 Mini', + provider: 'openai', + }, + { + id: 'o3-mini', + name: 'O3 Mini', + provider: 'openai', + }, + + // Google Models + { + id: 'gemini-2.5-pro', + name: 'Gemini 2.5 Pro', + provider: 'google', + }, + + // Cursor Custom Models + { + id: 'cursor-small', + name: 'Cursor Small', + provider: 'cursor', + }, +]; + +/** + * Fetch available models from running cursor daemon. + * + * @param port The port cursor daemon is running on + * @returns List of available models + */ +export async function fetchModelsFromDaemon(port: number): Promise { + return new Promise((resolve) => { + const req = http.request( + { + // Use 127.0.0.1 instead of localhost for more reliable local connections + hostname: '127.0.0.1', + port, + path: '/v1/models', + method: 'GET', + timeout: 5000, + }, + (res) => { + let data = ''; + + res.on('data', (chunk) => { + data += chunk; + }); + + res.on('end', () => { + try { + const response = JSON.parse(data) as { data?: Array<{ id: string }> }; + if (response.data && Array.isArray(response.data)) { + const models: CursorModel[] = response.data.map((m) => ({ + id: m.id, + name: formatModelName(m.id), + provider: detectProvider(m.id), + isDefault: m.id === 'gpt-4.1', + })); + resolve(models.length > 0 ? models : DEFAULT_CURSOR_MODELS); + } else { + resolve(DEFAULT_CURSOR_MODELS); + } + } catch { + resolve(DEFAULT_CURSOR_MODELS); + } + }); + } + ); + + req.on('error', () => { + resolve(DEFAULT_CURSOR_MODELS); + }); + + req.on('timeout', () => { + req.destroy(); + resolve(DEFAULT_CURSOR_MODELS); + }); + + req.end(); + }); +} + +/** + * Get available models (from daemon or defaults). + */ +export async function getAvailableModels(port: number): Promise { + return fetchModelsFromDaemon(port); +} + +/** + * Get the default model. + * Uses gpt-4.1 as it's commonly available. + */ +export function getDefaultModel(): string { + return 'gpt-4.1'; +} + +/** + * Detect provider from model ID. + */ +function detectProvider(modelId: string): string { + if (modelId.includes('claude')) return 'anthropic'; + if (modelId.includes('gpt') || modelId.includes('o3')) return 'openai'; + if (modelId.includes('gemini')) return 'google'; + if (modelId.includes('cursor')) return 'cursor'; + return 'openai'; +} + +/** + * Format model ID to human-readable name. + */ +function formatModelName(modelId: string): string { + // Find model in catalog for metadata + const model = DEFAULT_CURSOR_MODELS.find((m) => m.id === modelId); + if (model) { + return model.name; + } + + // Fallback: convert kebab-case to title case + return modelId + .split('-') + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(' '); +} diff --git a/src/cursor/index.ts b/src/cursor/index.ts new file mode 100644 index 00000000..014cf84d --- /dev/null +++ b/src/cursor/index.ts @@ -0,0 +1,30 @@ +/** + * Cursor Module Index + * + * Central exports for Cursor IDE integration. + */ + +// Types +export * from './types'; + +// Auth +export { + autoDetectTokens, + saveCredentials, + loadCredentials, + checkAuthStatus, +} from './cursor-auth'; + +// Daemon +export { isDaemonRunning, getDaemonStatus, startDaemon, stopDaemon } from './cursor-daemon'; + +// Models +export { + DEFAULT_CURSOR_MODELS, + fetchModelsFromDaemon, + getAvailableModels, + getDefaultModel, +} from './cursor-models'; + +// Executor +export { CursorExecutor } from './cursor-executor'; From fe97d720d41f83a35acf90307ef4471fb02a4cc6 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Wed, 11 Feb 2026 19:06:59 +0700 Subject: [PATCH 03/17] fix(cursor): fix test isolation and daemon exit handling - Convert PID_FILE constant to getPidFilePath() function to respect CCS_HOME changes at runtime - Add proc.on('exit') handler to clear interval on silent process crashes - Ensures test isolation by computing paths dynamically --- src/cursor/cursor-daemon.ts | 33 +- src/cursor/cursor-executor.ts | 1457 ++++++++++++------------- src/cursor/cursor-protobuf-decoder.ts | 408 ++++--- src/cursor/cursor-protobuf-encoder.ts | 317 +++--- src/cursor/cursor-protobuf-schema.ts | 269 +++-- src/cursor/cursor-protobuf.ts | 309 +++--- src/cursor/cursor-translator.ts | 196 ++-- src/cursor/index.ts | 7 +- 8 files changed, 1458 insertions(+), 1538 deletions(-) diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts index 0166be41..9fe6681c 100644 --- a/src/cursor/cursor-daemon.ts +++ b/src/cursor/cursor-daemon.ts @@ -25,7 +25,13 @@ function getCursorDir(): string { return path.join(getCcsDir(), 'cursor'); } -const PID_FILE = path.join(getCursorDir(), 'daemon.pid'); +/** + * Get PID file path. + * Computed at runtime to respect CCS_HOME changes (e.g., in tests). + */ +function getPidFilePath(): string { + return path.join(getCursorDir(), 'daemon.pid'); +} /** * Check if cursor daemon is running on the specified port. @@ -77,9 +83,10 @@ export async function getDaemonStatus(port: number): Promise * Read PID from file. */ function getPidFromFile(): number | null { + const pidFile = getPidFilePath(); try { - if (fs.existsSync(PID_FILE)) { - const content = fs.readFileSync(PID_FILE, 'utf8').trim(); + if (fs.existsSync(pidFile)) { + const content = fs.readFileSync(pidFile, 'utf8').trim(); const pid = parseInt(content, 10); return isNaN(pid) ? null : pid; } @@ -93,12 +100,13 @@ function getPidFromFile(): number | null { * Write PID to file. */ function writePidToFile(pid: number): void { + const pidFile = getPidFilePath(); try { - const dir = path.dirname(PID_FILE); + const dir = path.dirname(pidFile); if (!fs.existsSync(dir)) { fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); } - fs.writeFileSync(PID_FILE, pid.toString(), { mode: 0o600 }); + fs.writeFileSync(pidFile, pid.toString(), { mode: 0o600 }); } catch { // Ignore errors } @@ -108,9 +116,10 @@ function writePidToFile(pid: number): void { * Remove PID file. */ function removePidFile(): void { + const pidFile = getPidFilePath(); try { - if (fs.existsSync(PID_FILE)) { - fs.unlinkSync(PID_FILE); + if (fs.existsSync(pidFile)) { + fs.unlinkSync(pidFile); } } catch { // Ignore errors @@ -197,6 +206,16 @@ export async function startDaemon( error: `Failed to start daemon: ${err.message}`, }); }); + + proc.on('exit', (code) => { + if (code !== 0 && code !== null) { + clearInterval(checkInterval); + resolve({ + success: false, + error: `Daemon process exited with code ${code}`, + }); + } + }); } catch (err) { resolve({ success: false, diff --git a/src/cursor/cursor-executor.ts b/src/cursor/cursor-executor.ts index 28ce9f55..2d011b3a 100644 --- a/src/cursor/cursor-executor.ts +++ b/src/cursor/cursor-executor.ts @@ -3,784 +3,769 @@ * 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 { 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, + 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; + 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; + 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 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; +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.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 index 7b3e0d6a..7a5c12b6 100644 --- a/src/cursor/cursor-protobuf-decoder.ts +++ b/src/cursor/cursor-protobuf-decoder.ts @@ -3,34 +3,27 @@ * 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; - while (pos < buffer.length) { - const b = buffer[pos]; - result |= (b & 0x7f) << shift; - pos++; - if (!(b & 0x80)) break; - shift += 7; - } + while (pos < buffer.length) { + const b = buffer[pos]; + result |= (b & 0x7f) << shift; + pos++; + if (!(b & 0x80)) break; + shift += 7; + } - return [result, pos]; + return [result, pos]; } /** @@ -38,63 +31,60 @@ 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); + 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, []); + } + fields.get(fieldNum)!.push({ wireType, value: value as Uint8Array | number }); + pos = newPos; + } - return fields; + return fields; } /** @@ -102,200 +92,184 @@ 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 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 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 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 - ); + // 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 (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_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 - } - } + 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 - ); - } + // 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, - }; - } + if (toolCallId && toolName) { + return { + id: toolCallId, + type: 'function', + function: { + name: toolName, + arguments: rawArgs || '{}', + }, + isLast, + }; + } - return null; + 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)) { + 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 - } - } + // 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 }; + 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 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 - ); + // 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 }; - } - } + 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..857be448 100644 --- a/src/cursor/cursor-protobuf-encoder.ts +++ b/src/cursor/cursor-protobuf-encoder.ts @@ -3,260 +3,229 @@ * Implements ConnectRPC protobuf wire format encoding */ -import { randomUUID } from "crypto"; -import * as zlib from "zlib"; +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"; + 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); + 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; + 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..b26d8281 100644 --- a/src/cursor/cursor-protobuf.ts +++ b/src/cursor/cursor-protobuf.ts @@ -3,210 +3,193 @@ * 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, +} 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[] = []; + 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; + // 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 || [], - }); + formattedMessages.push({ + content: msg.content, + role, + messageId: msgId, + isLast, + hasTools, + toolResults: msg.tool_results || [], + }); - messageIds.push({ messageId: msgId, role }); - } + 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; + // 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 - ) - ) - ); + // 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 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 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))] - : []; + 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" - ), - ]; + // 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); + 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; + 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 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, + 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..452c7d39 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, + }; } diff --git a/src/cursor/index.ts b/src/cursor/index.ts index 014cf84d..46832336 100644 --- a/src/cursor/index.ts +++ b/src/cursor/index.ts @@ -8,12 +8,7 @@ export * from './types'; // Auth -export { - autoDetectTokens, - saveCredentials, - loadCredentials, - checkAuthStatus, -} from './cursor-auth'; +export { autoDetectTokens, saveCredentials, loadCredentials, checkAuthStatus } from './cursor-auth'; // Daemon export { isDaemonRunning, getDaemonStatus, startDaemon, stopDaemon } from './cursor-daemon'; From 9f0ea25448a8e4ca3019052812452885a4058190 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 04:03:01 +0700 Subject: [PATCH 04/17] fix(cursor): address PR #527 review feedback - Wire cursor command into main router (ccs.ts) following copilot pattern - Centralize default port (4242) and model (gpt-4.1) as constants - Remove duplicate types already in cursor-protobuf-schema from dev - Handle daemon exit code 0 before health check succeeds - Export PID helpers and model utils for testability - Add unit tests for cursor-daemon (PID file ops, isDaemonRunning) - Add unit tests for cursor-models (detectProvider, formatModelName, defaults) --- src/ccs.ts | 10 ++ src/commands/cursor-command.ts | 6 +- src/cursor/cursor-daemon.ts | 15 ++- src/cursor/cursor-models.ts | 14 ++- src/cursor/index.ts | 12 ++- tests/unit/cursor/cursor-daemon.test.ts | 123 ++++++++++++++++++++++++ tests/unit/cursor/cursor-models.test.ts | 82 ++++++++++++++++ 7 files changed, 250 insertions(+), 12 deletions(-) create mode 100644 tests/unit/cursor/cursor-daemon.test.ts create mode 100644 tests/unit/cursor/cursor-models.test.ts diff --git a/src/ccs.ts b/src/ccs.ts index 43d7eba2..720a37dd 100644 --- a/src/ccs.ts +++ b/src/ccs.ts @@ -532,6 +532,16 @@ async function main(): Promise { return; } + // Special case: cursor command (Cursor IDE integration) + // Only route to command handler for known subcommands, otherwise treat as profile + const CURSOR_SUBCOMMANDS = ['auth', 'status', 'models', 'start', 'stop', 'help', '--help', '-h']; + if (firstArg === 'cursor' && (args.length === 1 || CURSOR_SUBCOMMANDS.includes(args[1]))) { + // `ccs cursor ` - route to cursor command handler + const { handleCursorCommand } = await import('./commands/cursor-command'); + const exitCode = await handleCursorCommand(args.slice(1)); + process.exit(exitCode); + } + // Special case: copilot command (GitHub Copilot integration) // Only route to command handler for known subcommands, otherwise treat as profile const COPILOT_SUBCOMMANDS = [ diff --git a/src/commands/cursor-command.ts b/src/commands/cursor-command.ts index ecbb6602..aa4033f1 100644 --- a/src/commands/cursor-command.ts +++ b/src/commands/cursor-command.ts @@ -11,13 +11,15 @@ import { stopDaemon, getDaemonStatus, getAvailableModels, + DEFAULT_CURSOR_PORT, + DEFAULT_CURSOR_MODEL, } from '../cursor'; import { ok, fail, info, color } from '../utils/ui'; // Temporary default config until #521 adds cursor to unified config const DEFAULT_CURSOR_CONFIG = { - port: 4242, - model: 'gpt-4.1', + port: DEFAULT_CURSOR_PORT, + model: DEFAULT_CURSOR_MODEL, }; /** diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts index 9fe6681c..1d96e74d 100644 --- a/src/cursor/cursor-daemon.ts +++ b/src/cursor/cursor-daemon.ts @@ -82,7 +82,7 @@ export async function getDaemonStatus(port: number): Promise /** * Read PID from file. */ -function getPidFromFile(): number | null { +export function getPidFromFile(): number | null { const pidFile = getPidFilePath(); try { if (fs.existsSync(pidFile)) { @@ -99,7 +99,7 @@ function getPidFromFile(): number | null { /** * Write PID to file. */ -function writePidToFile(pid: number): void { +export function writePidToFile(pid: number): void { const pidFile = getPidFilePath(); try { const dir = path.dirname(pidFile); @@ -115,7 +115,7 @@ function writePidToFile(pid: number): void { /** * Remove PID file. */ -function removePidFile(): void { +export function removePidFile(): void { const pidFile = getPidFilePath(); try { if (fs.existsSync(pidFile)) { @@ -208,8 +208,13 @@ export async function startDaemon( }); proc.on('exit', (code) => { - if (code !== 0 && code !== null) { - clearInterval(checkInterval); + clearInterval(checkInterval); + if (code === 0) { + resolve({ + success: false, + error: 'Daemon process exited unexpectedly with code 0', + }); + } else if (code !== null) { resolve({ success: false, error: `Daemon process exited with code ${code}`, diff --git a/src/cursor/cursor-models.ts b/src/cursor/cursor-models.ts index 4735e4c5..2a35baa7 100644 --- a/src/cursor/cursor-models.ts +++ b/src/cursor/cursor-models.ts @@ -8,6 +8,12 @@ import * as http from 'http'; import type { CursorModel } from './types'; +/** Default daemon port */ +export const DEFAULT_CURSOR_PORT = 4242; + +/** Default model ID */ +export const DEFAULT_CURSOR_MODEL = 'gpt-4.1'; + /** * Default models available through Cursor IDE. * Used as fallback when daemon is not reachable. @@ -96,7 +102,7 @@ export async function fetchModelsFromDaemon(port: number): Promise 0 ? models : DEFAULT_CURSOR_MODELS); } else { @@ -134,13 +140,13 @@ export async function getAvailableModels(port: number): Promise { * Uses gpt-4.1 as it's commonly available. */ export function getDefaultModel(): string { - return 'gpt-4.1'; + return DEFAULT_CURSOR_MODEL; } /** * Detect provider from model ID. */ -function detectProvider(modelId: string): string { +export function detectProvider(modelId: string): string { if (modelId.includes('claude')) return 'anthropic'; if (modelId.includes('gpt') || modelId.includes('o3')) return 'openai'; if (modelId.includes('gemini')) return 'google'; @@ -151,7 +157,7 @@ function detectProvider(modelId: string): string { /** * Format model ID to human-readable name. */ -function formatModelName(modelId: string): string { +export function formatModelName(modelId: string): string { // Find model in catalog for metadata const model = DEFAULT_CURSOR_MODELS.find((m) => m.id === modelId); if (model) { diff --git a/src/cursor/index.ts b/src/cursor/index.ts index 46832336..d589d799 100644 --- a/src/cursor/index.ts +++ b/src/cursor/index.ts @@ -11,11 +11,21 @@ export * from './types'; export { autoDetectTokens, saveCredentials, loadCredentials, checkAuthStatus } from './cursor-auth'; // Daemon -export { isDaemonRunning, getDaemonStatus, startDaemon, stopDaemon } from './cursor-daemon'; +export { + isDaemonRunning, + getDaemonStatus, + startDaemon, + stopDaemon, + getPidFromFile, + writePidToFile, + removePidFile, +} from './cursor-daemon'; // Models export { DEFAULT_CURSOR_MODELS, + DEFAULT_CURSOR_PORT, + DEFAULT_CURSOR_MODEL, fetchModelsFromDaemon, getAvailableModels, getDefaultModel, diff --git a/tests/unit/cursor/cursor-daemon.test.ts b/tests/unit/cursor/cursor-daemon.test.ts new file mode 100644 index 00000000..a4c374bb --- /dev/null +++ b/tests/unit/cursor/cursor-daemon.test.ts @@ -0,0 +1,123 @@ +/** + * Unit tests for Cursor daemon module + */ + +import { describe, it, expect, beforeEach, afterEach } from 'bun:test'; +import * as fs from 'fs'; +import * as path from 'path'; +import * as os from 'os'; +import { + getPidFromFile, + writePidToFile, + removePidFile, + isDaemonRunning, +} from '../../../src/cursor/cursor-daemon'; + +// Test isolation +let originalCcsHome: string | undefined; +let tempDir: string; + +beforeEach(() => { + originalCcsHome = process.env.CCS_HOME; + tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ccs-daemon-test-')); + process.env.CCS_HOME = tempDir; +}); + +afterEach(() => { + if (originalCcsHome !== undefined) { + process.env.CCS_HOME = originalCcsHome; + } else { + delete process.env.CCS_HOME; + } + + // Cleanup temp directory + try { + fs.rmSync(tempDir, { recursive: true, force: true }); + } catch { + // Ignore cleanup errors + } +}); + +// CCS_HOME is set to tempDir; getCcsDir() appends '.ccs' to it +const ccsDir = () => path.join(tempDir, '.ccs'); + +describe('getPidFromFile', () => { + it('returns null when no PID file exists', () => { + expect(getPidFromFile()).toBeNull(); + }); + + it('returns PID when valid PID file exists', () => { + const cursorDir = path.join(ccsDir(), 'cursor'); + fs.mkdirSync(cursorDir, { recursive: true }); + fs.writeFileSync(path.join(cursorDir, 'daemon.pid'), '12345'); + + expect(getPidFromFile()).toBe(12345); + }); + + it('returns null when PID file contains invalid content', () => { + const cursorDir = path.join(ccsDir(), 'cursor'); + fs.mkdirSync(cursorDir, { recursive: true }); + fs.writeFileSync(path.join(cursorDir, 'daemon.pid'), 'not-a-number'); + + expect(getPidFromFile()).toBeNull(); + }); + + it('trims whitespace from PID file content', () => { + const cursorDir = path.join(ccsDir(), 'cursor'); + fs.mkdirSync(cursorDir, { recursive: true }); + fs.writeFileSync(path.join(cursorDir, 'daemon.pid'), ' 42 \n'); + + expect(getPidFromFile()).toBe(42); + }); +}); + +describe('writePidToFile', () => { + it('creates PID file with correct content', () => { + writePidToFile(12345); + + const pidFile = path.join(ccsDir(), 'cursor', 'daemon.pid'); + expect(fs.existsSync(pidFile)).toBe(true); + expect(fs.readFileSync(pidFile, 'utf8')).toBe('12345'); + }); + + it('creates cursor directory if it does not exist', () => { + const cursorDir = path.join(ccsDir(), 'cursor'); + expect(fs.existsSync(cursorDir)).toBe(false); + + writePidToFile(999); + + expect(fs.existsSync(cursorDir)).toBe(true); + }); + + it('overwrites existing PID file', () => { + writePidToFile(111); + writePidToFile(222); + + const pidFile = path.join(ccsDir(), 'cursor', 'daemon.pid'); + expect(fs.readFileSync(pidFile, 'utf8')).toBe('222'); + }); +}); + +describe('removePidFile', () => { + it('removes existing PID file', () => { + writePidToFile(12345); + const pidFile = path.join(ccsDir(), 'cursor', 'daemon.pid'); + expect(fs.existsSync(pidFile)).toBe(true); + + removePidFile(); + + expect(fs.existsSync(pidFile)).toBe(false); + }); + + it('does not throw when PID file does not exist', () => { + expect(() => removePidFile()).not.toThrow(); + }); +}); + +describe('isDaemonRunning', () => { + it('returns false when no daemon is running on port', async () => { + // Use a port that should not have anything running + const result = await isDaemonRunning(19999); + expect(result).toBe(false); + }); +}); diff --git a/tests/unit/cursor/cursor-models.test.ts b/tests/unit/cursor/cursor-models.test.ts new file mode 100644 index 00000000..9cdd183b --- /dev/null +++ b/tests/unit/cursor/cursor-models.test.ts @@ -0,0 +1,82 @@ +/** + * Unit tests for Cursor models module + */ + +import { describe, it, expect } from 'bun:test'; +import { + DEFAULT_CURSOR_MODELS, + DEFAULT_CURSOR_PORT, + DEFAULT_CURSOR_MODEL, + getDefaultModel, + detectProvider, + formatModelName, +} from '../../../src/cursor/cursor-models'; + +describe('DEFAULT_CURSOR_MODELS', () => { + it('contains models from multiple providers', () => { + const providers = new Set(DEFAULT_CURSOR_MODELS.map((m) => m.provider)); + expect(providers.has('anthropic')).toBe(true); + expect(providers.has('openai')).toBe(true); + expect(providers.has('google')).toBe(true); + }); + + it('has exactly one default model', () => { + const defaults = DEFAULT_CURSOR_MODELS.filter((m) => m.isDefault); + expect(defaults).toHaveLength(1); + expect(defaults[0].id).toBe(DEFAULT_CURSOR_MODEL); + }); +}); + +describe('DEFAULT_CURSOR_PORT', () => { + it('is 4242', () => { + expect(DEFAULT_CURSOR_PORT).toBe(4242); + }); +}); + +describe('DEFAULT_CURSOR_MODEL', () => { + it('is gpt-4.1', () => { + expect(DEFAULT_CURSOR_MODEL).toBe('gpt-4.1'); + }); +}); + +describe('getDefaultModel', () => { + it('returns the default model constant', () => { + expect(getDefaultModel()).toBe(DEFAULT_CURSOR_MODEL); + }); +}); + +describe('detectProvider', () => { + it('detects anthropic models', () => { + expect(detectProvider('claude-sonnet-4')).toBe('anthropic'); + expect(detectProvider('claude-opus-4')).toBe('anthropic'); + }); + + it('detects openai models', () => { + expect(detectProvider('gpt-4.1')).toBe('openai'); + expect(detectProvider('gpt-5-mini')).toBe('openai'); + expect(detectProvider('o3-mini')).toBe('openai'); + }); + + it('detects google models', () => { + expect(detectProvider('gemini-2.5-pro')).toBe('google'); + }); + + it('detects cursor models', () => { + expect(detectProvider('cursor-small')).toBe('cursor'); + }); + + it('defaults to openai for unknown models', () => { + expect(detectProvider('unknown-model')).toBe('openai'); + }); +}); + +describe('formatModelName', () => { + it('returns catalog name for known models', () => { + expect(formatModelName('claude-sonnet-4')).toBe('Claude Sonnet 4'); + expect(formatModelName('gpt-4.1')).toBe('GPT-4.1'); + }); + + it('converts kebab-case to title case for unknown models', () => { + expect(formatModelName('my-custom-model')).toBe('My Custom Model'); + }); +}); From 9f9db7dcea29f8ed0e2b8d52dc8ade81f8ab050d Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 04:11:31 +0700 Subject: [PATCH 05/17] fix(cursor): save credentials after auto-detect and fix signal hang - handleAuth() now calls saveCredentials() after successful auto-detect - Handle code === null (signal kill) in daemon exit handler to prevent promise from hanging indefinitely - Remove unnecessary await on synchronous functions --- src/commands/cursor-command.ts | 13 ++++++++++--- src/cursor/cursor-daemon.ts | 9 +++++++-- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/commands/cursor-command.ts b/src/commands/cursor-command.ts index aa4033f1..2385a3be 100644 --- a/src/commands/cursor-command.ts +++ b/src/commands/cursor-command.ts @@ -6,6 +6,7 @@ import { autoDetectTokens, + saveCredentials, checkAuthStatus, startDaemon, stopDaemon, @@ -86,9 +87,15 @@ async function handleAuth(): Promise { // Try auto-detection first console.log(info('Attempting auto-detection...')); - const autoResult = await autoDetectTokens(); + const autoResult = autoDetectTokens(); if (autoResult.found && autoResult.accessToken && autoResult.machineId) { + saveCredentials({ + accessToken: autoResult.accessToken, + machineId: autoResult.machineId, + authMethod: 'auto-detect', + importedAt: new Date().toISOString(), + }); console.log(ok('Auto-detected Cursor credentials')); console.log(''); console.log('Next steps:'); @@ -123,7 +130,7 @@ async function handleStatus(): Promise { // TODO: Load from unified config when #521 is complete const cursorConfig = DEFAULT_CURSOR_CONFIG; - const authStatus = await checkAuthStatus(); + const authStatus = checkAuthStatus(); const daemonStatus = await getDaemonStatus(cursorConfig.port); console.log('Cursor IDE Status'); @@ -203,7 +210,7 @@ async function handleStart(): Promise { const cursorConfig = DEFAULT_CURSOR_CONFIG; // Check auth first - const authStatus = await checkAuthStatus(); + const authStatus = checkAuthStatus(); if (!authStatus.authenticated) { console.error(fail('Not authenticated. Run: ccs cursor auth')); return 1; diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts index 1d96e74d..0b240747 100644 --- a/src/cursor/cursor-daemon.ts +++ b/src/cursor/cursor-daemon.ts @@ -207,9 +207,14 @@ export async function startDaemon( }); }); - proc.on('exit', (code) => { + proc.on('exit', (code, signal) => { clearInterval(checkInterval); - if (code === 0) { + if (code === null) { + resolve({ + success: false, + error: `Daemon process was killed by signal ${signal}`, + }); + } else if (code === 0) { resolve({ success: false, error: 'Daemon process exited unexpectedly with code 0', From afb5e746b3c11951147c381b298bc562a078685c Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 04:14:28 +0700 Subject: [PATCH 06/17] fix(cursor): address remaining PR #527 review feedback - Add SIGKILL escalation in stopDaemon after SIGTERM timeout - Document router difference between cursor/copilot help behavior - Fix detectProvider to handle o1/o4 models via regex pattern - Add fetchModelsFromDaemon fallback test for unreachable daemon - Update CLAUDE.md help table with cursor command entry --- CLAUDE.md | 1 + src/ccs.ts | 2 ++ src/cursor/cursor-daemon.ts | 8 ++++++++ src/cursor/cursor-models.ts | 2 +- tests/unit/cursor/cursor-models.test.ts | 17 +++++++++++++++++ 5 files changed, 29 insertions(+), 1 deletion(-) diff --git a/CLAUDE.md b/CLAUDE.md index a8aaa564..715f18d0 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -129,6 +129,7 @@ bun run validate # Step 3: Final check (must pass) | `ccs cliproxy --help` | `src/commands/cliproxy-command.ts` → `showHelp()` | | `ccs config --help` | `src/commands/config-command.ts` → `showHelp()` | | `ccs copilot --help` | `src/commands/copilot-command.ts` → `handleHelp()` | +| `ccs cursor --help` | `src/commands/cursor-command.ts` → `handleHelp()` | | `ccs doctor --help` | `src/commands/doctor-command.ts` → `showHelp()` | | `ccs migrate --help` | `src/commands/migrate-command.ts` → `printMigrateHelp()` | | `ccs env --help` | `src/commands/env-command.ts` → `showHelp()` | diff --git a/src/ccs.ts b/src/ccs.ts index 720a37dd..0161870c 100644 --- a/src/ccs.ts +++ b/src/ccs.ts @@ -534,6 +534,8 @@ async function main(): Promise { // Special case: cursor command (Cursor IDE integration) // Only route to command handler for known subcommands, otherwise treat as profile + // Note: Bare `ccs cursor` shows help (unlike copilot which falls through to profile) + // This is intentional — cursor has no profile-switching mode const CURSOR_SUBCOMMANDS = ['auth', 'status', 'models', 'start', 'stop', 'help', '--help', '-h']; if (firstArg === 'cursor' && (args.length === 1 || CURSOR_SUBCOMMANDS.includes(args[1]))) { // `ccs cursor ` - route to cursor command handler diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts index 0b240747..0efe8f9a 100644 --- a/src/cursor/cursor-daemon.ts +++ b/src/cursor/cursor-daemon.ts @@ -265,6 +265,14 @@ export async function stopDaemon(): Promise<{ success: boolean; error?: string } } } + // Escalate to SIGKILL if process still alive after SIGTERM attempts + try { + process.kill(pid, 0); // Check if still alive + process.kill(pid, 'SIGKILL'); // Escalate to force kill + } catch { + // Already dead — good + } + removePidFile(); return { success: true }; } catch (err) { diff --git a/src/cursor/cursor-models.ts b/src/cursor/cursor-models.ts index 2a35baa7..f11c9ed1 100644 --- a/src/cursor/cursor-models.ts +++ b/src/cursor/cursor-models.ts @@ -148,7 +148,7 @@ export function getDefaultModel(): string { */ export function detectProvider(modelId: string): string { if (modelId.includes('claude')) return 'anthropic'; - if (modelId.includes('gpt') || modelId.includes('o3')) return 'openai'; + if (modelId.includes('gpt') || /^o\d/.test(modelId)) return 'openai'; if (modelId.includes('gemini')) return 'google'; if (modelId.includes('cursor')) return 'cursor'; return 'openai'; diff --git a/tests/unit/cursor/cursor-models.test.ts b/tests/unit/cursor/cursor-models.test.ts index 9cdd183b..d8872dfb 100644 --- a/tests/unit/cursor/cursor-models.test.ts +++ b/tests/unit/cursor/cursor-models.test.ts @@ -10,6 +10,7 @@ import { getDefaultModel, detectProvider, formatModelName, + fetchModelsFromDaemon, } from '../../../src/cursor/cursor-models'; describe('DEFAULT_CURSOR_MODELS', () => { @@ -57,6 +58,12 @@ describe('detectProvider', () => { expect(detectProvider('o3-mini')).toBe('openai'); }); + it('detects o1 and o4 models as openai', () => { + expect(detectProvider('o1')).toBe('openai'); + expect(detectProvider('o1-preview')).toBe('openai'); + expect(detectProvider('o4-mini')).toBe('openai'); + }); + it('detects google models', () => { expect(detectProvider('gemini-2.5-pro')).toBe('google'); }); @@ -80,3 +87,13 @@ describe('formatModelName', () => { expect(formatModelName('my-custom-model')).toBe('My Custom Model'); }); }); + +describe('fetchModelsFromDaemon', () => { + it('falls back to DEFAULT_CURSOR_MODELS when daemon is unreachable', async () => { + // Use a port that nothing is listening on + const unreachablePort = 9999; + const models = await fetchModelsFromDaemon(unreachablePort); + + expect(models).toEqual(DEFAULT_CURSOR_MODELS); + }); +}); From 7d4e6d6b65d467cf182710805b4ee15f44a4f5f0 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 04:27:35 +0700 Subject: [PATCH 07/17] fix(cursor): add resolve guard, port validation, and daemon tests - Add double-resolve guard in startDaemon with safeResolve wrapper - Add port validation (1-65535) before Node.js script interpolation - Fix misleading comment in stopDaemon (no PID file handling) - Add getDaemonStatus test for no daemon running case - Add stopDaemon tests for graceful non-existent PID handling --- src/cursor/cursor-daemon.ts | 37 ++++++++++++++--------- tests/unit/cursor/cursor-daemon.test.ts | 39 +++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 13 deletions(-) diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts index 0efe8f9a..0f016677 100644 --- a/src/cursor/cursor-daemon.ts +++ b/src/cursor/cursor-daemon.ts @@ -140,10 +140,25 @@ export async function startDaemon( return { success: true, pid: getPidFromFile() ?? undefined }; } + // Validate port before interpolation (prevents injection) + if (!Number.isInteger(config.port) || config.port < 1 || config.port > 65535) { + return { success: false, error: `Invalid port: ${config.port}` }; + } + // For now, create a simple structure that will be filled in later // The actual server implementation will be added in a separate task return new Promise((resolve) => { let proc: ChildProcess; + let resolved = false; + + const safeResolve = (result: { success: boolean; pid?: number; error?: string }) => { + if (resolved) return; + resolved = true; + if (checkInterval) clearInterval(checkInterval); + resolve(result); + }; + + let checkInterval: NodeJS.Timeout | null = null; try { // Spawn a placeholder Node.js process @@ -184,15 +199,13 @@ export async function startDaemon( // Wait for daemon to be ready (poll for up to 30 seconds) let attempts = 0; const maxAttempts = 30; - const checkInterval = setInterval(async () => { + checkInterval = setInterval(async () => { attempts++; if (await isDaemonRunning(config.port)) { - clearInterval(checkInterval); - resolve({ success: true, pid: proc.pid }); + safeResolve({ success: true, pid: proc.pid }); } else if (attempts >= maxAttempts) { - clearInterval(checkInterval); - resolve({ + safeResolve({ success: false, error: 'Daemon did not start within 30 seconds', }); @@ -200,34 +213,32 @@ export async function startDaemon( }, 1000); proc.on('error', (err) => { - clearInterval(checkInterval); - resolve({ + safeResolve({ success: false, error: `Failed to start daemon: ${err.message}`, }); }); proc.on('exit', (code, signal) => { - clearInterval(checkInterval); if (code === null) { - resolve({ + safeResolve({ success: false, error: `Daemon process was killed by signal ${signal}`, }); } else if (code === 0) { - resolve({ + safeResolve({ success: false, error: 'Daemon process exited unexpectedly with code 0', }); } else if (code !== null) { - resolve({ + safeResolve({ success: false, error: `Daemon process exited with code ${code}`, }); } }); } catch (err) { - resolve({ + safeResolve({ success: false, error: `Failed to spawn daemon: ${(err as Error).message}`, }); @@ -242,7 +253,7 @@ export async function stopDaemon(): Promise<{ success: boolean; error?: string } const pid = getPidFromFile(); if (!pid) { - // No PID file, try to find by port + // No PID file — daemon is not running or was already stopped removePidFile(); return { success: true }; } diff --git a/tests/unit/cursor/cursor-daemon.test.ts b/tests/unit/cursor/cursor-daemon.test.ts index a4c374bb..b07012a7 100644 --- a/tests/unit/cursor/cursor-daemon.test.ts +++ b/tests/unit/cursor/cursor-daemon.test.ts @@ -11,6 +11,8 @@ import { writePidToFile, removePidFile, isDaemonRunning, + getDaemonStatus, + stopDaemon, } from '../../../src/cursor/cursor-daemon'; // Test isolation @@ -121,3 +123,40 @@ describe('isDaemonRunning', () => { expect(result).toBe(false); }); }); + +describe('getDaemonStatus', () => { + it('returns status with running=false when no daemon running', async () => { + const status = await getDaemonStatus(19999); + expect(status.running).toBe(false); + expect(status.port).toBe(19999); + expect(status.pid).toBeUndefined(); + }); + + it('returns status with pid when PID file exists but daemon not running', async () => { + writePidToFile(99999); + const status = await getDaemonStatus(19999); + expect(status.running).toBe(false); + expect(status.port).toBe(19999); + expect(status.pid).toBeUndefined(); + }); +}); + +describe('stopDaemon', () => { + it('returns success when no PID file exists', async () => { + const result = await stopDaemon(); + expect(result.success).toBe(true); + expect(result.error).toBeUndefined(); + }); + + it('returns success when PID refers to non-existent process', async () => { + // Write a PID that doesn't exist + writePidToFile(999999); + const result = await stopDaemon(); + expect(result.success).toBe(true); + expect(result.error).toBeUndefined(); + + // PID file should be removed + const pidFile = path.join(ccsDir(), 'cursor', 'daemon.pid'); + expect(fs.existsSync(pidFile)).toBe(false); + }); +}); From 88ad13ee7ba7957a6d1756e994b707d6f7402e2a Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 07:17:03 +0700 Subject: [PATCH 08/17] fix(cursor): kill orphaned daemon on timeout and fix exit codes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit MEDIUM fixes: - Kill orphaned process when health check times out after 30s - Prevents zombie processes from consuming resources LOW fixes: - Return exit code 1 for unknown cursor subcommands (was 0) - Simplify exit handler dead code branch (else if code !== null → else) --- src/commands/cursor-command.ts | 3 ++- src/cursor/cursor-daemon.ts | 10 +++++++++- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/commands/cursor-command.ts b/src/commands/cursor-command.ts index 2385a3be..99cd7551 100644 --- a/src/commands/cursor-command.ts +++ b/src/commands/cursor-command.ts @@ -48,7 +48,8 @@ export async function handleCursorCommand(args: string[]): Promise { default: console.error(fail(`Unknown subcommand: ${subcommand}`)); console.error(''); - return handleHelp(); + handleHelp(); + return 1; } } diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts index 0f016677..07243a4d 100644 --- a/src/cursor/cursor-daemon.ts +++ b/src/cursor/cursor-daemon.ts @@ -205,6 +205,14 @@ export async function startDaemon( if (await isDaemonRunning(config.port)) { safeResolve({ success: true, pid: proc.pid }); } else if (attempts >= maxAttempts) { + // Kill orphaned process + if (proc.pid) { + try { + process.kill(proc.pid, 'SIGTERM'); + } catch { + /* already dead */ + } + } safeResolve({ success: false, error: 'Daemon did not start within 30 seconds', @@ -230,7 +238,7 @@ export async function startDaemon( success: false, error: 'Daemon process exited unexpectedly with code 0', }); - } else if (code !== null) { + } else { safeResolve({ success: false, error: `Daemon process exited with code ${code}`, From 36f0308a72141e0481c9044a4e49b35b3065cf73 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 07:24:10 +0700 Subject: [PATCH 09/17] fix(cursor): add response body handling and size limit - Drain health check response body with res.resume() - Add 1MB body size limit in fetchModelsFromDaemon --- src/cursor/cursor-daemon.ts | 1 + src/cursor/cursor-models.ts | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts index 07243a4d..4da46322 100644 --- a/src/cursor/cursor-daemon.ts +++ b/src/cursor/cursor-daemon.ts @@ -48,6 +48,7 @@ export async function isDaemonRunning(port: number): Promise { timeout: 3000, }, (res) => { + res.resume(); // Drain response body resolve(res.statusCode === 200); } ); diff --git a/src/cursor/cursor-models.ts b/src/cursor/cursor-models.ts index f11c9ed1..3cb8cd4d 100644 --- a/src/cursor/cursor-models.ts +++ b/src/cursor/cursor-models.ts @@ -88,10 +88,15 @@ export async function fetchModelsFromDaemon(port: number): Promise { + const MAX_BODY_SIZE = 1024 * 1024; // 1MB limit let data = ''; res.on('data', (chunk) => { data += chunk; + if (data.length > MAX_BODY_SIZE) { + req.destroy(); + resolve(DEFAULT_CURSOR_MODELS); + } }); res.on('end', () => { From 94789676b9642d539e9365fc03a961691981ed12 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 07:37:20 +0700 Subject: [PATCH 10/17] fix(cursor): use process.execPath and add safeResolve to model fetcher - Replace 'node' with process.execPath for cross-platform reliability - Add safeResolve guard in fetchModelsFromDaemon matching startDaemon pattern --- src/cursor/cursor-daemon.ts | 2 +- src/cursor/cursor-models.ts | 19 +++++++++++++------ 2 files changed, 14 insertions(+), 7 deletions(-) diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts index 4da46322..eae9295c 100644 --- a/src/cursor/cursor-daemon.ts +++ b/src/cursor/cursor-daemon.ts @@ -184,7 +184,7 @@ export async function startDaemon( `, ]; - proc = spawn('node', args, { + proc = spawn(process.execPath, args, { stdio: ['ignore', 'pipe', 'pipe'], detached: true, shell: process.platform === 'win32', diff --git a/src/cursor/cursor-models.ts b/src/cursor/cursor-models.ts index 3cb8cd4d..05a0a19d 100644 --- a/src/cursor/cursor-models.ts +++ b/src/cursor/cursor-models.ts @@ -78,6 +78,13 @@ export const DEFAULT_CURSOR_MODELS: CursorModel[] = [ */ export async function fetchModelsFromDaemon(port: number): Promise { return new Promise((resolve) => { + let resolved = false; + const safeResolve = (models: CursorModel[]) => { + if (resolved) return; + resolved = true; + resolve(models); + }; + const req = http.request( { // Use 127.0.0.1 instead of localhost for more reliable local connections @@ -95,7 +102,7 @@ export async function fetchModelsFromDaemon(port: number): Promise MAX_BODY_SIZE) { req.destroy(); - resolve(DEFAULT_CURSOR_MODELS); + safeResolve(DEFAULT_CURSOR_MODELS); } }); @@ -109,24 +116,24 @@ export async function fetchModelsFromDaemon(port: number): Promise 0 ? models : DEFAULT_CURSOR_MODELS); + safeResolve(models.length > 0 ? models : DEFAULT_CURSOR_MODELS); } else { - resolve(DEFAULT_CURSOR_MODELS); + safeResolve(DEFAULT_CURSOR_MODELS); } } catch { - resolve(DEFAULT_CURSOR_MODELS); + safeResolve(DEFAULT_CURSOR_MODELS); } }); } ); req.on('error', () => { - resolve(DEFAULT_CURSOR_MODELS); + safeResolve(DEFAULT_CURSOR_MODELS); }); req.on('timeout', () => { req.destroy(); - resolve(DEFAULT_CURSOR_MODELS); + safeResolve(DEFAULT_CURSOR_MODELS); }); req.end(); From ce1915366d5012097b5b6814c2c672d04f16ab61 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 07:51:22 +0700 Subject: [PATCH 11/17] fix(cursor): use stdio ignore, sequential polling, move CursorConfig to types - Change spawn stdio from piped to 'ignore' preventing buffer deadlock - Replace setInterval with sequential setTimeout polling - Fix TOCTOU in SIGKILL escalation (send directly without probing) - Move CursorConfig interface to types.ts - Change detectProvider default from 'openai' to 'unknown' - Remove redundant removePidFile() when PID is null --- src/cursor/cursor-daemon.ts | 26 ++++++++++--------------- src/cursor/cursor-models.ts | 2 +- src/cursor/types.ts | 9 +++++++++ tests/unit/cursor/cursor-models.test.ts | 4 ++-- 4 files changed, 22 insertions(+), 19 deletions(-) diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts index eae9295c..87e886a0 100644 --- a/src/cursor/cursor-daemon.ts +++ b/src/cursor/cursor-daemon.ts @@ -9,15 +9,9 @@ import { spawn, ChildProcess } from 'child_process'; import * as fs from 'fs'; import * as path from 'path'; import * as http from 'http'; -import type { CursorDaemonStatus } from './types'; +import type { CursorConfig, CursorDaemonStatus } from './types'; import { getCcsDir } from '../utils/config-manager'; -// Temporary interface until #521 adds cursor to unified config -interface CursorConfig { - port: number; - model: string; -} - /** * Get Cursor directory path. */ @@ -155,11 +149,11 @@ export async function startDaemon( const safeResolve = (result: { success: boolean; pid?: number; error?: string }) => { if (resolved) return; resolved = true; - if (checkInterval) clearInterval(checkInterval); + if (checkTimeout) clearTimeout(checkTimeout); resolve(result); }; - let checkInterval: NodeJS.Timeout | null = null; + let checkTimeout: NodeJS.Timeout | null = null; try { // Spawn a placeholder Node.js process @@ -185,9 +179,8 @@ export async function startDaemon( ]; proc = spawn(process.execPath, args, { - stdio: ['ignore', 'pipe', 'pipe'], + stdio: 'ignore', detached: true, - shell: process.platform === 'win32', }); // Unref so parent can exit @@ -200,7 +193,7 @@ export async function startDaemon( // Wait for daemon to be ready (poll for up to 30 seconds) let attempts = 0; const maxAttempts = 30; - checkInterval = setInterval(async () => { + const pollHealth = async () => { attempts++; if (await isDaemonRunning(config.port)) { @@ -218,8 +211,11 @@ export async function startDaemon( success: false, error: 'Daemon did not start within 30 seconds', }); + } else { + checkTimeout = setTimeout(pollHealth, 1000); } - }, 1000); + }; + checkTimeout = setTimeout(pollHealth, 1000); proc.on('error', (err) => { safeResolve({ @@ -263,7 +259,6 @@ export async function stopDaemon(): Promise<{ success: boolean; error?: string } if (!pid) { // No PID file — daemon is not running or was already stopped - removePidFile(); return { success: true }; } @@ -287,8 +282,7 @@ export async function stopDaemon(): Promise<{ success: boolean; error?: string } // Escalate to SIGKILL if process still alive after SIGTERM attempts try { - process.kill(pid, 0); // Check if still alive - process.kill(pid, 'SIGKILL'); // Escalate to force kill + process.kill(pid, 'SIGKILL'); } catch { // Already dead — good } diff --git a/src/cursor/cursor-models.ts b/src/cursor/cursor-models.ts index 05a0a19d..ec68b801 100644 --- a/src/cursor/cursor-models.ts +++ b/src/cursor/cursor-models.ts @@ -163,7 +163,7 @@ export function detectProvider(modelId: string): string { if (modelId.includes('gpt') || /^o\d/.test(modelId)) return 'openai'; if (modelId.includes('gemini')) return 'google'; if (modelId.includes('cursor')) return 'cursor'; - return 'openai'; + return 'unknown'; } /** diff --git a/src/cursor/types.ts b/src/cursor/types.ts index 5dbc4fe9..c16150cc 100644 --- a/src/cursor/types.ts +++ b/src/cursor/types.ts @@ -4,6 +4,15 @@ * TypeScript interfaces for the Cursor module. */ +/** + * Cursor daemon configuration. + * Temporary interface until #521 adds cursor to unified config. + */ +export interface CursorConfig { + port: number; + model: string; +} + /** * Cursor authentication credentials */ diff --git a/tests/unit/cursor/cursor-models.test.ts b/tests/unit/cursor/cursor-models.test.ts index d8872dfb..f998d2b6 100644 --- a/tests/unit/cursor/cursor-models.test.ts +++ b/tests/unit/cursor/cursor-models.test.ts @@ -72,8 +72,8 @@ describe('detectProvider', () => { expect(detectProvider('cursor-small')).toBe('cursor'); }); - it('defaults to openai for unknown models', () => { - expect(detectProvider('unknown-model')).toBe('openai'); + it('defaults to unknown for unrecognized models', () => { + expect(detectProvider('unknown-model')).toBe('unknown'); }); }); From 887efa406957bb88f0dfdfe12732b1ac0e1cfae1 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 07:59:39 +0700 Subject: [PATCH 12/17] fix(cursor): show auto-detect error message, add subcommand sync comment --- src/ccs.ts | 1 + src/commands/cursor-command.ts | 6 +++++- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/ccs.ts b/src/ccs.ts index 0161870c..8d3a7f2e 100644 --- a/src/ccs.ts +++ b/src/ccs.ts @@ -536,6 +536,7 @@ async function main(): Promise { // Only route to command handler for known subcommands, otherwise treat as profile // Note: Bare `ccs cursor` shows help (unlike copilot which falls through to profile) // This is intentional — cursor has no profile-switching mode + // Keep in sync with cursor-command.ts switch cases const CURSOR_SUBCOMMANDS = ['auth', 'status', 'models', 'start', 'stop', 'help', '--help', '-h']; if (firstArg === 'cursor' && (args.length === 1 || CURSOR_SUBCOMMANDS.includes(args[1]))) { // `ccs cursor ` - route to cursor command handler diff --git a/src/commands/cursor-command.ts b/src/commands/cursor-command.ts index 99cd7551..1ae9c4df 100644 --- a/src/commands/cursor-command.ts +++ b/src/commands/cursor-command.ts @@ -107,7 +107,11 @@ async function handleAuth(): Promise { // Fall back to manual import console.log(''); - console.log('Auto-detection failed. Please provide credentials manually.'); + if (autoResult.error) { + console.log(`Auto-detection failed: ${autoResult.error}`); + } else { + console.log('Auto-detection failed. Please provide credentials manually.'); + } console.log(''); console.log('To find your Cursor credentials:'); console.log(' 1. Open Cursor IDE'); From cda037e7e5a9a77bb6bb9768e3d601008d102b70 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 08:11:41 +0700 Subject: [PATCH 13/17] fix(cursor): clean up PID file on startDaemon failure and improve daemon robustness - Add removePidFile() in safeResolve on failure to prevent stale PIDs - Only send SIGKILL in stopDaemon if SIGTERM wait loop exhausted - Check isDaemonRunning before model fetch to avoid 5s timeout - Add port validation unit tests for startDaemon --- src/cursor/cursor-daemon.ts | 13 ++++++++----- src/cursor/cursor-models.ts | 5 +++++ tests/unit/cursor/cursor-daemon.test.ts | 21 +++++++++++++++++++++ 3 files changed, 34 insertions(+), 5 deletions(-) diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts index 87e886a0..1ed5a484 100644 --- a/src/cursor/cursor-daemon.ts +++ b/src/cursor/cursor-daemon.ts @@ -150,6 +150,7 @@ export async function startDaemon( if (resolved) return; resolved = true; if (checkTimeout) clearTimeout(checkTimeout); + if (!result.success) removePidFile(); resolve(result); }; @@ -280,11 +281,13 @@ export async function stopDaemon(): Promise<{ success: boolean; error?: string } } } - // Escalate to SIGKILL if process still alive after SIGTERM attempts - try { - process.kill(pid, 'SIGKILL'); - } catch { - // Already dead — good + // Escalate to SIGKILL only if SIGTERM wait loop exhausted + if (attempts >= 10) { + try { + process.kill(pid, 'SIGKILL'); + } catch { + // Already dead — good + } } removePidFile(); diff --git a/src/cursor/cursor-models.ts b/src/cursor/cursor-models.ts index ec68b801..931e89c5 100644 --- a/src/cursor/cursor-models.ts +++ b/src/cursor/cursor-models.ts @@ -7,6 +7,7 @@ import * as http from 'http'; import type { CursorModel } from './types'; +import { isDaemonRunning } from './cursor-daemon'; /** Default daemon port */ export const DEFAULT_CURSOR_PORT = 4242; @@ -142,8 +143,12 @@ export async function fetchModelsFromDaemon(port: number): Promise { + if (!(await isDaemonRunning(port))) { + return DEFAULT_CURSOR_MODELS; + } return fetchModelsFromDaemon(port); } diff --git a/tests/unit/cursor/cursor-daemon.test.ts b/tests/unit/cursor/cursor-daemon.test.ts index b07012a7..acdecab8 100644 --- a/tests/unit/cursor/cursor-daemon.test.ts +++ b/tests/unit/cursor/cursor-daemon.test.ts @@ -13,6 +13,7 @@ import { isDaemonRunning, getDaemonStatus, stopDaemon, + startDaemon, } from '../../../src/cursor/cursor-daemon'; // Test isolation @@ -116,6 +117,26 @@ describe('removePidFile', () => { }); }); +describe('startDaemon', () => { + it('rejects invalid port (0)', async () => { + const result = await startDaemon({ port: 0, model: 'test' }); + expect(result.success).toBe(false); + expect(result.error).toContain('Invalid port'); + }); + + it('rejects invalid port (65536)', async () => { + const result = await startDaemon({ port: 65536, model: 'test' }); + expect(result.success).toBe(false); + expect(result.error).toContain('Invalid port'); + }); + + it('rejects non-integer port', async () => { + const result = await startDaemon({ port: 3.14, model: 'test' }); + expect(result.success).toBe(false); + expect(result.error).toContain('Invalid port'); + }); +}); + describe('isDaemonRunning', () => { it('returns false when no daemon is running on port', async () => { // Use a port that should not have anything running From 934238740e124f6b89d04f571fe201153dbf85af Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 08:21:39 +0700 Subject: [PATCH 14/17] fix(cursor): export missing symbols, eliminate subcommand sync risk, improve tests - Export detectProvider and formatModelName from barrel index - Export CURSOR_SUBCOMMANDS from cursor-command.ts, import in ccs.ts - Use getCcsDir() in tests instead of manual path construction - Add handleCursorCommand routing test for unknown subcommand --- src/ccs.ts | 16 +++++---- src/commands/cursor-command.ts | 12 +++++++ src/cursor/index.ts | 2 ++ tests/unit/cursor/cursor-daemon.test.ts | 45 +++++++++++++++---------- 4 files changed, 50 insertions(+), 25 deletions(-) diff --git a/src/ccs.ts b/src/ccs.ts index 8d3a7f2e..2880dab9 100644 --- a/src/ccs.ts +++ b/src/ccs.ts @@ -536,13 +536,15 @@ async function main(): Promise { // Only route to command handler for known subcommands, otherwise treat as profile // Note: Bare `ccs cursor` shows help (unlike copilot which falls through to profile) // This is intentional — cursor has no profile-switching mode - // Keep in sync with cursor-command.ts switch cases - const CURSOR_SUBCOMMANDS = ['auth', 'status', 'models', 'start', 'stop', 'help', '--help', '-h']; - if (firstArg === 'cursor' && (args.length === 1 || CURSOR_SUBCOMMANDS.includes(args[1]))) { - // `ccs cursor ` - route to cursor command handler - const { handleCursorCommand } = await import('./commands/cursor-command'); - const exitCode = await handleCursorCommand(args.slice(1)); - process.exit(exitCode); + if (firstArg === 'cursor') { + const { handleCursorCommand, CURSOR_SUBCOMMANDS } = await import('./commands/cursor-command'); + if ( + args.length === 1 || + CURSOR_SUBCOMMANDS.includes(args[1] as (typeof CURSOR_SUBCOMMANDS)[number]) + ) { + const exitCode = await handleCursorCommand(args.slice(1)); + process.exit(exitCode); + } } // Special case: copilot command (GitHub Copilot integration) diff --git a/src/commands/cursor-command.ts b/src/commands/cursor-command.ts index 1ae9c4df..b7139586 100644 --- a/src/commands/cursor-command.ts +++ b/src/commands/cursor-command.ts @@ -23,6 +23,18 @@ const DEFAULT_CURSOR_CONFIG = { model: DEFAULT_CURSOR_MODEL, }; +/** Valid cursor subcommands — imported by ccs.ts for routing */ +export const CURSOR_SUBCOMMANDS = [ + 'auth', + 'status', + 'models', + 'start', + 'stop', + 'help', + '--help', + '-h', +] as const; + /** * Handle cursor subcommand. */ diff --git a/src/cursor/index.ts b/src/cursor/index.ts index d589d799..3647a612 100644 --- a/src/cursor/index.ts +++ b/src/cursor/index.ts @@ -29,6 +29,8 @@ export { fetchModelsFromDaemon, getAvailableModels, getDefaultModel, + detectProvider, + formatModelName, } from './cursor-models'; // Executor diff --git a/tests/unit/cursor/cursor-daemon.test.ts b/tests/unit/cursor/cursor-daemon.test.ts index acdecab8..1d0ab32a 100644 --- a/tests/unit/cursor/cursor-daemon.test.ts +++ b/tests/unit/cursor/cursor-daemon.test.ts @@ -15,6 +15,8 @@ import { stopDaemon, startDaemon, } from '../../../src/cursor/cursor-daemon'; +import { getCcsDir } from '../../../src/utils/config-manager'; +import { handleCursorCommand } from '../../../src/commands/cursor-command'; // Test isolation let originalCcsHome: string | undefined; @@ -41,8 +43,8 @@ afterEach(() => { } }); -// CCS_HOME is set to tempDir; getCcsDir() appends '.ccs' to it -const ccsDir = () => path.join(tempDir, '.ccs'); +// Use getCcsDir() for consistent path resolution with production code +const getTestCursorDir = () => path.join(getCcsDir(), 'cursor'); describe('getPidFromFile', () => { it('returns null when no PID file exists', () => { @@ -50,25 +52,25 @@ describe('getPidFromFile', () => { }); it('returns PID when valid PID file exists', () => { - const cursorDir = path.join(ccsDir(), 'cursor'); - fs.mkdirSync(cursorDir, { recursive: true }); - fs.writeFileSync(path.join(cursorDir, 'daemon.pid'), '12345'); + const dir = getTestCursorDir(); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'daemon.pid'), '12345'); expect(getPidFromFile()).toBe(12345); }); it('returns null when PID file contains invalid content', () => { - const cursorDir = path.join(ccsDir(), 'cursor'); - fs.mkdirSync(cursorDir, { recursive: true }); - fs.writeFileSync(path.join(cursorDir, 'daemon.pid'), 'not-a-number'); + const dir = getTestCursorDir(); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'daemon.pid'), 'not-a-number'); expect(getPidFromFile()).toBeNull(); }); it('trims whitespace from PID file content', () => { - const cursorDir = path.join(ccsDir(), 'cursor'); - fs.mkdirSync(cursorDir, { recursive: true }); - fs.writeFileSync(path.join(cursorDir, 'daemon.pid'), ' 42 \n'); + const dir = getTestCursorDir(); + fs.mkdirSync(dir, { recursive: true }); + fs.writeFileSync(path.join(dir, 'daemon.pid'), ' 42 \n'); expect(getPidFromFile()).toBe(42); }); @@ -78,25 +80,25 @@ describe('writePidToFile', () => { it('creates PID file with correct content', () => { writePidToFile(12345); - const pidFile = path.join(ccsDir(), 'cursor', 'daemon.pid'); + const pidFile = path.join(getTestCursorDir(), 'daemon.pid'); expect(fs.existsSync(pidFile)).toBe(true); expect(fs.readFileSync(pidFile, 'utf8')).toBe('12345'); }); it('creates cursor directory if it does not exist', () => { - const cursorDir = path.join(ccsDir(), 'cursor'); - expect(fs.existsSync(cursorDir)).toBe(false); + const dir = getTestCursorDir(); + expect(fs.existsSync(dir)).toBe(false); writePidToFile(999); - expect(fs.existsSync(cursorDir)).toBe(true); + expect(fs.existsSync(dir)).toBe(true); }); it('overwrites existing PID file', () => { writePidToFile(111); writePidToFile(222); - const pidFile = path.join(ccsDir(), 'cursor', 'daemon.pid'); + const pidFile = path.join(getTestCursorDir(), 'daemon.pid'); expect(fs.readFileSync(pidFile, 'utf8')).toBe('222'); }); }); @@ -104,7 +106,7 @@ describe('writePidToFile', () => { describe('removePidFile', () => { it('removes existing PID file', () => { writePidToFile(12345); - const pidFile = path.join(ccsDir(), 'cursor', 'daemon.pid'); + const pidFile = path.join(getTestCursorDir(), 'daemon.pid'); expect(fs.existsSync(pidFile)).toBe(true); removePidFile(); @@ -177,7 +179,14 @@ describe('stopDaemon', () => { expect(result.error).toBeUndefined(); // PID file should be removed - const pidFile = path.join(ccsDir(), 'cursor', 'daemon.pid'); + const pidFile = path.join(getTestCursorDir(), 'daemon.pid'); expect(fs.existsSync(pidFile)).toBe(false); }); }); + +describe('handleCursorCommand', () => { + it('returns exit code 1 for unknown subcommand', async () => { + const exitCode = await handleCursorCommand(['nonexistent']); + expect(exitCode).toBe(1); + }); +}); From 760a5c3ca4fb10f408ddafc2bcd9a1c20e805e23 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 08:28:32 +0700 Subject: [PATCH 15/17] fix(cursor): harden stopDaemon PID validation, tighten regex, add lifecycle test MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Validate PID belongs to cursor daemon via /proc before signaling - Tighten detectProvider regex to avoid over-matching o-prefixed models - Add integration test for daemon start→health→stop lifecycle - Add void cast on discarded handleHelp() return value - Update model catalog date comment --- src/commands/cursor-command.ts | 2 +- src/cursor/cursor-daemon.ts | 12 ++++++++++++ src/cursor/cursor-models.ts | 4 ++-- tests/unit/cursor/cursor-daemon.test.ts | 23 +++++++++++++++++++++++ 4 files changed, 38 insertions(+), 3 deletions(-) diff --git a/src/commands/cursor-command.ts b/src/commands/cursor-command.ts index b7139586..c5547380 100644 --- a/src/commands/cursor-command.ts +++ b/src/commands/cursor-command.ts @@ -60,7 +60,7 @@ export async function handleCursorCommand(args: string[]): Promise { default: console.error(fail(`Unknown subcommand: ${subcommand}`)); console.error(''); - handleHelp(); + void handleHelp(); // Print help but keep exit code 1 return 1; } } diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts index 1ed5a484..19ad0034 100644 --- a/src/cursor/cursor-daemon.ts +++ b/src/cursor/cursor-daemon.ts @@ -264,6 +264,18 @@ export async function stopDaemon(): Promise<{ success: boolean; error?: string } } try { + // Verify the PID belongs to our daemon before signaling + try { + const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8'); + if (!cmdline.includes('cursor') && !cmdline.includes('/health')) { + // PID was reused by an unrelated process + removePidFile(); + return { success: true }; + } + } catch { + // /proc not available (macOS/Windows) or process gone — proceed with kill + } + // Send SIGTERM to the process process.kill(pid, 'SIGTERM'); diff --git a/src/cursor/cursor-models.ts b/src/cursor/cursor-models.ts index 931e89c5..cc74cb1e 100644 --- a/src/cursor/cursor-models.ts +++ b/src/cursor/cursor-models.ts @@ -2,7 +2,7 @@ * Cursor Model Catalog * * Manages available models from Cursor IDE. - * Based on Cursor's supported models as of Feb 2025. + * Based on Cursor's supported models catalog. */ import * as http from 'http'; @@ -165,7 +165,7 @@ export function getDefaultModel(): string { */ export function detectProvider(modelId: string): string { if (modelId.includes('claude')) return 'anthropic'; - if (modelId.includes('gpt') || /^o\d/.test(modelId)) return 'openai'; + if (modelId.includes('gpt') || /^o[1-9]\d*(-|$)/.test(modelId)) return 'openai'; if (modelId.includes('gemini')) return 'google'; if (modelId.includes('cursor')) return 'cursor'; return 'unknown'; diff --git a/tests/unit/cursor/cursor-daemon.test.ts b/tests/unit/cursor/cursor-daemon.test.ts index 1d0ab32a..4865dbed 100644 --- a/tests/unit/cursor/cursor-daemon.test.ts +++ b/tests/unit/cursor/cursor-daemon.test.ts @@ -137,6 +137,29 @@ describe('startDaemon', () => { expect(result.success).toBe(false); expect(result.error).toContain('Invalid port'); }); + + it( + 'starts and stops daemon successfully', + async () => { + const port = 18765; + const result = await startDaemon({ port, model: 'test' }); + expect(result.success).toBe(true); + expect(result.pid).toBeDefined(); + + // Verify health + const running = await isDaemonRunning(port); + expect(running).toBe(true); + + // Stop + const stopResult = await stopDaemon(); + expect(stopResult.success).toBe(true); + + // Verify stopped + const stillRunning = await isDaemonRunning(port); + expect(stillRunning).toBe(false); + }, + 35000 + ); }); describe('isDaemonRunning', () => { From bfc9361701376b0a2d5541f2c8e48e95e2637539 Mon Sep 17 00:00:00 2001 From: Tam Nhu Tran Date: Thu, 12 Feb 2026 08:37:01 +0700 Subject: [PATCH 16/17] fix(cursor): fix router fall-through, add daemon marker, use random test port - Route all `ccs cursor *` to handleCursorCommand (no profile-switching) - Add --ccs-daemon marker to spawned process for stable PID validation - Use random port in lifecycle integration test to prevent CI conflicts - Remove unnecessary .toFixed(1) on integer tokenAge --- src/ccs.ts | 15 ++++----------- src/commands/cursor-command.ts | 2 +- src/cursor/cursor-daemon.ts | 5 +++-- tests/unit/cursor/cursor-daemon.test.ts | 2 +- 4 files changed, 9 insertions(+), 15 deletions(-) diff --git a/src/ccs.ts b/src/ccs.ts index 2880dab9..c12e35b3 100644 --- a/src/ccs.ts +++ b/src/ccs.ts @@ -533,18 +533,11 @@ async function main(): Promise { } // Special case: cursor command (Cursor IDE integration) - // Only route to command handler for known subcommands, otherwise treat as profile - // Note: Bare `ccs cursor` shows help (unlike copilot which falls through to profile) - // This is intentional — cursor has no profile-switching mode + // All `ccs cursor *` routes to cursor command handler — cursor has no profile-switching mode if (firstArg === 'cursor') { - const { handleCursorCommand, CURSOR_SUBCOMMANDS } = await import('./commands/cursor-command'); - if ( - args.length === 1 || - CURSOR_SUBCOMMANDS.includes(args[1] as (typeof CURSOR_SUBCOMMANDS)[number]) - ) { - const exitCode = await handleCursorCommand(args.slice(1)); - process.exit(exitCode); - } + const { handleCursorCommand } = await import('./commands/cursor-command'); + const exitCode = await handleCursorCommand(args.slice(1)); + process.exit(exitCode); } // Special case: copilot command (GitHub Copilot integration) diff --git a/src/commands/cursor-command.ts b/src/commands/cursor-command.ts index c5547380..ad6ce59a 100644 --- a/src/commands/cursor-command.ts +++ b/src/commands/cursor-command.ts @@ -160,7 +160,7 @@ async function handleStatus(): Promise { console.log(`Authentication: ${authIcon} ${authText}`); if (authStatus.authenticated && authStatus.tokenAge !== undefined) { - console.log(` Token age: ${authStatus.tokenAge.toFixed(1)} hours`); + console.log(` Token age: ${authStatus.tokenAge} hours`); } // Daemon status diff --git a/src/cursor/cursor-daemon.ts b/src/cursor/cursor-daemon.ts index 19ad0034..99fef7b2 100644 --- a/src/cursor/cursor-daemon.ts +++ b/src/cursor/cursor-daemon.ts @@ -179,7 +179,8 @@ export async function startDaemon( `, ]; - proc = spawn(process.execPath, args, { + // Append --ccs-daemon marker for PID validation in stopDaemon + proc = spawn(process.execPath, [...args, '--ccs-daemon'], { stdio: 'ignore', detached: true, }); @@ -267,7 +268,7 @@ export async function stopDaemon(): Promise<{ success: boolean; error?: string } // Verify the PID belongs to our daemon before signaling try { const cmdline = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8'); - if (!cmdline.includes('cursor') && !cmdline.includes('/health')) { + if (!cmdline.includes('--ccs-daemon')) { // PID was reused by an unrelated process removePidFile(); return { success: true }; diff --git a/tests/unit/cursor/cursor-daemon.test.ts b/tests/unit/cursor/cursor-daemon.test.ts index 4865dbed..e6480b9d 100644 --- a/tests/unit/cursor/cursor-daemon.test.ts +++ b/tests/unit/cursor/cursor-daemon.test.ts @@ -141,7 +141,7 @@ describe('startDaemon', () => { it( 'starts and stops daemon successfully', async () => { - const port = 18765; + const port = 10000 + Math.floor(Math.random() * 50000); const result = await startDaemon({ port, model: 'test' }); expect(result.success).toBe(true); expect(result.pid).toBeDefined(); From f6400b4bf92d65dee6f096a7482c7106c841e312 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" Date: Thu, 12 Feb 2026 03:49:10 +0000 Subject: [PATCH 17/17] chore(release): 7.43.0-dev.3 [skip ci] --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 4b1dcab9..554eeb92 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@kaitranntt/ccs", - "version": "7.43.0-dev.2", + "version": "7.43.0-dev.3", "description": "Claude Code Switch - Instant profile switching between Claude Sonnet 4.5 and GLM 4.6", "keywords": [ "cli",