@cloudcli-ai/cloudcli 1.28.0

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