@cloudcli-ai/cloudcli 1.29.1 → 1.29.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 (113) hide show
  1. package/dist/assets/{index-ByHZ8-LL.css → index-D-9h5kNf.css} +1 -1
  2. package/dist/assets/{index-BOWaxSnV.js → index-y8yqvoLv.js} +229 -229
  3. package/dist/index.html +2 -2
  4. package/dist-server/server/claude-sdk.js +694 -0
  5. package/dist-server/server/claude-sdk.js.map +1 -0
  6. package/dist-server/server/cli.js +642 -0
  7. package/dist-server/server/cli.js.map +1 -0
  8. package/dist-server/server/constants/config.js +6 -0
  9. package/dist-server/server/constants/config.js.map +1 -0
  10. package/dist-server/server/cursor-cli.js +271 -0
  11. package/dist-server/server/cursor-cli.js.map +1 -0
  12. package/dist-server/server/database/db.js +535 -0
  13. package/dist-server/server/database/db.js.map +1 -0
  14. package/dist-server/server/database/schema.js +97 -0
  15. package/dist-server/server/database/schema.js.map +1 -0
  16. package/dist-server/server/gemini-cli.js +394 -0
  17. package/dist-server/server/gemini-cli.js.map +1 -0
  18. package/dist-server/server/gemini-response-handler.js +72 -0
  19. package/dist-server/server/gemini-response-handler.js.map +1 -0
  20. package/dist-server/server/index.js +2244 -0
  21. package/dist-server/server/index.js.map +1 -0
  22. package/dist-server/server/load-env.js +32 -0
  23. package/dist-server/server/load-env.js.map +1 -0
  24. package/dist-server/server/middleware/auth.js +111 -0
  25. package/dist-server/server/middleware/auth.js.map +1 -0
  26. package/dist-server/server/openai-codex.js +367 -0
  27. package/dist-server/server/openai-codex.js.map +1 -0
  28. package/dist-server/server/projects.js +2331 -0
  29. package/dist-server/server/projects.js.map +1 -0
  30. package/dist-server/server/providers/claude/adapter.js +266 -0
  31. package/dist-server/server/providers/claude/adapter.js.map +1 -0
  32. package/dist-server/server/providers/codex/adapter.js +232 -0
  33. package/dist-server/server/providers/codex/adapter.js.map +1 -0
  34. package/dist-server/server/providers/cursor/adapter.js +347 -0
  35. package/dist-server/server/providers/cursor/adapter.js.map +1 -0
  36. package/dist-server/server/providers/gemini/adapter.js +174 -0
  37. package/dist-server/server/providers/gemini/adapter.js.map +1 -0
  38. package/dist-server/server/providers/registry.js +39 -0
  39. package/dist-server/server/providers/registry.js.map +1 -0
  40. package/dist-server/server/providers/types.js +106 -0
  41. package/dist-server/server/providers/types.js.map +1 -0
  42. package/dist-server/server/providers/utils.js +28 -0
  43. package/dist-server/server/providers/utils.js.map +1 -0
  44. package/dist-server/server/routes/agent.js +1147 -0
  45. package/dist-server/server/routes/agent.js.map +1 -0
  46. package/dist-server/server/routes/auth.js +117 -0
  47. package/dist-server/server/routes/auth.js.map +1 -0
  48. package/dist-server/server/routes/cli-auth.js +406 -0
  49. package/dist-server/server/routes/cli-auth.js.map +1 -0
  50. package/dist-server/server/routes/codex.js +294 -0
  51. package/dist-server/server/routes/codex.js.map +1 -0
  52. package/dist-server/server/routes/commands.js +531 -0
  53. package/dist-server/server/routes/commands.js.map +1 -0
  54. package/dist-server/server/routes/cursor.js +545 -0
  55. package/dist-server/server/routes/cursor.js.map +1 -0
  56. package/dist-server/server/routes/gemini.js +21 -0
  57. package/dist-server/server/routes/gemini.js.map +1 -0
  58. package/dist-server/server/routes/git.js +1259 -0
  59. package/dist-server/server/routes/git.js.map +1 -0
  60. package/dist-server/server/routes/mcp-utils.js +46 -0
  61. package/dist-server/server/routes/mcp-utils.js.map +1 -0
  62. package/dist-server/server/routes/mcp.js +480 -0
  63. package/dist-server/server/routes/mcp.js.map +1 -0
  64. package/dist-server/server/routes/messages.js +56 -0
  65. package/dist-server/server/routes/messages.js.map +1 -0
  66. package/dist-server/server/routes/plugins.js +266 -0
  67. package/dist-server/server/routes/plugins.js.map +1 -0
  68. package/dist-server/server/routes/projects.js +505 -0
  69. package/dist-server/server/routes/projects.js.map +1 -0
  70. package/dist-server/server/routes/settings.js +249 -0
  71. package/dist-server/server/routes/settings.js.map +1 -0
  72. package/dist-server/server/routes/taskmaster.js +1832 -0
  73. package/dist-server/server/routes/taskmaster.js.map +1 -0
  74. package/dist-server/server/routes/user.js +115 -0
  75. package/dist-server/server/routes/user.js.map +1 -0
  76. package/dist-server/server/services/notification-orchestrator.js +177 -0
  77. package/dist-server/server/services/notification-orchestrator.js.map +1 -0
  78. package/dist-server/server/services/vapid-keys.js +26 -0
  79. package/dist-server/server/services/vapid-keys.js.map +1 -0
  80. package/dist-server/server/sessionManager.js +194 -0
  81. package/dist-server/server/sessionManager.js.map +1 -0
  82. package/dist-server/server/utils/commandParser.js +255 -0
  83. package/dist-server/server/utils/commandParser.js.map +1 -0
  84. package/dist-server/server/utils/frontmatter.js +16 -0
  85. package/dist-server/server/utils/frontmatter.js.map +1 -0
  86. package/dist-server/server/utils/gitConfig.js +36 -0
  87. package/dist-server/server/utils/gitConfig.js.map +1 -0
  88. package/dist-server/server/utils/mcp-detector.js +183 -0
  89. package/dist-server/server/utils/mcp-detector.js.map +1 -0
  90. package/dist-server/server/utils/plugin-loader.js +413 -0
  91. package/dist-server/server/utils/plugin-loader.js.map +1 -0
  92. package/dist-server/server/utils/plugin-process-manager.js +163 -0
  93. package/dist-server/server/utils/plugin-process-manager.js.map +1 -0
  94. package/dist-server/server/utils/runtime-paths.js +30 -0
  95. package/dist-server/server/utils/runtime-paths.js.map +1 -0
  96. package/dist-server/server/utils/taskmaster-websocket.js +118 -0
  97. package/dist-server/server/utils/taskmaster-websocket.js.map +1 -0
  98. package/dist-server/shared/modelConstants.js +87 -0
  99. package/dist-server/shared/modelConstants.js.map +1 -0
  100. package/dist-server/shared/networkHosts.js +20 -0
  101. package/dist-server/shared/networkHosts.js.map +1 -0
  102. package/package.json +21 -10
  103. package/server/cli.js +35 -33
  104. package/server/database/db.js +24 -61
  105. package/server/database/schema.js +102 -0
  106. package/server/index.js +12 -12
  107. package/server/load-env.js +11 -6
  108. package/server/routes/commands.js +6 -4
  109. package/server/routes/cursor.js +0 -218
  110. package/server/tsconfig.json +33 -0
  111. package/server/utils/runtime-paths.js +37 -0
  112. package/shared/modelConstants.js +4 -2
  113. package/server/database/init.sql +0 -99
@@ -0,0 +1,2331 @@
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
+ import { promises as fs } from 'fs';
60
+ import fsSync from 'fs';
61
+ import path from 'path';
62
+ import readline from 'readline';
63
+ import crypto from 'crypto';
64
+ import sqlite3 from 'sqlite3';
65
+ import { open } from 'sqlite';
66
+ import os from 'os';
67
+ import sessionManager from './sessionManager.js';
68
+ import { applyCustomSessionNames } from './database/db.js';
69
+ // Import TaskMaster detection functions
70
+ async function detectTaskMasterFolder(projectPath) {
71
+ try {
72
+ const taskMasterPath = path.join(projectPath, '.taskmaster');
73
+ // Check if .taskmaster directory exists
74
+ try {
75
+ const stats = await fs.stat(taskMasterPath);
76
+ if (!stats.isDirectory()) {
77
+ return {
78
+ hasTaskmaster: false,
79
+ reason: '.taskmaster exists but is not a directory'
80
+ };
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
+ // Check for key TaskMaster files
93
+ const keyFiles = [
94
+ 'tasks/tasks.json',
95
+ 'config.json'
96
+ ];
97
+ const fileStatus = {};
98
+ let hasEssentialFiles = true;
99
+ for (const file of keyFiles) {
100
+ const filePath = path.join(taskMasterPath, file);
101
+ try {
102
+ await fs.access(filePath);
103
+ fileStatus[file] = true;
104
+ }
105
+ catch (error) {
106
+ fileStatus[file] = false;
107
+ if (file === 'tasks/tasks.json') {
108
+ hasEssentialFiles = false;
109
+ }
110
+ }
111
+ }
112
+ // Parse tasks.json if it exists for metadata
113
+ let taskMetadata = null;
114
+ if (fileStatus['tasks/tasks.json']) {
115
+ try {
116
+ const tasksPath = path.join(taskMasterPath, 'tasks/tasks.json');
117
+ const tasksContent = await fs.readFile(tasksPath, 'utf8');
118
+ const tasksData = JSON.parse(tasksContent);
119
+ // Handle both tagged and legacy formats
120
+ let tasks = [];
121
+ if (tasksData.tasks) {
122
+ // Legacy format
123
+ tasks = tasksData.tasks;
124
+ }
125
+ else {
126
+ // Tagged format - get tasks from all tags
127
+ Object.values(tasksData).forEach(tagData => {
128
+ if (tagData.tasks) {
129
+ tasks = tasks.concat(tagData.tasks);
130
+ }
131
+ });
132
+ }
133
+ // Calculate task statistics
134
+ const stats = tasks.reduce((acc, task) => {
135
+ acc.total++;
136
+ acc[task.status] = (acc[task.status] || 0) + 1;
137
+ // Count subtasks
138
+ if (task.subtasks) {
139
+ task.subtasks.forEach(subtask => {
140
+ acc.subtotalTasks++;
141
+ acc.subtasks = acc.subtasks || {};
142
+ acc.subtasks[subtask.status] = (acc.subtasks[subtask.status] || 0) + 1;
143
+ });
144
+ }
145
+ return acc;
146
+ }, {
147
+ total: 0,
148
+ subtotalTasks: 0,
149
+ pending: 0,
150
+ 'in-progress': 0,
151
+ done: 0,
152
+ review: 0,
153
+ deferred: 0,
154
+ cancelled: 0,
155
+ subtasks: {}
156
+ });
157
+ taskMetadata = {
158
+ taskCount: stats.total,
159
+ subtaskCount: stats.subtotalTasks,
160
+ completed: stats.done || 0,
161
+ pending: stats.pending || 0,
162
+ inProgress: stats['in-progress'] || 0,
163
+ review: stats.review || 0,
164
+ completionPercentage: stats.total > 0 ? Math.round((stats.done / stats.total) * 100) : 0,
165
+ lastModified: (await fs.stat(tasksPath)).mtime.toISOString()
166
+ };
167
+ }
168
+ catch (parseError) {
169
+ console.warn('Failed to parse tasks.json:', parseError.message);
170
+ taskMetadata = { error: 'Failed to parse tasks.json' };
171
+ }
172
+ }
173
+ return {
174
+ hasTaskmaster: true,
175
+ hasEssentialFiles,
176
+ files: fileStatus,
177
+ metadata: taskMetadata,
178
+ path: taskMasterPath
179
+ };
180
+ }
181
+ catch (error) {
182
+ console.error('Error detecting TaskMaster folder:', error);
183
+ return {
184
+ hasTaskmaster: false,
185
+ reason: `Error checking directory: ${error.message}`
186
+ };
187
+ }
188
+ }
189
+ // Cache for extracted project directories
190
+ const projectDirectoryCache = new Map();
191
+ // Clear cache when needed (called when project files change)
192
+ function clearProjectDirectoryCache() {
193
+ projectDirectoryCache.clear();
194
+ }
195
+ // Load project configuration file
196
+ async function loadProjectConfig() {
197
+ const configPath = path.join(os.homedir(), '.claude', 'project-config.json');
198
+ try {
199
+ const configData = await fs.readFile(configPath, 'utf8');
200
+ return JSON.parse(configData);
201
+ }
202
+ catch (error) {
203
+ // Return empty config if file doesn't exist
204
+ return {};
205
+ }
206
+ }
207
+ // Save project configuration file
208
+ async function saveProjectConfig(config) {
209
+ const claudeDir = path.join(os.homedir(), '.claude');
210
+ const configPath = path.join(claudeDir, 'project-config.json');
211
+ // Ensure the .claude directory exists
212
+ try {
213
+ await fs.mkdir(claudeDir, { recursive: true });
214
+ }
215
+ catch (error) {
216
+ if (error.code !== 'EEXIST') {
217
+ throw error;
218
+ }
219
+ }
220
+ await fs.writeFile(configPath, JSON.stringify(config, null, 2), 'utf8');
221
+ }
222
+ // Generate better display name from path
223
+ async function generateDisplayName(projectName, actualProjectDir = null) {
224
+ // Use actual project directory if provided, otherwise decode from project name
225
+ let projectPath = actualProjectDir || projectName.replace(/-/g, '/');
226
+ // Try to read package.json from the project path
227
+ try {
228
+ const packageJsonPath = path.join(projectPath, 'package.json');
229
+ const packageData = await fs.readFile(packageJsonPath, 'utf8');
230
+ const packageJson = JSON.parse(packageData);
231
+ // Return the name from package.json if it exists
232
+ if (packageJson.name) {
233
+ return packageJson.name;
234
+ }
235
+ }
236
+ catch (error) {
237
+ // Fall back to path-based naming if package.json doesn't exist or can't be read
238
+ }
239
+ // If it starts with /, it's an absolute path
240
+ if (projectPath.startsWith('/')) {
241
+ const parts = projectPath.split('/').filter(Boolean);
242
+ // Return only the last folder name
243
+ return parts[parts.length - 1] || projectPath;
244
+ }
245
+ return projectPath;
246
+ }
247
+ // Extract the actual project directory from JSONL sessions (with caching)
248
+ async function extractProjectDirectory(projectName) {
249
+ // Check cache first
250
+ if (projectDirectoryCache.has(projectName)) {
251
+ return projectDirectoryCache.get(projectName);
252
+ }
253
+ // Check project config for originalPath (manually added projects via UI or platform)
254
+ // This handles projects with dashes in their directory names correctly
255
+ const config = await loadProjectConfig();
256
+ if (config[projectName]?.originalPath) {
257
+ const originalPath = config[projectName].originalPath;
258
+ projectDirectoryCache.set(projectName, originalPath);
259
+ return originalPath;
260
+ }
261
+ const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
262
+ const cwdCounts = new Map();
263
+ let latestTimestamp = 0;
264
+ let latestCwd = null;
265
+ let extractedPath;
266
+ try {
267
+ // Check if the project directory exists
268
+ await fs.access(projectDir);
269
+ const files = await fs.readdir(projectDir);
270
+ const jsonlFiles = files.filter(file => file.endsWith('.jsonl'));
271
+ if (jsonlFiles.length === 0) {
272
+ // Fall back to decoded project name if no sessions
273
+ extractedPath = projectName.replace(/-/g, '/');
274
+ }
275
+ else {
276
+ // Process all JSONL files to collect cwd values
277
+ for (const file of jsonlFiles) {
278
+ const jsonlFile = path.join(projectDir, file);
279
+ const fileStream = fsSync.createReadStream(jsonlFile);
280
+ const rl = readline.createInterface({
281
+ input: fileStream,
282
+ crlfDelay: Infinity
283
+ });
284
+ for await (const line of rl) {
285
+ if (line.trim()) {
286
+ try {
287
+ const entry = JSON.parse(line);
288
+ if (entry.cwd) {
289
+ // Count occurrences of each cwd
290
+ cwdCounts.set(entry.cwd, (cwdCounts.get(entry.cwd) || 0) + 1);
291
+ // Track the most recent cwd
292
+ const timestamp = new Date(entry.timestamp || 0).getTime();
293
+ if (timestamp > latestTimestamp) {
294
+ latestTimestamp = timestamp;
295
+ latestCwd = entry.cwd;
296
+ }
297
+ }
298
+ }
299
+ catch (parseError) {
300
+ // Skip malformed lines
301
+ }
302
+ }
303
+ }
304
+ }
305
+ // Determine the best cwd to use
306
+ if (cwdCounts.size === 0) {
307
+ // No cwd found, fall back to decoded project name
308
+ extractedPath = projectName.replace(/-/g, '/');
309
+ }
310
+ else if (cwdCounts.size === 1) {
311
+ // Only one cwd, use it
312
+ extractedPath = Array.from(cwdCounts.keys())[0];
313
+ }
314
+ else {
315
+ // Multiple cwd values - prefer the most recent one if it has reasonable usage
316
+ const mostRecentCount = cwdCounts.get(latestCwd) || 0;
317
+ const maxCount = Math.max(...cwdCounts.values());
318
+ // Use most recent if it has at least 25% of the max count
319
+ if (mostRecentCount >= maxCount * 0.25) {
320
+ extractedPath = latestCwd;
321
+ }
322
+ else {
323
+ // Otherwise use the most frequently used cwd
324
+ for (const [cwd, count] of cwdCounts.entries()) {
325
+ if (count === maxCount) {
326
+ extractedPath = cwd;
327
+ break;
328
+ }
329
+ }
330
+ }
331
+ // Fallback (shouldn't reach here)
332
+ if (!extractedPath) {
333
+ extractedPath = latestCwd || projectName.replace(/-/g, '/');
334
+ }
335
+ }
336
+ }
337
+ // Cache the result
338
+ projectDirectoryCache.set(projectName, extractedPath);
339
+ return extractedPath;
340
+ }
341
+ catch (error) {
342
+ // If the directory doesn't exist, just use the decoded project name
343
+ if (error.code === 'ENOENT') {
344
+ extractedPath = projectName.replace(/-/g, '/');
345
+ }
346
+ else {
347
+ console.error(`Error extracting project directory for ${projectName}:`, error);
348
+ // Fall back to decoded project name for other errors
349
+ extractedPath = projectName.replace(/-/g, '/');
350
+ }
351
+ // Cache the fallback result too
352
+ projectDirectoryCache.set(projectName, extractedPath);
353
+ return extractedPath;
354
+ }
355
+ }
356
+ async function getProjects(progressCallback = null) {
357
+ const claudeDir = path.join(os.homedir(), '.claude', 'projects');
358
+ const config = await loadProjectConfig();
359
+ const projects = [];
360
+ const existingProjects = new Set();
361
+ const codexSessionsIndexRef = { sessionsByProject: null };
362
+ let totalProjects = 0;
363
+ let processedProjects = 0;
364
+ let directories = [];
365
+ try {
366
+ // Check if the .claude/projects directory exists
367
+ await fs.access(claudeDir);
368
+ // First, get existing Claude projects from the file system
369
+ const entries = await fs.readdir(claudeDir, { withFileTypes: true });
370
+ directories = entries.filter(e => e.isDirectory());
371
+ // Build set of existing project names for later
372
+ directories.forEach(e => existingProjects.add(e.name));
373
+ // Count manual projects not already in directories
374
+ const manualProjectsCount = Object.entries(config)
375
+ .filter(([name, cfg]) => cfg.manuallyAdded && !existingProjects.has(name))
376
+ .length;
377
+ totalProjects = directories.length + manualProjectsCount;
378
+ for (const entry of directories) {
379
+ processedProjects++;
380
+ // Emit progress
381
+ if (progressCallback) {
382
+ progressCallback({
383
+ phase: 'loading',
384
+ current: processedProjects,
385
+ total: totalProjects,
386
+ currentProject: entry.name
387
+ });
388
+ }
389
+ // Extract actual project directory from JSONL sessions
390
+ const actualProjectDir = await extractProjectDirectory(entry.name);
391
+ // Get display name from config or generate one
392
+ const customName = config[entry.name]?.displayName;
393
+ const autoDisplayName = await generateDisplayName(entry.name, actualProjectDir);
394
+ const fullPath = actualProjectDir;
395
+ const project = {
396
+ name: entry.name,
397
+ path: actualProjectDir,
398
+ displayName: customName || autoDisplayName,
399
+ fullPath: fullPath,
400
+ isCustomName: !!customName,
401
+ sessions: [],
402
+ geminiSessions: [],
403
+ sessionMeta: {
404
+ hasMore: false,
405
+ total: 0
406
+ }
407
+ };
408
+ // Try to get sessions for this project (just first 5 for performance)
409
+ try {
410
+ const sessionResult = await getSessions(entry.name, 5, 0);
411
+ project.sessions = sessionResult.sessions || [];
412
+ project.sessionMeta = {
413
+ hasMore: sessionResult.hasMore,
414
+ total: sessionResult.total
415
+ };
416
+ }
417
+ catch (e) {
418
+ console.warn(`Could not load sessions for project ${entry.name}:`, e.message);
419
+ project.sessionMeta = {
420
+ hasMore: false,
421
+ total: 0
422
+ };
423
+ }
424
+ applyCustomSessionNames(project.sessions, 'claude');
425
+ // Also fetch Cursor sessions for this project
426
+ try {
427
+ project.cursorSessions = await getCursorSessions(actualProjectDir);
428
+ }
429
+ catch (e) {
430
+ console.warn(`Could not load Cursor sessions for project ${entry.name}:`, e.message);
431
+ project.cursorSessions = [];
432
+ }
433
+ applyCustomSessionNames(project.cursorSessions, 'cursor');
434
+ // Also fetch Codex sessions for this project
435
+ try {
436
+ project.codexSessions = await getCodexSessions(actualProjectDir, {
437
+ indexRef: codexSessionsIndexRef,
438
+ });
439
+ }
440
+ catch (e) {
441
+ console.warn(`Could not load Codex sessions for project ${entry.name}:`, e.message);
442
+ project.codexSessions = [];
443
+ }
444
+ applyCustomSessionNames(project.codexSessions, 'codex');
445
+ // Also fetch Gemini sessions for this project (UI + CLI)
446
+ try {
447
+ const uiSessions = sessionManager.getProjectSessions(actualProjectDir) || [];
448
+ const cliSessions = await getGeminiCliSessions(actualProjectDir);
449
+ const uiIds = new Set(uiSessions.map(s => s.id));
450
+ const mergedGemini = [...uiSessions, ...cliSessions.filter(s => !uiIds.has(s.id))];
451
+ project.geminiSessions = mergedGemini;
452
+ }
453
+ catch (e) {
454
+ console.warn(`Could not load Gemini sessions for project ${entry.name}:`, e.message);
455
+ project.geminiSessions = [];
456
+ }
457
+ applyCustomSessionNames(project.geminiSessions, 'gemini');
458
+ // Add TaskMaster detection
459
+ try {
460
+ const taskMasterResult = await detectTaskMasterFolder(actualProjectDir);
461
+ project.taskmaster = {
462
+ hasTaskmaster: taskMasterResult.hasTaskmaster,
463
+ hasEssentialFiles: taskMasterResult.hasEssentialFiles,
464
+ metadata: taskMasterResult.metadata,
465
+ status: taskMasterResult.hasTaskmaster && taskMasterResult.hasEssentialFiles ? 'configured' : 'not-configured'
466
+ };
467
+ }
468
+ catch (e) {
469
+ console.warn(`Could not detect TaskMaster for project ${entry.name}:`, e.message);
470
+ project.taskmaster = {
471
+ hasTaskmaster: false,
472
+ hasEssentialFiles: false,
473
+ metadata: null,
474
+ status: 'error'
475
+ };
476
+ }
477
+ projects.push(project);
478
+ }
479
+ }
480
+ catch (error) {
481
+ // If the directory doesn't exist (ENOENT), that's okay - just continue with empty projects
482
+ if (error.code !== 'ENOENT') {
483
+ console.error('Error reading projects directory:', error);
484
+ }
485
+ // Calculate total for manual projects only (no directories exist)
486
+ totalProjects = Object.entries(config)
487
+ .filter(([name, cfg]) => cfg.manuallyAdded)
488
+ .length;
489
+ }
490
+ // Add manually configured projects that don't exist as folders yet
491
+ for (const [projectName, projectConfig] of Object.entries(config)) {
492
+ if (!existingProjects.has(projectName) && projectConfig.manuallyAdded) {
493
+ processedProjects++;
494
+ // Emit progress for manual projects
495
+ if (progressCallback) {
496
+ progressCallback({
497
+ phase: 'loading',
498
+ current: processedProjects,
499
+ total: totalProjects,
500
+ currentProject: projectName
501
+ });
502
+ }
503
+ // Use the original path if available, otherwise extract from potential sessions
504
+ let actualProjectDir = projectConfig.originalPath;
505
+ if (!actualProjectDir) {
506
+ try {
507
+ actualProjectDir = await extractProjectDirectory(projectName);
508
+ }
509
+ catch (error) {
510
+ // Fall back to decoded project name
511
+ actualProjectDir = projectName.replace(/-/g, '/');
512
+ }
513
+ }
514
+ const project = {
515
+ name: projectName,
516
+ path: actualProjectDir,
517
+ displayName: projectConfig.displayName || await generateDisplayName(projectName, actualProjectDir),
518
+ fullPath: actualProjectDir,
519
+ isCustomName: !!projectConfig.displayName,
520
+ isManuallyAdded: true,
521
+ sessions: [],
522
+ geminiSessions: [],
523
+ sessionMeta: {
524
+ hasMore: false,
525
+ total: 0
526
+ },
527
+ cursorSessions: [],
528
+ codexSessions: []
529
+ };
530
+ // Try to fetch Cursor sessions for manual projects too
531
+ try {
532
+ project.cursorSessions = await getCursorSessions(actualProjectDir);
533
+ }
534
+ catch (e) {
535
+ console.warn(`Could not load Cursor sessions for manual project ${projectName}:`, e.message);
536
+ }
537
+ applyCustomSessionNames(project.cursorSessions, 'cursor');
538
+ // Try to fetch Codex sessions for manual projects too
539
+ try {
540
+ project.codexSessions = await getCodexSessions(actualProjectDir, {
541
+ indexRef: codexSessionsIndexRef,
542
+ });
543
+ }
544
+ catch (e) {
545
+ console.warn(`Could not load Codex sessions for manual project ${projectName}:`, e.message);
546
+ }
547
+ applyCustomSessionNames(project.codexSessions, 'codex');
548
+ // Try to fetch Gemini sessions for manual projects too (UI + CLI)
549
+ try {
550
+ const uiSessions = sessionManager.getProjectSessions(actualProjectDir) || [];
551
+ const cliSessions = await getGeminiCliSessions(actualProjectDir);
552
+ const uiIds = new Set(uiSessions.map(s => s.id));
553
+ project.geminiSessions = [...uiSessions, ...cliSessions.filter(s => !uiIds.has(s.id))];
554
+ }
555
+ catch (e) {
556
+ console.warn(`Could not load Gemini sessions for manual project ${projectName}:`, e.message);
557
+ }
558
+ applyCustomSessionNames(project.geminiSessions, 'gemini');
559
+ // Add TaskMaster detection for manual projects
560
+ try {
561
+ const taskMasterResult = await detectTaskMasterFolder(actualProjectDir);
562
+ // Determine TaskMaster status
563
+ let taskMasterStatus = 'not-configured';
564
+ if (taskMasterResult.hasTaskmaster && taskMasterResult.hasEssentialFiles) {
565
+ taskMasterStatus = 'taskmaster-only'; // We don't check MCP for manual projects in bulk
566
+ }
567
+ project.taskmaster = {
568
+ status: taskMasterStatus,
569
+ hasTaskmaster: taskMasterResult.hasTaskmaster,
570
+ hasEssentialFiles: taskMasterResult.hasEssentialFiles,
571
+ metadata: taskMasterResult.metadata
572
+ };
573
+ }
574
+ catch (error) {
575
+ console.warn(`TaskMaster detection failed for manual project ${projectName}:`, error.message);
576
+ project.taskmaster = {
577
+ status: 'error',
578
+ hasTaskmaster: false,
579
+ hasEssentialFiles: false,
580
+ error: error.message
581
+ };
582
+ }
583
+ projects.push(project);
584
+ }
585
+ }
586
+ // Emit completion after all projects (including manual) are processed
587
+ if (progressCallback) {
588
+ progressCallback({
589
+ phase: 'complete',
590
+ current: totalProjects,
591
+ total: totalProjects
592
+ });
593
+ }
594
+ return projects;
595
+ }
596
+ async function getSessions(projectName, limit = 5, offset = 0) {
597
+ const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
598
+ try {
599
+ const files = await fs.readdir(projectDir);
600
+ // agent-*.jsonl files contain session start data at this point. This needs to be revisited
601
+ // periodically to make sure only accurate data is there and no new functionality is added there
602
+ const jsonlFiles = files.filter(file => file.endsWith('.jsonl') && !file.startsWith('agent-'));
603
+ if (jsonlFiles.length === 0) {
604
+ return { sessions: [], hasMore: false, total: 0 };
605
+ }
606
+ // Sort files by modification time (newest first)
607
+ const filesWithStats = await Promise.all(jsonlFiles.map(async (file) => {
608
+ const filePath = path.join(projectDir, file);
609
+ const stats = await fs.stat(filePath);
610
+ return { file, mtime: stats.mtime };
611
+ }));
612
+ filesWithStats.sort((a, b) => b.mtime - a.mtime);
613
+ const allSessions = new Map();
614
+ const allEntries = [];
615
+ const uuidToSessionMap = new Map();
616
+ // Collect all sessions and entries from all files
617
+ for (const { file } of filesWithStats) {
618
+ const jsonlFile = path.join(projectDir, file);
619
+ const result = await parseJsonlSessions(jsonlFile);
620
+ result.sessions.forEach(session => {
621
+ if (!allSessions.has(session.id)) {
622
+ allSessions.set(session.id, session);
623
+ }
624
+ });
625
+ allEntries.push(...result.entries);
626
+ // Early exit optimization for large projects
627
+ if (allSessions.size >= (limit + offset) * 2 && allEntries.length >= Math.min(3, filesWithStats.length)) {
628
+ break;
629
+ }
630
+ }
631
+ // Build UUID-to-session mapping for timeline detection
632
+ allEntries.forEach(entry => {
633
+ if (entry.uuid && entry.sessionId) {
634
+ uuidToSessionMap.set(entry.uuid, entry.sessionId);
635
+ }
636
+ });
637
+ // Group sessions by first user message ID
638
+ const sessionGroups = new Map(); // firstUserMsgId -> { latestSession, allSessions[] }
639
+ const sessionToFirstUserMsgId = new Map(); // sessionId -> firstUserMsgId
640
+ // Find the first user message for each session
641
+ allEntries.forEach(entry => {
642
+ if (entry.sessionId && entry.type === 'user' && entry.parentUuid === null && entry.uuid) {
643
+ // This is a first user message in a session (parentUuid is null)
644
+ const firstUserMsgId = entry.uuid;
645
+ if (!sessionToFirstUserMsgId.has(entry.sessionId)) {
646
+ sessionToFirstUserMsgId.set(entry.sessionId, firstUserMsgId);
647
+ const session = allSessions.get(entry.sessionId);
648
+ if (session) {
649
+ if (!sessionGroups.has(firstUserMsgId)) {
650
+ sessionGroups.set(firstUserMsgId, {
651
+ latestSession: session,
652
+ allSessions: [session]
653
+ });
654
+ }
655
+ else {
656
+ const group = sessionGroups.get(firstUserMsgId);
657
+ group.allSessions.push(session);
658
+ // Update latest session if this one is more recent
659
+ if (new Date(session.lastActivity) > new Date(group.latestSession.lastActivity)) {
660
+ group.latestSession = session;
661
+ }
662
+ }
663
+ }
664
+ }
665
+ }
666
+ });
667
+ // Collect all sessions that don't belong to any group (standalone sessions)
668
+ const groupedSessionIds = new Set();
669
+ sessionGroups.forEach(group => {
670
+ group.allSessions.forEach(session => groupedSessionIds.add(session.id));
671
+ });
672
+ const standaloneSessionsArray = Array.from(allSessions.values())
673
+ .filter(session => !groupedSessionIds.has(session.id));
674
+ // Combine grouped sessions (only show latest from each group) + standalone sessions
675
+ const latestFromGroups = Array.from(sessionGroups.values()).map(group => {
676
+ const session = { ...group.latestSession };
677
+ // Add metadata about grouping
678
+ if (group.allSessions.length > 1) {
679
+ session.isGrouped = true;
680
+ session.groupSize = group.allSessions.length;
681
+ session.groupSessions = group.allSessions.map(s => s.id);
682
+ }
683
+ return session;
684
+ });
685
+ const visibleSessions = [...latestFromGroups, ...standaloneSessionsArray]
686
+ .filter(session => !session.summary.startsWith('{ "'))
687
+ .sort((a, b) => new Date(b.lastActivity) - new Date(a.lastActivity));
688
+ const total = visibleSessions.length;
689
+ const paginatedSessions = visibleSessions.slice(offset, offset + limit);
690
+ const hasMore = offset + limit < total;
691
+ return {
692
+ sessions: paginatedSessions,
693
+ hasMore,
694
+ total,
695
+ offset,
696
+ limit
697
+ };
698
+ }
699
+ catch (error) {
700
+ console.error(`Error reading sessions for project ${projectName}:`, error);
701
+ return { sessions: [], hasMore: false, total: 0 };
702
+ }
703
+ }
704
+ async function parseJsonlSessions(filePath) {
705
+ const sessions = new Map();
706
+ const entries = [];
707
+ const pendingSummaries = new Map(); // leafUuid -> summary for entries without sessionId
708
+ try {
709
+ const fileStream = fsSync.createReadStream(filePath);
710
+ const rl = readline.createInterface({
711
+ input: fileStream,
712
+ crlfDelay: Infinity
713
+ });
714
+ for await (const line of rl) {
715
+ if (line.trim()) {
716
+ try {
717
+ const entry = JSON.parse(line);
718
+ entries.push(entry);
719
+ // Handle summary entries that don't have sessionId yet
720
+ if (entry.type === 'summary' && entry.summary && !entry.sessionId && entry.leafUuid) {
721
+ pendingSummaries.set(entry.leafUuid, entry.summary);
722
+ }
723
+ if (entry.sessionId) {
724
+ if (!sessions.has(entry.sessionId)) {
725
+ sessions.set(entry.sessionId, {
726
+ id: entry.sessionId,
727
+ summary: 'New Session',
728
+ messageCount: 0,
729
+ lastActivity: new Date(),
730
+ cwd: entry.cwd || '',
731
+ lastUserMessage: null,
732
+ lastAssistantMessage: null
733
+ });
734
+ }
735
+ const session = sessions.get(entry.sessionId);
736
+ // Apply pending summary if this entry has a parentUuid that matches a pending summary
737
+ if (session.summary === 'New Session' && entry.parentUuid && pendingSummaries.has(entry.parentUuid)) {
738
+ session.summary = pendingSummaries.get(entry.parentUuid);
739
+ }
740
+ // Update summary from summary entries with sessionId
741
+ if (entry.type === 'summary' && entry.summary) {
742
+ session.summary = entry.summary;
743
+ }
744
+ // Track last user and assistant messages (skip system messages)
745
+ if (entry.message?.role === 'user' && entry.message?.content) {
746
+ const content = entry.message.content;
747
+ // Extract text from array format if needed
748
+ let textContent = content;
749
+ if (Array.isArray(content) && content.length > 0 && content[0].type === 'text') {
750
+ textContent = content[0].text;
751
+ }
752
+ const isSystemMessage = typeof textContent === 'string' && (textContent.startsWith('<command-name>') ||
753
+ textContent.startsWith('<command-message>') ||
754
+ textContent.startsWith('<command-args>') ||
755
+ textContent.startsWith('<local-command-stdout>') ||
756
+ textContent.startsWith('<system-reminder>') ||
757
+ textContent.startsWith('Caveat:') ||
758
+ textContent.startsWith('This session is being continued from a previous') ||
759
+ textContent.startsWith('Invalid API key') ||
760
+ textContent.includes('{"subtasks":') || // Filter Task Master prompts
761
+ textContent.includes('CRITICAL: You MUST respond with ONLY a JSON') || // Filter Task Master system prompts
762
+ textContent === 'Warmup' // Explicitly filter out "Warmup"
763
+ );
764
+ if (typeof textContent === 'string' && textContent.length > 0 && !isSystemMessage) {
765
+ session.lastUserMessage = textContent;
766
+ }
767
+ }
768
+ else if (entry.message?.role === 'assistant' && entry.message?.content) {
769
+ // Skip API error messages using the isApiErrorMessage flag
770
+ if (entry.isApiErrorMessage === true) {
771
+ // Skip this message entirely
772
+ }
773
+ else {
774
+ // Track last assistant text message
775
+ let assistantText = null;
776
+ if (Array.isArray(entry.message.content)) {
777
+ for (const part of entry.message.content) {
778
+ if (part.type === 'text' && part.text) {
779
+ assistantText = part.text;
780
+ }
781
+ }
782
+ }
783
+ else if (typeof entry.message.content === 'string') {
784
+ assistantText = entry.message.content;
785
+ }
786
+ // Additional filter for assistant messages with system content
787
+ const isSystemAssistantMessage = typeof assistantText === 'string' && (assistantText.startsWith('Invalid API key') ||
788
+ assistantText.includes('{"subtasks":') ||
789
+ assistantText.includes('CRITICAL: You MUST respond with ONLY a JSON'));
790
+ if (assistantText && !isSystemAssistantMessage) {
791
+ session.lastAssistantMessage = assistantText;
792
+ }
793
+ }
794
+ }
795
+ session.messageCount++;
796
+ if (entry.timestamp) {
797
+ session.lastActivity = new Date(entry.timestamp);
798
+ }
799
+ }
800
+ }
801
+ catch (parseError) {
802
+ // Skip malformed lines silently
803
+ }
804
+ }
805
+ }
806
+ // After processing all entries, set final summary based on last message if no summary exists
807
+ for (const session of sessions.values()) {
808
+ if (session.summary === 'New Session') {
809
+ // Prefer last user message, fall back to last assistant message
810
+ const lastMessage = session.lastUserMessage || session.lastAssistantMessage;
811
+ if (lastMessage) {
812
+ session.summary = lastMessage.length > 50 ? lastMessage.substring(0, 50) + '...' : lastMessage;
813
+ }
814
+ }
815
+ }
816
+ // Filter out sessions that contain JSON responses (Task Master errors)
817
+ const allSessions = Array.from(sessions.values());
818
+ const filteredSessions = allSessions.filter(session => {
819
+ const shouldFilter = session.summary.startsWith('{ "');
820
+ if (shouldFilter) {
821
+ }
822
+ // Log a sample of summaries to debug
823
+ if (Math.random() < 0.01) { // Log 1% of sessions
824
+ }
825
+ return !shouldFilter;
826
+ });
827
+ return {
828
+ sessions: filteredSessions,
829
+ entries: entries
830
+ };
831
+ }
832
+ catch (error) {
833
+ console.error('Error reading JSONL file:', error);
834
+ return { sessions: [], entries: [] };
835
+ }
836
+ }
837
+ // Parse an agent JSONL file and extract tool uses
838
+ async function parseAgentTools(filePath) {
839
+ const tools = [];
840
+ try {
841
+ const fileStream = fsSync.createReadStream(filePath);
842
+ const rl = readline.createInterface({
843
+ input: fileStream,
844
+ crlfDelay: Infinity
845
+ });
846
+ for await (const line of rl) {
847
+ if (line.trim()) {
848
+ try {
849
+ const entry = JSON.parse(line);
850
+ // Look for assistant messages with tool_use
851
+ if (entry.message?.role === 'assistant' && Array.isArray(entry.message?.content)) {
852
+ for (const part of entry.message.content) {
853
+ if (part.type === 'tool_use') {
854
+ tools.push({
855
+ toolId: part.id,
856
+ toolName: part.name,
857
+ toolInput: part.input,
858
+ timestamp: entry.timestamp
859
+ });
860
+ }
861
+ }
862
+ }
863
+ // Look for tool results
864
+ if (entry.message?.role === 'user' && Array.isArray(entry.message?.content)) {
865
+ for (const part of entry.message.content) {
866
+ if (part.type === 'tool_result') {
867
+ // Find the matching tool and add result
868
+ const tool = tools.find(t => t.toolId === part.tool_use_id);
869
+ if (tool) {
870
+ tool.toolResult = {
871
+ content: typeof part.content === 'string' ? part.content :
872
+ Array.isArray(part.content) ? part.content.map(c => c.text || '').join('\n') :
873
+ JSON.stringify(part.content),
874
+ isError: Boolean(part.is_error)
875
+ };
876
+ }
877
+ }
878
+ }
879
+ }
880
+ }
881
+ catch (parseError) {
882
+ // Skip malformed lines
883
+ }
884
+ }
885
+ }
886
+ }
887
+ catch (error) {
888
+ console.warn(`Error parsing agent file ${filePath}:`, error.message);
889
+ }
890
+ return tools;
891
+ }
892
+ // Get messages for a specific session with pagination support
893
+ async function getSessionMessages(projectName, sessionId, limit = null, offset = 0) {
894
+ const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
895
+ try {
896
+ const files = await fs.readdir(projectDir);
897
+ // agent-*.jsonl files contain subagent tool history - we'll process them separately
898
+ const jsonlFiles = files.filter(file => file.endsWith('.jsonl') && !file.startsWith('agent-'));
899
+ const agentFiles = files.filter(file => file.endsWith('.jsonl') && file.startsWith('agent-'));
900
+ if (jsonlFiles.length === 0) {
901
+ return { messages: [], total: 0, hasMore: false };
902
+ }
903
+ const messages = [];
904
+ // Map of agentId -> tools for subagent tool grouping
905
+ const agentToolsCache = new Map();
906
+ // Process all JSONL files to find messages for this session
907
+ for (const file of jsonlFiles) {
908
+ const jsonlFile = path.join(projectDir, file);
909
+ const fileStream = fsSync.createReadStream(jsonlFile);
910
+ const rl = readline.createInterface({
911
+ input: fileStream,
912
+ crlfDelay: Infinity
913
+ });
914
+ for await (const line of rl) {
915
+ if (line.trim()) {
916
+ try {
917
+ const entry = JSON.parse(line);
918
+ if (entry.sessionId === sessionId) {
919
+ messages.push(entry);
920
+ }
921
+ }
922
+ catch (parseError) {
923
+ // Silently skip malformed JSONL lines (common with concurrent writes)
924
+ }
925
+ }
926
+ }
927
+ }
928
+ // Collect agentIds from Task tool results
929
+ const agentIds = new Set();
930
+ for (const message of messages) {
931
+ if (message.toolUseResult?.agentId) {
932
+ agentIds.add(message.toolUseResult.agentId);
933
+ }
934
+ }
935
+ // Load agent tools for each agentId found
936
+ for (const agentId of agentIds) {
937
+ const agentFileName = `agent-${agentId}.jsonl`;
938
+ if (agentFiles.includes(agentFileName)) {
939
+ const agentFilePath = path.join(projectDir, agentFileName);
940
+ const tools = await parseAgentTools(agentFilePath);
941
+ agentToolsCache.set(agentId, tools);
942
+ }
943
+ }
944
+ // Attach agent tools to their parent Task messages
945
+ for (const message of messages) {
946
+ if (message.toolUseResult?.agentId) {
947
+ const agentId = message.toolUseResult.agentId;
948
+ const agentTools = agentToolsCache.get(agentId);
949
+ if (agentTools && agentTools.length > 0) {
950
+ message.subagentTools = agentTools;
951
+ }
952
+ }
953
+ }
954
+ // Sort messages by timestamp
955
+ const sortedMessages = messages.sort((a, b) => new Date(a.timestamp || 0) - new Date(b.timestamp || 0));
956
+ const total = sortedMessages.length;
957
+ // If no limit is specified, return all messages (backward compatibility)
958
+ if (limit === null) {
959
+ return sortedMessages;
960
+ }
961
+ // Apply pagination - for recent messages, we need to slice from the end
962
+ // offset 0 should give us the most recent messages
963
+ const startIndex = Math.max(0, total - offset - limit);
964
+ const endIndex = total - offset;
965
+ const paginatedMessages = sortedMessages.slice(startIndex, endIndex);
966
+ const hasMore = startIndex > 0;
967
+ return {
968
+ messages: paginatedMessages,
969
+ total,
970
+ hasMore,
971
+ offset,
972
+ limit
973
+ };
974
+ }
975
+ catch (error) {
976
+ console.error(`Error reading messages for session ${sessionId}:`, error);
977
+ return limit === null ? [] : { messages: [], total: 0, hasMore: false };
978
+ }
979
+ }
980
+ // Rename a project's display name
981
+ async function renameProject(projectName, newDisplayName) {
982
+ const config = await loadProjectConfig();
983
+ if (!newDisplayName || newDisplayName.trim() === '') {
984
+ // Remove custom name if empty, will fall back to auto-generated
985
+ if (config[projectName]) {
986
+ delete config[projectName].displayName;
987
+ }
988
+ }
989
+ else {
990
+ // Set custom display name, preserving other properties (manuallyAdded, originalPath)
991
+ config[projectName] = {
992
+ ...config[projectName],
993
+ displayName: newDisplayName.trim()
994
+ };
995
+ }
996
+ await saveProjectConfig(config);
997
+ return true;
998
+ }
999
+ // Delete a session from a project
1000
+ async function deleteSession(projectName, sessionId) {
1001
+ const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
1002
+ try {
1003
+ const files = await fs.readdir(projectDir);
1004
+ const jsonlFiles = files.filter(file => file.endsWith('.jsonl'));
1005
+ if (jsonlFiles.length === 0) {
1006
+ throw new Error('No session files found for this project');
1007
+ }
1008
+ // Check all JSONL files to find which one contains the session
1009
+ for (const file of jsonlFiles) {
1010
+ const jsonlFile = path.join(projectDir, file);
1011
+ const content = await fs.readFile(jsonlFile, 'utf8');
1012
+ const lines = content.split('\n').filter(line => line.trim());
1013
+ // Check if this file contains the session
1014
+ const hasSession = lines.some(line => {
1015
+ try {
1016
+ const data = JSON.parse(line);
1017
+ return data.sessionId === sessionId;
1018
+ }
1019
+ catch {
1020
+ return false;
1021
+ }
1022
+ });
1023
+ if (hasSession) {
1024
+ // Filter out all entries for this session
1025
+ const filteredLines = lines.filter(line => {
1026
+ try {
1027
+ const data = JSON.parse(line);
1028
+ return data.sessionId !== sessionId;
1029
+ }
1030
+ catch {
1031
+ return true; // Keep malformed lines
1032
+ }
1033
+ });
1034
+ // Write back the filtered content
1035
+ await fs.writeFile(jsonlFile, filteredLines.join('\n') + (filteredLines.length > 0 ? '\n' : ''));
1036
+ return true;
1037
+ }
1038
+ }
1039
+ throw new Error(`Session ${sessionId} not found in any files`);
1040
+ }
1041
+ catch (error) {
1042
+ console.error(`Error deleting session ${sessionId} from project ${projectName}:`, error);
1043
+ throw error;
1044
+ }
1045
+ }
1046
+ // Check if a project is empty (has no sessions)
1047
+ async function isProjectEmpty(projectName) {
1048
+ try {
1049
+ const sessionsResult = await getSessions(projectName, 1, 0);
1050
+ return sessionsResult.total === 0;
1051
+ }
1052
+ catch (error) {
1053
+ console.error(`Error checking if project ${projectName} is empty:`, error);
1054
+ return false;
1055
+ }
1056
+ }
1057
+ // Delete a project (force=true to delete even with sessions)
1058
+ async function deleteProject(projectName, force = false) {
1059
+ const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
1060
+ try {
1061
+ const isEmpty = await isProjectEmpty(projectName);
1062
+ if (!isEmpty && !force) {
1063
+ throw new Error('Cannot delete project with existing sessions');
1064
+ }
1065
+ const config = await loadProjectConfig();
1066
+ let projectPath = config[projectName]?.path || config[projectName]?.originalPath;
1067
+ // Fallback to extractProjectDirectory if projectPath is not in config
1068
+ if (!projectPath) {
1069
+ projectPath = await extractProjectDirectory(projectName);
1070
+ }
1071
+ // Remove the project directory (includes all Claude sessions)
1072
+ await fs.rm(projectDir, { recursive: true, force: true });
1073
+ // Delete all Codex sessions associated with this project
1074
+ if (projectPath) {
1075
+ try {
1076
+ const codexSessions = await getCodexSessions(projectPath, { limit: 0 });
1077
+ for (const session of codexSessions) {
1078
+ try {
1079
+ await deleteCodexSession(session.id);
1080
+ }
1081
+ catch (err) {
1082
+ console.warn(`Failed to delete Codex session ${session.id}:`, err.message);
1083
+ }
1084
+ }
1085
+ }
1086
+ catch (err) {
1087
+ console.warn('Failed to delete Codex sessions:', err.message);
1088
+ }
1089
+ // Delete Cursor sessions directory if it exists
1090
+ try {
1091
+ const hash = crypto.createHash('md5').update(projectPath).digest('hex');
1092
+ const cursorProjectDir = path.join(os.homedir(), '.cursor', 'chats', hash);
1093
+ await fs.rm(cursorProjectDir, { recursive: true, force: true });
1094
+ }
1095
+ catch (err) {
1096
+ // Cursor dir may not exist, ignore
1097
+ }
1098
+ }
1099
+ // Remove from project config
1100
+ delete config[projectName];
1101
+ await saveProjectConfig(config);
1102
+ return true;
1103
+ }
1104
+ catch (error) {
1105
+ console.error(`Error deleting project ${projectName}:`, error);
1106
+ throw error;
1107
+ }
1108
+ }
1109
+ // Add a project manually to the config (without creating folders)
1110
+ async function addProjectManually(projectPath, displayName = null) {
1111
+ const absolutePath = path.resolve(projectPath);
1112
+ try {
1113
+ // Check if the path exists
1114
+ await fs.access(absolutePath);
1115
+ }
1116
+ catch (error) {
1117
+ throw new Error(`Path does not exist: ${absolutePath}`);
1118
+ }
1119
+ // Generate project name (encode path for use as directory name)
1120
+ const projectName = absolutePath.replace(/[\\/:\s~_]/g, '-');
1121
+ // Check if project already exists in config
1122
+ const config = await loadProjectConfig();
1123
+ const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
1124
+ if (config[projectName]) {
1125
+ throw new Error(`Project already configured for path: ${absolutePath}`);
1126
+ }
1127
+ // Allow adding projects even if the directory exists - this enables tracking
1128
+ // existing Claude Code or Cursor projects in the UI
1129
+ // Add to config as manually added project
1130
+ config[projectName] = {
1131
+ manuallyAdded: true,
1132
+ originalPath: absolutePath
1133
+ };
1134
+ if (displayName) {
1135
+ config[projectName].displayName = displayName;
1136
+ }
1137
+ await saveProjectConfig(config);
1138
+ return {
1139
+ name: projectName,
1140
+ path: absolutePath,
1141
+ fullPath: absolutePath,
1142
+ displayName: displayName || await generateDisplayName(projectName, absolutePath),
1143
+ isManuallyAdded: true,
1144
+ sessions: [],
1145
+ cursorSessions: []
1146
+ };
1147
+ }
1148
+ // Fetch Cursor sessions for a given project path
1149
+ async function getCursorSessions(projectPath) {
1150
+ try {
1151
+ // Calculate cwdID hash for the project path (Cursor uses MD5 hash)
1152
+ const cwdId = crypto.createHash('md5').update(projectPath).digest('hex');
1153
+ const cursorChatsPath = path.join(os.homedir(), '.cursor', 'chats', cwdId);
1154
+ // Check if the directory exists
1155
+ try {
1156
+ await fs.access(cursorChatsPath);
1157
+ }
1158
+ catch (error) {
1159
+ // No sessions for this project
1160
+ return [];
1161
+ }
1162
+ // List all session directories
1163
+ const sessionDirs = await fs.readdir(cursorChatsPath);
1164
+ const sessions = [];
1165
+ for (const sessionId of sessionDirs) {
1166
+ const sessionPath = path.join(cursorChatsPath, sessionId);
1167
+ const storeDbPath = path.join(sessionPath, 'store.db');
1168
+ try {
1169
+ // Check if store.db exists
1170
+ await fs.access(storeDbPath);
1171
+ // Capture store.db mtime as a reliable fallback timestamp
1172
+ let dbStatMtimeMs = null;
1173
+ try {
1174
+ const stat = await fs.stat(storeDbPath);
1175
+ dbStatMtimeMs = stat.mtimeMs;
1176
+ }
1177
+ catch (_) { }
1178
+ // Open SQLite database
1179
+ const db = await open({
1180
+ filename: storeDbPath,
1181
+ driver: sqlite3.Database,
1182
+ mode: sqlite3.OPEN_READONLY
1183
+ });
1184
+ // Get metadata from meta table
1185
+ const metaRows = await db.all(`
1186
+ SELECT key, value FROM meta
1187
+ `);
1188
+ // Parse metadata
1189
+ let metadata = {};
1190
+ for (const row of metaRows) {
1191
+ if (row.value) {
1192
+ try {
1193
+ // Try to decode as hex-encoded JSON
1194
+ const hexMatch = row.value.toString().match(/^[0-9a-fA-F]+$/);
1195
+ if (hexMatch) {
1196
+ const jsonStr = Buffer.from(row.value, 'hex').toString('utf8');
1197
+ metadata[row.key] = JSON.parse(jsonStr);
1198
+ }
1199
+ else {
1200
+ metadata[row.key] = row.value.toString();
1201
+ }
1202
+ }
1203
+ catch (e) {
1204
+ metadata[row.key] = row.value.toString();
1205
+ }
1206
+ }
1207
+ }
1208
+ // Get message count
1209
+ const messageCountResult = await db.get(`
1210
+ SELECT COUNT(*) as count FROM blobs
1211
+ `);
1212
+ await db.close();
1213
+ // Extract session info
1214
+ const sessionName = metadata.title || metadata.sessionTitle || 'Untitled Session';
1215
+ // Determine timestamp - prefer createdAt from metadata, fall back to db file mtime
1216
+ let createdAt = null;
1217
+ if (metadata.createdAt) {
1218
+ createdAt = new Date(metadata.createdAt).toISOString();
1219
+ }
1220
+ else if (dbStatMtimeMs) {
1221
+ createdAt = new Date(dbStatMtimeMs).toISOString();
1222
+ }
1223
+ else {
1224
+ createdAt = new Date().toISOString();
1225
+ }
1226
+ sessions.push({
1227
+ id: sessionId,
1228
+ name: sessionName,
1229
+ createdAt: createdAt,
1230
+ lastActivity: createdAt, // For compatibility with Claude sessions
1231
+ messageCount: messageCountResult.count || 0,
1232
+ projectPath: projectPath
1233
+ });
1234
+ }
1235
+ catch (error) {
1236
+ console.warn(`Could not read Cursor session ${sessionId}:`, error.message);
1237
+ }
1238
+ }
1239
+ // Sort sessions by creation time (newest first)
1240
+ sessions.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
1241
+ // Return only the first 5 sessions for performance
1242
+ return sessions.slice(0, 5);
1243
+ }
1244
+ catch (error) {
1245
+ console.error('Error fetching Cursor sessions:', error);
1246
+ return [];
1247
+ }
1248
+ }
1249
+ function normalizeComparablePath(inputPath) {
1250
+ if (!inputPath || typeof inputPath !== 'string') {
1251
+ return '';
1252
+ }
1253
+ const withoutLongPathPrefix = inputPath.startsWith('\\\\?\\')
1254
+ ? inputPath.slice(4)
1255
+ : inputPath;
1256
+ const normalized = path.normalize(withoutLongPathPrefix.trim());
1257
+ if (!normalized) {
1258
+ return '';
1259
+ }
1260
+ const resolved = path.resolve(normalized);
1261
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
1262
+ }
1263
+ async function findCodexJsonlFiles(dir) {
1264
+ const files = [];
1265
+ try {
1266
+ const entries = await fs.readdir(dir, { withFileTypes: true });
1267
+ for (const entry of entries) {
1268
+ const fullPath = path.join(dir, entry.name);
1269
+ if (entry.isDirectory()) {
1270
+ files.push(...await findCodexJsonlFiles(fullPath));
1271
+ }
1272
+ else if (entry.name.endsWith('.jsonl')) {
1273
+ files.push(fullPath);
1274
+ }
1275
+ }
1276
+ }
1277
+ catch (error) {
1278
+ // Skip directories we can't read
1279
+ }
1280
+ return files;
1281
+ }
1282
+ async function buildCodexSessionsIndex() {
1283
+ const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
1284
+ const sessionsByProject = new Map();
1285
+ try {
1286
+ await fs.access(codexSessionsDir);
1287
+ }
1288
+ catch (error) {
1289
+ return sessionsByProject;
1290
+ }
1291
+ const jsonlFiles = await findCodexJsonlFiles(codexSessionsDir);
1292
+ for (const filePath of jsonlFiles) {
1293
+ try {
1294
+ const sessionData = await parseCodexSessionFile(filePath);
1295
+ if (!sessionData || !sessionData.id) {
1296
+ continue;
1297
+ }
1298
+ const normalizedProjectPath = normalizeComparablePath(sessionData.cwd);
1299
+ if (!normalizedProjectPath) {
1300
+ continue;
1301
+ }
1302
+ const session = {
1303
+ id: sessionData.id,
1304
+ summary: sessionData.summary || 'Codex Session',
1305
+ messageCount: sessionData.messageCount || 0,
1306
+ lastActivity: sessionData.timestamp ? new Date(sessionData.timestamp) : new Date(),
1307
+ cwd: sessionData.cwd,
1308
+ model: sessionData.model,
1309
+ filePath,
1310
+ provider: 'codex',
1311
+ };
1312
+ if (!sessionsByProject.has(normalizedProjectPath)) {
1313
+ sessionsByProject.set(normalizedProjectPath, []);
1314
+ }
1315
+ sessionsByProject.get(normalizedProjectPath).push(session);
1316
+ }
1317
+ catch (error) {
1318
+ console.warn(`Could not parse Codex session file ${filePath}:`, error.message);
1319
+ }
1320
+ }
1321
+ for (const sessions of sessionsByProject.values()) {
1322
+ sessions.sort((a, b) => new Date(b.lastActivity) - new Date(a.lastActivity));
1323
+ }
1324
+ return sessionsByProject;
1325
+ }
1326
+ // Fetch Codex sessions for a given project path
1327
+ async function getCodexSessions(projectPath, options = {}) {
1328
+ const { limit = 5, indexRef = null } = options;
1329
+ try {
1330
+ const normalizedProjectPath = normalizeComparablePath(projectPath);
1331
+ if (!normalizedProjectPath) {
1332
+ return [];
1333
+ }
1334
+ if (indexRef && !indexRef.sessionsByProject) {
1335
+ indexRef.sessionsByProject = await buildCodexSessionsIndex();
1336
+ }
1337
+ const sessionsByProject = indexRef?.sessionsByProject || await buildCodexSessionsIndex();
1338
+ const sessions = sessionsByProject.get(normalizedProjectPath) || [];
1339
+ // Return limited sessions for performance (0 = unlimited for deletion)
1340
+ return limit > 0 ? sessions.slice(0, limit) : [...sessions];
1341
+ }
1342
+ catch (error) {
1343
+ console.error('Error fetching Codex sessions:', error);
1344
+ return [];
1345
+ }
1346
+ }
1347
+ function isVisibleCodexUserMessage(payload) {
1348
+ if (!payload || payload.type !== 'user_message') {
1349
+ return false;
1350
+ }
1351
+ // Codex logs internal context (environment, instructions) as non-plain user_message kinds.
1352
+ if (payload.kind && payload.kind !== 'plain') {
1353
+ return false;
1354
+ }
1355
+ if (typeof payload.message !== 'string' || payload.message.trim().length === 0) {
1356
+ return false;
1357
+ }
1358
+ return true;
1359
+ }
1360
+ // Parse a Codex session JSONL file to extract metadata
1361
+ async function parseCodexSessionFile(filePath) {
1362
+ try {
1363
+ const fileStream = fsSync.createReadStream(filePath);
1364
+ const rl = readline.createInterface({
1365
+ input: fileStream,
1366
+ crlfDelay: Infinity
1367
+ });
1368
+ let sessionMeta = null;
1369
+ let lastTimestamp = null;
1370
+ let lastUserMessage = null;
1371
+ let messageCount = 0;
1372
+ for await (const line of rl) {
1373
+ if (line.trim()) {
1374
+ try {
1375
+ const entry = JSON.parse(line);
1376
+ // Track timestamp
1377
+ if (entry.timestamp) {
1378
+ lastTimestamp = entry.timestamp;
1379
+ }
1380
+ // Extract session metadata
1381
+ if (entry.type === 'session_meta' && entry.payload) {
1382
+ sessionMeta = {
1383
+ id: entry.payload.id,
1384
+ cwd: entry.payload.cwd,
1385
+ model: entry.payload.model || entry.payload.model_provider,
1386
+ timestamp: entry.timestamp,
1387
+ git: entry.payload.git
1388
+ };
1389
+ }
1390
+ // Count visible user messages and extract summary from the latest plain user input.
1391
+ if (entry.type === 'event_msg' && isVisibleCodexUserMessage(entry.payload)) {
1392
+ messageCount++;
1393
+ if (entry.payload.message) {
1394
+ lastUserMessage = entry.payload.message;
1395
+ }
1396
+ }
1397
+ if (entry.type === 'response_item' && entry.payload?.type === 'message' && entry.payload.role === 'assistant') {
1398
+ messageCount++;
1399
+ }
1400
+ }
1401
+ catch (parseError) {
1402
+ // Skip malformed lines
1403
+ }
1404
+ }
1405
+ }
1406
+ if (sessionMeta) {
1407
+ return {
1408
+ ...sessionMeta,
1409
+ timestamp: lastTimestamp || sessionMeta.timestamp,
1410
+ summary: lastUserMessage ?
1411
+ (lastUserMessage.length > 50 ? lastUserMessage.substring(0, 50) + '...' : lastUserMessage) :
1412
+ 'Codex Session',
1413
+ messageCount
1414
+ };
1415
+ }
1416
+ return null;
1417
+ }
1418
+ catch (error) {
1419
+ console.error('Error parsing Codex session file:', error);
1420
+ return null;
1421
+ }
1422
+ }
1423
+ // Get messages for a specific Codex session
1424
+ async function getCodexSessionMessages(sessionId, limit = null, offset = 0) {
1425
+ try {
1426
+ const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
1427
+ // Find the session file by searching for the session ID
1428
+ const findSessionFile = async (dir) => {
1429
+ try {
1430
+ const entries = await fs.readdir(dir, { withFileTypes: true });
1431
+ for (const entry of entries) {
1432
+ const fullPath = path.join(dir, entry.name);
1433
+ if (entry.isDirectory()) {
1434
+ const found = await findSessionFile(fullPath);
1435
+ if (found)
1436
+ return found;
1437
+ }
1438
+ else if (entry.name.includes(sessionId) && entry.name.endsWith('.jsonl')) {
1439
+ return fullPath;
1440
+ }
1441
+ }
1442
+ }
1443
+ catch (error) {
1444
+ // Skip directories we can't read
1445
+ }
1446
+ return null;
1447
+ };
1448
+ const sessionFilePath = await findSessionFile(codexSessionsDir);
1449
+ if (!sessionFilePath) {
1450
+ console.warn(`Codex session file not found for session ${sessionId}`);
1451
+ return { messages: [], total: 0, hasMore: false };
1452
+ }
1453
+ const messages = [];
1454
+ let tokenUsage = null;
1455
+ const fileStream = fsSync.createReadStream(sessionFilePath);
1456
+ const rl = readline.createInterface({
1457
+ input: fileStream,
1458
+ crlfDelay: Infinity
1459
+ });
1460
+ // Helper to extract text from Codex content array
1461
+ const extractText = (content) => {
1462
+ if (!Array.isArray(content))
1463
+ return content;
1464
+ return content
1465
+ .map(item => {
1466
+ if (item.type === 'input_text' || item.type === 'output_text') {
1467
+ return item.text;
1468
+ }
1469
+ if (item.type === 'text') {
1470
+ return item.text;
1471
+ }
1472
+ return '';
1473
+ })
1474
+ .filter(Boolean)
1475
+ .join('\n');
1476
+ };
1477
+ for await (const line of rl) {
1478
+ if (line.trim()) {
1479
+ try {
1480
+ const entry = JSON.parse(line);
1481
+ // Extract token usage from token_count events (keep latest)
1482
+ if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload?.info) {
1483
+ const info = entry.payload.info;
1484
+ if (info.total_token_usage) {
1485
+ tokenUsage = {
1486
+ used: info.total_token_usage.total_tokens || 0,
1487
+ total: info.model_context_window || 200000
1488
+ };
1489
+ }
1490
+ }
1491
+ // Use event_msg.user_message for user-visible inputs.
1492
+ if (entry.type === 'event_msg' && isVisibleCodexUserMessage(entry.payload)) {
1493
+ messages.push({
1494
+ type: 'user',
1495
+ timestamp: entry.timestamp,
1496
+ message: {
1497
+ role: 'user',
1498
+ content: entry.payload.message
1499
+ }
1500
+ });
1501
+ }
1502
+ // response_item.message may include internal prompts for non-assistant roles.
1503
+ // Keep only assistant output from response_item.
1504
+ if (entry.type === 'response_item' &&
1505
+ entry.payload?.type === 'message' &&
1506
+ entry.payload.role === 'assistant') {
1507
+ const content = entry.payload.content;
1508
+ const textContent = extractText(content);
1509
+ // Only add if there's actual content
1510
+ if (textContent?.trim()) {
1511
+ messages.push({
1512
+ type: 'assistant',
1513
+ timestamp: entry.timestamp,
1514
+ message: {
1515
+ role: 'assistant',
1516
+ content: textContent
1517
+ }
1518
+ });
1519
+ }
1520
+ }
1521
+ if (entry.type === 'response_item' && entry.payload?.type === 'reasoning') {
1522
+ const summaryText = entry.payload.summary
1523
+ ?.map(s => s.text)
1524
+ .filter(Boolean)
1525
+ .join('\n');
1526
+ if (summaryText?.trim()) {
1527
+ messages.push({
1528
+ type: 'thinking',
1529
+ timestamp: entry.timestamp,
1530
+ message: {
1531
+ role: 'assistant',
1532
+ content: summaryText
1533
+ }
1534
+ });
1535
+ }
1536
+ }
1537
+ if (entry.type === 'response_item' && entry.payload?.type === 'function_call') {
1538
+ let toolName = entry.payload.name;
1539
+ let toolInput = entry.payload.arguments;
1540
+ // Map Codex tool names to Claude equivalents
1541
+ if (toolName === 'shell_command') {
1542
+ toolName = 'Bash';
1543
+ try {
1544
+ const args = JSON.parse(entry.payload.arguments);
1545
+ toolInput = JSON.stringify({ command: args.command });
1546
+ }
1547
+ catch (e) {
1548
+ // Keep original if parsing fails
1549
+ }
1550
+ }
1551
+ messages.push({
1552
+ type: 'tool_use',
1553
+ timestamp: entry.timestamp,
1554
+ toolName: toolName,
1555
+ toolInput: toolInput,
1556
+ toolCallId: entry.payload.call_id
1557
+ });
1558
+ }
1559
+ if (entry.type === 'response_item' && entry.payload?.type === 'function_call_output') {
1560
+ messages.push({
1561
+ type: 'tool_result',
1562
+ timestamp: entry.timestamp,
1563
+ toolCallId: entry.payload.call_id,
1564
+ output: entry.payload.output
1565
+ });
1566
+ }
1567
+ if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call') {
1568
+ const toolName = entry.payload.name || 'custom_tool';
1569
+ const input = entry.payload.input || '';
1570
+ if (toolName === 'apply_patch') {
1571
+ // Parse Codex patch format and convert to Claude Edit format
1572
+ const fileMatch = input.match(/\*\*\* Update File: (.+)/);
1573
+ const filePath = fileMatch ? fileMatch[1].trim() : 'unknown';
1574
+ // Extract old and new content from patch
1575
+ const lines = input.split('\n');
1576
+ const oldLines = [];
1577
+ const newLines = [];
1578
+ for (const line of lines) {
1579
+ if (line.startsWith('-') && !line.startsWith('---')) {
1580
+ oldLines.push(line.substring(1));
1581
+ }
1582
+ else if (line.startsWith('+') && !line.startsWith('+++')) {
1583
+ newLines.push(line.substring(1));
1584
+ }
1585
+ }
1586
+ messages.push({
1587
+ type: 'tool_use',
1588
+ timestamp: entry.timestamp,
1589
+ toolName: 'Edit',
1590
+ toolInput: JSON.stringify({
1591
+ file_path: filePath,
1592
+ old_string: oldLines.join('\n'),
1593
+ new_string: newLines.join('\n')
1594
+ }),
1595
+ toolCallId: entry.payload.call_id
1596
+ });
1597
+ }
1598
+ else {
1599
+ messages.push({
1600
+ type: 'tool_use',
1601
+ timestamp: entry.timestamp,
1602
+ toolName: toolName,
1603
+ toolInput: input,
1604
+ toolCallId: entry.payload.call_id
1605
+ });
1606
+ }
1607
+ }
1608
+ if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call_output') {
1609
+ messages.push({
1610
+ type: 'tool_result',
1611
+ timestamp: entry.timestamp,
1612
+ toolCallId: entry.payload.call_id,
1613
+ output: entry.payload.output || ''
1614
+ });
1615
+ }
1616
+ }
1617
+ catch (parseError) {
1618
+ // Skip malformed lines
1619
+ }
1620
+ }
1621
+ }
1622
+ // Sort by timestamp
1623
+ messages.sort((a, b) => new Date(a.timestamp || 0) - new Date(b.timestamp || 0));
1624
+ const total = messages.length;
1625
+ // Apply pagination if limit is specified
1626
+ if (limit !== null) {
1627
+ const startIndex = Math.max(0, total - offset - limit);
1628
+ const endIndex = total - offset;
1629
+ const paginatedMessages = messages.slice(startIndex, endIndex);
1630
+ const hasMore = startIndex > 0;
1631
+ return {
1632
+ messages: paginatedMessages,
1633
+ total,
1634
+ hasMore,
1635
+ offset,
1636
+ limit,
1637
+ tokenUsage
1638
+ };
1639
+ }
1640
+ return { messages, tokenUsage };
1641
+ }
1642
+ catch (error) {
1643
+ console.error(`Error reading Codex session messages for ${sessionId}:`, error);
1644
+ return { messages: [], total: 0, hasMore: false };
1645
+ }
1646
+ }
1647
+ async function deleteCodexSession(sessionId) {
1648
+ try {
1649
+ const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
1650
+ const findJsonlFiles = async (dir) => {
1651
+ const files = [];
1652
+ try {
1653
+ const entries = await fs.readdir(dir, { withFileTypes: true });
1654
+ for (const entry of entries) {
1655
+ const fullPath = path.join(dir, entry.name);
1656
+ if (entry.isDirectory()) {
1657
+ files.push(...await findJsonlFiles(fullPath));
1658
+ }
1659
+ else if (entry.name.endsWith('.jsonl')) {
1660
+ files.push(fullPath);
1661
+ }
1662
+ }
1663
+ }
1664
+ catch (error) { }
1665
+ return files;
1666
+ };
1667
+ const jsonlFiles = await findJsonlFiles(codexSessionsDir);
1668
+ for (const filePath of jsonlFiles) {
1669
+ const sessionData = await parseCodexSessionFile(filePath);
1670
+ if (sessionData && sessionData.id === sessionId) {
1671
+ await fs.unlink(filePath);
1672
+ return true;
1673
+ }
1674
+ }
1675
+ throw new Error(`Codex session file not found for session ${sessionId}`);
1676
+ }
1677
+ catch (error) {
1678
+ console.error(`Error deleting Codex session ${sessionId}:`, error);
1679
+ throw error;
1680
+ }
1681
+ }
1682
+ async function searchConversations(query, limit = 50, onProjectResult = null, signal = null) {
1683
+ const safeQuery = typeof query === 'string' ? query.trim() : '';
1684
+ const safeLimit = Math.max(1, Math.min(Number.isFinite(limit) ? limit : 50, 200));
1685
+ const claudeDir = path.join(os.homedir(), '.claude', 'projects');
1686
+ const config = await loadProjectConfig();
1687
+ const results = [];
1688
+ let totalMatches = 0;
1689
+ const words = safeQuery.toLowerCase().split(/\s+/).filter(w => w.length > 0);
1690
+ if (words.length === 0)
1691
+ return { results: [], totalMatches: 0, query: safeQuery };
1692
+ const isAborted = () => signal?.aborted === true;
1693
+ const isSystemMessage = (textContent) => {
1694
+ return typeof textContent === 'string' && (textContent.startsWith('<command-name>') ||
1695
+ textContent.startsWith('<command-message>') ||
1696
+ textContent.startsWith('<command-args>') ||
1697
+ textContent.startsWith('<local-command-stdout>') ||
1698
+ textContent.startsWith('<system-reminder>') ||
1699
+ textContent.startsWith('Caveat:') ||
1700
+ textContent.startsWith('This session is being continued from a previous') ||
1701
+ textContent.startsWith('Invalid API key') ||
1702
+ textContent.includes('{"subtasks":') ||
1703
+ textContent.includes('CRITICAL: You MUST respond with ONLY a JSON') ||
1704
+ textContent === 'Warmup');
1705
+ };
1706
+ const extractText = (content) => {
1707
+ if (typeof content === 'string')
1708
+ return content;
1709
+ if (Array.isArray(content)) {
1710
+ return content
1711
+ .filter(part => part.type === 'text' && part.text)
1712
+ .map(part => part.text)
1713
+ .join(' ');
1714
+ }
1715
+ return '';
1716
+ };
1717
+ const escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
1718
+ const wordPatterns = words.map(w => new RegExp(`(?<!\\p{L})${escapeRegex(w)}(?!\\p{L})`, 'u'));
1719
+ const allWordsMatch = (textLower) => {
1720
+ return wordPatterns.every(p => p.test(textLower));
1721
+ };
1722
+ const buildSnippet = (text, textLower, snippetLen = 150) => {
1723
+ let firstIndex = -1;
1724
+ let firstWordLen = 0;
1725
+ for (const w of words) {
1726
+ const re = new RegExp(`(?<!\\p{L})${escapeRegex(w)}(?!\\p{L})`, 'u');
1727
+ const m = re.exec(textLower);
1728
+ if (m && (firstIndex === -1 || m.index < firstIndex)) {
1729
+ firstIndex = m.index;
1730
+ firstWordLen = w.length;
1731
+ }
1732
+ }
1733
+ if (firstIndex === -1)
1734
+ firstIndex = 0;
1735
+ const halfLen = Math.floor(snippetLen / 2);
1736
+ let start = Math.max(0, firstIndex - halfLen);
1737
+ let end = Math.min(text.length, firstIndex + halfLen + firstWordLen);
1738
+ let snippet = text.slice(start, end).replace(/\n/g, ' ');
1739
+ const prefix = start > 0 ? '...' : '';
1740
+ const suffix = end < text.length ? '...' : '';
1741
+ snippet = prefix + snippet + suffix;
1742
+ const snippetLower = snippet.toLowerCase();
1743
+ const highlights = [];
1744
+ for (const word of words) {
1745
+ const re = new RegExp(`(?<!\\p{L})${escapeRegex(word)}(?!\\p{L})`, 'gu');
1746
+ let match;
1747
+ while ((match = re.exec(snippetLower)) !== null) {
1748
+ highlights.push({ start: match.index, end: match.index + word.length });
1749
+ }
1750
+ }
1751
+ highlights.sort((a, b) => a.start - b.start);
1752
+ const merged = [];
1753
+ for (const h of highlights) {
1754
+ const last = merged[merged.length - 1];
1755
+ if (last && h.start <= last.end) {
1756
+ last.end = Math.max(last.end, h.end);
1757
+ }
1758
+ else {
1759
+ merged.push({ ...h });
1760
+ }
1761
+ }
1762
+ return { snippet, highlights: merged };
1763
+ };
1764
+ try {
1765
+ await fs.access(claudeDir);
1766
+ const entries = await fs.readdir(claudeDir, { withFileTypes: true });
1767
+ const projectDirs = entries.filter(e => e.isDirectory());
1768
+ let scannedProjects = 0;
1769
+ const totalProjects = projectDirs.length;
1770
+ for (const projectEntry of projectDirs) {
1771
+ if (totalMatches >= safeLimit || isAborted())
1772
+ break;
1773
+ const projectName = projectEntry.name;
1774
+ const projectDir = path.join(claudeDir, projectName);
1775
+ const displayName = config[projectName]?.displayName
1776
+ || await generateDisplayName(projectName);
1777
+ let files;
1778
+ try {
1779
+ files = await fs.readdir(projectDir);
1780
+ }
1781
+ catch {
1782
+ continue;
1783
+ }
1784
+ const jsonlFiles = files.filter(file => file.endsWith('.jsonl') && !file.startsWith('agent-'));
1785
+ const projectResult = {
1786
+ projectName,
1787
+ projectDisplayName: displayName,
1788
+ sessions: []
1789
+ };
1790
+ for (const file of jsonlFiles) {
1791
+ if (totalMatches >= safeLimit || isAborted())
1792
+ break;
1793
+ const filePath = path.join(projectDir, file);
1794
+ const sessionMatches = new Map();
1795
+ const sessionSummaries = new Map();
1796
+ const pendingSummaries = new Map();
1797
+ const sessionLastMessages = new Map();
1798
+ let currentSessionId = null;
1799
+ try {
1800
+ const fileStream = fsSync.createReadStream(filePath);
1801
+ const rl = readline.createInterface({
1802
+ input: fileStream,
1803
+ crlfDelay: Infinity
1804
+ });
1805
+ for await (const line of rl) {
1806
+ if (totalMatches >= safeLimit || isAborted())
1807
+ break;
1808
+ if (!line.trim())
1809
+ continue;
1810
+ let entry;
1811
+ try {
1812
+ entry = JSON.parse(line);
1813
+ }
1814
+ catch {
1815
+ continue;
1816
+ }
1817
+ if (entry.sessionId) {
1818
+ currentSessionId = entry.sessionId;
1819
+ }
1820
+ if (entry.type === 'summary' && entry.summary) {
1821
+ const sid = entry.sessionId || currentSessionId;
1822
+ if (sid) {
1823
+ sessionSummaries.set(sid, entry.summary);
1824
+ }
1825
+ else if (entry.leafUuid) {
1826
+ pendingSummaries.set(entry.leafUuid, entry.summary);
1827
+ }
1828
+ }
1829
+ // Apply pending summary via parentUuid
1830
+ if (entry.parentUuid && currentSessionId && !sessionSummaries.has(currentSessionId)) {
1831
+ const pending = pendingSummaries.get(entry.parentUuid);
1832
+ if (pending)
1833
+ sessionSummaries.set(currentSessionId, pending);
1834
+ }
1835
+ // Track last user/assistant message for fallback title
1836
+ if (entry.message?.content && currentSessionId && !entry.isApiErrorMessage) {
1837
+ const role = entry.message.role;
1838
+ if (role === 'user' || role === 'assistant') {
1839
+ const text = extractText(entry.message.content);
1840
+ if (text && !isSystemMessage(text)) {
1841
+ if (!sessionLastMessages.has(currentSessionId)) {
1842
+ sessionLastMessages.set(currentSessionId, {});
1843
+ }
1844
+ const msgs = sessionLastMessages.get(currentSessionId);
1845
+ if (role === 'user')
1846
+ msgs.user = text;
1847
+ else
1848
+ msgs.assistant = text;
1849
+ }
1850
+ }
1851
+ }
1852
+ if (!entry.message?.content)
1853
+ continue;
1854
+ if (entry.message.role !== 'user' && entry.message.role !== 'assistant')
1855
+ continue;
1856
+ if (entry.isApiErrorMessage)
1857
+ continue;
1858
+ const text = extractText(entry.message.content);
1859
+ if (!text || isSystemMessage(text))
1860
+ continue;
1861
+ const textLower = text.toLowerCase();
1862
+ if (!allWordsMatch(textLower))
1863
+ continue;
1864
+ const sessionId = entry.sessionId || currentSessionId || file.replace('.jsonl', '');
1865
+ if (!sessionMatches.has(sessionId)) {
1866
+ sessionMatches.set(sessionId, []);
1867
+ }
1868
+ const matches = sessionMatches.get(sessionId);
1869
+ if (matches.length < 2) {
1870
+ const { snippet, highlights } = buildSnippet(text, textLower);
1871
+ matches.push({
1872
+ role: entry.message.role,
1873
+ snippet,
1874
+ highlights,
1875
+ timestamp: entry.timestamp || null,
1876
+ provider: 'claude',
1877
+ messageUuid: entry.uuid || null
1878
+ });
1879
+ totalMatches++;
1880
+ }
1881
+ }
1882
+ }
1883
+ catch {
1884
+ continue;
1885
+ }
1886
+ for (const [sessionId, matches] of sessionMatches) {
1887
+ projectResult.sessions.push({
1888
+ sessionId,
1889
+ provider: 'claude',
1890
+ sessionSummary: sessionSummaries.get(sessionId) || (() => {
1891
+ const msgs = sessionLastMessages.get(sessionId);
1892
+ const lastMsg = msgs?.user || msgs?.assistant;
1893
+ return lastMsg ? (lastMsg.length > 50 ? lastMsg.substring(0, 50) + '...' : lastMsg) : 'New Session';
1894
+ })(),
1895
+ matches
1896
+ });
1897
+ }
1898
+ }
1899
+ // Search Codex sessions for this project
1900
+ try {
1901
+ const actualProjectDir = await extractProjectDirectory(projectName);
1902
+ if (actualProjectDir && !isAborted() && totalMatches < safeLimit) {
1903
+ await searchCodexSessionsForProject(actualProjectDir, projectResult, words, allWordsMatch, extractText, isSystemMessage, buildSnippet, safeLimit, () => totalMatches, (n) => { totalMatches += n; }, isAborted);
1904
+ }
1905
+ }
1906
+ catch {
1907
+ // Skip codex search errors
1908
+ }
1909
+ // Search Gemini sessions for this project
1910
+ try {
1911
+ const actualProjectDir = await extractProjectDirectory(projectName);
1912
+ if (actualProjectDir && !isAborted() && totalMatches < safeLimit) {
1913
+ await searchGeminiSessionsForProject(actualProjectDir, projectResult, words, allWordsMatch, buildSnippet, safeLimit, () => totalMatches, (n) => { totalMatches += n; });
1914
+ }
1915
+ }
1916
+ catch {
1917
+ // Skip gemini search errors
1918
+ }
1919
+ scannedProjects++;
1920
+ if (projectResult.sessions.length > 0) {
1921
+ results.push(projectResult);
1922
+ if (onProjectResult) {
1923
+ onProjectResult({ projectResult, totalMatches, scannedProjects, totalProjects });
1924
+ }
1925
+ }
1926
+ else if (onProjectResult && scannedProjects % 10 === 0) {
1927
+ onProjectResult({ projectResult: null, totalMatches, scannedProjects, totalProjects });
1928
+ }
1929
+ }
1930
+ }
1931
+ catch {
1932
+ // claudeDir doesn't exist
1933
+ }
1934
+ return { results, totalMatches, query: safeQuery };
1935
+ }
1936
+ async function searchCodexSessionsForProject(projectPath, projectResult, words, allWordsMatch, extractText, isSystemMessage, buildSnippet, limit, getTotalMatches, addMatches, isAborted) {
1937
+ const normalizedProjectPath = normalizeComparablePath(projectPath);
1938
+ if (!normalizedProjectPath)
1939
+ return;
1940
+ const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
1941
+ try {
1942
+ await fs.access(codexSessionsDir);
1943
+ }
1944
+ catch {
1945
+ return;
1946
+ }
1947
+ const jsonlFiles = await findCodexJsonlFiles(codexSessionsDir);
1948
+ for (const filePath of jsonlFiles) {
1949
+ if (getTotalMatches() >= limit || isAborted())
1950
+ break;
1951
+ try {
1952
+ const fileStream = fsSync.createReadStream(filePath);
1953
+ const rl = readline.createInterface({ input: fileStream, crlfDelay: Infinity });
1954
+ // First pass: read session_meta to check project path match
1955
+ let sessionMeta = null;
1956
+ for await (const line of rl) {
1957
+ if (!line.trim())
1958
+ continue;
1959
+ try {
1960
+ const entry = JSON.parse(line);
1961
+ if (entry.type === 'session_meta' && entry.payload) {
1962
+ sessionMeta = entry.payload;
1963
+ break;
1964
+ }
1965
+ }
1966
+ catch {
1967
+ continue;
1968
+ }
1969
+ }
1970
+ // Skip sessions that don't belong to this project
1971
+ if (!sessionMeta)
1972
+ continue;
1973
+ const sessionProjectPath = normalizeComparablePath(sessionMeta.cwd);
1974
+ if (sessionProjectPath !== normalizedProjectPath)
1975
+ continue;
1976
+ // Second pass: re-read file to find matching messages
1977
+ const fileStream2 = fsSync.createReadStream(filePath);
1978
+ const rl2 = readline.createInterface({ input: fileStream2, crlfDelay: Infinity });
1979
+ let lastUserMessage = null;
1980
+ const matches = [];
1981
+ for await (const line of rl2) {
1982
+ if (getTotalMatches() >= limit || isAborted())
1983
+ break;
1984
+ if (!line.trim())
1985
+ continue;
1986
+ let entry;
1987
+ try {
1988
+ entry = JSON.parse(line);
1989
+ }
1990
+ catch {
1991
+ continue;
1992
+ }
1993
+ let text = null;
1994
+ let role = null;
1995
+ if (entry.type === 'event_msg' && entry.payload?.type === 'user_message' && entry.payload.message) {
1996
+ text = entry.payload.message;
1997
+ role = 'user';
1998
+ lastUserMessage = text;
1999
+ }
2000
+ else if (entry.type === 'response_item' && entry.payload?.type === 'message') {
2001
+ const contentParts = entry.payload.content || [];
2002
+ if (entry.payload.role === 'user') {
2003
+ text = contentParts
2004
+ .filter(p => p.type === 'input_text' && p.text)
2005
+ .map(p => p.text)
2006
+ .join(' ');
2007
+ role = 'user';
2008
+ if (text)
2009
+ lastUserMessage = text;
2010
+ }
2011
+ else if (entry.payload.role === 'assistant') {
2012
+ text = contentParts
2013
+ .filter(p => p.type === 'output_text' && p.text)
2014
+ .map(p => p.text)
2015
+ .join(' ');
2016
+ role = 'assistant';
2017
+ }
2018
+ }
2019
+ if (!text || !role)
2020
+ continue;
2021
+ const textLower = text.toLowerCase();
2022
+ if (!allWordsMatch(textLower))
2023
+ continue;
2024
+ if (matches.length < 2) {
2025
+ const { snippet, highlights } = buildSnippet(text, textLower);
2026
+ matches.push({ role, snippet, highlights, timestamp: entry.timestamp || null, provider: 'codex' });
2027
+ addMatches(1);
2028
+ }
2029
+ }
2030
+ if (matches.length > 0) {
2031
+ projectResult.sessions.push({
2032
+ sessionId: sessionMeta.id,
2033
+ provider: 'codex',
2034
+ sessionSummary: lastUserMessage
2035
+ ? (lastUserMessage.length > 50 ? lastUserMessage.substring(0, 50) + '...' : lastUserMessage)
2036
+ : 'Codex Session',
2037
+ matches
2038
+ });
2039
+ }
2040
+ }
2041
+ catch {
2042
+ continue;
2043
+ }
2044
+ }
2045
+ }
2046
+ async function searchGeminiSessionsForProject(projectPath, projectResult, words, allWordsMatch, buildSnippet, limit, getTotalMatches, addMatches) {
2047
+ // 1) Search in-memory sessions (created via UI)
2048
+ for (const [sessionId, session] of sessionManager.sessions) {
2049
+ if (getTotalMatches() >= limit)
2050
+ break;
2051
+ if (session.projectPath !== projectPath)
2052
+ continue;
2053
+ const matches = [];
2054
+ for (const msg of session.messages) {
2055
+ if (getTotalMatches() >= limit)
2056
+ break;
2057
+ if (msg.role !== 'user' && msg.role !== 'assistant')
2058
+ continue;
2059
+ const text = typeof msg.content === 'string' ? msg.content
2060
+ : Array.isArray(msg.content) ? msg.content.filter(p => p.type === 'text').map(p => p.text).join(' ')
2061
+ : '';
2062
+ if (!text)
2063
+ continue;
2064
+ const textLower = text.toLowerCase();
2065
+ if (!allWordsMatch(textLower))
2066
+ continue;
2067
+ if (matches.length < 2) {
2068
+ const { snippet, highlights } = buildSnippet(text, textLower);
2069
+ matches.push({
2070
+ role: msg.role, snippet, highlights,
2071
+ timestamp: msg.timestamp ? msg.timestamp.toISOString() : null,
2072
+ provider: 'gemini'
2073
+ });
2074
+ addMatches(1);
2075
+ }
2076
+ }
2077
+ if (matches.length > 0) {
2078
+ const firstUserMsg = session.messages.find(m => m.role === 'user');
2079
+ const summary = firstUserMsg?.content
2080
+ ? (typeof firstUserMsg.content === 'string'
2081
+ ? (firstUserMsg.content.length > 50 ? firstUserMsg.content.substring(0, 50) + '...' : firstUserMsg.content)
2082
+ : 'Gemini Session')
2083
+ : 'Gemini Session';
2084
+ projectResult.sessions.push({
2085
+ sessionId,
2086
+ provider: 'gemini',
2087
+ sessionSummary: summary,
2088
+ matches
2089
+ });
2090
+ }
2091
+ }
2092
+ // 2) Search Gemini CLI sessions on disk (~/.gemini/tmp/<project>/chats/*.json)
2093
+ const normalizedProjectPath = normalizeComparablePath(projectPath);
2094
+ if (!normalizedProjectPath)
2095
+ return;
2096
+ const geminiTmpDir = path.join(os.homedir(), '.gemini', 'tmp');
2097
+ try {
2098
+ await fs.access(geminiTmpDir);
2099
+ }
2100
+ catch {
2101
+ return;
2102
+ }
2103
+ const trackedSessionIds = new Set();
2104
+ for (const [sid] of sessionManager.sessions) {
2105
+ trackedSessionIds.add(sid);
2106
+ }
2107
+ let projectDirs;
2108
+ try {
2109
+ projectDirs = await fs.readdir(geminiTmpDir);
2110
+ }
2111
+ catch {
2112
+ return;
2113
+ }
2114
+ for (const projectDir of projectDirs) {
2115
+ if (getTotalMatches() >= limit)
2116
+ break;
2117
+ const projectRootFile = path.join(geminiTmpDir, projectDir, '.project_root');
2118
+ let projectRoot;
2119
+ try {
2120
+ projectRoot = (await fs.readFile(projectRootFile, 'utf8')).trim();
2121
+ }
2122
+ catch {
2123
+ continue;
2124
+ }
2125
+ if (normalizeComparablePath(projectRoot) !== normalizedProjectPath)
2126
+ continue;
2127
+ const chatsDir = path.join(geminiTmpDir, projectDir, 'chats');
2128
+ let chatFiles;
2129
+ try {
2130
+ chatFiles = await fs.readdir(chatsDir);
2131
+ }
2132
+ catch {
2133
+ continue;
2134
+ }
2135
+ for (const chatFile of chatFiles) {
2136
+ if (getTotalMatches() >= limit)
2137
+ break;
2138
+ if (!chatFile.endsWith('.json'))
2139
+ continue;
2140
+ try {
2141
+ const filePath = path.join(chatsDir, chatFile);
2142
+ const data = await fs.readFile(filePath, 'utf8');
2143
+ const session = JSON.parse(data);
2144
+ if (!session.messages || !Array.isArray(session.messages))
2145
+ continue;
2146
+ const cliSessionId = session.sessionId || chatFile.replace('.json', '');
2147
+ if (trackedSessionIds.has(cliSessionId))
2148
+ continue;
2149
+ const matches = [];
2150
+ let firstUserText = null;
2151
+ for (const msg of session.messages) {
2152
+ if (getTotalMatches() >= limit)
2153
+ break;
2154
+ const role = msg.type === 'user' ? 'user'
2155
+ : (msg.type === 'gemini' || msg.type === 'assistant') ? 'assistant'
2156
+ : null;
2157
+ if (!role)
2158
+ continue;
2159
+ let text = '';
2160
+ if (typeof msg.content === 'string') {
2161
+ text = msg.content;
2162
+ }
2163
+ else if (Array.isArray(msg.content)) {
2164
+ text = msg.content
2165
+ .filter(p => p.text)
2166
+ .map(p => p.text)
2167
+ .join(' ');
2168
+ }
2169
+ if (!text)
2170
+ continue;
2171
+ if (role === 'user' && !firstUserText)
2172
+ firstUserText = text;
2173
+ const textLower = text.toLowerCase();
2174
+ if (!allWordsMatch(textLower))
2175
+ continue;
2176
+ if (matches.length < 2) {
2177
+ const { snippet, highlights } = buildSnippet(text, textLower);
2178
+ matches.push({
2179
+ role, snippet, highlights,
2180
+ timestamp: msg.timestamp || null,
2181
+ provider: 'gemini'
2182
+ });
2183
+ addMatches(1);
2184
+ }
2185
+ }
2186
+ if (matches.length > 0) {
2187
+ const summary = firstUserText
2188
+ ? (firstUserText.length > 50 ? firstUserText.substring(0, 50) + '...' : firstUserText)
2189
+ : 'Gemini CLI Session';
2190
+ projectResult.sessions.push({
2191
+ sessionId: cliSessionId,
2192
+ provider: 'gemini',
2193
+ sessionSummary: summary,
2194
+ matches
2195
+ });
2196
+ }
2197
+ }
2198
+ catch {
2199
+ continue;
2200
+ }
2201
+ }
2202
+ }
2203
+ }
2204
+ async function getGeminiCliSessions(projectPath) {
2205
+ const normalizedProjectPath = normalizeComparablePath(projectPath);
2206
+ if (!normalizedProjectPath)
2207
+ return [];
2208
+ const geminiTmpDir = path.join(os.homedir(), '.gemini', 'tmp');
2209
+ try {
2210
+ await fs.access(geminiTmpDir);
2211
+ }
2212
+ catch {
2213
+ return [];
2214
+ }
2215
+ const sessions = [];
2216
+ let projectDirs;
2217
+ try {
2218
+ projectDirs = await fs.readdir(geminiTmpDir);
2219
+ }
2220
+ catch {
2221
+ return [];
2222
+ }
2223
+ for (const projectDir of projectDirs) {
2224
+ const projectRootFile = path.join(geminiTmpDir, projectDir, '.project_root');
2225
+ let projectRoot;
2226
+ try {
2227
+ projectRoot = (await fs.readFile(projectRootFile, 'utf8')).trim();
2228
+ }
2229
+ catch {
2230
+ continue;
2231
+ }
2232
+ if (normalizeComparablePath(projectRoot) !== normalizedProjectPath)
2233
+ continue;
2234
+ const chatsDir = path.join(geminiTmpDir, projectDir, 'chats');
2235
+ let chatFiles;
2236
+ try {
2237
+ chatFiles = await fs.readdir(chatsDir);
2238
+ }
2239
+ catch {
2240
+ continue;
2241
+ }
2242
+ for (const chatFile of chatFiles) {
2243
+ if (!chatFile.endsWith('.json'))
2244
+ continue;
2245
+ try {
2246
+ const filePath = path.join(chatsDir, chatFile);
2247
+ const data = await fs.readFile(filePath, 'utf8');
2248
+ const session = JSON.parse(data);
2249
+ if (!session.messages || !Array.isArray(session.messages))
2250
+ continue;
2251
+ const sessionId = session.sessionId || chatFile.replace('.json', '');
2252
+ const firstUserMsg = session.messages.find(m => m.type === 'user');
2253
+ let summary = 'Gemini CLI Session';
2254
+ if (firstUserMsg) {
2255
+ const text = Array.isArray(firstUserMsg.content)
2256
+ ? firstUserMsg.content.filter(p => p.text).map(p => p.text).join(' ')
2257
+ : (typeof firstUserMsg.content === 'string' ? firstUserMsg.content : '');
2258
+ if (text) {
2259
+ summary = text.length > 50 ? text.substring(0, 50) + '...' : text;
2260
+ }
2261
+ }
2262
+ sessions.push({
2263
+ id: sessionId,
2264
+ summary,
2265
+ messageCount: session.messages.length,
2266
+ lastActivity: session.lastUpdated || session.startTime || null,
2267
+ provider: 'gemini'
2268
+ });
2269
+ }
2270
+ catch {
2271
+ continue;
2272
+ }
2273
+ }
2274
+ }
2275
+ return sessions.sort((a, b) => new Date(b.lastActivity || 0) - new Date(a.lastActivity || 0));
2276
+ }
2277
+ async function getGeminiCliSessionMessages(sessionId) {
2278
+ const geminiTmpDir = path.join(os.homedir(), '.gemini', 'tmp');
2279
+ let projectDirs;
2280
+ try {
2281
+ projectDirs = await fs.readdir(geminiTmpDir);
2282
+ }
2283
+ catch {
2284
+ return [];
2285
+ }
2286
+ for (const projectDir of projectDirs) {
2287
+ const chatsDir = path.join(geminiTmpDir, projectDir, 'chats');
2288
+ let chatFiles;
2289
+ try {
2290
+ chatFiles = await fs.readdir(chatsDir);
2291
+ }
2292
+ catch {
2293
+ continue;
2294
+ }
2295
+ for (const chatFile of chatFiles) {
2296
+ if (!chatFile.endsWith('.json'))
2297
+ continue;
2298
+ try {
2299
+ const filePath = path.join(chatsDir, chatFile);
2300
+ const data = await fs.readFile(filePath, 'utf8');
2301
+ const session = JSON.parse(data);
2302
+ const fileSessionId = session.sessionId || chatFile.replace('.json', '');
2303
+ if (fileSessionId !== sessionId)
2304
+ continue;
2305
+ return (session.messages || []).map(msg => {
2306
+ const role = msg.type === 'user' ? 'user'
2307
+ : (msg.type === 'gemini' || msg.type === 'assistant') ? 'assistant'
2308
+ : msg.type;
2309
+ let content = '';
2310
+ if (typeof msg.content === 'string') {
2311
+ content = msg.content;
2312
+ }
2313
+ else if (Array.isArray(msg.content)) {
2314
+ content = msg.content.filter(p => p.text).map(p => p.text).join('\n');
2315
+ }
2316
+ return {
2317
+ type: 'message',
2318
+ message: { role, content },
2319
+ timestamp: msg.timestamp || null
2320
+ };
2321
+ });
2322
+ }
2323
+ catch {
2324
+ continue;
2325
+ }
2326
+ }
2327
+ }
2328
+ return [];
2329
+ }
2330
+ export { getProjects, getSessions, getSessionMessages, parseJsonlSessions, renameProject, deleteSession, isProjectEmpty, deleteProject, addProjectManually, loadProjectConfig, saveProjectConfig, extractProjectDirectory, clearProjectDirectoryCache, getCodexSessions, getCodexSessionMessages, deleteCodexSession, getGeminiCliSessions, getGeminiCliSessionMessages, searchConversations };
2331
+ //# sourceMappingURL=projects.js.map