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