notioncode 0.1.0 → 0.1.2

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