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