JIMMYGGG commited on
Commit
fc6ce0b
·
verified ·
1 Parent(s): 407d39e

Upload 4 files

Browse files
Files changed (4) hide show
  1. package.json +17 -0
  2. server.js +326 -0
  3. start.bat +28 -0
  4. start.sh +21 -0
package.json ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "cursor-api",
3
+ "version": "1.0.0",
4
+ "type": "module",
5
+ "description": "Cursor API wrapper for OpenAI format",
6
+ "main": "server.js",
7
+ "scripts": {
8
+ "start": "node server.js",
9
+ "install-start": "npm install && npm start"
10
+ },
11
+ "dependencies": {
12
+ "body-parser": "^1.20.3",
13
+ "express": "^4.21.1",
14
+ "node-fetch": "^3.3.2",
15
+ "uuid": "^9.0.1"
16
+ }
17
+ }
server.js ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import express from 'express';
2
+ import bodyParser from 'body-parser';
3
+ import fetch from 'node-fetch';
4
+ import { v4 as uuidv4 } from 'uuid';
5
+
6
+
7
+ const app = express();
8
+ app.use(bodyParser.json());
9
+
10
+ // Helper function to convert string to hex bytes
11
+ function stringToHex(str,model_name) {
12
+ const bytes = Buffer.from(str, 'utf-8');
13
+ const byteLength = bytes.length;
14
+
15
+ // Calculate lengths and fields similar to Python version
16
+ const FIXED_HEADER = 2;
17
+ const SEPARATOR = 1;
18
+ const FIXED_SUFFIX_LENGTH = 0xA3 + model_name.length;
19
+
20
+ // 计算文本长度字段 (类似 Python 中的 base_length1)
21
+ let textLengthField1, textLengthFieldSize1;
22
+ if (byteLength < 128) {
23
+ textLengthField1 = byteLength.toString(16).padStart(2, '0');
24
+ textLengthFieldSize1 = 1;
25
+ } else {
26
+ const lowByte1 = (byteLength & 0x7F) | 0x80;
27
+ const highByte1 = (byteLength >> 7) & 0xFF;
28
+ textLengthField1 = lowByte1.toString(16).padStart(2, '0') + highByte1.toString(16).padStart(2, '0');
29
+ textLengthFieldSize1 = 2;
30
+ }
31
+
32
+ // 计算基础长度 (类似 Python 中的 base_length)
33
+ const baseLength = byteLength + 0x2A;
34
+ let textLengthField, textLengthFieldSize;
35
+ if (baseLength < 128) {
36
+ textLengthField = baseLength.toString(16).padStart(2, '0');
37
+ textLengthFieldSize = 1;
38
+ } else {
39
+ const lowByte = (baseLength & 0x7F) | 0x80;
40
+ const highByte = (baseLength >> 7) & 0xFF;
41
+ textLengthField = lowByte.toString(16).padStart(2, '0') + highByte.toString(16).padStart(2, '0');
42
+ textLengthFieldSize = 2;
43
+ }
44
+
45
+ // 计算总消息长度
46
+ const messageTotalLength = FIXED_HEADER + textLengthFieldSize + SEPARATOR +
47
+ textLengthFieldSize1 + byteLength + FIXED_SUFFIX_LENGTH;
48
+
49
+ const messageLengthHex = messageTotalLength.toString(16).padStart(10, '0');
50
+
51
+ // 构造完整的十六进制字符串
52
+ const hexString = (
53
+ messageLengthHex +
54
+ "12" +
55
+ textLengthField +
56
+ "0A" +
57
+ textLengthField1 +
58
+ bytes.toString('hex') +
59
+ "10016A2432343163636435662D393162612D343131382D393239612D3936626330313631626432612" +
60
+ "2002A132F643A2F6964656150726F2F656475626F73733A1E0A"+
61
+ // 将模型名称长度转换为两位十六进制,并确保是大写
62
+ Buffer.from(model_name, 'utf-8').length.toString(16).padStart(2, '0').toUpperCase() +
63
+ Buffer.from(model_name, 'utf-8').toString('hex').toUpperCase() +
64
+ "22004A" +
65
+ "24" + "61383761396133342D323164642D343863372D623434662D616636633365636536663765" +
66
+ "680070007A2436393337376535612D386332642D343835342D623564392D653062623232336163303061" +
67
+ "800101B00100C00100E00100E80100"
68
+ ).toUpperCase();
69
+ return Buffer.from(hexString, 'hex');
70
+ }
71
+ // 添加一个测试路由
72
+ app.get('/test', (req, res) => {
73
+ console.log('Test endpoint hit!');
74
+ res.json({ message: 'Test successful' });
75
+ });
76
+ // OpenAI-style chat completions endpoint
77
+ // ... existing code ...
78
+ // ... existing code ...
79
+
80
+ // Add model list endpoint before the chat completions endpoint
81
+ app.get('/v1/models', (req, res) => {
82
+ const models = [
83
+ {
84
+ id: "claude-3.5-sonnet",
85
+ object: "model",
86
+ created: 1706745938,
87
+ owned_by: "cursor"
88
+ },
89
+ {
90
+ id: "gpt-4o",
91
+ object: "model",
92
+ created: 1706745938,
93
+ owned_by: "cursor"
94
+ },
95
+ {
96
+ id: "claude-3-5-sonnet-20241022",
97
+ object: "model",
98
+ created: 1706745938,
99
+ owned_by: "cursor"
100
+ },
101
+ {
102
+ id: "gpt-4o-mini",
103
+ object: "model",
104
+ created: 1706745938,
105
+ owned_by: "cursor"
106
+ },
107
+ {
108
+ id: "o1-mini",
109
+ object: "model",
110
+ created: 1706745938,
111
+ owned_by: "cursor"
112
+ },
113
+ {
114
+ id: "o1-preview",
115
+ object: "model",
116
+ created: 1706745938,
117
+ owned_by: "cursor"
118
+ },
119
+ {
120
+ id: "cursor-small",
121
+ object: "model",
122
+ created: 1706745938,
123
+ owned_by: "cursor"
124
+ }
125
+ ];
126
+
127
+ res.json({
128
+ object: "list",
129
+ data: models
130
+ });
131
+ });
132
+ // 添加一个全局变量来追踪当前使用的密钥索引
133
+ let currentKeyIndex = 0;
134
+ // ... existing code ...
135
+ app.post('/v1/chat/completions', async (req, res) => {
136
+ try {
137
+ const { model,messages, stream = false } = req.body;
138
+ let authToken = req.headers.authorization?.replace('Bearer ', '');
139
+ // 处理逗号分隔的密钥
140
+ const keys = authToken.split(',').map(key => key.trim());
141
+ if (keys.length > 0) {
142
+ // 确保 currentKeyIndex 不会越界
143
+ if (currentKeyIndex >= keys.length) {
144
+ currentKeyIndex = 0;
145
+ }
146
+ // 使用当前索引获取密钥
147
+ authToken = keys[currentKeyIndex];
148
+ // 更新索引
149
+ currentKeyIndex = (currentKeyIndex + 1);
150
+ }
151
+ if (authToken && authToken.includes('%3A%3A')) {
152
+ authToken = authToken.split('%3A%3A')[1];
153
+ }
154
+ if (!messages || !Array.isArray(messages) || messages.length === 0 || !authToken) {
155
+ return res.status(400).json({
156
+ error: 'Invalid request. Messages should be a non-empty array and authorization is required'
157
+ });
158
+ }
159
+
160
+ if (stream) {
161
+ res.setHeader('Content-Type', 'text/event-stream');
162
+ res.setHeader('Cache-Control', 'no-cache');
163
+ res.setHeader('Connection', 'keep-alive');
164
+ }
165
+
166
+ const formattedMessages = messages.map(msg => `${msg.role}:${msg.content}`).join('\n');
167
+ const hexData = stringToHex(formattedMessages, model);
168
+
169
+ const response = await fetch("https://api2.cursor.sh/aiserver.v1.AiService/StreamChat", {
170
+ method: 'POST',
171
+ headers: {
172
+ 'Content-Type': 'application/connect+proto',
173
+ 'authorization': `Bearer ${authToken}`,
174
+ 'connect-accept-encoding': 'gzip,br',
175
+ 'connect-protocol-version': '1',
176
+ 'user-agent': 'connect-es/1.4.0',
177
+ 'x-amzn-trace-id': `Root=${uuidv4()}`,
178
+ 'x-cursor-checksum': 'zo6Qjequ9b9734d1f13c3438ba25ea31ac93d9287248b9d30434934e9fcbfa6b3b22029e/7e4af391f67188693b722eff0090e8e6608bca8fa320ef20a0ccb5d7d62dfdef',
179
+ 'x-cursor-client-version': '0.42.3',
180
+ 'x-cursor-timezone': 'Asia/Shanghai',
181
+ 'x-ghost-mode': 'false',
182
+ 'x-request-id': uuidv4(),
183
+ 'Host': 'api2.cursor.sh'
184
+ },
185
+ body: hexData
186
+ });
187
+ function extractTextFromChunk(chunk) {
188
+ let i = 0;
189
+ let results = [];
190
+
191
+ while (i < chunk.length) {
192
+ // Skip initial zero bytes
193
+ while (i < chunk.length && chunk[i] === 0) {
194
+ i++;
195
+ }
196
+
197
+ if (i >= chunk.length) {
198
+ break;
199
+ }
200
+
201
+ // Skip length byte and newline
202
+ i += 2;
203
+
204
+ // Read content length
205
+ const contentLength = chunk[i];
206
+ i++;
207
+
208
+ // Extract actual content if there's enough data
209
+ if (i + contentLength <= chunk.length) {
210
+ const text = chunk.slice(i, i + contentLength).toString('utf-8');
211
+ if (text.length > 0) {
212
+ results.push(text);
213
+ }
214
+ }
215
+
216
+ i += contentLength;
217
+ }
218
+
219
+ return results.join(''); // Join all extracted text pieces
220
+ }
221
+ if (stream) {
222
+ const responseId = `chatcmpl-${uuidv4()}`;
223
+
224
+
225
+
226
+ // 使用类似 Python 的方式处理流
227
+ for await (const chunk of response.body) {
228
+ // 检查 chunk 是否以 0x00000000 开头
229
+ if (chunk && Buffer.isBuffer(chunk) &&
230
+ chunk.length >= 4 &&
231
+ chunk[0] === 0x00 &&
232
+ chunk[1] === 0x00 &&
233
+ chunk[2] === 0x00 &&
234
+ chunk[3] === 0x00) {
235
+ try {
236
+ // 跳过前7个字节的头部数据
237
+ const text = extractTextFromChunk(chunk);
238
+ if (text.length > 0) {
239
+ // 发送内容块
240
+ res.write(`data: ${JSON.stringify({
241
+ id: responseId,
242
+ object: 'chat.completion.chunk',
243
+ created: Math.floor(Date.now() / 1000),
244
+ model: model,
245
+ choices: [{
246
+ index: 0,
247
+ delta: {
248
+ content: text
249
+ }
250
+ }]
251
+ })}\n\n`);
252
+ }
253
+ } catch (error) {
254
+ console.error('Chunk processing error:', error);
255
+ continue;
256
+ }
257
+ }
258
+ }
259
+
260
+
261
+
262
+ res.write('data: [DONE]\n\n');
263
+ return res.end();
264
+ } else {
265
+ const responseId = `chatcmpl-${uuidv4()}`;
266
+
267
+
268
+
269
+ // 使用类似 Python 的方式处理流
270
+ let text =""
271
+ for await (const chunk of response.body) {
272
+ // 检查 chunk 是否以 0x00000000 开头
273
+ if (chunk && Buffer.isBuffer(chunk) &&
274
+ chunk.length >= 4 &&
275
+ chunk[0] === 0x00 &&
276
+ chunk[1] === 0x00 &&
277
+ chunk[2] === 0x00 &&
278
+ chunk[3] === 0x00) {
279
+ try {
280
+ // 跳过前7个字节的头部数据
281
+ text = text+extractTextFromChunk(chunk);
282
+
283
+ } catch (error) {
284
+ console.error('Chunk processing error:', error);
285
+ continue;
286
+ }
287
+ }
288
+ }
289
+
290
+ return res.json({
291
+ id: `chatcmpl-${uuidv4()}`,
292
+ object: 'chat.completion',
293
+ created: Math.floor(Date.now() / 1000),
294
+ model: 'claude-3-sonnet-20241022',
295
+ choices: [{
296
+ index: 0,
297
+ message: {
298
+ role: 'assistant',
299
+ content: text
300
+ },
301
+ finish_reason: 'stop'
302
+ }],
303
+ usage: {
304
+ prompt_tokens: 0,
305
+ completion_tokens: 0,
306
+ total_tokens: 0
307
+ }
308
+ });
309
+ }
310
+ } catch (error) {
311
+ console.error('Error:', error);
312
+ if (!res.headersSent) {
313
+ if (req.body.stream) {
314
+ res.write(`data: ${JSON.stringify({ error: 'Internal server error' })}\n\n`);
315
+ return res.end();
316
+ } else {
317
+ return res.status(500).json({ error: 'Internal server error' });
318
+ }
319
+ }
320
+ }
321
+ });
322
+
323
+ const PORT = process.env.PORT || 3000;
324
+ app.listen(PORT, () => {
325
+ console.log(`Server running on port ${PORT}`);
326
+ });
start.bat ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ echo Starting Cursor API Server...
3
+
4
+ :: Check if node_modules exists
5
+ if not exist "node_modules\" (
6
+ echo Installing dependencies...
7
+ call npm install express body-parser node-fetch uuid
8
+ )
9
+
10
+ :: Check if package.json exists
11
+ if not exist "package.json" (
12
+ echo Creating package.json...
13
+ echo {> package.json
14
+ echo "type": "module",>> package.json
15
+ echo "dependencies": {>> package.json
16
+ echo "express": "^4.18.2",>> package.json
17
+ echo "body-parser": "^1.20.2",>> package.json
18
+ echo "node-fetch": "^3.3.2",>> package.json
19
+ echo "uuid": "^9.0.1">> package.json
20
+ echo }>> package.json
21
+ echo }>> package.json
22
+ )
23
+
24
+ :: Start the server
25
+ echo Starting server...
26
+ node server.js
27
+
28
+ pause
start.sh ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # 安装必要的系统依赖
4
+ echo "Installing system dependencies..."
5
+ pkg update -y
6
+ pkg upgrade -y
7
+ pkg install -y openssl nodejs
8
+
9
+ # 检查 node 是否安装
10
+ if ! command -v node &> /dev/null; then
11
+ echo "Node.js is not installed. Please install Node.js first."
12
+ exit 1
13
+ fi
14
+
15
+ # 安装依赖
16
+ echo "Installing dependencies..."
17
+ npm install --yes
18
+
19
+ # 启动服务器
20
+ echo "Starting server..."
21
+ node server.js