notioncode 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +10 -4
  2. package/agent-runtime-server/package-lock.json +4381 -0
  3. package/agent-runtime-server/package.json +36 -0
  4. package/agent-runtime-server/scripts/fix-node-pty.js +67 -0
  5. package/agent-runtime-server/server/agent-session-service.js +816 -0
  6. package/agent-runtime-server/server/claude-sdk.js +836 -0
  7. package/agent-runtime-server/server/cli.js +330 -0
  8. package/agent-runtime-server/server/constants/config.js +5 -0
  9. package/agent-runtime-server/server/cursor-cli.js +335 -0
  10. package/agent-runtime-server/server/database/db.js +653 -0
  11. package/agent-runtime-server/server/database/init.sql +99 -0
  12. package/agent-runtime-server/server/gemini-cli.js +460 -0
  13. package/agent-runtime-server/server/gemini-response-handler.js +79 -0
  14. package/agent-runtime-server/server/index.js +2569 -0
  15. package/agent-runtime-server/server/load-env.js +32 -0
  16. package/agent-runtime-server/server/middleware/auth.js +132 -0
  17. package/agent-runtime-server/server/openai-codex.js +512 -0
  18. package/agent-runtime-server/server/projects.js +2594 -0
  19. package/agent-runtime-server/server/providers/claude/adapter.js +278 -0
  20. package/agent-runtime-server/server/providers/codex/adapter.js +248 -0
  21. package/agent-runtime-server/server/providers/cursor/adapter.js +353 -0
  22. package/agent-runtime-server/server/providers/gemini/adapter.js +186 -0
  23. package/agent-runtime-server/server/providers/registry.js +44 -0
  24. package/agent-runtime-server/server/providers/types.js +119 -0
  25. package/agent-runtime-server/server/providers/utils.js +29 -0
  26. package/agent-runtime-server/server/routes/agent-sessions.js +238 -0
  27. package/agent-runtime-server/server/routes/agent.js +1244 -0
  28. package/agent-runtime-server/server/routes/auth.js +144 -0
  29. package/agent-runtime-server/server/routes/cli-auth.js +478 -0
  30. package/agent-runtime-server/server/routes/codex.js +329 -0
  31. package/agent-runtime-server/server/routes/commands.js +596 -0
  32. package/agent-runtime-server/server/routes/cursor.js +798 -0
  33. package/agent-runtime-server/server/routes/gemini.js +24 -0
  34. package/agent-runtime-server/server/routes/git.js +1508 -0
  35. package/agent-runtime-server/server/routes/mcp-utils.js +48 -0
  36. package/agent-runtime-server/server/routes/mcp.js +552 -0
  37. package/agent-runtime-server/server/routes/messages.js +61 -0
  38. package/agent-runtime-server/server/routes/plugins.js +307 -0
  39. package/agent-runtime-server/server/routes/projects.js +548 -0
  40. package/agent-runtime-server/server/routes/settings.js +276 -0
  41. package/agent-runtime-server/server/routes/taskmaster.js +1963 -0
  42. package/agent-runtime-server/server/routes/user.js +123 -0
  43. package/agent-runtime-server/server/services/notification-orchestrator.js +227 -0
  44. package/agent-runtime-server/server/services/vapid-keys.js +35 -0
  45. package/agent-runtime-server/server/sessionManager.js +226 -0
  46. package/agent-runtime-server/server/utils/commandParser.js +303 -0
  47. package/agent-runtime-server/server/utils/frontmatter.js +18 -0
  48. package/agent-runtime-server/server/utils/gitConfig.js +34 -0
  49. package/agent-runtime-server/server/utils/mcp-detector.js +198 -0
  50. package/agent-runtime-server/server/utils/plugin-loader.js +457 -0
  51. package/agent-runtime-server/server/utils/plugin-process-manager.js +184 -0
  52. package/agent-runtime-server/server/utils/taskmaster-websocket.js +129 -0
  53. package/agent-runtime-server/shared/modelConstants.js +12 -0
  54. package/agent-runtime-server/shared/modelConstants.test.js +34 -0
  55. package/agent-runtime-server/shared/networkHosts.js +22 -0
  56. package/agent-runtime-server/test_sdk.mjs +16 -0
  57. package/bin/bridges/darwin-x64/nocode-bridge +0 -0
  58. package/bin/{nocode-local.js → notioncode.js} +0 -0
  59. package/dist/assets/icon-CQtd7WEB.png +0 -0
  60. package/dist/assets/index-Ctr1ES45.js +1 -0
  61. package/dist/assets/index-DhCWie1Z.css +1 -0
  62. package/dist/assets/index-DzqxG7Z8.js +689 -0
  63. package/dist/index.html +46 -0
  64. package/dist/onboarding/step1_create.png +0 -0
  65. package/dist/onboarding/step2_capabilities.png +0 -0
  66. package/dist/onboarding/step2b_content_access.png +0 -0
  67. package/dist/onboarding/step2c_page_access.png +0 -0
  68. package/dist/onboarding/step3_token.png +0 -0
  69. package/dist/onboarding/step4_webhook.png +0 -0
  70. package/dist/onboarding/step6a_verify.png +0 -0
  71. package/dist/onboarding/step6b_copy_verify_token.png +0 -0
  72. package/dist/tinyfish-fish-only.png +0 -0
  73. package/lib/install.js +33 -2
  74. package/lib/start.js +157 -25
  75. package/package.json +7 -4
  76. package/src/shared/modelRegistry.d.ts +24 -0
  77. package/src/shared/modelRegistry.js +163 -0
@@ -0,0 +1,798 @@
1
+ import express from 'express';
2
+ import { promises as fs } from 'fs';
3
+ import path from 'path';
4
+ import os from 'os';
5
+ import { spawn } from 'child_process';
6
+ import sqlite3 from 'sqlite3';
7
+ import { open } from 'sqlite';
8
+ import crypto from 'crypto';
9
+ import { CURSOR_MODELS } from '../../shared/modelConstants.js';
10
+ import { applyCustomSessionNames } from '../database/db.js';
11
+
12
+ const router = express.Router();
13
+
14
+ // GET /api/cursor/config - Read Cursor CLI configuration
15
+ router.get('/config', async (req, res) => {
16
+ try {
17
+ const configPath = path.join(os.homedir(), '.cursor', 'cli-config.json');
18
+
19
+ try {
20
+ const configContent = await fs.readFile(configPath, 'utf8');
21
+ const config = JSON.parse(configContent);
22
+
23
+ res.json({
24
+ success: true,
25
+ config: config,
26
+ path: configPath
27
+ });
28
+ } catch (error) {
29
+ // Config doesn't exist or is invalid
30
+ console.log('Cursor config not found or invalid:', error.message);
31
+
32
+ // Return default config
33
+ res.json({
34
+ success: true,
35
+ config: {
36
+ version: 1,
37
+ model: {
38
+ modelId: CURSOR_MODELS.DEFAULT,
39
+ displayName: "GPT-5"
40
+ },
41
+ permissions: {
42
+ allow: [],
43
+ deny: []
44
+ }
45
+ },
46
+ isDefault: true
47
+ });
48
+ }
49
+ } catch (error) {
50
+ console.error('Error reading Cursor config:', error);
51
+ res.status(500).json({
52
+ error: 'Failed to read Cursor configuration',
53
+ details: error.message
54
+ });
55
+ }
56
+ });
57
+
58
+ // POST /api/cursor/config - Update Cursor CLI configuration
59
+ router.post('/config', async (req, res) => {
60
+ try {
61
+ const { permissions, model } = req.body;
62
+ const configPath = path.join(os.homedir(), '.cursor', 'cli-config.json');
63
+
64
+ // Read existing config or create default
65
+ let config = {
66
+ version: 1,
67
+ editor: {
68
+ vimMode: false
69
+ },
70
+ hasChangedDefaultModel: false,
71
+ privacyCache: {
72
+ ghostMode: false,
73
+ privacyMode: 3,
74
+ updatedAt: Date.now()
75
+ }
76
+ };
77
+
78
+ try {
79
+ const existing = await fs.readFile(configPath, 'utf8');
80
+ config = JSON.parse(existing);
81
+ } catch (error) {
82
+ // Config doesn't exist, use defaults
83
+ console.log('Creating new Cursor config');
84
+ }
85
+
86
+ // Update permissions if provided
87
+ if (permissions) {
88
+ config.permissions = {
89
+ allow: permissions.allow || [],
90
+ deny: permissions.deny || []
91
+ };
92
+ }
93
+
94
+ // Update model if provided
95
+ if (model) {
96
+ config.model = model;
97
+ config.hasChangedDefaultModel = true;
98
+ }
99
+
100
+ // Ensure directory exists
101
+ const configDir = path.dirname(configPath);
102
+ await fs.mkdir(configDir, { recursive: true });
103
+
104
+ // Write updated config
105
+ await fs.writeFile(configPath, JSON.stringify(config, null, 2));
106
+
107
+ res.json({
108
+ success: true,
109
+ config: config,
110
+ message: 'Cursor configuration updated successfully'
111
+ });
112
+ } catch (error) {
113
+ console.error('Error updating Cursor config:', error);
114
+ res.status(500).json({
115
+ error: 'Failed to update Cursor configuration',
116
+ details: error.message
117
+ });
118
+ }
119
+ });
120
+
121
+ // GET /api/cursor/mcp - Read Cursor MCP servers configuration
122
+ router.get('/mcp', async (req, res) => {
123
+ try {
124
+ const mcpPath = path.join(os.homedir(), '.cursor', 'mcp.json');
125
+
126
+ try {
127
+ const mcpContent = await fs.readFile(mcpPath, 'utf8');
128
+ const mcpConfig = JSON.parse(mcpContent);
129
+
130
+ // Convert to UI-friendly format
131
+ const servers = [];
132
+ if (mcpConfig.mcpServers && typeof mcpConfig.mcpServers === 'object') {
133
+ for (const [name, config] of Object.entries(mcpConfig.mcpServers)) {
134
+ const server = {
135
+ id: name,
136
+ name: name,
137
+ type: 'stdio',
138
+ scope: 'cursor',
139
+ config: {},
140
+ raw: config
141
+ };
142
+
143
+ // Determine transport type and extract config
144
+ if (config.command) {
145
+ server.type = 'stdio';
146
+ server.config.command = config.command;
147
+ server.config.args = config.args || [];
148
+ server.config.env = config.env || {};
149
+ } else if (config.url) {
150
+ server.type = config.transport || 'http';
151
+ server.config.url = config.url;
152
+ server.config.headers = config.headers || {};
153
+ }
154
+
155
+ servers.push(server);
156
+ }
157
+ }
158
+
159
+ res.json({
160
+ success: true,
161
+ servers: servers,
162
+ path: mcpPath
163
+ });
164
+ } catch (error) {
165
+ // MCP config doesn't exist
166
+ console.log('Cursor MCP config not found:', error.message);
167
+ res.json({
168
+ success: true,
169
+ servers: [],
170
+ isDefault: true
171
+ });
172
+ }
173
+ } catch (error) {
174
+ console.error('Error reading Cursor MCP config:', error);
175
+ res.status(500).json({
176
+ error: 'Failed to read Cursor MCP configuration',
177
+ details: error.message
178
+ });
179
+ }
180
+ });
181
+
182
+ // POST /api/cursor/mcp/add - Add MCP server to Cursor configuration
183
+ router.post('/mcp/add', async (req, res) => {
184
+ try {
185
+ const { name, type = 'stdio', command, args = [], url, headers = {}, env = {} } = req.body;
186
+ const mcpPath = path.join(os.homedir(), '.cursor', 'mcp.json');
187
+
188
+ console.log(`➕ Adding MCP server to Cursor config: ${name}`);
189
+
190
+ // Read existing config or create new
191
+ let mcpConfig = { mcpServers: {} };
192
+
193
+ try {
194
+ const existing = await fs.readFile(mcpPath, 'utf8');
195
+ mcpConfig = JSON.parse(existing);
196
+ if (!mcpConfig.mcpServers) {
197
+ mcpConfig.mcpServers = {};
198
+ }
199
+ } catch (error) {
200
+ console.log('Creating new Cursor MCP config');
201
+ }
202
+
203
+ // Build server config based on type
204
+ let serverConfig = {};
205
+
206
+ if (type === 'stdio') {
207
+ serverConfig = {
208
+ command: command,
209
+ args: args,
210
+ env: env
211
+ };
212
+ } else if (type === 'http' || type === 'sse') {
213
+ serverConfig = {
214
+ url: url,
215
+ transport: type,
216
+ headers: headers
217
+ };
218
+ }
219
+
220
+ // Add server to config
221
+ mcpConfig.mcpServers[name] = serverConfig;
222
+
223
+ // Ensure directory exists
224
+ const mcpDir = path.dirname(mcpPath);
225
+ await fs.mkdir(mcpDir, { recursive: true });
226
+
227
+ // Write updated config
228
+ await fs.writeFile(mcpPath, JSON.stringify(mcpConfig, null, 2));
229
+
230
+ res.json({
231
+ success: true,
232
+ message: `MCP server "${name}" added to Cursor configuration`,
233
+ config: mcpConfig
234
+ });
235
+ } catch (error) {
236
+ console.error('Error adding MCP server to Cursor:', error);
237
+ res.status(500).json({
238
+ error: 'Failed to add MCP server',
239
+ details: error.message
240
+ });
241
+ }
242
+ });
243
+
244
+ // DELETE /api/cursor/mcp/:name - Remove MCP server from Cursor configuration
245
+ router.delete('/mcp/:name', async (req, res) => {
246
+ try {
247
+ const { name } = req.params;
248
+ const mcpPath = path.join(os.homedir(), '.cursor', 'mcp.json');
249
+
250
+ console.log(`🗑️ Removing MCP server from Cursor config: ${name}`);
251
+
252
+ // Read existing config
253
+ let mcpConfig = { mcpServers: {} };
254
+
255
+ try {
256
+ const existing = await fs.readFile(mcpPath, 'utf8');
257
+ mcpConfig = JSON.parse(existing);
258
+ } catch (error) {
259
+ return res.status(404).json({
260
+ error: 'Cursor MCP configuration not found'
261
+ });
262
+ }
263
+
264
+ // Check if server exists
265
+ if (!mcpConfig.mcpServers || !mcpConfig.mcpServers[name]) {
266
+ return res.status(404).json({
267
+ error: `MCP server "${name}" not found in Cursor configuration`
268
+ });
269
+ }
270
+
271
+ // Remove server from config
272
+ delete mcpConfig.mcpServers[name];
273
+
274
+ // Write updated config
275
+ await fs.writeFile(mcpPath, JSON.stringify(mcpConfig, null, 2));
276
+
277
+ res.json({
278
+ success: true,
279
+ message: `MCP server "${name}" removed from Cursor configuration`,
280
+ config: mcpConfig
281
+ });
282
+ } catch (error) {
283
+ console.error('Error removing MCP server from Cursor:', error);
284
+ res.status(500).json({
285
+ error: 'Failed to remove MCP server',
286
+ details: error.message
287
+ });
288
+ }
289
+ });
290
+
291
+ // POST /api/cursor/mcp/add-json - Add MCP server using JSON format
292
+ router.post('/mcp/add-json', async (req, res) => {
293
+ try {
294
+ const { name, jsonConfig } = req.body;
295
+ const mcpPath = path.join(os.homedir(), '.cursor', 'mcp.json');
296
+
297
+ console.log(`➕ Adding MCP server to Cursor config via JSON: ${name}`);
298
+
299
+ // Validate and parse JSON config
300
+ let parsedConfig;
301
+ try {
302
+ parsedConfig = typeof jsonConfig === 'string' ? JSON.parse(jsonConfig) : jsonConfig;
303
+ } catch (parseError) {
304
+ return res.status(400).json({
305
+ error: 'Invalid JSON configuration',
306
+ details: parseError.message
307
+ });
308
+ }
309
+
310
+ // Read existing config or create new
311
+ let mcpConfig = { mcpServers: {} };
312
+
313
+ try {
314
+ const existing = await fs.readFile(mcpPath, 'utf8');
315
+ mcpConfig = JSON.parse(existing);
316
+ if (!mcpConfig.mcpServers) {
317
+ mcpConfig.mcpServers = {};
318
+ }
319
+ } catch (error) {
320
+ console.log('Creating new Cursor MCP config');
321
+ }
322
+
323
+ // Add server to config
324
+ mcpConfig.mcpServers[name] = parsedConfig;
325
+
326
+ // Ensure directory exists
327
+ const mcpDir = path.dirname(mcpPath);
328
+ await fs.mkdir(mcpDir, { recursive: true });
329
+
330
+ // Write updated config
331
+ await fs.writeFile(mcpPath, JSON.stringify(mcpConfig, null, 2));
332
+
333
+ res.json({
334
+ success: true,
335
+ message: `MCP server "${name}" added to Cursor configuration via JSON`,
336
+ config: mcpConfig
337
+ });
338
+ } catch (error) {
339
+ console.error('Error adding MCP server to Cursor via JSON:', error);
340
+ res.status(500).json({
341
+ error: 'Failed to add MCP server',
342
+ details: error.message
343
+ });
344
+ }
345
+ });
346
+
347
+ // GET /api/cursor/sessions - Get Cursor sessions from SQLite database
348
+ router.get('/sessions', async (req, res) => {
349
+ try {
350
+ const { projectPath } = req.query;
351
+
352
+ // Calculate cwdID hash for the project path (Cursor uses MD5 hash)
353
+ const cwdId = crypto.createHash('md5').update(projectPath || process.cwd()).digest('hex');
354
+ const cursorChatsPath = path.join(os.homedir(), '.cursor', 'chats', cwdId);
355
+
356
+
357
+ // Check if the directory exists
358
+ try {
359
+ await fs.access(cursorChatsPath);
360
+ } catch (error) {
361
+ // No sessions for this project
362
+ return res.json({
363
+ success: true,
364
+ sessions: [],
365
+ cwdId: cwdId,
366
+ path: cursorChatsPath
367
+ });
368
+ }
369
+
370
+ // List all session directories
371
+ const sessionDirs = await fs.readdir(cursorChatsPath);
372
+ const sessions = [];
373
+
374
+ for (const sessionId of sessionDirs) {
375
+ const sessionPath = path.join(cursorChatsPath, sessionId);
376
+ const storeDbPath = path.join(sessionPath, 'store.db');
377
+ let dbStatMtimeMs = null;
378
+
379
+ try {
380
+ // Check if store.db exists
381
+ await fs.access(storeDbPath);
382
+
383
+ // Capture store.db mtime as a reliable fallback timestamp (last activity)
384
+ try {
385
+ const stat = await fs.stat(storeDbPath);
386
+ dbStatMtimeMs = stat.mtimeMs;
387
+ } catch (_) {}
388
+
389
+ // Open SQLite database
390
+ const db = await open({
391
+ filename: storeDbPath,
392
+ driver: sqlite3.Database,
393
+ mode: sqlite3.OPEN_READONLY
394
+ });
395
+
396
+ // Get metadata from meta table
397
+ const metaRows = await db.all(`
398
+ SELECT key, value FROM meta
399
+ `);
400
+
401
+ let sessionData = {
402
+ id: sessionId,
403
+ name: 'Untitled Session',
404
+ createdAt: null,
405
+ mode: null,
406
+ projectPath: projectPath,
407
+ lastMessage: null,
408
+ messageCount: 0
409
+ };
410
+
411
+ // Parse meta table entries
412
+ for (const row of metaRows) {
413
+ if (row.value) {
414
+ try {
415
+ // Try to decode as hex-encoded JSON
416
+ const hexMatch = row.value.toString().match(/^[0-9a-fA-F]+$/);
417
+ if (hexMatch) {
418
+ const jsonStr = Buffer.from(row.value, 'hex').toString('utf8');
419
+ const data = JSON.parse(jsonStr);
420
+
421
+ if (row.key === 'agent') {
422
+ sessionData.name = data.name || sessionData.name;
423
+ // Normalize createdAt to ISO string in milliseconds
424
+ let createdAt = data.createdAt;
425
+ if (typeof createdAt === 'number') {
426
+ if (createdAt < 1e12) {
427
+ createdAt = createdAt * 1000; // seconds -> ms
428
+ }
429
+ sessionData.createdAt = new Date(createdAt).toISOString();
430
+ } else if (typeof createdAt === 'string') {
431
+ const n = Number(createdAt);
432
+ if (!Number.isNaN(n)) {
433
+ const ms = n < 1e12 ? n * 1000 : n;
434
+ sessionData.createdAt = new Date(ms).toISOString();
435
+ } else {
436
+ // Assume it's already an ISO/date string
437
+ const d = new Date(createdAt);
438
+ sessionData.createdAt = isNaN(d.getTime()) ? null : d.toISOString();
439
+ }
440
+ } else {
441
+ sessionData.createdAt = sessionData.createdAt || null;
442
+ }
443
+ sessionData.mode = data.mode;
444
+ sessionData.agentId = data.agentId;
445
+ sessionData.latestRootBlobId = data.latestRootBlobId;
446
+ }
447
+ } else {
448
+ // If not hex, use raw value for simple keys
449
+ if (row.key === 'name') {
450
+ sessionData.name = row.value.toString();
451
+ }
452
+ }
453
+ } catch (e) {
454
+ console.log(`Could not parse meta value for key ${row.key}:`, e.message);
455
+ }
456
+ }
457
+ }
458
+
459
+ // Get message count from JSON blobs only (actual messages, not DAG structure)
460
+ try {
461
+ const blobCount = await db.get(`
462
+ SELECT COUNT(*) as count
463
+ FROM blobs
464
+ WHERE substr(data, 1, 1) = X'7B'
465
+ `);
466
+ sessionData.messageCount = blobCount.count;
467
+
468
+ // Get the most recent JSON blob for preview (actual message, not DAG structure)
469
+ const lastBlob = await db.get(`
470
+ SELECT data FROM blobs
471
+ WHERE substr(data, 1, 1) = X'7B'
472
+ ORDER BY rowid DESC
473
+ LIMIT 1
474
+ `);
475
+
476
+ if (lastBlob && lastBlob.data) {
477
+ try {
478
+ // Try to extract readable preview from blob (may contain binary with embedded JSON)
479
+ const raw = lastBlob.data.toString('utf8');
480
+ let preview = '';
481
+ // Attempt direct JSON parse
482
+ try {
483
+ const parsed = JSON.parse(raw);
484
+ if (parsed?.content) {
485
+ if (Array.isArray(parsed.content)) {
486
+ const firstText = parsed.content.find(p => p?.type === 'text' && p.text)?.text || '';
487
+ preview = firstText;
488
+ } else if (typeof parsed.content === 'string') {
489
+ preview = parsed.content;
490
+ }
491
+ }
492
+ } catch (_) {}
493
+ if (!preview) {
494
+ // Strip non-printable and try to find JSON chunk
495
+ const cleaned = raw.replace(/[^\x09\x0A\x0D\x20-\x7E]/g, '');
496
+ const s = cleaned;
497
+ const start = s.indexOf('{');
498
+ const end = s.lastIndexOf('}');
499
+ if (start !== -1 && end > start) {
500
+ const jsonStr = s.slice(start, end + 1);
501
+ try {
502
+ const parsed = JSON.parse(jsonStr);
503
+ if (parsed?.content) {
504
+ if (Array.isArray(parsed.content)) {
505
+ const firstText = parsed.content.find(p => p?.type === 'text' && p.text)?.text || '';
506
+ preview = firstText;
507
+ } else if (typeof parsed.content === 'string') {
508
+ preview = parsed.content;
509
+ }
510
+ }
511
+ } catch (_) {
512
+ preview = s;
513
+ }
514
+ } else {
515
+ preview = s;
516
+ }
517
+ }
518
+ if (preview && preview.length > 0) {
519
+ sessionData.lastMessage = preview.substring(0, 100) + (preview.length > 100 ? '...' : '');
520
+ }
521
+ } catch (e) {
522
+ console.log('Could not parse blob data:', e.message);
523
+ }
524
+ }
525
+ } catch (e) {
526
+ console.log('Could not read blobs:', e.message);
527
+ }
528
+
529
+ await db.close();
530
+
531
+ // Finalize createdAt: use parsed meta value when valid, else fall back to store.db mtime
532
+ if (!sessionData.createdAt) {
533
+ if (dbStatMtimeMs && Number.isFinite(dbStatMtimeMs)) {
534
+ sessionData.createdAt = new Date(dbStatMtimeMs).toISOString();
535
+ }
536
+ }
537
+
538
+ sessions.push(sessionData);
539
+
540
+ } catch (error) {
541
+ console.log(`Could not read session ${sessionId}:`, error.message);
542
+ }
543
+ }
544
+
545
+ // Fallback: ensure createdAt is a valid ISO string (use session directory mtime as last resort)
546
+ for (const s of sessions) {
547
+ if (!s.createdAt) {
548
+ try {
549
+ const sessionDir = path.join(cursorChatsPath, s.id);
550
+ const st = await fs.stat(sessionDir);
551
+ s.createdAt = new Date(st.mtimeMs).toISOString();
552
+ } catch {
553
+ s.createdAt = new Date().toISOString();
554
+ }
555
+ }
556
+ }
557
+ // Sort sessions by creation date (newest first)
558
+ sessions.sort((a, b) => {
559
+ if (!a.createdAt) return 1;
560
+ if (!b.createdAt) return -1;
561
+ return new Date(b.createdAt) - new Date(a.createdAt);
562
+ });
563
+
564
+ applyCustomSessionNames(sessions, 'cursor');
565
+
566
+ res.json({
567
+ success: true,
568
+ sessions: sessions,
569
+ cwdId: cwdId,
570
+ path: cursorChatsPath
571
+ });
572
+
573
+ } catch (error) {
574
+ console.error('Error reading Cursor sessions:', error);
575
+ res.status(500).json({
576
+ error: 'Failed to read Cursor sessions',
577
+ details: error.message
578
+ });
579
+ }
580
+ });
581
+
582
+ // GET /api/cursor/sessions/:sessionId - Get specific Cursor session from SQLite
583
+ router.get('/sessions/:sessionId', async (req, res) => {
584
+ try {
585
+ const { sessionId } = req.params;
586
+ const { projectPath } = req.query;
587
+
588
+ // Calculate cwdID hash for the project path
589
+ const cwdId = crypto.createHash('md5').update(projectPath || process.cwd()).digest('hex');
590
+ const storeDbPath = path.join(os.homedir(), '.cursor', 'chats', cwdId, sessionId, 'store.db');
591
+
592
+
593
+ // Open SQLite database
594
+ const db = await open({
595
+ filename: storeDbPath,
596
+ driver: sqlite3.Database,
597
+ mode: sqlite3.OPEN_READONLY
598
+ });
599
+
600
+ // Get all blobs to build the DAG structure
601
+ const allBlobs = await db.all(`
602
+ SELECT rowid, id, data FROM blobs
603
+ `);
604
+
605
+ // Build the DAG structure from parent-child relationships
606
+ const blobMap = new Map(); // id -> blob data
607
+ const parentRefs = new Map(); // blob id -> [parent blob ids]
608
+ const childRefs = new Map(); // blob id -> [child blob ids]
609
+ const jsonBlobs = []; // Clean JSON messages
610
+
611
+ for (const blob of allBlobs) {
612
+ blobMap.set(blob.id, blob);
613
+
614
+ // Check if this is a JSON blob (actual message) or protobuf (DAG structure)
615
+ if (blob.data && blob.data[0] === 0x7B) { // Starts with '{' - JSON blob
616
+ try {
617
+ const parsed = JSON.parse(blob.data.toString('utf8'));
618
+ jsonBlobs.push({ ...blob, parsed });
619
+ } catch (e) {
620
+ console.log('Failed to parse JSON blob:', blob.rowid);
621
+ }
622
+ } else if (blob.data) { // Protobuf blob - extract parent references
623
+ const parents = [];
624
+ let i = 0;
625
+
626
+ // Scan for parent references (0x0A 0x20 followed by 32-byte hash)
627
+ while (i < blob.data.length - 33) {
628
+ if (blob.data[i] === 0x0A && blob.data[i+1] === 0x20) {
629
+ const parentHash = blob.data.slice(i+2, i+34).toString('hex');
630
+ if (blobMap.has(parentHash)) {
631
+ parents.push(parentHash);
632
+ }
633
+ i += 34;
634
+ } else {
635
+ i++;
636
+ }
637
+ }
638
+
639
+ if (parents.length > 0) {
640
+ parentRefs.set(blob.id, parents);
641
+ // Update child references
642
+ for (const parentId of parents) {
643
+ if (!childRefs.has(parentId)) {
644
+ childRefs.set(parentId, []);
645
+ }
646
+ childRefs.get(parentId).push(blob.id);
647
+ }
648
+ }
649
+ }
650
+ }
651
+
652
+ // Perform topological sort to get chronological order
653
+ const visited = new Set();
654
+ const sorted = [];
655
+
656
+ // DFS-based topological sort
657
+ function visit(nodeId) {
658
+ if (visited.has(nodeId)) return;
659
+ visited.add(nodeId);
660
+
661
+ // Visit all parents first (dependencies)
662
+ const parents = parentRefs.get(nodeId) || [];
663
+ for (const parentId of parents) {
664
+ visit(parentId);
665
+ }
666
+
667
+ // Add this node after all its parents
668
+ const blob = blobMap.get(nodeId);
669
+ if (blob) {
670
+ sorted.push(blob);
671
+ }
672
+ }
673
+
674
+ // Start with nodes that have no parents (roots)
675
+ for (const blob of allBlobs) {
676
+ if (!parentRefs.has(blob.id)) {
677
+ visit(blob.id);
678
+ }
679
+ }
680
+
681
+ // Visit any remaining nodes (disconnected components)
682
+ for (const blob of allBlobs) {
683
+ visit(blob.id);
684
+ }
685
+
686
+ // Now extract JSON messages in the order they appear in the sorted DAG
687
+ const messageOrder = new Map(); // JSON blob id -> order index
688
+ let orderIndex = 0;
689
+
690
+ for (const blob of sorted) {
691
+ // Check if this blob references any JSON messages
692
+ if (blob.data && blob.data[0] !== 0x7B) { // Protobuf blob
693
+ // Look for JSON blob references
694
+ for (const jsonBlob of jsonBlobs) {
695
+ try {
696
+ const jsonIdBytes = Buffer.from(jsonBlob.id, 'hex');
697
+ if (blob.data.includes(jsonIdBytes)) {
698
+ if (!messageOrder.has(jsonBlob.id)) {
699
+ messageOrder.set(jsonBlob.id, orderIndex++);
700
+ }
701
+ }
702
+ } catch (e) {
703
+ // Skip if can't convert ID
704
+ }
705
+ }
706
+ }
707
+ }
708
+
709
+ // Sort JSON blobs by their appearance order in the DAG
710
+ const sortedJsonBlobs = jsonBlobs.sort((a, b) => {
711
+ const orderA = messageOrder.get(a.id) ?? Number.MAX_SAFE_INTEGER;
712
+ const orderB = messageOrder.get(b.id) ?? Number.MAX_SAFE_INTEGER;
713
+ if (orderA !== orderB) return orderA - orderB;
714
+ // Fallback to rowid if not in order map
715
+ return a.rowid - b.rowid;
716
+ });
717
+
718
+ // Use sorted JSON blobs
719
+ const blobs = sortedJsonBlobs.map((blob, idx) => ({
720
+ ...blob,
721
+ sequence_num: idx + 1,
722
+ original_rowid: blob.rowid
723
+ }));
724
+
725
+ // Get metadata from meta table
726
+ const metaRows = await db.all(`
727
+ SELECT key, value FROM meta
728
+ `);
729
+
730
+ // Parse metadata
731
+ let metadata = {};
732
+ for (const row of metaRows) {
733
+ if (row.value) {
734
+ try {
735
+ // Try to decode as hex-encoded JSON
736
+ const hexMatch = row.value.toString().match(/^[0-9a-fA-F]+$/);
737
+ if (hexMatch) {
738
+ const jsonStr = Buffer.from(row.value, 'hex').toString('utf8');
739
+ metadata[row.key] = JSON.parse(jsonStr);
740
+ } else {
741
+ metadata[row.key] = row.value.toString();
742
+ }
743
+ } catch (e) {
744
+ metadata[row.key] = row.value.toString();
745
+ }
746
+ }
747
+ }
748
+
749
+ // Extract messages from sorted JSON blobs
750
+ const messages = [];
751
+ for (const blob of blobs) {
752
+ try {
753
+ // We already parsed JSON blobs earlier
754
+ const parsed = blob.parsed;
755
+
756
+ if (parsed) {
757
+ // Filter out ONLY system messages at the server level
758
+ // Check both direct role and nested message.role
759
+ const role = parsed?.role || parsed?.message?.role;
760
+ if (role === 'system') {
761
+ continue; // Skip only system messages
762
+ }
763
+ messages.push({
764
+ id: blob.id,
765
+ sequence: blob.sequence_num,
766
+ rowid: blob.original_rowid,
767
+ content: parsed
768
+ });
769
+ }
770
+ } catch (e) {
771
+ // Skip blobs that cause errors
772
+ console.log(`Skipping blob ${blob.id}: ${e.message}`);
773
+ }
774
+ }
775
+
776
+ await db.close();
777
+
778
+ res.json({
779
+ success: true,
780
+ session: {
781
+ id: sessionId,
782
+ projectPath: projectPath,
783
+ messages: messages,
784
+ metadata: metadata,
785
+ cwdId: cwdId
786
+ }
787
+ });
788
+
789
+ } catch (error) {
790
+ console.error('Error reading Cursor session:', error);
791
+ res.status(500).json({
792
+ error: 'Failed to read Cursor session',
793
+ details: error.message
794
+ });
795
+ }
796
+ });
797
+
798
+ export default router;