mirror of
https://github.com/tiennm99/ccs.git
synced 2026-10-14 20:17:03 +00:00
feat(cursor): harden daemon integration and model discovery
This commit is contained in:
1 parent
4bd6877dcf
commit
c639cefa7b
11 files changed
+953
-252
No files matched your search
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* Cursor Client Policy
|
||||
*
|
||||
* Single source of truth for Cursor request identity headers and checksum generation.
|
||||
*/
|
||||
|
||||
import * as crypto from 'crypto';
|
||||
import type { CursorCredentials } from './cursor-protobuf-schema';
|
||||
|
||||
export const CURSOR_CLIENT_VERSION = '2.3.41';
|
||||
export const CURSOR_USER_AGENT = 'connect-es/1.6.1';
|
||||
|
||||
function getClientOs(): string {
|
||||
if (process.platform === 'win32') return 'windows';
|
||||
if (process.platform === 'darwin') return 'macos';
|
||||
return 'linux';
|
||||
}
|
||||
|
||||
function getClientArch(): string {
|
||||
return process.arch === 'arm64' ? 'aarch64' : 'x64';
|
||||
}
|
||||
|
||||
export function normalizeCursorAccessToken(accessToken: string): string {
|
||||
const delimIdx = accessToken.indexOf('::');
|
||||
return delimIdx !== -1 ? accessToken.slice(delimIdx + 2) : accessToken;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate checksum using Jyh cipher (time-based XOR with rolling key seed=165)
|
||||
*/
|
||||
export function generateCursorChecksum(machineId: string, nowMs: number = Date.now()): string {
|
||||
if (!machineId) {
|
||||
throw new Error('Machine ID is required for Cursor API');
|
||||
}
|
||||
|
||||
const timestamp = Math.floor(nowMs / 1000000);
|
||||
// JS bitwise shifts wrap modulo 32, so >>40 and >>32 give wrong results.
|
||||
// Use Math.trunc division for upper bytes that exceed 32-bit range.
|
||||
const byteArray = new Uint8Array([
|
||||
Math.trunc(timestamp / 2 ** 40) & 0xff,
|
||||
Math.trunc(timestamp / 2 ** 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}`;
|
||||
}
|
||||
|
||||
function buildCursorBaseHeaders(credentials: CursorCredentials): Record<string, string> {
|
||||
const cleanToken = normalizeCursorAccessToken(credentials.accessToken);
|
||||
|
||||
if (!cleanToken) {
|
||||
throw new Error('Access token is empty after parsing');
|
||||
}
|
||||
|
||||
if (!credentials.machineId) {
|
||||
throw new Error('Machine ID is required for Cursor API');
|
||||
}
|
||||
|
||||
const ghostMode = credentials.ghostMode !== false;
|
||||
const tokenHash = crypto.createHash('sha256').update(cleanToken).digest('hex');
|
||||
|
||||
return {
|
||||
authorization: `Bearer ${cleanToken}`,
|
||||
'x-amzn-trace-id': `Root=${crypto.randomUUID()}`,
|
||||
'x-client-key': tokenHash,
|
||||
'x-cursor-checksum': generateCursorChecksum(credentials.machineId),
|
||||
'x-cursor-client-version': CURSOR_CLIENT_VERSION,
|
||||
'x-cursor-client-type': 'ide',
|
||||
'x-cursor-client-os': getClientOs(),
|
||||
'x-cursor-client-arch': getClientArch(),
|
||||
'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': tokenHash.substring(0, 36),
|
||||
};
|
||||
}
|
||||
|
||||
export function buildCursorConnectHeaders(credentials: CursorCredentials): Record<string, string> {
|
||||
return {
|
||||
...buildCursorBaseHeaders(credentials),
|
||||
'connect-accept-encoding': 'gzip',
|
||||
'connect-protocol-version': '1',
|
||||
'content-type': 'application/connect+proto',
|
||||
'user-agent': CURSOR_USER_AGENT,
|
||||
};
|
||||
}
|
||||
|
||||
export function buildCursorModelsHeaders(credentials: CursorCredentials): Record<string, string> {
|
||||
return {
|
||||
...buildCursorBaseHeaders(credentials),
|
||||
accept: 'application/json',
|
||||
'user-agent': CURSOR_USER_AGENT,
|
||||
};
|
||||
}
|
||||
@@ -8,7 +8,7 @@ import * as http from 'http';
|
||||
import { Readable } from 'stream';
|
||||
import { CursorExecutor } from './cursor-executor';
|
||||
import { checkAuthStatus } from './cursor-auth';
|
||||
import { DEFAULT_CURSOR_MODEL, DEFAULT_CURSOR_MODELS } from './cursor-models';
|
||||
import { DEFAULT_CURSOR_MODEL, getModelsForDaemon } from './cursor-models';
|
||||
import type { CursorTool } from './cursor-protobuf-schema';
|
||||
|
||||
interface DaemonRuntimeOptions {
|
||||
@@ -184,7 +184,19 @@ export function startCursorDaemonServer(options: DaemonRuntimeOptions): http.Ser
|
||||
}
|
||||
|
||||
if (method === 'GET' && requestUrl === '/v1/models') {
|
||||
const data = DEFAULT_CURSOR_MODELS.map((model) => ({
|
||||
const authStatus = checkAuthStatus();
|
||||
const models = await getModelsForDaemon({
|
||||
credentials:
|
||||
authStatus.authenticated && !authStatus.expired && authStatus.credentials
|
||||
? {
|
||||
accessToken: authStatus.credentials.accessToken,
|
||||
machineId: authStatus.credentials.machineId,
|
||||
ghostMode: options.ghostMode,
|
||||
}
|
||||
: null,
|
||||
});
|
||||
|
||||
const data = models.map((model) => ({
|
||||
id: model.id,
|
||||
object: 'model',
|
||||
created: 0,
|
||||
|
||||
@@ -0,0 +1,173 @@
|
||||
/**
|
||||
* Cursor Default Model Catalog
|
||||
*/
|
||||
|
||||
import type { CursorModel } from './types';
|
||||
|
||||
/** Default model ID */
|
||||
export const DEFAULT_CURSOR_MODEL = 'gpt-5.3-codex';
|
||||
|
||||
/**
|
||||
* Default models available through Cursor IDE.
|
||||
* Used as fallback when daemon is not reachable.
|
||||
* Source: Cursor docs model catalog (Feb 2026)
|
||||
*/
|
||||
export const DEFAULT_CURSOR_MODELS: CursorModel[] = [
|
||||
// Anthropic Models
|
||||
{
|
||||
id: 'claude-4.6-opus',
|
||||
name: 'Claude 4.6 Opus',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
{
|
||||
id: 'claude-4.6-opus-fast-mode',
|
||||
name: 'Claude 4.6 Opus (Fast mode)',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
{
|
||||
id: 'claude-4.5-sonnet',
|
||||
name: 'Claude 4.5 Sonnet',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
{
|
||||
id: 'claude-4.5-opus',
|
||||
name: 'Claude 4.5 Opus',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
{
|
||||
id: 'claude-4.5-haiku',
|
||||
name: 'Claude 4.5 Haiku',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
{
|
||||
id: 'claude-4-sonnet',
|
||||
name: 'Claude 4 Sonnet',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
{
|
||||
id: 'claude-4-sonnet-1m',
|
||||
name: 'Claude 4 Sonnet 1M',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
|
||||
// Cursor Models
|
||||
{
|
||||
id: 'composer-1.5',
|
||||
name: 'Composer 1.5',
|
||||
provider: 'cursor',
|
||||
},
|
||||
{
|
||||
id: 'composer-1',
|
||||
name: 'Composer 1',
|
||||
provider: 'cursor',
|
||||
},
|
||||
|
||||
// OpenAI Models
|
||||
{
|
||||
id: 'gpt-5.3-codex',
|
||||
name: 'GPT-5.3 Codex',
|
||||
provider: 'openai',
|
||||
isDefault: true,
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.2-codex',
|
||||
name: 'GPT-5.2 Codex',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.2',
|
||||
name: 'GPT-5.2',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.1-codex',
|
||||
name: 'GPT-5.1 Codex',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.1-codex-max',
|
||||
name: 'GPT-5.1 Codex Max',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.1-codex-mini',
|
||||
name: 'GPT-5.1 Codex Mini',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5-codex',
|
||||
name: 'GPT-5-Codex',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5',
|
||||
name: 'GPT-5',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5-fast',
|
||||
name: 'GPT-5 Fast',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5-mini',
|
||||
name: 'GPT-5 Mini',
|
||||
provider: 'openai',
|
||||
},
|
||||
|
||||
// Google Models
|
||||
{
|
||||
id: 'gemini-3-pro',
|
||||
name: 'Gemini 3 Pro',
|
||||
provider: 'google',
|
||||
},
|
||||
{
|
||||
id: 'gemini-3-pro-image-preview',
|
||||
name: 'Gemini 3 Pro Image Preview',
|
||||
provider: 'google',
|
||||
},
|
||||
{
|
||||
id: 'gemini-3-flash',
|
||||
name: 'Gemini 3 Flash',
|
||||
provider: 'google',
|
||||
},
|
||||
{
|
||||
id: 'gemini-2.5-flash',
|
||||
name: 'Gemini 2.5 Flash',
|
||||
provider: 'google',
|
||||
},
|
||||
|
||||
// xAI Models
|
||||
{
|
||||
id: 'grok-code',
|
||||
name: 'Grok Code',
|
||||
provider: 'xai',
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* Detect provider from model ID.
|
||||
*/
|
||||
export function detectProvider(modelId: string): string {
|
||||
if (modelId.includes('claude')) return 'anthropic';
|
||||
if (modelId.includes('gpt') || /^o[1-9]\d*(-|$)/.test(modelId)) return 'openai';
|
||||
if (modelId.includes('gemini')) return 'google';
|
||||
if (modelId.includes('cursor') || modelId.includes('composer')) return 'cursor';
|
||||
if (modelId.includes('grok')) return 'xai';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
/**
|
||||
* Format model ID to human-readable name.
|
||||
*/
|
||||
export function formatModelName(modelId: string): string {
|
||||
const model = DEFAULT_CURSOR_MODELS.find((m) => m.id === modelId);
|
||||
if (model) {
|
||||
return model.name;
|
||||
}
|
||||
|
||||
return modelId
|
||||
.split('-')
|
||||
.map((word) => word.charAt(0).toUpperCase() + word.slice(1))
|
||||
.join(' ');
|
||||
}
|
||||
@@ -3,11 +3,11 @@
|
||||
* Handles HTTP/2 requests to Cursor API with protobuf encoding/decoding
|
||||
*/
|
||||
|
||||
import * as crypto from 'crypto';
|
||||
import type { IncomingHttpHeaders } from 'http';
|
||||
import { generateCursorBody, extractTextFromResponse } from './cursor-protobuf.js';
|
||||
import { buildCursorRequest } from './cursor-translator.js';
|
||||
import type { CursorTool, CursorCredentials } from './cursor-protobuf-schema.js';
|
||||
import { buildCursorConnectHeaders, generateCursorChecksum } from './cursor-client-policy.js';
|
||||
|
||||
import { StreamingFrameParser, decompressPayload } from './cursor-stream-parser.js';
|
||||
|
||||
@@ -92,8 +92,6 @@ function createErrorResponse(jsonError: {
|
||||
export class CursorExecutor {
|
||||
private readonly baseUrl = 'https://api2.cursor.sh';
|
||||
private readonly chatPath = '/aiserver.v1.AiService/StreamChat';
|
||||
private readonly CURSOR_CLIENT_VERSION = '2.3.41';
|
||||
private readonly CURSOR_USER_AGENT = 'connect-es/1.6.1';
|
||||
|
||||
buildUrl(): string {
|
||||
return `${this.baseUrl}${this.chatPath}`;
|
||||
@@ -103,87 +101,11 @@ export class CursorExecutor {
|
||||
* Generate checksum using Jyh cipher (time-based XOR with rolling key seed=165)
|
||||
*/
|
||||
generateChecksum(machineId: string): string {
|
||||
const timestamp = Math.floor(Date.now() / 1000000);
|
||||
// JS bitwise shifts wrap modulo 32, so >>40 and >>32 give wrong results.
|
||||
// Use Math.trunc division for upper bytes that exceed 32-bit range.
|
||||
const byteArray = new Uint8Array([
|
||||
Math.trunc(timestamp / 2 ** 40) & 0xff,
|
||||
Math.trunc(timestamp / 2 ** 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}`;
|
||||
return generateCursorChecksum(machineId);
|
||||
}
|
||||
|
||||
buildHeaders(credentials: CursorCredentials): Record<string, string> {
|
||||
const accessToken = credentials.accessToken;
|
||||
const machineId = credentials.machineId;
|
||||
const ghostMode = credentials.ghostMode !== false;
|
||||
|
||||
if (!machineId) {
|
||||
throw new Error('Machine ID is required for Cursor API');
|
||||
}
|
||||
|
||||
const delimIdx = accessToken.indexOf('::');
|
||||
const cleanToken = delimIdx !== -1 ? accessToken.slice(delimIdx + 2) : accessToken;
|
||||
|
||||
if (!cleanToken) {
|
||||
throw new Error('Access token is empty after parsing');
|
||||
}
|
||||
|
||||
return {
|
||||
authorization: `Bearer ${cleanToken}`,
|
||||
'connect-accept-encoding': 'gzip',
|
||||
'connect-protocol-version': '1',
|
||||
'content-type': 'application/connect+proto',
|
||||
'user-agent': this.CURSOR_USER_AGENT,
|
||||
'x-amzn-trace-id': `Root=${crypto.randomUUID()}`,
|
||||
'x-client-key': crypto.createHash('sha256').update(cleanToken).digest('hex'),
|
||||
'x-cursor-checksum': this.generateChecksum(machineId),
|
||||
'x-cursor-client-version': this.CURSOR_CLIENT_VERSION,
|
||||
'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),
|
||||
};
|
||||
return buildCursorConnectHeaders(credentials);
|
||||
}
|
||||
|
||||
transformRequest(
|
||||
@@ -589,6 +511,15 @@ export class CursorExecutor {
|
||||
emitSSE(buildChunk(delta, null));
|
||||
chunkCount++;
|
||||
}
|
||||
|
||||
if (frame.type === 'thinking') {
|
||||
const delta =
|
||||
chunkCount === 0 && toolCallCount === 0
|
||||
? { role: 'assistant', reasoning_content: frame.text }
|
||||
: { reasoning_content: frame.text };
|
||||
emitSSE(buildChunk(delta, null));
|
||||
chunkCount++;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -659,6 +590,7 @@ export class CursorExecutor {
|
||||
private *parseProtobufFrames(buffer: Buffer): Generator<
|
||||
| { type: 'error'; response: Response }
|
||||
| { type: 'text'; text: string }
|
||||
| { type: 'thinking'; text: string }
|
||||
| {
|
||||
type: 'toolCall';
|
||||
toolCall: {
|
||||
@@ -732,6 +664,10 @@ export class CursorExecutor {
|
||||
if (result.text) {
|
||||
yield { type: 'text', text: result.text };
|
||||
}
|
||||
|
||||
if (result.thinking) {
|
||||
yield { type: 'thinking', text: result.thinking };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -740,6 +676,7 @@ export class CursorExecutor {
|
||||
const created = Math.floor(Date.now() / 1000);
|
||||
|
||||
let totalContent = '';
|
||||
let totalReasoning = '';
|
||||
const toolCalls: Array<{
|
||||
id: string;
|
||||
type: string;
|
||||
@@ -793,6 +730,10 @@ export class CursorExecutor {
|
||||
if (frame.type === 'text') {
|
||||
totalContent += frame.text;
|
||||
}
|
||||
|
||||
if (frame.type === 'thinking') {
|
||||
totalReasoning += frame.text;
|
||||
}
|
||||
}
|
||||
|
||||
// Finalize remaining tool calls
|
||||
@@ -814,6 +755,7 @@ export class CursorExecutor {
|
||||
const message: {
|
||||
role: string;
|
||||
content: string | null;
|
||||
reasoning_content?: string | null;
|
||||
tool_calls?: Array<{
|
||||
id: string;
|
||||
type: string;
|
||||
@@ -828,6 +770,10 @@ export class CursorExecutor {
|
||||
message.tool_calls = toolCalls;
|
||||
}
|
||||
|
||||
if (totalReasoning) {
|
||||
message.reasoning_content = totalReasoning;
|
||||
}
|
||||
|
||||
const completion = {
|
||||
id: responseId,
|
||||
object: 'chat.completion',
|
||||
@@ -992,6 +938,27 @@ export class CursorExecutor {
|
||||
})}\n\n`
|
||||
);
|
||||
}
|
||||
|
||||
if (frame.type === 'thinking') {
|
||||
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', reasoning_content: frame.text }
|
||||
: { reasoning_content: frame.text },
|
||||
finish_reason: null,
|
||||
},
|
||||
],
|
||||
})}\n\n`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (chunks.length === 0 && toolCalls.length === 0) {
|
||||
|
||||
+138
-165
@@ -2,156 +2,158 @@
|
||||
* Cursor Model Catalog
|
||||
*
|
||||
* Manages available models from Cursor IDE.
|
||||
* Based on Cursor's supported models catalog.
|
||||
*/
|
||||
|
||||
import * as http from 'http';
|
||||
import type { CursorModel } from './types';
|
||||
import type { CursorCredentials } from './cursor-protobuf-schema';
|
||||
import { isDaemonRunning } from './cursor-daemon';
|
||||
import { buildCursorModelsHeaders } from './cursor-client-policy';
|
||||
import {
|
||||
DEFAULT_CURSOR_MODEL,
|
||||
DEFAULT_CURSOR_MODELS,
|
||||
detectProvider,
|
||||
formatModelName,
|
||||
} from './cursor-default-models';
|
||||
|
||||
/** Default daemon port */
|
||||
export const DEFAULT_CURSOR_PORT = 20129;
|
||||
|
||||
/** Default model ID */
|
||||
export const DEFAULT_CURSOR_MODEL = 'gpt-5.3-codex';
|
||||
export { DEFAULT_CURSOR_MODEL, DEFAULT_CURSOR_MODELS, detectProvider, formatModelName };
|
||||
|
||||
/**
|
||||
* Default models available through Cursor IDE.
|
||||
* Used as fallback when daemon is not reachable.
|
||||
* Source: Cursor docs model catalog (Feb 2026)
|
||||
*/
|
||||
export const DEFAULT_CURSOR_MODELS: CursorModel[] = [
|
||||
// Anthropic Models
|
||||
{
|
||||
id: 'claude-4.6-opus',
|
||||
name: 'Claude 4.6 Opus',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
{
|
||||
id: 'claude-4.6-opus-fast-mode',
|
||||
name: 'Claude 4.6 Opus (Fast mode)',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
{
|
||||
id: 'claude-4.5-sonnet',
|
||||
name: 'Claude 4.5 Sonnet',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
{
|
||||
id: 'claude-4.5-opus',
|
||||
name: 'Claude 4.5 Opus',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
{
|
||||
id: 'claude-4.5-haiku',
|
||||
name: 'Claude 4.5 Haiku',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
{
|
||||
id: 'claude-4-sonnet',
|
||||
name: 'Claude 4 Sonnet',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
{
|
||||
id: 'claude-4-sonnet-1m',
|
||||
name: 'Claude 4 Sonnet 1M',
|
||||
provider: 'anthropic',
|
||||
},
|
||||
const CURSOR_MODELS_API_ENDPOINT = 'https://api2.cursor.sh/v1/models';
|
||||
const CURSOR_MODELS_CACHE_TTL_MS = 5 * 60 * 1000;
|
||||
|
||||
// Cursor Models
|
||||
{
|
||||
id: 'composer-1.5',
|
||||
name: 'Composer 1.5',
|
||||
provider: 'cursor',
|
||||
},
|
||||
{
|
||||
id: 'composer-1',
|
||||
name: 'Composer 1',
|
||||
provider: 'cursor',
|
||||
},
|
||||
let liveModelsCache: {
|
||||
models: CursorModel[];
|
||||
expiresAtMs: number;
|
||||
} | null = null;
|
||||
|
||||
// OpenAI Models
|
||||
{
|
||||
id: 'gpt-5.3-codex',
|
||||
name: 'GPT-5.3 Codex',
|
||||
provider: 'openai',
|
||||
isDefault: true,
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.2-codex',
|
||||
name: 'GPT-5.2 Codex',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.2',
|
||||
name: 'GPT-5.2',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.1-codex',
|
||||
name: 'GPT-5.1 Codex',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.1-codex-max',
|
||||
name: 'GPT-5.1 Codex Max',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5.1-codex-mini',
|
||||
name: 'GPT-5.1 Codex Mini',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5-codex',
|
||||
name: 'GPT-5-Codex',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5',
|
||||
name: 'GPT-5',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5-fast',
|
||||
name: 'GPT-5 Fast',
|
||||
provider: 'openai',
|
||||
},
|
||||
{
|
||||
id: 'gpt-5-mini',
|
||||
name: 'GPT-5 Mini',
|
||||
provider: 'openai',
|
||||
},
|
||||
interface CursorModelsApiResponse {
|
||||
data?: Array<{ id?: unknown; name?: unknown; provider?: unknown }>;
|
||||
models?: Array<{ id?: unknown; name?: unknown; provider?: unknown }>;
|
||||
}
|
||||
|
||||
// Google Models
|
||||
{
|
||||
id: 'gemini-3-pro',
|
||||
name: 'Gemini 3 Pro',
|
||||
provider: 'google',
|
||||
},
|
||||
{
|
||||
id: 'gemini-3-pro-image-preview',
|
||||
name: 'Gemini 3 Pro Image Preview',
|
||||
provider: 'google',
|
||||
},
|
||||
{
|
||||
id: 'gemini-3-flash',
|
||||
name: 'Gemini 3 Flash',
|
||||
provider: 'google',
|
||||
},
|
||||
{
|
||||
id: 'gemini-2.5-flash',
|
||||
name: 'Gemini 2.5 Flash',
|
||||
provider: 'google',
|
||||
},
|
||||
function normalizeModelRecords(
|
||||
records: Array<{ id?: unknown; name?: unknown; provider?: unknown }>
|
||||
): CursorModel[] {
|
||||
const models: CursorModel[] = [];
|
||||
for (const record of records) {
|
||||
if (!record || typeof record !== 'object') continue;
|
||||
if (typeof record.id !== 'string' || !record.id) continue;
|
||||
const modelId = record.id;
|
||||
const modelName = typeof record.name === 'string' && record.name ? record.name : modelId;
|
||||
const provider =
|
||||
typeof record.provider === 'string' && record.provider
|
||||
? record.provider
|
||||
: detectProvider(modelId);
|
||||
models.push({
|
||||
id: modelId,
|
||||
name: modelName,
|
||||
provider,
|
||||
isDefault: modelId === DEFAULT_CURSOR_MODEL,
|
||||
});
|
||||
}
|
||||
return models;
|
||||
}
|
||||
|
||||
// xAI Models
|
||||
{
|
||||
id: 'grok-code',
|
||||
name: 'Grok Code',
|
||||
provider: 'xai',
|
||||
},
|
||||
];
|
||||
function parseApiModelsResponse(payload: unknown): CursorModel[] | null {
|
||||
if (!payload || typeof payload !== 'object') return null;
|
||||
const response = payload as CursorModelsApiResponse;
|
||||
const records = Array.isArray(response.data)
|
||||
? response.data
|
||||
: Array.isArray(response.models)
|
||||
? response.models
|
||||
: null;
|
||||
|
||||
if (!records) return null;
|
||||
|
||||
const models = normalizeModelRecords(records);
|
||||
return models.length > 0 ? models : null;
|
||||
}
|
||||
|
||||
function getCachedLiveModels(nowMs: number = Date.now()): CursorModel[] | null {
|
||||
if (!liveModelsCache) return null;
|
||||
if (liveModelsCache.expiresAtMs <= nowMs) {
|
||||
liveModelsCache = null;
|
||||
return null;
|
||||
}
|
||||
return liveModelsCache.models;
|
||||
}
|
||||
|
||||
function setCachedLiveModels(models: CursorModel[], nowMs: number = Date.now()): void {
|
||||
liveModelsCache = {
|
||||
models,
|
||||
expiresAtMs: nowMs + CURSOR_MODELS_CACHE_TTL_MS,
|
||||
};
|
||||
}
|
||||
|
||||
export function clearCursorModelsCache(): void {
|
||||
liveModelsCache = null;
|
||||
}
|
||||
|
||||
export async function fetchModelsFromCursorApi(
|
||||
credentials: CursorCredentials,
|
||||
options: {
|
||||
endpoint?: string;
|
||||
timeoutMs?: number;
|
||||
} = {}
|
||||
): Promise<CursorModel[] | null> {
|
||||
if (!credentials.accessToken || !credentials.machineId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const endpoint = options.endpoint || CURSOR_MODELS_API_ENDPOINT;
|
||||
const timeoutMs = options.timeoutMs ?? 5000;
|
||||
const abortController = new AbortController();
|
||||
const timeout = setTimeout(() => abortController.abort(), timeoutMs);
|
||||
|
||||
try {
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'GET',
|
||||
headers: buildCursorModelsHeaders(credentials),
|
||||
signal: abortController.signal,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const payload = (await response.json()) as unknown;
|
||||
return parseApiModelsResponse(payload);
|
||||
} catch {
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
export async function getModelsForDaemon(
|
||||
options: {
|
||||
credentials?: CursorCredentials | null;
|
||||
endpoint?: string;
|
||||
timeoutMs?: number;
|
||||
} = {}
|
||||
): Promise<CursorModel[]> {
|
||||
const cached = getCachedLiveModels();
|
||||
if (cached) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const credentials = options.credentials;
|
||||
if (credentials?.accessToken && credentials.machineId) {
|
||||
const liveModels = await fetchModelsFromCursorApi(credentials, {
|
||||
endpoint: options.endpoint,
|
||||
timeoutMs: options.timeoutMs,
|
||||
});
|
||||
if (liveModels && liveModels.length > 0) {
|
||||
setCachedLiveModels(liveModels);
|
||||
return liveModels;
|
||||
}
|
||||
}
|
||||
|
||||
return DEFAULT_CURSOR_MODELS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch available models from running cursor daemon.
|
||||
@@ -241,32 +243,3 @@ export async function getAvailableModels(port: number): Promise<CursorModel[]> {
|
||||
export function getDefaultModel(): string {
|
||||
return DEFAULT_CURSOR_MODEL;
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect provider from model ID.
|
||||
*/
|
||||
export function detectProvider(modelId: string): string {
|
||||
if (modelId.includes('claude')) return 'anthropic';
|
||||
if (modelId.includes('gpt') || /^o[1-9]\d*(-|$)/.test(modelId)) return 'openai';
|
||||
if (modelId.includes('gemini')) return 'google';
|
||||
if (modelId.includes('cursor') || modelId.includes('composer')) return 'cursor';
|
||||
if (modelId.includes('grok')) return 'xai';
|
||||
return 'unknown';
|
||||
}
|
||||
|
||||
/**
|
||||
* Format model ID to human-readable name.
|
||||
*/
|
||||
export 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(' ');
|
||||
}
|
||||
@@ -34,8 +34,11 @@ export {
|
||||
DEFAULT_CURSOR_PORT,
|
||||
DEFAULT_CURSOR_MODEL,
|
||||
fetchModelsFromDaemon,
|
||||
fetchModelsFromCursorApi,
|
||||
getModelsForDaemon,
|
||||
getAvailableModels,
|
||||
getDefaultModel,
|
||||
clearCursorModelsCache,
|
||||
detectProvider,
|
||||
formatModelName,
|
||||
} from './cursor-models';
|
||||
|
||||
Reference in new issue
Block a user