claude-wec 1.0.0
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.
- package/LICENSE +675 -0
- package/README.md +371 -0
- package/dist/api-docs.html +879 -0
- package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
- package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
- package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
- package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
- package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
- package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
- package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
- package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
- package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
- package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
- package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
- package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
- package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
- package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
- package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
- package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
- package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
- package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
- package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
- package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
- package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
- package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
- package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
- package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
- package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
- package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
- package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
- package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
- package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
- package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
- package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
- package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
- package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
- package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
- package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
- package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
- package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
- package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
- package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
- package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
- package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
- package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
- package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
- package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
- package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
- package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
- package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
- package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
- package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
- package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
- package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
- package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
- package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
- package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
- package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
- package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
- package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
- package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
- package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
- package/dist/assets/index-cIxJ4RXb.js +1226 -0
- package/dist/assets/index-oyEz69sP.css +32 -0
- package/dist/assets/vendor-codemirror-CJLzwpLB.js +39 -0
- package/dist/assets/vendor-react-DcyRfQm3.js +59 -0
- package/dist/assets/vendor-xterm-DfaPXD3y.js +66 -0
- package/dist/clear-cache.html +85 -0
- package/dist/convert-icons.md +53 -0
- package/dist/favicon.png +0 -0
- package/dist/favicon.svg +9 -0
- package/dist/generate-icons.js +49 -0
- package/dist/icons/claude-ai-icon.svg +1 -0
- package/dist/icons/codex-white.svg +3 -0
- package/dist/icons/codex.svg +3 -0
- package/dist/icons/cursor-white.svg +12 -0
- package/dist/icons/cursor.svg +1 -0
- package/dist/icons/generate-icons.md +19 -0
- package/dist/icons/icon-128x128.png +0 -0
- package/dist/icons/icon-128x128.svg +12 -0
- package/dist/icons/icon-144x144.png +0 -0
- package/dist/icons/icon-144x144.svg +12 -0
- package/dist/icons/icon-152x152.png +0 -0
- package/dist/icons/icon-152x152.svg +12 -0
- package/dist/icons/icon-192x192.png +0 -0
- package/dist/icons/icon-192x192.svg +12 -0
- package/dist/icons/icon-384x384.png +0 -0
- package/dist/icons/icon-384x384.svg +12 -0
- package/dist/icons/icon-512x512.png +0 -0
- package/dist/icons/icon-512x512.svg +12 -0
- package/dist/icons/icon-72x72.png +0 -0
- package/dist/icons/icon-72x72.svg +12 -0
- package/dist/icons/icon-96x96.png +0 -0
- package/dist/icons/icon-96x96.svg +12 -0
- package/dist/icons/icon-template.svg +12 -0
- package/dist/index.html +52 -0
- package/dist/logo-128.png +0 -0
- package/dist/logo-256.png +0 -0
- package/dist/logo-32.png +0 -0
- package/dist/logo-512.png +0 -0
- package/dist/logo-64.png +0 -0
- package/dist/logo.svg +17 -0
- package/dist/manifest.json +61 -0
- package/dist/screenshots/cli-selection.png +0 -0
- package/dist/screenshots/desktop-main.png +0 -0
- package/dist/screenshots/mobile-chat.png +0 -0
- package/dist/screenshots/tools-modal.png +0 -0
- package/dist/sw.js +49 -0
- package/package.json +109 -0
- package/server/claude-sdk.js +721 -0
- package/server/cli.js +327 -0
- package/server/cursor-cli.js +267 -0
- package/server/database/auth.db +0 -0
- package/server/database/db.js +361 -0
- package/server/database/init.sql +52 -0
- package/server/index.js +1747 -0
- package/server/middleware/auth.js +111 -0
- package/server/openai-codex.js +389 -0
- package/server/projects.js +1604 -0
- package/server/routes/agent.js +1230 -0
- package/server/routes/auth.js +135 -0
- package/server/routes/cli-auth.js +263 -0
- package/server/routes/codex.js +345 -0
- package/server/routes/commands.js +521 -0
- package/server/routes/cursor.js +795 -0
- package/server/routes/git.js +1128 -0
- package/server/routes/mcp-utils.js +48 -0
- package/server/routes/mcp.js +552 -0
- package/server/routes/projects.js +378 -0
- package/server/routes/settings.js +178 -0
- package/server/routes/taskmaster.js +1963 -0
- package/server/routes/user.js +106 -0
- package/server/utils/commandParser.js +303 -0
- package/server/utils/gitConfig.js +24 -0
- package/server/utils/mcp-detector.js +198 -0
- package/server/utils/taskmaster-websocket.js +129 -0
- package/shared/modelConstants.js +65 -0
|
@@ -0,0 +1,1604 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PROJECT DISCOVERY AND MANAGEMENT SYSTEM
|
|
3
|
+
* ========================================
|
|
4
|
+
*
|
|
5
|
+
* This module manages project discovery for both Claude CLI and Cursor CLI sessions.
|
|
6
|
+
*
|
|
7
|
+
* ## Architecture Overview
|
|
8
|
+
*
|
|
9
|
+
* 1. **Claude Projects** (stored in ~/.claude/projects/)
|
|
10
|
+
* - Each project is a directory named with the project path encoded (/ replaced with -)
|
|
11
|
+
* - Contains .jsonl files with conversation history including 'cwd' field
|
|
12
|
+
* - Project metadata stored in ~/.claude/project-config.json
|
|
13
|
+
*
|
|
14
|
+
* 2. **Cursor Projects** (stored in ~/.cursor/chats/)
|
|
15
|
+
* - Each project directory is named with MD5 hash of the absolute project path
|
|
16
|
+
* - Example: /Users/john/myproject -> MD5 -> a1b2c3d4e5f6...
|
|
17
|
+
* - Contains session directories with SQLite databases (store.db)
|
|
18
|
+
* - Project path is NOT stored in the database - only in the MD5 hash
|
|
19
|
+
*
|
|
20
|
+
* ## Project Discovery Strategy
|
|
21
|
+
*
|
|
22
|
+
* 1. **Claude Projects Discovery**:
|
|
23
|
+
* - Scan ~/.claude/projects/ directory for Claude project folders
|
|
24
|
+
* - Extract actual project path from .jsonl files (cwd field)
|
|
25
|
+
* - Fall back to decoded directory name if no sessions exist
|
|
26
|
+
*
|
|
27
|
+
* 2. **Cursor Sessions Discovery**:
|
|
28
|
+
* - For each KNOWN project (from Claude or manually added)
|
|
29
|
+
* - Compute MD5 hash of the project's absolute path
|
|
30
|
+
* - Check if ~/.cursor/chats/{md5_hash}/ directory exists
|
|
31
|
+
* - Read session metadata from SQLite store.db files
|
|
32
|
+
*
|
|
33
|
+
* 3. **Manual Project Addition**:
|
|
34
|
+
* - Users can manually add project paths via UI
|
|
35
|
+
* - Stored in ~/.claude/project-config.json with 'manuallyAdded' flag
|
|
36
|
+
* - Allows discovering Cursor sessions for projects without Claude sessions
|
|
37
|
+
*
|
|
38
|
+
* ## Critical Limitations
|
|
39
|
+
*
|
|
40
|
+
* - **CANNOT discover Cursor-only projects**: From a quick check, there was no mention of
|
|
41
|
+
* the cwd of each project. if someone has the time, you can try to reverse engineer it.
|
|
42
|
+
*
|
|
43
|
+
* - **Project relocation breaks history**: If a project directory is moved or renamed,
|
|
44
|
+
* the MD5 hash changes, making old Cursor sessions inaccessible unless the old
|
|
45
|
+
* path is known and manually added.
|
|
46
|
+
*
|
|
47
|
+
* ## Error Handling
|
|
48
|
+
*
|
|
49
|
+
* - Missing ~/.claude directory is handled gracefully with automatic creation
|
|
50
|
+
* - ENOENT errors are caught and handled without crashing
|
|
51
|
+
* - Empty arrays returned when no projects/sessions exist
|
|
52
|
+
*
|
|
53
|
+
* ## Caching Strategy
|
|
54
|
+
*
|
|
55
|
+
* - Project directory extraction is cached to minimize file I/O
|
|
56
|
+
* - Cache is cleared when project configuration changes
|
|
57
|
+
* - Session data is fetched on-demand, not cached
|
|
58
|
+
*/
|
|
59
|
+
|
|
60
|
+
import { promises as fs } from 'fs';
|
|
61
|
+
import fsSync from 'fs';
|
|
62
|
+
import path from 'path';
|
|
63
|
+
import readline from 'readline';
|
|
64
|
+
import crypto from 'crypto';
|
|
65
|
+
import sqlite3 from 'sqlite3';
|
|
66
|
+
import { open } from 'sqlite';
|
|
67
|
+
import os from 'os';
|
|
68
|
+
|
|
69
|
+
// Import TaskMaster detection functions
|
|
70
|
+
async function detectTaskMasterFolder(projectPath) {
|
|
71
|
+
try {
|
|
72
|
+
const taskMasterPath = path.join(projectPath, '.taskmaster');
|
|
73
|
+
|
|
74
|
+
// Check if .taskmaster directory exists
|
|
75
|
+
try {
|
|
76
|
+
const stats = await fs.stat(taskMasterPath);
|
|
77
|
+
if (!stats.isDirectory()) {
|
|
78
|
+
return {
|
|
79
|
+
hasTaskmaster: false,
|
|
80
|
+
reason: '.taskmaster exists but is not a directory'
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
} catch (error) {
|
|
84
|
+
if (error.code === 'ENOENT') {
|
|
85
|
+
return {
|
|
86
|
+
hasTaskmaster: false,
|
|
87
|
+
reason: '.taskmaster directory not found'
|
|
88
|
+
};
|
|
89
|
+
}
|
|
90
|
+
throw error;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Check for key TaskMaster files
|
|
94
|
+
const keyFiles = [
|
|
95
|
+
'tasks/tasks.json',
|
|
96
|
+
'config.json'
|
|
97
|
+
];
|
|
98
|
+
|
|
99
|
+
const fileStatus = {};
|
|
100
|
+
let hasEssentialFiles = true;
|
|
101
|
+
|
|
102
|
+
for (const file of keyFiles) {
|
|
103
|
+
const filePath = path.join(taskMasterPath, file);
|
|
104
|
+
try {
|
|
105
|
+
await fs.access(filePath);
|
|
106
|
+
fileStatus[file] = true;
|
|
107
|
+
} catch (error) {
|
|
108
|
+
fileStatus[file] = false;
|
|
109
|
+
if (file === 'tasks/tasks.json') {
|
|
110
|
+
hasEssentialFiles = false;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Parse tasks.json if it exists for metadata
|
|
116
|
+
let taskMetadata = null;
|
|
117
|
+
if (fileStatus['tasks/tasks.json']) {
|
|
118
|
+
try {
|
|
119
|
+
const tasksPath = path.join(taskMasterPath, 'tasks/tasks.json');
|
|
120
|
+
const tasksContent = await fs.readFile(tasksPath, 'utf8');
|
|
121
|
+
const tasksData = JSON.parse(tasksContent);
|
|
122
|
+
|
|
123
|
+
// Handle both tagged and legacy formats
|
|
124
|
+
let tasks = [];
|
|
125
|
+
if (tasksData.tasks) {
|
|
126
|
+
// Legacy format
|
|
127
|
+
tasks = tasksData.tasks;
|
|
128
|
+
} else {
|
|
129
|
+
// Tagged format - get tasks from all tags
|
|
130
|
+
Object.values(tasksData).forEach(tagData => {
|
|
131
|
+
if (tagData.tasks) {
|
|
132
|
+
tasks = tasks.concat(tagData.tasks);
|
|
133
|
+
}
|
|
134
|
+
});
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
// Calculate task statistics
|
|
138
|
+
const stats = tasks.reduce((acc, task) => {
|
|
139
|
+
acc.total++;
|
|
140
|
+
acc[task.status] = (acc[task.status] || 0) + 1;
|
|
141
|
+
|
|
142
|
+
// Count subtasks
|
|
143
|
+
if (task.subtasks) {
|
|
144
|
+
task.subtasks.forEach(subtask => {
|
|
145
|
+
acc.subtotalTasks++;
|
|
146
|
+
acc.subtasks = acc.subtasks || {};
|
|
147
|
+
acc.subtasks[subtask.status] = (acc.subtasks[subtask.status] || 0) + 1;
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
return acc;
|
|
152
|
+
}, {
|
|
153
|
+
total: 0,
|
|
154
|
+
subtotalTasks: 0,
|
|
155
|
+
pending: 0,
|
|
156
|
+
'in-progress': 0,
|
|
157
|
+
done: 0,
|
|
158
|
+
review: 0,
|
|
159
|
+
deferred: 0,
|
|
160
|
+
cancelled: 0,
|
|
161
|
+
subtasks: {}
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
taskMetadata = {
|
|
165
|
+
taskCount: stats.total,
|
|
166
|
+
subtaskCount: stats.subtotalTasks,
|
|
167
|
+
completed: stats.done || 0,
|
|
168
|
+
pending: stats.pending || 0,
|
|
169
|
+
inProgress: stats['in-progress'] || 0,
|
|
170
|
+
review: stats.review || 0,
|
|
171
|
+
completionPercentage: stats.total > 0 ? Math.round((stats.done / stats.total) * 100) : 0,
|
|
172
|
+
lastModified: (await fs.stat(tasksPath)).mtime.toISOString()
|
|
173
|
+
};
|
|
174
|
+
} catch (parseError) {
|
|
175
|
+
console.warn('Failed to parse tasks.json:', parseError.message);
|
|
176
|
+
taskMetadata = { error: 'Failed to parse tasks.json' };
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
return {
|
|
181
|
+
hasTaskmaster: true,
|
|
182
|
+
hasEssentialFiles,
|
|
183
|
+
files: fileStatus,
|
|
184
|
+
metadata: taskMetadata,
|
|
185
|
+
path: taskMasterPath
|
|
186
|
+
};
|
|
187
|
+
|
|
188
|
+
} catch (error) {
|
|
189
|
+
console.error('Error detecting TaskMaster folder:', error);
|
|
190
|
+
return {
|
|
191
|
+
hasTaskmaster: false,
|
|
192
|
+
reason: `Error checking directory: ${error.message}`
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// Cache for extracted project directories
|
|
198
|
+
const projectDirectoryCache = new Map();
|
|
199
|
+
|
|
200
|
+
// Clear cache when needed (called when project files change)
|
|
201
|
+
function clearProjectDirectoryCache() {
|
|
202
|
+
projectDirectoryCache.clear();
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
// Load project configuration file
|
|
206
|
+
async function loadProjectConfig() {
|
|
207
|
+
const configPath = path.join(os.homedir(), '.claude', 'project-config.json');
|
|
208
|
+
try {
|
|
209
|
+
const configData = await fs.readFile(configPath, 'utf8');
|
|
210
|
+
return JSON.parse(configData);
|
|
211
|
+
} catch (error) {
|
|
212
|
+
// Return empty config if file doesn't exist
|
|
213
|
+
return {};
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Save project configuration file
|
|
218
|
+
async function saveProjectConfig(config) {
|
|
219
|
+
const claudeDir = path.join(os.homedir(), '.claude');
|
|
220
|
+
const configPath = path.join(claudeDir, 'project-config.json');
|
|
221
|
+
|
|
222
|
+
// Ensure the .claude directory exists
|
|
223
|
+
try {
|
|
224
|
+
await fs.mkdir(claudeDir, { recursive: true });
|
|
225
|
+
} catch (error) {
|
|
226
|
+
if (error.code !== 'EEXIST') {
|
|
227
|
+
throw error;
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
await fs.writeFile(configPath, JSON.stringify(config, null, 2), 'utf8');
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// Generate better display name from path
|
|
235
|
+
async function generateDisplayName(projectName, actualProjectDir = null) {
|
|
236
|
+
// Use actual project directory if provided, otherwise decode from project name
|
|
237
|
+
let projectPath = actualProjectDir || projectName.replace(/-/g, '/');
|
|
238
|
+
|
|
239
|
+
// Try to read package.json from the project path
|
|
240
|
+
try {
|
|
241
|
+
const packageJsonPath = path.join(projectPath, 'package.json');
|
|
242
|
+
const packageData = await fs.readFile(packageJsonPath, 'utf8');
|
|
243
|
+
const packageJson = JSON.parse(packageData);
|
|
244
|
+
|
|
245
|
+
// Return the name from package.json if it exists
|
|
246
|
+
if (packageJson.name) {
|
|
247
|
+
return packageJson.name;
|
|
248
|
+
}
|
|
249
|
+
} catch (error) {
|
|
250
|
+
// Fall back to path-based naming if package.json doesn't exist or can't be read
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// If it starts with /, it's an absolute path
|
|
254
|
+
if (projectPath.startsWith('/')) {
|
|
255
|
+
const parts = projectPath.split('/').filter(Boolean);
|
|
256
|
+
// Return only the last folder name
|
|
257
|
+
return parts[parts.length - 1] || projectPath;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
return projectPath;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Extract the actual project directory from JSONL sessions (with caching)
|
|
264
|
+
async function extractProjectDirectory(projectName) {
|
|
265
|
+
// Check cache first
|
|
266
|
+
if (projectDirectoryCache.has(projectName)) {
|
|
267
|
+
return projectDirectoryCache.get(projectName);
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
// Check project config for originalPath (manually added projects via UI or platform)
|
|
271
|
+
// This handles projects with dashes in their directory names correctly
|
|
272
|
+
const config = await loadProjectConfig();
|
|
273
|
+
if (config[projectName]?.originalPath) {
|
|
274
|
+
const originalPath = config[projectName].originalPath;
|
|
275
|
+
projectDirectoryCache.set(projectName, originalPath);
|
|
276
|
+
return originalPath;
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
|
|
280
|
+
const cwdCounts = new Map();
|
|
281
|
+
let latestTimestamp = 0;
|
|
282
|
+
let latestCwd = null;
|
|
283
|
+
let extractedPath;
|
|
284
|
+
|
|
285
|
+
try {
|
|
286
|
+
// Check if the project directory exists
|
|
287
|
+
await fs.access(projectDir);
|
|
288
|
+
|
|
289
|
+
const files = await fs.readdir(projectDir);
|
|
290
|
+
const jsonlFiles = files.filter(file => file.endsWith('.jsonl'));
|
|
291
|
+
|
|
292
|
+
if (jsonlFiles.length === 0) {
|
|
293
|
+
// Fall back to decoded project name if no sessions
|
|
294
|
+
extractedPath = projectName.replace(/-/g, '/');
|
|
295
|
+
} else {
|
|
296
|
+
// Process all JSONL files to collect cwd values
|
|
297
|
+
for (const file of jsonlFiles) {
|
|
298
|
+
const jsonlFile = path.join(projectDir, file);
|
|
299
|
+
const fileStream = fsSync.createReadStream(jsonlFile);
|
|
300
|
+
const rl = readline.createInterface({
|
|
301
|
+
input: fileStream,
|
|
302
|
+
crlfDelay: Infinity
|
|
303
|
+
});
|
|
304
|
+
|
|
305
|
+
for await (const line of rl) {
|
|
306
|
+
if (line.trim()) {
|
|
307
|
+
try {
|
|
308
|
+
const entry = JSON.parse(line);
|
|
309
|
+
|
|
310
|
+
if (entry.cwd) {
|
|
311
|
+
// Count occurrences of each cwd
|
|
312
|
+
cwdCounts.set(entry.cwd, (cwdCounts.get(entry.cwd) || 0) + 1);
|
|
313
|
+
|
|
314
|
+
// Track the most recent cwd
|
|
315
|
+
const timestamp = new Date(entry.timestamp || 0).getTime();
|
|
316
|
+
if (timestamp > latestTimestamp) {
|
|
317
|
+
latestTimestamp = timestamp;
|
|
318
|
+
latestCwd = entry.cwd;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
} catch (parseError) {
|
|
322
|
+
// Skip malformed lines
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// Determine the best cwd to use
|
|
329
|
+
if (cwdCounts.size === 0) {
|
|
330
|
+
// No cwd found, fall back to decoded project name
|
|
331
|
+
extractedPath = projectName.replace(/-/g, '/');
|
|
332
|
+
} else if (cwdCounts.size === 1) {
|
|
333
|
+
// Only one cwd, use it
|
|
334
|
+
extractedPath = Array.from(cwdCounts.keys())[0];
|
|
335
|
+
} else {
|
|
336
|
+
// Multiple cwd values - prefer the most recent one if it has reasonable usage
|
|
337
|
+
const mostRecentCount = cwdCounts.get(latestCwd) || 0;
|
|
338
|
+
const maxCount = Math.max(...cwdCounts.values());
|
|
339
|
+
|
|
340
|
+
// Use most recent if it has at least 25% of the max count
|
|
341
|
+
if (mostRecentCount >= maxCount * 0.25) {
|
|
342
|
+
extractedPath = latestCwd;
|
|
343
|
+
} else {
|
|
344
|
+
// Otherwise use the most frequently used cwd
|
|
345
|
+
for (const [cwd, count] of cwdCounts.entries()) {
|
|
346
|
+
if (count === maxCount) {
|
|
347
|
+
extractedPath = cwd;
|
|
348
|
+
break;
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Fallback (shouldn't reach here)
|
|
354
|
+
if (!extractedPath) {
|
|
355
|
+
extractedPath = latestCwd || projectName.replace(/-/g, '/');
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
// Cache the result
|
|
361
|
+
projectDirectoryCache.set(projectName, extractedPath);
|
|
362
|
+
|
|
363
|
+
return extractedPath;
|
|
364
|
+
|
|
365
|
+
} catch (error) {
|
|
366
|
+
// If the directory doesn't exist, just use the decoded project name
|
|
367
|
+
if (error.code === 'ENOENT') {
|
|
368
|
+
extractedPath = projectName.replace(/-/g, '/');
|
|
369
|
+
} else {
|
|
370
|
+
console.error(`Error extracting project directory for ${projectName}:`, error);
|
|
371
|
+
// Fall back to decoded project name for other errors
|
|
372
|
+
extractedPath = projectName.replace(/-/g, '/');
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
// Cache the fallback result too
|
|
376
|
+
projectDirectoryCache.set(projectName, extractedPath);
|
|
377
|
+
|
|
378
|
+
return extractedPath;
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
async function getProjects() {
|
|
383
|
+
const claudeDir = path.join(os.homedir(), '.claude', 'projects');
|
|
384
|
+
const config = await loadProjectConfig();
|
|
385
|
+
const projects = [];
|
|
386
|
+
const existingProjects = new Set();
|
|
387
|
+
|
|
388
|
+
try {
|
|
389
|
+
// Check if the .claude/projects directory exists
|
|
390
|
+
await fs.access(claudeDir);
|
|
391
|
+
|
|
392
|
+
// First, get existing Claude projects from the file system
|
|
393
|
+
const entries = await fs.readdir(claudeDir, { withFileTypes: true });
|
|
394
|
+
|
|
395
|
+
for (const entry of entries) {
|
|
396
|
+
if (entry.isDirectory()) {
|
|
397
|
+
existingProjects.add(entry.name);
|
|
398
|
+
const projectPath = path.join(claudeDir, entry.name);
|
|
399
|
+
|
|
400
|
+
// Extract actual project directory from JSONL sessions
|
|
401
|
+
const actualProjectDir = await extractProjectDirectory(entry.name);
|
|
402
|
+
|
|
403
|
+
// Get display name from config or generate one
|
|
404
|
+
const customName = config[entry.name]?.displayName;
|
|
405
|
+
const autoDisplayName = await generateDisplayName(entry.name, actualProjectDir);
|
|
406
|
+
const fullPath = actualProjectDir;
|
|
407
|
+
|
|
408
|
+
const project = {
|
|
409
|
+
name: entry.name,
|
|
410
|
+
path: actualProjectDir,
|
|
411
|
+
displayName: customName || autoDisplayName,
|
|
412
|
+
fullPath: fullPath,
|
|
413
|
+
isCustomName: !!customName,
|
|
414
|
+
sessions: []
|
|
415
|
+
};
|
|
416
|
+
|
|
417
|
+
// Try to get sessions for this project (just first 5 for performance)
|
|
418
|
+
try {
|
|
419
|
+
const sessionResult = await getSessions(entry.name, 5, 0);
|
|
420
|
+
project.sessions = sessionResult.sessions || [];
|
|
421
|
+
project.sessionMeta = {
|
|
422
|
+
hasMore: sessionResult.hasMore,
|
|
423
|
+
total: sessionResult.total
|
|
424
|
+
};
|
|
425
|
+
} catch (e) {
|
|
426
|
+
console.warn(`Could not load sessions for project ${entry.name}:`, e.message);
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
// Also fetch Cursor sessions for this project
|
|
430
|
+
try {
|
|
431
|
+
project.cursorSessions = await getCursorSessions(actualProjectDir);
|
|
432
|
+
} catch (e) {
|
|
433
|
+
console.warn(`Could not load Cursor sessions for project ${entry.name}:`, e.message);
|
|
434
|
+
project.cursorSessions = [];
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
// Also fetch Codex sessions for this project
|
|
438
|
+
try {
|
|
439
|
+
project.codexSessions = await getCodexSessions(actualProjectDir);
|
|
440
|
+
} catch (e) {
|
|
441
|
+
console.warn(`Could not load Codex sessions for project ${entry.name}:`, e.message);
|
|
442
|
+
project.codexSessions = [];
|
|
443
|
+
}
|
|
444
|
+
|
|
445
|
+
// Add TaskMaster detection
|
|
446
|
+
try {
|
|
447
|
+
const taskMasterResult = await detectTaskMasterFolder(actualProjectDir);
|
|
448
|
+
project.taskmaster = {
|
|
449
|
+
hasTaskmaster: taskMasterResult.hasTaskmaster,
|
|
450
|
+
hasEssentialFiles: taskMasterResult.hasEssentialFiles,
|
|
451
|
+
metadata: taskMasterResult.metadata,
|
|
452
|
+
status: taskMasterResult.hasTaskmaster && taskMasterResult.hasEssentialFiles ? 'configured' : 'not-configured'
|
|
453
|
+
};
|
|
454
|
+
} catch (e) {
|
|
455
|
+
console.warn(`Could not detect TaskMaster for project ${entry.name}:`, e.message);
|
|
456
|
+
project.taskmaster = {
|
|
457
|
+
hasTaskmaster: false,
|
|
458
|
+
hasEssentialFiles: false,
|
|
459
|
+
metadata: null,
|
|
460
|
+
status: 'error'
|
|
461
|
+
};
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
projects.push(project);
|
|
465
|
+
}
|
|
466
|
+
}
|
|
467
|
+
} catch (error) {
|
|
468
|
+
// If the directory doesn't exist (ENOENT), that's okay - just continue with empty projects
|
|
469
|
+
if (error.code !== 'ENOENT') {
|
|
470
|
+
console.error('Error reading projects directory:', error);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
// Add manually configured projects that don't exist as folders yet
|
|
475
|
+
for (const [projectName, projectConfig] of Object.entries(config)) {
|
|
476
|
+
if (!existingProjects.has(projectName) && projectConfig.manuallyAdded) {
|
|
477
|
+
// Use the original path if available, otherwise extract from potential sessions
|
|
478
|
+
let actualProjectDir = projectConfig.originalPath;
|
|
479
|
+
|
|
480
|
+
if (!actualProjectDir) {
|
|
481
|
+
try {
|
|
482
|
+
actualProjectDir = await extractProjectDirectory(projectName);
|
|
483
|
+
} catch (error) {
|
|
484
|
+
// Fall back to decoded project name
|
|
485
|
+
actualProjectDir = projectName.replace(/-/g, '/');
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
const project = {
|
|
490
|
+
name: projectName,
|
|
491
|
+
path: actualProjectDir,
|
|
492
|
+
displayName: projectConfig.displayName || await generateDisplayName(projectName, actualProjectDir),
|
|
493
|
+
fullPath: actualProjectDir,
|
|
494
|
+
isCustomName: !!projectConfig.displayName,
|
|
495
|
+
isManuallyAdded: true,
|
|
496
|
+
sessions: [],
|
|
497
|
+
cursorSessions: [],
|
|
498
|
+
codexSessions: []
|
|
499
|
+
};
|
|
500
|
+
|
|
501
|
+
// Try to fetch Cursor sessions for manual projects too
|
|
502
|
+
try {
|
|
503
|
+
project.cursorSessions = await getCursorSessions(actualProjectDir);
|
|
504
|
+
} catch (e) {
|
|
505
|
+
console.warn(`Could not load Cursor sessions for manual project ${projectName}:`, e.message);
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
// Try to fetch Codex sessions for manual projects too
|
|
509
|
+
try {
|
|
510
|
+
project.codexSessions = await getCodexSessions(actualProjectDir);
|
|
511
|
+
} catch (e) {
|
|
512
|
+
console.warn(`Could not load Codex sessions for manual project ${projectName}:`, e.message);
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// Add TaskMaster detection for manual projects
|
|
516
|
+
try {
|
|
517
|
+
const taskMasterResult = await detectTaskMasterFolder(actualProjectDir);
|
|
518
|
+
|
|
519
|
+
// Determine TaskMaster status
|
|
520
|
+
let taskMasterStatus = 'not-configured';
|
|
521
|
+
if (taskMasterResult.hasTaskmaster && taskMasterResult.hasEssentialFiles) {
|
|
522
|
+
taskMasterStatus = 'taskmaster-only'; // We don't check MCP for manual projects in bulk
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
project.taskmaster = {
|
|
526
|
+
status: taskMasterStatus,
|
|
527
|
+
hasTaskmaster: taskMasterResult.hasTaskmaster,
|
|
528
|
+
hasEssentialFiles: taskMasterResult.hasEssentialFiles,
|
|
529
|
+
metadata: taskMasterResult.metadata
|
|
530
|
+
};
|
|
531
|
+
} catch (error) {
|
|
532
|
+
console.warn(`TaskMaster detection failed for manual project ${projectName}:`, error.message);
|
|
533
|
+
project.taskmaster = {
|
|
534
|
+
status: 'error',
|
|
535
|
+
hasTaskmaster: false,
|
|
536
|
+
hasEssentialFiles: false,
|
|
537
|
+
error: error.message
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
|
|
541
|
+
projects.push(project);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
return projects;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
async function getSessions(projectName, limit = 5, offset = 0) {
|
|
549
|
+
const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
|
|
550
|
+
|
|
551
|
+
try {
|
|
552
|
+
const files = await fs.readdir(projectDir);
|
|
553
|
+
// agent-*.jsonl files contain session start data at this point. This needs to be revisited
|
|
554
|
+
// periodically to make sure only accurate data is there and no new functionality is added there
|
|
555
|
+
const jsonlFiles = files.filter(file => file.endsWith('.jsonl') && !file.startsWith('agent-'));
|
|
556
|
+
|
|
557
|
+
if (jsonlFiles.length === 0) {
|
|
558
|
+
return { sessions: [], hasMore: false, total: 0 };
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
// Sort files by modification time (newest first)
|
|
562
|
+
const filesWithStats = await Promise.all(
|
|
563
|
+
jsonlFiles.map(async (file) => {
|
|
564
|
+
const filePath = path.join(projectDir, file);
|
|
565
|
+
const stats = await fs.stat(filePath);
|
|
566
|
+
return { file, mtime: stats.mtime };
|
|
567
|
+
})
|
|
568
|
+
);
|
|
569
|
+
filesWithStats.sort((a, b) => b.mtime - a.mtime);
|
|
570
|
+
|
|
571
|
+
const allSessions = new Map();
|
|
572
|
+
const allEntries = [];
|
|
573
|
+
const uuidToSessionMap = new Map();
|
|
574
|
+
|
|
575
|
+
// Collect all sessions and entries from all files
|
|
576
|
+
for (const { file } of filesWithStats) {
|
|
577
|
+
const jsonlFile = path.join(projectDir, file);
|
|
578
|
+
const result = await parseJsonlSessions(jsonlFile);
|
|
579
|
+
|
|
580
|
+
result.sessions.forEach(session => {
|
|
581
|
+
if (!allSessions.has(session.id)) {
|
|
582
|
+
allSessions.set(session.id, session);
|
|
583
|
+
}
|
|
584
|
+
});
|
|
585
|
+
|
|
586
|
+
allEntries.push(...result.entries);
|
|
587
|
+
|
|
588
|
+
// Early exit optimization for large projects
|
|
589
|
+
if (allSessions.size >= (limit + offset) * 2 && allEntries.length >= Math.min(3, filesWithStats.length)) {
|
|
590
|
+
break;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
// Build UUID-to-session mapping for timeline detection
|
|
595
|
+
allEntries.forEach(entry => {
|
|
596
|
+
if (entry.uuid && entry.sessionId) {
|
|
597
|
+
uuidToSessionMap.set(entry.uuid, entry.sessionId);
|
|
598
|
+
}
|
|
599
|
+
});
|
|
600
|
+
|
|
601
|
+
// Group sessions by first user message ID
|
|
602
|
+
const sessionGroups = new Map(); // firstUserMsgId -> { latestSession, allSessions[] }
|
|
603
|
+
const sessionToFirstUserMsgId = new Map(); // sessionId -> firstUserMsgId
|
|
604
|
+
|
|
605
|
+
// Find the first user message for each session
|
|
606
|
+
allEntries.forEach(entry => {
|
|
607
|
+
if (entry.sessionId && entry.type === 'user' && entry.parentUuid === null && entry.uuid) {
|
|
608
|
+
// This is a first user message in a session (parentUuid is null)
|
|
609
|
+
const firstUserMsgId = entry.uuid;
|
|
610
|
+
|
|
611
|
+
if (!sessionToFirstUserMsgId.has(entry.sessionId)) {
|
|
612
|
+
sessionToFirstUserMsgId.set(entry.sessionId, firstUserMsgId);
|
|
613
|
+
|
|
614
|
+
const session = allSessions.get(entry.sessionId);
|
|
615
|
+
if (session) {
|
|
616
|
+
if (!sessionGroups.has(firstUserMsgId)) {
|
|
617
|
+
sessionGroups.set(firstUserMsgId, {
|
|
618
|
+
latestSession: session,
|
|
619
|
+
allSessions: [session]
|
|
620
|
+
});
|
|
621
|
+
} else {
|
|
622
|
+
const group = sessionGroups.get(firstUserMsgId);
|
|
623
|
+
group.allSessions.push(session);
|
|
624
|
+
|
|
625
|
+
// Update latest session if this one is more recent
|
|
626
|
+
if (new Date(session.lastActivity) > new Date(group.latestSession.lastActivity)) {
|
|
627
|
+
group.latestSession = session;
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
});
|
|
634
|
+
|
|
635
|
+
// Collect all sessions that don't belong to any group (standalone sessions)
|
|
636
|
+
const groupedSessionIds = new Set();
|
|
637
|
+
sessionGroups.forEach(group => {
|
|
638
|
+
group.allSessions.forEach(session => groupedSessionIds.add(session.id));
|
|
639
|
+
});
|
|
640
|
+
|
|
641
|
+
const standaloneSessionsArray = Array.from(allSessions.values())
|
|
642
|
+
.filter(session => !groupedSessionIds.has(session.id));
|
|
643
|
+
|
|
644
|
+
// Combine grouped sessions (only show latest from each group) + standalone sessions
|
|
645
|
+
const latestFromGroups = Array.from(sessionGroups.values()).map(group => {
|
|
646
|
+
const session = { ...group.latestSession };
|
|
647
|
+
// Add metadata about grouping
|
|
648
|
+
if (group.allSessions.length > 1) {
|
|
649
|
+
session.isGrouped = true;
|
|
650
|
+
session.groupSize = group.allSessions.length;
|
|
651
|
+
session.groupSessions = group.allSessions.map(s => s.id);
|
|
652
|
+
}
|
|
653
|
+
return session;
|
|
654
|
+
});
|
|
655
|
+
const visibleSessions = [...latestFromGroups, ...standaloneSessionsArray]
|
|
656
|
+
.filter(session => !session.summary.startsWith('{ "'))
|
|
657
|
+
.sort((a, b) => new Date(b.lastActivity) - new Date(a.lastActivity));
|
|
658
|
+
|
|
659
|
+
const total = visibleSessions.length;
|
|
660
|
+
const paginatedSessions = visibleSessions.slice(offset, offset + limit);
|
|
661
|
+
const hasMore = offset + limit < total;
|
|
662
|
+
|
|
663
|
+
return {
|
|
664
|
+
sessions: paginatedSessions,
|
|
665
|
+
hasMore,
|
|
666
|
+
total,
|
|
667
|
+
offset,
|
|
668
|
+
limit
|
|
669
|
+
};
|
|
670
|
+
} catch (error) {
|
|
671
|
+
console.error(`Error reading sessions for project ${projectName}:`, error);
|
|
672
|
+
return { sessions: [], hasMore: false, total: 0 };
|
|
673
|
+
}
|
|
674
|
+
}
|
|
675
|
+
|
|
676
|
+
async function parseJsonlSessions(filePath) {
|
|
677
|
+
const sessions = new Map();
|
|
678
|
+
const entries = [];
|
|
679
|
+
const pendingSummaries = new Map(); // leafUuid -> summary for entries without sessionId
|
|
680
|
+
|
|
681
|
+
try {
|
|
682
|
+
const fileStream = fsSync.createReadStream(filePath);
|
|
683
|
+
const rl = readline.createInterface({
|
|
684
|
+
input: fileStream,
|
|
685
|
+
crlfDelay: Infinity
|
|
686
|
+
});
|
|
687
|
+
|
|
688
|
+
for await (const line of rl) {
|
|
689
|
+
if (line.trim()) {
|
|
690
|
+
try {
|
|
691
|
+
const entry = JSON.parse(line);
|
|
692
|
+
entries.push(entry);
|
|
693
|
+
|
|
694
|
+
// Handle summary entries that don't have sessionId yet
|
|
695
|
+
if (entry.type === 'summary' && entry.summary && !entry.sessionId && entry.leafUuid) {
|
|
696
|
+
pendingSummaries.set(entry.leafUuid, entry.summary);
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
if (entry.sessionId) {
|
|
700
|
+
if (!sessions.has(entry.sessionId)) {
|
|
701
|
+
sessions.set(entry.sessionId, {
|
|
702
|
+
id: entry.sessionId,
|
|
703
|
+
summary: 'New Session',
|
|
704
|
+
messageCount: 0,
|
|
705
|
+
lastActivity: new Date(),
|
|
706
|
+
cwd: entry.cwd || '',
|
|
707
|
+
lastUserMessage: null,
|
|
708
|
+
lastAssistantMessage: null
|
|
709
|
+
});
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
const session = sessions.get(entry.sessionId);
|
|
713
|
+
|
|
714
|
+
// Apply pending summary if this entry has a parentUuid that matches a pending summary
|
|
715
|
+
if (session.summary === 'New Session' && entry.parentUuid && pendingSummaries.has(entry.parentUuid)) {
|
|
716
|
+
session.summary = pendingSummaries.get(entry.parentUuid);
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
// Update summary from summary entries with sessionId
|
|
720
|
+
if (entry.type === 'summary' && entry.summary) {
|
|
721
|
+
session.summary = entry.summary;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
// Track last user and assistant messages (skip system messages)
|
|
725
|
+
if (entry.message?.role === 'user' && entry.message?.content) {
|
|
726
|
+
const content = entry.message.content;
|
|
727
|
+
|
|
728
|
+
// Extract text from array format if needed
|
|
729
|
+
let textContent = content;
|
|
730
|
+
if (Array.isArray(content) && content.length > 0 && content[0].type === 'text') {
|
|
731
|
+
textContent = content[0].text;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
const isSystemMessage = typeof textContent === 'string' && (
|
|
735
|
+
textContent.startsWith('<command-name>') ||
|
|
736
|
+
textContent.startsWith('<command-message>') ||
|
|
737
|
+
textContent.startsWith('<command-args>') ||
|
|
738
|
+
textContent.startsWith('<local-command-stdout>') ||
|
|
739
|
+
textContent.startsWith('<system-reminder>') ||
|
|
740
|
+
textContent.startsWith('Caveat:') ||
|
|
741
|
+
textContent.startsWith('This session is being continued from a previous') ||
|
|
742
|
+
textContent.startsWith('Invalid API key') ||
|
|
743
|
+
textContent.includes('{"subtasks":') || // Filter Task Master prompts
|
|
744
|
+
textContent.includes('CRITICAL: You MUST respond with ONLY a JSON') || // Filter Task Master system prompts
|
|
745
|
+
textContent === 'Warmup' // Explicitly filter out "Warmup"
|
|
746
|
+
);
|
|
747
|
+
|
|
748
|
+
if (typeof textContent === 'string' && textContent.length > 0 && !isSystemMessage) {
|
|
749
|
+
session.lastUserMessage = textContent;
|
|
750
|
+
}
|
|
751
|
+
} else if (entry.message?.role === 'assistant' && entry.message?.content) {
|
|
752
|
+
// Skip API error messages using the isApiErrorMessage flag
|
|
753
|
+
if (entry.isApiErrorMessage === true) {
|
|
754
|
+
// Skip this message entirely
|
|
755
|
+
} else {
|
|
756
|
+
// Track last assistant text message
|
|
757
|
+
let assistantText = null;
|
|
758
|
+
|
|
759
|
+
if (Array.isArray(entry.message.content)) {
|
|
760
|
+
for (const part of entry.message.content) {
|
|
761
|
+
if (part.type === 'text' && part.text) {
|
|
762
|
+
assistantText = part.text;
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
} else if (typeof entry.message.content === 'string') {
|
|
766
|
+
assistantText = entry.message.content;
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// Additional filter for assistant messages with system content
|
|
770
|
+
const isSystemAssistantMessage = typeof assistantText === 'string' && (
|
|
771
|
+
assistantText.startsWith('Invalid API key') ||
|
|
772
|
+
assistantText.includes('{"subtasks":') ||
|
|
773
|
+
assistantText.includes('CRITICAL: You MUST respond with ONLY a JSON')
|
|
774
|
+
);
|
|
775
|
+
|
|
776
|
+
if (assistantText && !isSystemAssistantMessage) {
|
|
777
|
+
session.lastAssistantMessage = assistantText;
|
|
778
|
+
}
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
session.messageCount++;
|
|
783
|
+
|
|
784
|
+
if (entry.timestamp) {
|
|
785
|
+
session.lastActivity = new Date(entry.timestamp);
|
|
786
|
+
}
|
|
787
|
+
}
|
|
788
|
+
} catch (parseError) {
|
|
789
|
+
// Skip malformed lines silently
|
|
790
|
+
}
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
// After processing all entries, set final summary based on last message if no summary exists
|
|
795
|
+
for (const session of sessions.values()) {
|
|
796
|
+
if (session.summary === 'New Session') {
|
|
797
|
+
// Prefer last user message, fall back to last assistant message
|
|
798
|
+
const lastMessage = session.lastUserMessage || session.lastAssistantMessage;
|
|
799
|
+
if (lastMessage) {
|
|
800
|
+
session.summary = lastMessage.length > 50 ? lastMessage.substring(0, 50) + '...' : lastMessage;
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
}
|
|
804
|
+
|
|
805
|
+
// Filter out sessions that contain JSON responses (Task Master errors)
|
|
806
|
+
const allSessions = Array.from(sessions.values());
|
|
807
|
+
const filteredSessions = allSessions.filter(session => {
|
|
808
|
+
const shouldFilter = session.summary.startsWith('{ "');
|
|
809
|
+
if (shouldFilter) {
|
|
810
|
+
}
|
|
811
|
+
// Log a sample of summaries to debug
|
|
812
|
+
if (Math.random() < 0.01) { // Log 1% of sessions
|
|
813
|
+
}
|
|
814
|
+
return !shouldFilter;
|
|
815
|
+
});
|
|
816
|
+
|
|
817
|
+
|
|
818
|
+
return {
|
|
819
|
+
sessions: filteredSessions,
|
|
820
|
+
entries: entries
|
|
821
|
+
};
|
|
822
|
+
|
|
823
|
+
} catch (error) {
|
|
824
|
+
console.error('Error reading JSONL file:', error);
|
|
825
|
+
return { sessions: [], entries: [] };
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
|
|
829
|
+
// Get messages for a specific session with pagination support
|
|
830
|
+
async function getSessionMessages(projectName, sessionId, limit = null, offset = 0) {
|
|
831
|
+
const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
|
|
832
|
+
|
|
833
|
+
try {
|
|
834
|
+
const files = await fs.readdir(projectDir);
|
|
835
|
+
// agent-*.jsonl files contain session start data at this point. This needs to be revisited
|
|
836
|
+
// periodically to make sure only accurate data is there and no new functionality is added there
|
|
837
|
+
const jsonlFiles = files.filter(file => file.endsWith('.jsonl') && !file.startsWith('agent-'));
|
|
838
|
+
|
|
839
|
+
if (jsonlFiles.length === 0) {
|
|
840
|
+
return { messages: [], total: 0, hasMore: false };
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
const messages = [];
|
|
844
|
+
|
|
845
|
+
// Process all JSONL files to find messages for this session
|
|
846
|
+
for (const file of jsonlFiles) {
|
|
847
|
+
const jsonlFile = path.join(projectDir, file);
|
|
848
|
+
const fileStream = fsSync.createReadStream(jsonlFile);
|
|
849
|
+
const rl = readline.createInterface({
|
|
850
|
+
input: fileStream,
|
|
851
|
+
crlfDelay: Infinity
|
|
852
|
+
});
|
|
853
|
+
|
|
854
|
+
for await (const line of rl) {
|
|
855
|
+
if (line.trim()) {
|
|
856
|
+
try {
|
|
857
|
+
const entry = JSON.parse(line);
|
|
858
|
+
if (entry.sessionId === sessionId) {
|
|
859
|
+
messages.push(entry);
|
|
860
|
+
}
|
|
861
|
+
} catch (parseError) {
|
|
862
|
+
console.warn('Error parsing line:', parseError.message);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
// Sort messages by timestamp
|
|
869
|
+
const sortedMessages = messages.sort((a, b) =>
|
|
870
|
+
new Date(a.timestamp || 0) - new Date(b.timestamp || 0)
|
|
871
|
+
);
|
|
872
|
+
|
|
873
|
+
const total = sortedMessages.length;
|
|
874
|
+
|
|
875
|
+
// If no limit is specified, return all messages (backward compatibility)
|
|
876
|
+
if (limit === null) {
|
|
877
|
+
return sortedMessages;
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
// Apply pagination - for recent messages, we need to slice from the end
|
|
881
|
+
// offset 0 should give us the most recent messages
|
|
882
|
+
const startIndex = Math.max(0, total - offset - limit);
|
|
883
|
+
const endIndex = total - offset;
|
|
884
|
+
const paginatedMessages = sortedMessages.slice(startIndex, endIndex);
|
|
885
|
+
const hasMore = startIndex > 0;
|
|
886
|
+
|
|
887
|
+
return {
|
|
888
|
+
messages: paginatedMessages,
|
|
889
|
+
total,
|
|
890
|
+
hasMore,
|
|
891
|
+
offset,
|
|
892
|
+
limit
|
|
893
|
+
};
|
|
894
|
+
} catch (error) {
|
|
895
|
+
console.error(`Error reading messages for session ${sessionId}:`, error);
|
|
896
|
+
return limit === null ? [] : { messages: [], total: 0, hasMore: false };
|
|
897
|
+
}
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
// Rename a project's display name
|
|
901
|
+
async function renameProject(projectName, newDisplayName) {
|
|
902
|
+
const config = await loadProjectConfig();
|
|
903
|
+
|
|
904
|
+
if (!newDisplayName || newDisplayName.trim() === '') {
|
|
905
|
+
// Remove custom name if empty, will fall back to auto-generated
|
|
906
|
+
delete config[projectName];
|
|
907
|
+
} else {
|
|
908
|
+
// Set custom display name
|
|
909
|
+
config[projectName] = {
|
|
910
|
+
displayName: newDisplayName.trim()
|
|
911
|
+
};
|
|
912
|
+
}
|
|
913
|
+
|
|
914
|
+
await saveProjectConfig(config);
|
|
915
|
+
return true;
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
// Delete a session from a project
|
|
919
|
+
async function deleteSession(projectName, sessionId) {
|
|
920
|
+
const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
|
|
921
|
+
|
|
922
|
+
try {
|
|
923
|
+
const files = await fs.readdir(projectDir);
|
|
924
|
+
const jsonlFiles = files.filter(file => file.endsWith('.jsonl'));
|
|
925
|
+
|
|
926
|
+
if (jsonlFiles.length === 0) {
|
|
927
|
+
throw new Error('No session files found for this project');
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
// Check all JSONL files to find which one contains the session
|
|
931
|
+
for (const file of jsonlFiles) {
|
|
932
|
+
const jsonlFile = path.join(projectDir, file);
|
|
933
|
+
const content = await fs.readFile(jsonlFile, 'utf8');
|
|
934
|
+
const lines = content.split('\n').filter(line => line.trim());
|
|
935
|
+
|
|
936
|
+
// Check if this file contains the session
|
|
937
|
+
const hasSession = lines.some(line => {
|
|
938
|
+
try {
|
|
939
|
+
const data = JSON.parse(line);
|
|
940
|
+
return data.sessionId === sessionId;
|
|
941
|
+
} catch {
|
|
942
|
+
return false;
|
|
943
|
+
}
|
|
944
|
+
});
|
|
945
|
+
|
|
946
|
+
if (hasSession) {
|
|
947
|
+
// Filter out all entries for this session
|
|
948
|
+
const filteredLines = lines.filter(line => {
|
|
949
|
+
try {
|
|
950
|
+
const data = JSON.parse(line);
|
|
951
|
+
return data.sessionId !== sessionId;
|
|
952
|
+
} catch {
|
|
953
|
+
return true; // Keep malformed lines
|
|
954
|
+
}
|
|
955
|
+
});
|
|
956
|
+
|
|
957
|
+
// Write back the filtered content
|
|
958
|
+
await fs.writeFile(jsonlFile, filteredLines.join('\n') + (filteredLines.length > 0 ? '\n' : ''));
|
|
959
|
+
return true;
|
|
960
|
+
}
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
throw new Error(`Session ${sessionId} not found in any files`);
|
|
964
|
+
} catch (error) {
|
|
965
|
+
console.error(`Error deleting session ${sessionId} from project ${projectName}:`, error);
|
|
966
|
+
throw error;
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
// Check if a project is empty (has no sessions)
|
|
971
|
+
async function isProjectEmpty(projectName) {
|
|
972
|
+
try {
|
|
973
|
+
const sessionsResult = await getSessions(projectName, 1, 0);
|
|
974
|
+
return sessionsResult.total === 0;
|
|
975
|
+
} catch (error) {
|
|
976
|
+
console.error(`Error checking if project ${projectName} is empty:`, error);
|
|
977
|
+
return false;
|
|
978
|
+
}
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
// Delete an empty project
|
|
982
|
+
async function deleteProject(projectName) {
|
|
983
|
+
const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
|
|
984
|
+
|
|
985
|
+
try {
|
|
986
|
+
// First check if the project is empty
|
|
987
|
+
const isEmpty = await isProjectEmpty(projectName);
|
|
988
|
+
if (!isEmpty) {
|
|
989
|
+
throw new Error('Cannot delete project with existing sessions');
|
|
990
|
+
}
|
|
991
|
+
|
|
992
|
+
// Remove the project directory
|
|
993
|
+
await fs.rm(projectDir, { recursive: true, force: true });
|
|
994
|
+
|
|
995
|
+
// Remove from project config
|
|
996
|
+
const config = await loadProjectConfig();
|
|
997
|
+
delete config[projectName];
|
|
998
|
+
await saveProjectConfig(config);
|
|
999
|
+
|
|
1000
|
+
return true;
|
|
1001
|
+
} catch (error) {
|
|
1002
|
+
console.error(`Error deleting project ${projectName}:`, error);
|
|
1003
|
+
throw error;
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
// Add a project manually to the config (without creating folders)
|
|
1008
|
+
async function addProjectManually(projectPath, displayName = null) {
|
|
1009
|
+
const absolutePath = path.resolve(projectPath);
|
|
1010
|
+
|
|
1011
|
+
try {
|
|
1012
|
+
// Check if the path exists
|
|
1013
|
+
await fs.access(absolutePath);
|
|
1014
|
+
} catch (error) {
|
|
1015
|
+
throw new Error(`Path does not exist: ${absolutePath}`);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
// Generate project name (encode path for use as directory name)
|
|
1019
|
+
const projectName = absolutePath.replace(/\//g, '-');
|
|
1020
|
+
|
|
1021
|
+
// Check if project already exists in config
|
|
1022
|
+
const config = await loadProjectConfig();
|
|
1023
|
+
const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
|
|
1024
|
+
|
|
1025
|
+
if (config[projectName]) {
|
|
1026
|
+
throw new Error(`Project already configured for path: ${absolutePath}`);
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
// Allow adding projects even if the directory exists - this enables tracking
|
|
1030
|
+
// existing Claude Code or Cursor projects in the UI
|
|
1031
|
+
|
|
1032
|
+
// Add to config as manually added project
|
|
1033
|
+
config[projectName] = {
|
|
1034
|
+
manuallyAdded: true,
|
|
1035
|
+
originalPath: absolutePath
|
|
1036
|
+
};
|
|
1037
|
+
|
|
1038
|
+
if (displayName) {
|
|
1039
|
+
config[projectName].displayName = displayName;
|
|
1040
|
+
}
|
|
1041
|
+
|
|
1042
|
+
await saveProjectConfig(config);
|
|
1043
|
+
|
|
1044
|
+
|
|
1045
|
+
return {
|
|
1046
|
+
name: projectName,
|
|
1047
|
+
path: absolutePath,
|
|
1048
|
+
fullPath: absolutePath,
|
|
1049
|
+
displayName: displayName || await generateDisplayName(projectName, absolutePath),
|
|
1050
|
+
isManuallyAdded: true,
|
|
1051
|
+
sessions: [],
|
|
1052
|
+
cursorSessions: []
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
|
|
1056
|
+
// Fetch Cursor sessions for a given project path
|
|
1057
|
+
async function getCursorSessions(projectPath) {
|
|
1058
|
+
try {
|
|
1059
|
+
// Calculate cwdID hash for the project path (Cursor uses MD5 hash)
|
|
1060
|
+
const cwdId = crypto.createHash('md5').update(projectPath).digest('hex');
|
|
1061
|
+
const cursorChatsPath = path.join(os.homedir(), '.cursor', 'chats', cwdId);
|
|
1062
|
+
|
|
1063
|
+
// Check if the directory exists
|
|
1064
|
+
try {
|
|
1065
|
+
await fs.access(cursorChatsPath);
|
|
1066
|
+
} catch (error) {
|
|
1067
|
+
// No sessions for this project
|
|
1068
|
+
return [];
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
// List all session directories
|
|
1072
|
+
const sessionDirs = await fs.readdir(cursorChatsPath);
|
|
1073
|
+
const sessions = [];
|
|
1074
|
+
|
|
1075
|
+
for (const sessionId of sessionDirs) {
|
|
1076
|
+
const sessionPath = path.join(cursorChatsPath, sessionId);
|
|
1077
|
+
const storeDbPath = path.join(sessionPath, 'store.db');
|
|
1078
|
+
|
|
1079
|
+
try {
|
|
1080
|
+
// Check if store.db exists
|
|
1081
|
+
await fs.access(storeDbPath);
|
|
1082
|
+
|
|
1083
|
+
// Capture store.db mtime as a reliable fallback timestamp
|
|
1084
|
+
let dbStatMtimeMs = null;
|
|
1085
|
+
try {
|
|
1086
|
+
const stat = await fs.stat(storeDbPath);
|
|
1087
|
+
dbStatMtimeMs = stat.mtimeMs;
|
|
1088
|
+
} catch (_) {}
|
|
1089
|
+
|
|
1090
|
+
// Open SQLite database
|
|
1091
|
+
const db = await open({
|
|
1092
|
+
filename: storeDbPath,
|
|
1093
|
+
driver: sqlite3.Database,
|
|
1094
|
+
mode: sqlite3.OPEN_READONLY
|
|
1095
|
+
});
|
|
1096
|
+
|
|
1097
|
+
// Get metadata from meta table
|
|
1098
|
+
const metaRows = await db.all(`
|
|
1099
|
+
SELECT key, value FROM meta
|
|
1100
|
+
`);
|
|
1101
|
+
|
|
1102
|
+
// Parse metadata
|
|
1103
|
+
let metadata = {};
|
|
1104
|
+
for (const row of metaRows) {
|
|
1105
|
+
if (row.value) {
|
|
1106
|
+
try {
|
|
1107
|
+
// Try to decode as hex-encoded JSON
|
|
1108
|
+
const hexMatch = row.value.toString().match(/^[0-9a-fA-F]+$/);
|
|
1109
|
+
if (hexMatch) {
|
|
1110
|
+
const jsonStr = Buffer.from(row.value, 'hex').toString('utf8');
|
|
1111
|
+
metadata[row.key] = JSON.parse(jsonStr);
|
|
1112
|
+
} else {
|
|
1113
|
+
metadata[row.key] = row.value.toString();
|
|
1114
|
+
}
|
|
1115
|
+
} catch (e) {
|
|
1116
|
+
metadata[row.key] = row.value.toString();
|
|
1117
|
+
}
|
|
1118
|
+
}
|
|
1119
|
+
}
|
|
1120
|
+
|
|
1121
|
+
// Get message count
|
|
1122
|
+
const messageCountResult = await db.get(`
|
|
1123
|
+
SELECT COUNT(*) as count FROM blobs
|
|
1124
|
+
`);
|
|
1125
|
+
|
|
1126
|
+
await db.close();
|
|
1127
|
+
|
|
1128
|
+
// Extract session info
|
|
1129
|
+
const sessionName = metadata.title || metadata.sessionTitle || 'Untitled Session';
|
|
1130
|
+
|
|
1131
|
+
// Determine timestamp - prefer createdAt from metadata, fall back to db file mtime
|
|
1132
|
+
let createdAt = null;
|
|
1133
|
+
if (metadata.createdAt) {
|
|
1134
|
+
createdAt = new Date(metadata.createdAt).toISOString();
|
|
1135
|
+
} else if (dbStatMtimeMs) {
|
|
1136
|
+
createdAt = new Date(dbStatMtimeMs).toISOString();
|
|
1137
|
+
} else {
|
|
1138
|
+
createdAt = new Date().toISOString();
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
sessions.push({
|
|
1142
|
+
id: sessionId,
|
|
1143
|
+
name: sessionName,
|
|
1144
|
+
createdAt: createdAt,
|
|
1145
|
+
lastActivity: createdAt, // For compatibility with Claude sessions
|
|
1146
|
+
messageCount: messageCountResult.count || 0,
|
|
1147
|
+
projectPath: projectPath
|
|
1148
|
+
});
|
|
1149
|
+
|
|
1150
|
+
} catch (error) {
|
|
1151
|
+
console.warn(`Could not read Cursor session ${sessionId}:`, error.message);
|
|
1152
|
+
}
|
|
1153
|
+
}
|
|
1154
|
+
|
|
1155
|
+
// Sort sessions by creation time (newest first)
|
|
1156
|
+
sessions.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
|
|
1157
|
+
|
|
1158
|
+
// Return only the first 5 sessions for performance
|
|
1159
|
+
return sessions.slice(0, 5);
|
|
1160
|
+
|
|
1161
|
+
} catch (error) {
|
|
1162
|
+
console.error('Error fetching Cursor sessions:', error);
|
|
1163
|
+
return [];
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
|
|
1167
|
+
|
|
1168
|
+
// Fetch Codex sessions for a given project path
|
|
1169
|
+
async function getCodexSessions(projectPath) {
|
|
1170
|
+
try {
|
|
1171
|
+
const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
|
|
1172
|
+
const sessions = [];
|
|
1173
|
+
|
|
1174
|
+
// Check if the directory exists
|
|
1175
|
+
try {
|
|
1176
|
+
await fs.access(codexSessionsDir);
|
|
1177
|
+
} catch (error) {
|
|
1178
|
+
// No Codex sessions directory
|
|
1179
|
+
return [];
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
// Recursively find all .jsonl files in the sessions directory
|
|
1183
|
+
const findJsonlFiles = async (dir) => {
|
|
1184
|
+
const files = [];
|
|
1185
|
+
try {
|
|
1186
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
1187
|
+
for (const entry of entries) {
|
|
1188
|
+
const fullPath = path.join(dir, entry.name);
|
|
1189
|
+
if (entry.isDirectory()) {
|
|
1190
|
+
files.push(...await findJsonlFiles(fullPath));
|
|
1191
|
+
} else if (entry.name.endsWith('.jsonl')) {
|
|
1192
|
+
files.push(fullPath);
|
|
1193
|
+
}
|
|
1194
|
+
}
|
|
1195
|
+
} catch (error) {
|
|
1196
|
+
// Skip directories we can't read
|
|
1197
|
+
}
|
|
1198
|
+
return files;
|
|
1199
|
+
};
|
|
1200
|
+
|
|
1201
|
+
const jsonlFiles = await findJsonlFiles(codexSessionsDir);
|
|
1202
|
+
|
|
1203
|
+
// Process each file to find sessions matching the project path
|
|
1204
|
+
for (const filePath of jsonlFiles) {
|
|
1205
|
+
try {
|
|
1206
|
+
const sessionData = await parseCodexSessionFile(filePath);
|
|
1207
|
+
|
|
1208
|
+
// Check if this session matches the project path
|
|
1209
|
+
// Handle Windows long paths with \\?\ prefix
|
|
1210
|
+
const sessionCwd = sessionData?.cwd || '';
|
|
1211
|
+
const cleanSessionCwd = sessionCwd.startsWith('\\\\?\\') ? sessionCwd.slice(4) : sessionCwd;
|
|
1212
|
+
const cleanProjectPath = projectPath.startsWith('\\\\?\\') ? projectPath.slice(4) : projectPath;
|
|
1213
|
+
|
|
1214
|
+
if (sessionData && (sessionData.cwd === projectPath || cleanSessionCwd === cleanProjectPath || path.relative(cleanSessionCwd, cleanProjectPath) === '')) {
|
|
1215
|
+
sessions.push({
|
|
1216
|
+
id: sessionData.id,
|
|
1217
|
+
summary: sessionData.summary || 'Codex Session',
|
|
1218
|
+
messageCount: sessionData.messageCount || 0,
|
|
1219
|
+
lastActivity: sessionData.timestamp ? new Date(sessionData.timestamp) : new Date(),
|
|
1220
|
+
cwd: sessionData.cwd,
|
|
1221
|
+
model: sessionData.model,
|
|
1222
|
+
filePath: filePath,
|
|
1223
|
+
provider: 'codex'
|
|
1224
|
+
});
|
|
1225
|
+
}
|
|
1226
|
+
} catch (error) {
|
|
1227
|
+
console.warn(`Could not parse Codex session file ${filePath}:`, error.message);
|
|
1228
|
+
}
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
// Sort sessions by last activity (newest first)
|
|
1232
|
+
sessions.sort((a, b) => new Date(b.lastActivity) - new Date(a.lastActivity));
|
|
1233
|
+
|
|
1234
|
+
// Return only the first 5 sessions for performance
|
|
1235
|
+
return sessions.slice(0, 5);
|
|
1236
|
+
|
|
1237
|
+
} catch (error) {
|
|
1238
|
+
console.error('Error fetching Codex sessions:', error);
|
|
1239
|
+
return [];
|
|
1240
|
+
}
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
// Parse a Codex session JSONL file to extract metadata
|
|
1244
|
+
async function parseCodexSessionFile(filePath) {
|
|
1245
|
+
try {
|
|
1246
|
+
const fileStream = fsSync.createReadStream(filePath);
|
|
1247
|
+
const rl = readline.createInterface({
|
|
1248
|
+
input: fileStream,
|
|
1249
|
+
crlfDelay: Infinity
|
|
1250
|
+
});
|
|
1251
|
+
|
|
1252
|
+
let sessionMeta = null;
|
|
1253
|
+
let lastTimestamp = null;
|
|
1254
|
+
let lastUserMessage = null;
|
|
1255
|
+
let messageCount = 0;
|
|
1256
|
+
|
|
1257
|
+
for await (const line of rl) {
|
|
1258
|
+
if (line.trim()) {
|
|
1259
|
+
try {
|
|
1260
|
+
const entry = JSON.parse(line);
|
|
1261
|
+
|
|
1262
|
+
// Track timestamp
|
|
1263
|
+
if (entry.timestamp) {
|
|
1264
|
+
lastTimestamp = entry.timestamp;
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
// Extract session metadata
|
|
1268
|
+
if (entry.type === 'session_meta' && entry.payload) {
|
|
1269
|
+
sessionMeta = {
|
|
1270
|
+
id: entry.payload.id,
|
|
1271
|
+
cwd: entry.payload.cwd,
|
|
1272
|
+
model: entry.payload.model || entry.payload.model_provider,
|
|
1273
|
+
timestamp: entry.timestamp,
|
|
1274
|
+
git: entry.payload.git
|
|
1275
|
+
};
|
|
1276
|
+
}
|
|
1277
|
+
|
|
1278
|
+
// Count messages and extract user messages for summary
|
|
1279
|
+
if (entry.type === 'event_msg' && entry.payload?.type === 'user_message') {
|
|
1280
|
+
messageCount++;
|
|
1281
|
+
if (entry.payload.message) {
|
|
1282
|
+
lastUserMessage = entry.payload.message;
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
if (entry.type === 'response_item' && entry.payload?.type === 'message' && entry.payload.role === 'assistant') {
|
|
1287
|
+
messageCount++;
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
} catch (parseError) {
|
|
1291
|
+
// Skip malformed lines
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
|
|
1296
|
+
if (sessionMeta) {
|
|
1297
|
+
return {
|
|
1298
|
+
...sessionMeta,
|
|
1299
|
+
timestamp: lastTimestamp || sessionMeta.timestamp,
|
|
1300
|
+
summary: lastUserMessage ?
|
|
1301
|
+
(lastUserMessage.length > 50 ? lastUserMessage.substring(0, 50) + '...' : lastUserMessage) :
|
|
1302
|
+
'Codex Session',
|
|
1303
|
+
messageCount
|
|
1304
|
+
};
|
|
1305
|
+
}
|
|
1306
|
+
|
|
1307
|
+
return null;
|
|
1308
|
+
|
|
1309
|
+
} catch (error) {
|
|
1310
|
+
console.error('Error parsing Codex session file:', error);
|
|
1311
|
+
return null;
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
// Get messages for a specific Codex session
|
|
1316
|
+
async function getCodexSessionMessages(sessionId, limit = null, offset = 0) {
|
|
1317
|
+
try {
|
|
1318
|
+
const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
|
|
1319
|
+
|
|
1320
|
+
// Find the session file by searching for the session ID
|
|
1321
|
+
const findSessionFile = async (dir) => {
|
|
1322
|
+
try {
|
|
1323
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
1324
|
+
for (const entry of entries) {
|
|
1325
|
+
const fullPath = path.join(dir, entry.name);
|
|
1326
|
+
if (entry.isDirectory()) {
|
|
1327
|
+
const found = await findSessionFile(fullPath);
|
|
1328
|
+
if (found) return found;
|
|
1329
|
+
} else if (entry.name.includes(sessionId) && entry.name.endsWith('.jsonl')) {
|
|
1330
|
+
return fullPath;
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
} catch (error) {
|
|
1334
|
+
// Skip directories we can't read
|
|
1335
|
+
}
|
|
1336
|
+
return null;
|
|
1337
|
+
};
|
|
1338
|
+
|
|
1339
|
+
const sessionFilePath = await findSessionFile(codexSessionsDir);
|
|
1340
|
+
|
|
1341
|
+
if (!sessionFilePath) {
|
|
1342
|
+
console.warn(`Codex session file not found for session ${sessionId}`);
|
|
1343
|
+
return { messages: [], total: 0, hasMore: false };
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
const messages = [];
|
|
1347
|
+
let tokenUsage = null;
|
|
1348
|
+
const fileStream = fsSync.createReadStream(sessionFilePath);
|
|
1349
|
+
const rl = readline.createInterface({
|
|
1350
|
+
input: fileStream,
|
|
1351
|
+
crlfDelay: Infinity
|
|
1352
|
+
});
|
|
1353
|
+
|
|
1354
|
+
// Helper to extract text from Codex content array
|
|
1355
|
+
const extractText = (content) => {
|
|
1356
|
+
if (!Array.isArray(content)) return content;
|
|
1357
|
+
return content
|
|
1358
|
+
.map(item => {
|
|
1359
|
+
if (item.type === 'input_text' || item.type === 'output_text') {
|
|
1360
|
+
return item.text;
|
|
1361
|
+
}
|
|
1362
|
+
if (item.type === 'text') {
|
|
1363
|
+
return item.text;
|
|
1364
|
+
}
|
|
1365
|
+
return '';
|
|
1366
|
+
})
|
|
1367
|
+
.filter(Boolean)
|
|
1368
|
+
.join('\n');
|
|
1369
|
+
};
|
|
1370
|
+
|
|
1371
|
+
for await (const line of rl) {
|
|
1372
|
+
if (line.trim()) {
|
|
1373
|
+
try {
|
|
1374
|
+
const entry = JSON.parse(line);
|
|
1375
|
+
|
|
1376
|
+
// Extract token usage from token_count events (keep latest)
|
|
1377
|
+
if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload?.info) {
|
|
1378
|
+
const info = entry.payload.info;
|
|
1379
|
+
if (info.total_token_usage) {
|
|
1380
|
+
tokenUsage = {
|
|
1381
|
+
used: info.total_token_usage.total_tokens || 0,
|
|
1382
|
+
total: info.model_context_window || 200000
|
|
1383
|
+
};
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
// Extract messages from response_item
|
|
1388
|
+
if (entry.type === 'response_item' && entry.payload?.type === 'message') {
|
|
1389
|
+
const content = entry.payload.content;
|
|
1390
|
+
const role = entry.payload.role || 'assistant';
|
|
1391
|
+
const textContent = extractText(content);
|
|
1392
|
+
|
|
1393
|
+
// Skip system context messages (environment_context)
|
|
1394
|
+
if (textContent?.includes('<environment_context>')) {
|
|
1395
|
+
continue;
|
|
1396
|
+
}
|
|
1397
|
+
|
|
1398
|
+
// Only add if there's actual content
|
|
1399
|
+
if (textContent?.trim()) {
|
|
1400
|
+
messages.push({
|
|
1401
|
+
type: role === 'user' ? 'user' : 'assistant',
|
|
1402
|
+
timestamp: entry.timestamp,
|
|
1403
|
+
message: {
|
|
1404
|
+
role: role,
|
|
1405
|
+
content: textContent
|
|
1406
|
+
}
|
|
1407
|
+
});
|
|
1408
|
+
}
|
|
1409
|
+
}
|
|
1410
|
+
|
|
1411
|
+
if (entry.type === 'response_item' && entry.payload?.type === 'reasoning') {
|
|
1412
|
+
const summaryText = entry.payload.summary
|
|
1413
|
+
?.map(s => s.text)
|
|
1414
|
+
.filter(Boolean)
|
|
1415
|
+
.join('\n');
|
|
1416
|
+
if (summaryText?.trim()) {
|
|
1417
|
+
messages.push({
|
|
1418
|
+
type: 'thinking',
|
|
1419
|
+
timestamp: entry.timestamp,
|
|
1420
|
+
message: {
|
|
1421
|
+
role: 'assistant',
|
|
1422
|
+
content: summaryText
|
|
1423
|
+
}
|
|
1424
|
+
});
|
|
1425
|
+
}
|
|
1426
|
+
}
|
|
1427
|
+
|
|
1428
|
+
if (entry.type === 'response_item' && entry.payload?.type === 'function_call') {
|
|
1429
|
+
let toolName = entry.payload.name;
|
|
1430
|
+
let toolInput = entry.payload.arguments;
|
|
1431
|
+
|
|
1432
|
+
// Map Codex tool names to Claude equivalents
|
|
1433
|
+
if (toolName === 'shell_command') {
|
|
1434
|
+
toolName = 'Bash';
|
|
1435
|
+
try {
|
|
1436
|
+
const args = JSON.parse(entry.payload.arguments);
|
|
1437
|
+
toolInput = JSON.stringify({ command: args.command });
|
|
1438
|
+
} catch (e) {
|
|
1439
|
+
// Keep original if parsing fails
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
messages.push({
|
|
1444
|
+
type: 'tool_use',
|
|
1445
|
+
timestamp: entry.timestamp,
|
|
1446
|
+
toolName: toolName,
|
|
1447
|
+
toolInput: toolInput,
|
|
1448
|
+
toolCallId: entry.payload.call_id
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
|
|
1452
|
+
if (entry.type === 'response_item' && entry.payload?.type === 'function_call_output') {
|
|
1453
|
+
messages.push({
|
|
1454
|
+
type: 'tool_result',
|
|
1455
|
+
timestamp: entry.timestamp,
|
|
1456
|
+
toolCallId: entry.payload.call_id,
|
|
1457
|
+
output: entry.payload.output
|
|
1458
|
+
});
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call') {
|
|
1462
|
+
const toolName = entry.payload.name || 'custom_tool';
|
|
1463
|
+
const input = entry.payload.input || '';
|
|
1464
|
+
|
|
1465
|
+
if (toolName === 'apply_patch') {
|
|
1466
|
+
// Parse Codex patch format and convert to Claude Edit format
|
|
1467
|
+
const fileMatch = input.match(/\*\*\* Update File: (.+)/);
|
|
1468
|
+
const filePath = fileMatch ? fileMatch[1].trim() : 'unknown';
|
|
1469
|
+
|
|
1470
|
+
// Extract old and new content from patch
|
|
1471
|
+
const lines = input.split('\n');
|
|
1472
|
+
const oldLines = [];
|
|
1473
|
+
const newLines = [];
|
|
1474
|
+
|
|
1475
|
+
for (const line of lines) {
|
|
1476
|
+
if (line.startsWith('-') && !line.startsWith('---')) {
|
|
1477
|
+
oldLines.push(line.substring(1));
|
|
1478
|
+
} else if (line.startsWith('+') && !line.startsWith('+++')) {
|
|
1479
|
+
newLines.push(line.substring(1));
|
|
1480
|
+
}
|
|
1481
|
+
}
|
|
1482
|
+
|
|
1483
|
+
messages.push({
|
|
1484
|
+
type: 'tool_use',
|
|
1485
|
+
timestamp: entry.timestamp,
|
|
1486
|
+
toolName: 'Edit',
|
|
1487
|
+
toolInput: JSON.stringify({
|
|
1488
|
+
file_path: filePath,
|
|
1489
|
+
old_string: oldLines.join('\n'),
|
|
1490
|
+
new_string: newLines.join('\n')
|
|
1491
|
+
}),
|
|
1492
|
+
toolCallId: entry.payload.call_id
|
|
1493
|
+
});
|
|
1494
|
+
} else {
|
|
1495
|
+
messages.push({
|
|
1496
|
+
type: 'tool_use',
|
|
1497
|
+
timestamp: entry.timestamp,
|
|
1498
|
+
toolName: toolName,
|
|
1499
|
+
toolInput: input,
|
|
1500
|
+
toolCallId: entry.payload.call_id
|
|
1501
|
+
});
|
|
1502
|
+
}
|
|
1503
|
+
}
|
|
1504
|
+
|
|
1505
|
+
if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call_output') {
|
|
1506
|
+
messages.push({
|
|
1507
|
+
type: 'tool_result',
|
|
1508
|
+
timestamp: entry.timestamp,
|
|
1509
|
+
toolCallId: entry.payload.call_id,
|
|
1510
|
+
output: entry.payload.output || ''
|
|
1511
|
+
});
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
} catch (parseError) {
|
|
1515
|
+
// Skip malformed lines
|
|
1516
|
+
}
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
|
|
1520
|
+
// Sort by timestamp
|
|
1521
|
+
messages.sort((a, b) => new Date(a.timestamp || 0) - new Date(b.timestamp || 0));
|
|
1522
|
+
|
|
1523
|
+
const total = messages.length;
|
|
1524
|
+
|
|
1525
|
+
// Apply pagination if limit is specified
|
|
1526
|
+
if (limit !== null) {
|
|
1527
|
+
const startIndex = Math.max(0, total - offset - limit);
|
|
1528
|
+
const endIndex = total - offset;
|
|
1529
|
+
const paginatedMessages = messages.slice(startIndex, endIndex);
|
|
1530
|
+
const hasMore = startIndex > 0;
|
|
1531
|
+
|
|
1532
|
+
return {
|
|
1533
|
+
messages: paginatedMessages,
|
|
1534
|
+
total,
|
|
1535
|
+
hasMore,
|
|
1536
|
+
offset,
|
|
1537
|
+
limit,
|
|
1538
|
+
tokenUsage
|
|
1539
|
+
};
|
|
1540
|
+
}
|
|
1541
|
+
|
|
1542
|
+
return { messages, tokenUsage };
|
|
1543
|
+
|
|
1544
|
+
} catch (error) {
|
|
1545
|
+
console.error(`Error reading Codex session messages for ${sessionId}:`, error);
|
|
1546
|
+
return { messages: [], total: 0, hasMore: false };
|
|
1547
|
+
}
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
async function deleteCodexSession(sessionId) {
|
|
1551
|
+
try {
|
|
1552
|
+
const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
|
|
1553
|
+
|
|
1554
|
+
const findJsonlFiles = async (dir) => {
|
|
1555
|
+
const files = [];
|
|
1556
|
+
try {
|
|
1557
|
+
const entries = await fs.readdir(dir, { withFileTypes: true });
|
|
1558
|
+
for (const entry of entries) {
|
|
1559
|
+
const fullPath = path.join(dir, entry.name);
|
|
1560
|
+
if (entry.isDirectory()) {
|
|
1561
|
+
files.push(...await findJsonlFiles(fullPath));
|
|
1562
|
+
} else if (entry.name.endsWith('.jsonl')) {
|
|
1563
|
+
files.push(fullPath);
|
|
1564
|
+
}
|
|
1565
|
+
}
|
|
1566
|
+
} catch (error) {}
|
|
1567
|
+
return files;
|
|
1568
|
+
};
|
|
1569
|
+
|
|
1570
|
+
const jsonlFiles = await findJsonlFiles(codexSessionsDir);
|
|
1571
|
+
|
|
1572
|
+
for (const filePath of jsonlFiles) {
|
|
1573
|
+
const sessionData = await parseCodexSessionFile(filePath);
|
|
1574
|
+
if (sessionData && sessionData.id === sessionId) {
|
|
1575
|
+
await fs.unlink(filePath);
|
|
1576
|
+
return true;
|
|
1577
|
+
}
|
|
1578
|
+
}
|
|
1579
|
+
|
|
1580
|
+
throw new Error(`Codex session file not found for session ${sessionId}`);
|
|
1581
|
+
} catch (error) {
|
|
1582
|
+
console.error(`Error deleting Codex session ${sessionId}:`, error);
|
|
1583
|
+
throw error;
|
|
1584
|
+
}
|
|
1585
|
+
}
|
|
1586
|
+
|
|
1587
|
+
export {
|
|
1588
|
+
getProjects,
|
|
1589
|
+
getSessions,
|
|
1590
|
+
getSessionMessages,
|
|
1591
|
+
parseJsonlSessions,
|
|
1592
|
+
renameProject,
|
|
1593
|
+
deleteSession,
|
|
1594
|
+
isProjectEmpty,
|
|
1595
|
+
deleteProject,
|
|
1596
|
+
addProjectManually,
|
|
1597
|
+
loadProjectConfig,
|
|
1598
|
+
saveProjectConfig,
|
|
1599
|
+
extractProjectDirectory,
|
|
1600
|
+
clearProjectDirectoryCache,
|
|
1601
|
+
getCodexSessions,
|
|
1602
|
+
getCodexSessionMessages,
|
|
1603
|
+
deleteCodexSession
|
|
1604
|
+
};
|