upfynai-code 0.1.0 → 2.2.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 (340) hide show
  1. package/client/dist/api-docs.html +879 -0
  2. package/client/dist/assets/AppContent-CTSHQdyq.js +513 -0
  3. package/client/dist/assets/CanvasPanel-Cig0Mo9s.js +6 -0
  4. package/client/dist/assets/CanvasPanel-q4HEqNtV.css +1 -0
  5. package/client/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  6. package/client/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  7. package/client/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  8. package/client/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  9. package/client/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  10. package/client/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  11. package/client/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  12. package/client/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  13. package/client/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  14. package/client/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  15. package/client/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  16. package/client/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  17. package/client/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  18. package/client/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  19. package/client/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  20. package/client/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  21. package/client/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  22. package/client/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  23. package/client/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  24. package/client/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  25. package/client/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  26. package/client/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  27. package/client/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  28. package/client/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  29. package/client/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  30. package/client/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  31. package/client/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  32. package/client/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  33. package/client/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  34. package/client/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  35. package/client/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  36. package/client/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  37. package/client/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  38. package/client/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  39. package/client/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  40. package/client/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  41. package/client/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  42. package/client/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  43. package/client/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  44. package/client/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  45. package/client/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  46. package/client/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  47. package/client/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  48. package/client/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  49. package/client/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  50. package/client/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  51. package/client/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  52. package/client/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  53. package/client/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  54. package/client/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  55. package/client/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  56. package/client/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  57. package/client/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  58. package/client/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  59. package/client/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  60. package/client/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  61. package/client/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  62. package/client/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  63. package/client/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  64. package/client/dist/assets/LoginModal-silya-zP.js +11 -0
  65. package/client/dist/assets/MarkdownPreview-B3c7OEj6.js +1 -0
  66. package/client/dist/assets/Onboarding-Coxo6mFA.js +1 -0
  67. package/client/dist/assets/SetupForm-BzYOsbji.js +1 -0
  68. package/client/dist/assets/Tableau10-B-NsZVaP.js +1 -0
  69. package/client/dist/assets/_commonjs-dynamic-modules-TDtrdbi3.js +1 -0
  70. package/client/dist/assets/ar-SA-G6X2FPQ2-Bmw2-hDt.js +10 -0
  71. package/client/dist/assets/arc-BMqY7_Ci.js +1 -0
  72. package/client/dist/assets/array-BKyUJesY.js +1 -0
  73. package/client/dist/assets/az-AZ-76LH7QW2-Dh1le_qs.js +1 -0
  74. package/client/dist/assets/bg-BG-XCXSNQG7-Cbav8Z9z.js +5 -0
  75. package/client/dist/assets/blockDiagram-38ab4fdb-ChHJxsXw.js +118 -0
  76. package/client/dist/assets/bn-BD-2XOGV67Q-DCNjOaWz.js +5 -0
  77. package/client/dist/assets/c4Diagram-3d4e48cf-b8Xue4Z6.js +10 -0
  78. package/client/dist/assets/ca-ES-6MX7JW3Y-Dl_vM7NS.js +8 -0
  79. package/client/dist/assets/channel-CSnvHe_M.js +1 -0
  80. package/client/dist/assets/classDiagram-70f12bd4-BheP7Ggo.js +2 -0
  81. package/client/dist/assets/classDiagram-v2-f2320105-xtym7GEZ.js +2 -0
  82. package/client/dist/assets/clone-B75abXxS.js +1 -0
  83. package/client/dist/assets/createText-2e5e7dd3-_n4jI_fO.js +5 -0
  84. package/client/dist/assets/cs-CZ-2BRQDIVT-ftsKDdz4.js +11 -0
  85. package/client/dist/assets/da-DK-5WZEPLOC-DAjdwGRO.js +5 -0
  86. package/client/dist/assets/de-DE-XR44H4JA-BJXczHGT.js +8 -0
  87. package/client/dist/assets/directory-open-01563666-DWU9wJ6I.js +1 -0
  88. package/client/dist/assets/directory-open-4ed118d0-CunoC1EB.js +1 -0
  89. package/client/dist/assets/edges-e0da2a9e-CfPZr4YM.js +4 -0
  90. package/client/dist/assets/el-GR-BZB4AONW-DW2p_uy7.js +10 -0
  91. package/client/dist/assets/erDiagram-9861fffd-CF33V-Of.js +51 -0
  92. package/client/dist/assets/es-ES-U4NZUMDT-DLOIGnrl.js +9 -0
  93. package/client/dist/assets/eu-ES-A7QVB2H4-LJXbf89m.js +11 -0
  94. package/client/dist/assets/fa-IR-HGAKTJCU-Dvx65fgW.js +8 -0
  95. package/client/dist/assets/fi-FI-Z5N7JZ37-EoL65BQh.js +6 -0
  96. package/client/dist/assets/file-open-002ab408-DIuFHtCF.js +1 -0
  97. package/client/dist/assets/file-open-7c801643-684qeFg4.js +1 -0
  98. package/client/dist/assets/file-save-3189631c-C1wFhQhH.js +1 -0
  99. package/client/dist/assets/file-save-745eba88-Bb9F9Kg7.js +1 -0
  100. package/client/dist/assets/flowDb-956e92f1-HgoXVy2H.js +10 -0
  101. package/client/dist/assets/flowDiagram-66a62f08-tffoET0H.js +4 -0
  102. package/client/dist/assets/flowDiagram-v2-96b9c2cf-Byc3JCHh.js +1 -0
  103. package/client/dist/assets/flowchart-elk-definition-4a651766-DJbI2dpv.js +139 -0
  104. package/client/dist/assets/fr-FR-RHASNOE6-DNk_jdDs.js +9 -0
  105. package/client/dist/assets/ganttDiagram-c361ad54-2XX670FU.js +257 -0
  106. package/client/dist/assets/gitGraphDiagram-72cf32ee-CcUfruAo.js +70 -0
  107. package/client/dist/assets/gl-ES-HMX3MZ6V-dxzFjZlG.js +10 -0
  108. package/client/dist/assets/graph-BSbiMSBC.js +1 -0
  109. package/client/dist/assets/he-IL-6SHJWFNN-Cogsfdt1.js +10 -0
  110. package/client/dist/assets/hi-IN-IWLTKZ5I-L6wbgi4F.js +4 -0
  111. package/client/dist/assets/hu-HU-A5ZG7DT2-DSA6ZDsH.js +7 -0
  112. package/client/dist/assets/id-ID-SAP4L64H-BK_vGGS6.js +10 -0
  113. package/client/dist/assets/image-blob-reduce.esm-BLtmMM_J.js +2 -0
  114. package/client/dist/assets/index-3862675e-Bv32HUgT.js +1 -0
  115. package/client/dist/assets/index-B8wwD_Xo.css +1 -0
  116. package/client/dist/assets/index-BPwf8Fw3.js +27 -0
  117. package/client/dist/assets/index-D1urGMYu.js +95 -0
  118. package/client/dist/assets/infoDiagram-f8f76790-w4mR4pxn.js +7 -0
  119. package/client/dist/assets/init-Gi6I4Gst.js +1 -0
  120. package/client/dist/assets/it-IT-JPQ66NNP-BLdHYMhn.js +11 -0
  121. package/client/dist/assets/ja-JP-DBVTYXUO-B_vmexl_.js +8 -0
  122. package/client/dist/assets/journeyDiagram-49397b02-D9nmO17e.js +139 -0
  123. package/client/dist/assets/kaa-6HZHGXH3-5s-3jl6F.js +1 -0
  124. package/client/dist/assets/kab-KAB-ZGHBKWFO-2QaVDuSf.js +8 -0
  125. package/client/dist/assets/kk-KZ-P5N5QNE5-CTC52Vbi.js +1 -0
  126. package/client/dist/assets/km-KH-HSX4SM5Z-DxawH8UZ.js +11 -0
  127. package/client/dist/assets/ko-KR-MTYHY66A-CmosEM8_.js +9 -0
  128. package/client/dist/assets/ku-TR-6OUDTVRD-DbiLen4y.js +9 -0
  129. package/client/dist/assets/layout-jmt3H9tA.js +1 -0
  130. package/client/dist/assets/line-JTlRayUJ.js +1 -0
  131. package/client/dist/assets/linear-DJeB5p7x.js +1 -0
  132. package/client/dist/assets/lt-LT-XHIRWOB4-CH15wrjA.js +3 -0
  133. package/client/dist/assets/lv-LV-5QDEKY6T-dhgfPuCQ.js +7 -0
  134. package/client/dist/assets/mindmap-definition-fc14e90a-BOOrexmz.js +415 -0
  135. package/client/dist/assets/mr-IN-CRQNXWMA-3Gi6iq7A.js +13 -0
  136. package/client/dist/assets/my-MM-5M5IBNSE-CpH4rdJj.js +1 -0
  137. package/client/dist/assets/nb-NO-T6EIAALU-Du6iiGql.js +10 -0
  138. package/client/dist/assets/nl-NL-IS3SIHDZ-BGvsd1MT.js +8 -0
  139. package/client/dist/assets/nn-NO-6E72VCQL-B-odvJZW.js +8 -0
  140. package/client/dist/assets/oc-FR-POXYY2M6-COC8xNjo.js +8 -0
  141. package/client/dist/assets/ordinal-Cboi1Yqb.js +1 -0
  142. package/client/dist/assets/pa-IN-N4M65BXN-CE21PUQH.js +4 -0
  143. package/client/dist/assets/path-CbwjOpE9.js +1 -0
  144. package/client/dist/assets/pdf-TYrZqVzP.js +12 -0
  145. package/client/dist/assets/pdf.worker-BA9kU3Pw.mjs +61080 -0
  146. package/client/dist/assets/percentages-BXMCSKIN-C9GT0OD3.js +199 -0
  147. package/client/dist/assets/pica-VkdyTzi8.js +2 -0
  148. package/client/dist/assets/pieDiagram-8a3498a8-Cvfh7Qr5.js +35 -0
  149. package/client/dist/assets/pl-PL-T2D74RX3-D4xFVSoT.js +9 -0
  150. package/client/dist/assets/pt-BR-5N22H2LF-CCq257gA.js +9 -0
  151. package/client/dist/assets/pt-PT-UZXXM6DQ-1l8gt5vA.js +9 -0
  152. package/client/dist/assets/quadrantDiagram-120e2f19-BA0js1aD.js +7 -0
  153. package/client/dist/assets/requirementDiagram-deff3bca-B0QNFfIn.js +52 -0
  154. package/client/dist/assets/ro-RO-JPDTUUEW-yosBW01E.js +11 -0
  155. package/client/dist/assets/roundRect-mAH3dD0p.js +1 -0
  156. package/client/dist/assets/ru-RU-B4JR7IUQ-8LkEJUix.js +9 -0
  157. package/client/dist/assets/sankeyDiagram-04a897e0-D4T9eCXn.js +8 -0
  158. package/client/dist/assets/sequenceDiagram-704730f1-CfBUTCrO.js +122 -0
  159. package/client/dist/assets/si-LK-N5RQ5JYF-D8rjbqtd.js +1 -0
  160. package/client/dist/assets/sk-SK-C5VTKIMK-Bg14sAzN.js +6 -0
  161. package/client/dist/assets/sl-SI-NN7IZMDC-CMTib6Zs.js +6 -0
  162. package/client/dist/assets/stateDiagram-587899a1-BGgvmVSZ.js +1 -0
  163. package/client/dist/assets/stateDiagram-v2-d93cdb3a-Qn3DpYuO.js +1 -0
  164. package/client/dist/assets/styles-6aaf32cf-IdVZLPrD.js +207 -0
  165. package/client/dist/assets/styles-9a916d00-BAC3L45X.js +160 -0
  166. package/client/dist/assets/styles-c10674c1-COhXxX8c.js +116 -0
  167. package/client/dist/assets/subset-shared.chunk-BWHnFai4.js +22 -0
  168. package/client/dist/assets/subset-worker.chunk-C8QUSruZ.js +1 -0
  169. package/client/dist/assets/sv-SE-XGPEYMSR-C1425rOF.js +10 -0
  170. package/client/dist/assets/svgDrawCommon-08f97a94-Cfk-fgnN.js +1 -0
  171. package/client/dist/assets/ta-IN-2NMHFXQM-BHHo1zpF.js +9 -0
  172. package/client/dist/assets/th-TH-HPSO5L25-CZVzm_WT.js +2 -0
  173. package/client/dist/assets/timeline-definition-85554ec2-VAvuJith.js +61 -0
  174. package/client/dist/assets/tr-TR-DEFEU3FU-DE1lclCq.js +7 -0
  175. package/client/dist/assets/uk-UA-QMV73CPH-D4lJZ85O.js +6 -0
  176. package/client/dist/assets/vendor-codemirror-BARtJV1V.js +16 -0
  177. package/client/dist/assets/vendor-codemirror-langs-52_y1wip.js +20 -0
  178. package/client/dist/assets/vendor-i18n-ByAl-gdx.js +1 -0
  179. package/client/dist/assets/vendor-icons-D33IkSIf.js +1 -0
  180. package/client/dist/assets/vendor-markdown-CIVH08vJ.js +298 -0
  181. package/client/dist/assets/vendor-react-CHoMc7ka.js +8 -0
  182. package/client/dist/assets/vendor-syntax-Djb62v3a.js +9 -0
  183. package/client/dist/assets/vendor-xterm-DBb3RXlu.js +66 -0
  184. package/client/dist/assets/vendor-xterm-DrlLKa8f.css +1 -0
  185. package/client/dist/assets/vi-VN-M7AON7JQ-Dgc_SShk.js +5 -0
  186. package/client/dist/assets/xychartDiagram-e933f94c-BeyVBJhb.js +7 -0
  187. package/client/dist/assets/zh-CN-LNUGB5OW-MH4Yh8in.js +10 -0
  188. package/client/dist/assets/zh-HK-E62DVLB3-D4XHehjx.js +1 -0
  189. package/client/dist/assets/zh-TW-RAJ6MFWO--efj3evj.js +9 -0
  190. package/client/dist/clear-cache.html +85 -0
  191. package/client/dist/convert-icons.md +53 -0
  192. package/client/dist/favicon.png +0 -0
  193. package/client/dist/favicon.svg +9 -0
  194. package/client/dist/generate-icons.js +49 -0
  195. package/client/dist/icons/claude-ai-icon.svg +1 -0
  196. package/client/dist/icons/codex-white.svg +3 -0
  197. package/client/dist/icons/codex.svg +3 -0
  198. package/client/dist/icons/cursor-white.svg +12 -0
  199. package/client/dist/icons/cursor.svg +1 -0
  200. package/client/dist/icons/icon-128x128.png +0 -0
  201. package/client/dist/icons/icon-128x128.svg +12 -0
  202. package/client/dist/icons/icon-144x144.png +0 -0
  203. package/client/dist/icons/icon-144x144.svg +12 -0
  204. package/client/dist/icons/icon-152x152.png +0 -0
  205. package/client/dist/icons/icon-152x152.svg +12 -0
  206. package/client/dist/icons/icon-192x192.png +0 -0
  207. package/client/dist/icons/icon-192x192.svg +12 -0
  208. package/client/dist/icons/icon-384x384.png +0 -0
  209. package/client/dist/icons/icon-384x384.svg +12 -0
  210. package/client/dist/icons/icon-512x512.png +0 -0
  211. package/client/dist/icons/icon-512x512.svg +12 -0
  212. package/client/dist/icons/icon-72x72.png +0 -0
  213. package/client/dist/icons/icon-72x72.svg +12 -0
  214. package/client/dist/icons/icon-96x96.png +0 -0
  215. package/client/dist/icons/icon-96x96.svg +12 -0
  216. package/client/dist/icons/icon-template.svg +12 -0
  217. package/client/dist/index.html +128 -0
  218. package/client/dist/logo-128.png +0 -0
  219. package/client/dist/logo-256.png +0 -0
  220. package/client/dist/logo-32.png +0 -0
  221. package/client/dist/logo-512.png +0 -0
  222. package/client/dist/logo-64.png +0 -0
  223. package/client/dist/logo.svg +17 -0
  224. package/client/dist/manifest.json +61 -0
  225. package/client/dist/mcp-docs.html +119 -0
  226. package/client/dist/screenshots/cli-selection.png +0 -0
  227. package/client/dist/screenshots/desktop-main.png +0 -0
  228. package/client/dist/screenshots/mobile-chat.png +0 -0
  229. package/client/dist/screenshots/tools-modal.png +0 -0
  230. package/client/dist/sw.js +19 -0
  231. package/commands/upfynai-connect.md +46 -0
  232. package/commands/upfynai-disconnect.md +31 -0
  233. package/commands/upfynai-doctor.md +99 -0
  234. package/commands/upfynai-export.md +49 -0
  235. package/commands/upfynai-local.md +82 -0
  236. package/commands/upfynai-status.md +75 -0
  237. package/commands/upfynai-stop.md +49 -0
  238. package/commands/upfynai-uninstall.md +58 -0
  239. package/commands/upfynai.md +50 -0
  240. package/package.json +106 -47
  241. package/scripts/build-client.js +17 -0
  242. package/scripts/fix-node-pty.js +67 -0
  243. package/scripts/install-commands.js +78 -0
  244. package/server/claude-sdk.js +714 -0
  245. package/server/cli.js +419 -0
  246. package/server/constants/config.js +5 -0
  247. package/server/cursor-cli.js +270 -0
  248. package/server/database/auth.db +0 -0
  249. package/server/database/db.js +606 -0
  250. package/server/database/init.sql +70 -0
  251. package/server/index.js +2269 -0
  252. package/server/load-env.js +26 -0
  253. package/server/mcp-server.js +620 -0
  254. package/server/middleware/auth.js +158 -0
  255. package/server/openai-codex.js +403 -0
  256. package/server/projects.js +1849 -0
  257. package/server/relay-client.js +314 -0
  258. package/server/routes/agent.js +1231 -0
  259. package/server/routes/auth.js +220 -0
  260. package/server/routes/cli-auth.js +263 -0
  261. package/server/routes/codex.js +344 -0
  262. package/server/routes/commands.js +601 -0
  263. package/server/routes/cursor.js +808 -0
  264. package/server/routes/git.js +1165 -0
  265. package/server/routes/mcp-utils.js +48 -0
  266. package/server/routes/mcp.js +552 -0
  267. package/server/routes/payments.js +172 -0
  268. package/server/routes/projects.js +549 -0
  269. package/server/routes/settings.js +178 -0
  270. package/server/routes/taskmaster.js +1964 -0
  271. package/server/routes/user.js +106 -0
  272. package/server/utils/commandParser.js +303 -0
  273. package/server/utils/gitConfig.js +24 -0
  274. package/server/utils/mcp-detector.js +198 -0
  275. package/server/utils/taskmaster-websocket.js +129 -0
  276. package/shared/modelConstants.js +67 -0
  277. package/LICENSE +0 -22
  278. package/bin/cli.js +0 -86
  279. package/dist/assets/CanvasPanel-B48gAKVY.js +0 -538
  280. package/dist/assets/CanvasPanel-B48gAKVY.js.map +0 -1
  281. package/dist/assets/CanvasPanel-BsOG3EVs.css +0 -1
  282. package/dist/assets/index-CEhTwG68.css +0 -1
  283. package/dist/assets/index-GqAGWpJI.js +0 -70
  284. package/dist/assets/index-GqAGWpJI.js.map +0 -1
  285. package/dist/index.html +0 -18
  286. package/index.html +0 -17
  287. package/src/App.tsx +0 -226
  288. package/src/components/canvas/CanvasPanel.tsx +0 -62
  289. package/src/components/canvas/layout/graph-builder.ts +0 -136
  290. package/src/components/canvas/shapes/CompactionNodeShape.tsx +0 -76
  291. package/src/components/canvas/shapes/SessionNodeShape.tsx +0 -93
  292. package/src/components/canvas/shapes/StatuslineWidgetShape.tsx +0 -125
  293. package/src/components/canvas/shapes/TextResponseNodeShape.tsx +0 -86
  294. package/src/components/canvas/shapes/ToolCallNodeShape.tsx +0 -107
  295. package/src/components/canvas/shapes/ToolResultNodeShape.tsx +0 -87
  296. package/src/components/canvas/shapes/shared-styles.ts +0 -35
  297. package/src/components/chat/ChatPanel.tsx +0 -96
  298. package/src/components/chat/InputBar.tsx +0 -81
  299. package/src/components/chat/MessageList.tsx +0 -130
  300. package/src/components/chat/PermissionDialog.tsx +0 -70
  301. package/src/components/layout/FolderSelector.tsx +0 -152
  302. package/src/components/layout/ModelSelector.tsx +0 -65
  303. package/src/components/layout/SessionManager.tsx +0 -115
  304. package/src/components/statusline/StatuslineBar.tsx +0 -114
  305. package/src/main.tsx +0 -10
  306. package/src/server/claude-session.ts +0 -156
  307. package/src/server/index.ts +0 -149
  308. package/src/services/stream-consumer.ts +0 -330
  309. package/src/statusline-core/bin/statusline.sh +0 -121
  310. package/src/statusline-core/commands/sls-config.md +0 -42
  311. package/src/statusline-core/commands/sls-doctor.md +0 -35
  312. package/src/statusline-core/commands/sls-help.md +0 -48
  313. package/src/statusline-core/commands/sls-layout.md +0 -38
  314. package/src/statusline-core/commands/sls-preview.md +0 -34
  315. package/src/statusline-core/commands/sls-theme.md +0 -40
  316. package/src/statusline-core/installer.js +0 -228
  317. package/src/statusline-core/layouts/compact.sh +0 -21
  318. package/src/statusline-core/layouts/full.sh +0 -62
  319. package/src/statusline-core/layouts/standard.sh +0 -39
  320. package/src/statusline-core/lib/core.sh +0 -389
  321. package/src/statusline-core/lib/helpers.sh +0 -81
  322. package/src/statusline-core/lib/json-parser.sh +0 -71
  323. package/src/statusline-core/themes/catppuccin.sh +0 -32
  324. package/src/statusline-core/themes/default.sh +0 -37
  325. package/src/statusline-core/themes/gruvbox.sh +0 -32
  326. package/src/statusline-core/themes/nord.sh +0 -32
  327. package/src/statusline-core/themes/tokyo-night.sh +0 -32
  328. package/src/store/canvas-store.ts +0 -50
  329. package/src/store/chat-store.ts +0 -60
  330. package/src/store/permission-store.ts +0 -29
  331. package/src/store/session-store.ts +0 -52
  332. package/src/store/statusline-store.ts +0 -160
  333. package/src/styles/global.css +0 -117
  334. package/src/themes/index.ts +0 -149
  335. package/src/types/canvas-graph.ts +0 -24
  336. package/src/types/sdk-messages.ts +0 -156
  337. package/src/types/statusline-fields.ts +0 -67
  338. package/src/vite-env.d.ts +0 -1
  339. package/tsconfig.json +0 -26
  340. package/vite.config.ts +0 -24
@@ -0,0 +1,1849 @@
1
+ /**
2
+ * PROJECT DISCOVERY AND MANAGEMENT SYSTEM
3
+ * ========================================
4
+ *
5
+ * This module manages project discovery for both Claude CLI and Cursor CLI sessions.
6
+ *
7
+ * ## Architecture Overview
8
+ *
9
+ * 1. **Claude Projects** (stored in ~/.claude/projects/)
10
+ * - Each project is a directory named with the project path encoded (/ replaced with -)
11
+ * - Contains .jsonl files with conversation history including 'cwd' field
12
+ * - Project metadata stored in ~/.claude/project-config.json
13
+ *
14
+ * 2. **Cursor Projects** (stored in ~/.cursor/chats/)
15
+ * - Each project directory is named with MD5 hash of the absolute project path
16
+ * - Example: /Users/john/myproject -> MD5 -> a1b2c3d4e5f6...
17
+ * - Contains session directories with SQLite databases (store.db)
18
+ * - Project path is NOT stored in the database - only in the MD5 hash
19
+ *
20
+ * ## Project Discovery Strategy
21
+ *
22
+ * 1. **Claude Projects Discovery**:
23
+ * - Scan ~/.claude/projects/ directory for Claude project folders
24
+ * - Extract actual project path from .jsonl files (cwd field)
25
+ * - Fall back to decoded directory name if no sessions exist
26
+ *
27
+ * 2. **Cursor Sessions Discovery**:
28
+ * - For each KNOWN project (from Claude or manually added)
29
+ * - Compute MD5 hash of the project's absolute path
30
+ * - Check if ~/.cursor/chats/{md5_hash}/ directory exists
31
+ * - Read session metadata from SQLite store.db files
32
+ *
33
+ * 3. **Manual Project Addition**:
34
+ * - Users can manually add project paths via UI
35
+ * - Stored in ~/.claude/project-config.json with 'manuallyAdded' flag
36
+ * - Allows discovering Cursor sessions for projects without Claude sessions
37
+ *
38
+ * ## Critical Limitations
39
+ *
40
+ * - **CANNOT discover Cursor-only projects**: From a quick check, there was no mention of
41
+ * the cwd of each project. if someone has the time, you can try to reverse engineer it.
42
+ *
43
+ * - **Project relocation breaks history**: If a project directory is moved or renamed,
44
+ * the MD5 hash changes, making old Cursor sessions inaccessible unless the old
45
+ * path is known and manually added.
46
+ *
47
+ * ## Error Handling
48
+ *
49
+ * - Missing ~/.claude directory is handled gracefully with automatic creation
50
+ * - ENOENT errors are caught and handled without crashing
51
+ * - Empty arrays returned when no projects/sessions exist
52
+ *
53
+ * ## Caching Strategy
54
+ *
55
+ * - Project directory extraction is cached to minimize file I/O
56
+ * - Cache is cleared when project configuration changes
57
+ * - Session data is fetched on-demand, not cached
58
+ */
59
+
60
+ import { promises as fs } from 'fs';
61
+ import fsSync from 'fs';
62
+ import path from 'path';
63
+ import readline from 'readline';
64
+ import crypto from 'crypto';
65
+ // sqlite3 is a native module — conditionally imported (not available on Vercel)
66
+ let sqlite3 = null;
67
+ let sqliteOpen = null;
68
+ try {
69
+ sqlite3 = (await import('sqlite3')).default;
70
+ sqliteOpen = (await import('sqlite')).open;
71
+ } catch (e) {
72
+ console.warn('[WARN] sqlite3/sqlite not available. Project scanning from SQLite databases disabled.');
73
+ }
74
+ import os from 'os';
75
+
76
+ // Import TaskMaster detection functions
77
+ async function detectTaskMasterFolder(projectPath) {
78
+ try {
79
+ const taskMasterPath = path.join(projectPath, '.taskmaster');
80
+
81
+ // Check if .taskmaster directory exists
82
+ try {
83
+ const stats = await fs.stat(taskMasterPath);
84
+ if (!stats.isDirectory()) {
85
+ return {
86
+ hasTaskmaster: false,
87
+ reason: '.taskmaster exists but is not a directory'
88
+ };
89
+ }
90
+ } catch (error) {
91
+ if (error.code === 'ENOENT') {
92
+ return {
93
+ hasTaskmaster: false,
94
+ reason: '.taskmaster directory not found'
95
+ };
96
+ }
97
+ throw error;
98
+ }
99
+
100
+ // Check for key TaskMaster files
101
+ const keyFiles = [
102
+ 'tasks/tasks.json',
103
+ 'config.json'
104
+ ];
105
+
106
+ const fileStatus = {};
107
+ let hasEssentialFiles = true;
108
+
109
+ for (const file of keyFiles) {
110
+ const filePath = path.join(taskMasterPath, file);
111
+ try {
112
+ await fs.access(filePath);
113
+ fileStatus[file] = true;
114
+ } catch (error) {
115
+ fileStatus[file] = false;
116
+ if (file === 'tasks/tasks.json') {
117
+ hasEssentialFiles = false;
118
+ }
119
+ }
120
+ }
121
+
122
+ // Parse tasks.json if it exists for metadata
123
+ let taskMetadata = null;
124
+ if (fileStatus['tasks/tasks.json']) {
125
+ try {
126
+ const tasksPath = path.join(taskMasterPath, 'tasks/tasks.json');
127
+ const tasksContent = await fs.readFile(tasksPath, 'utf8');
128
+ const tasksData = JSON.parse(tasksContent);
129
+
130
+ // Handle both tagged and legacy formats
131
+ let tasks = [];
132
+ if (tasksData.tasks) {
133
+ // Legacy format
134
+ tasks = tasksData.tasks;
135
+ } else {
136
+ // Tagged format - get tasks from all tags
137
+ Object.values(tasksData).forEach(tagData => {
138
+ if (tagData.tasks) {
139
+ tasks = tasks.concat(tagData.tasks);
140
+ }
141
+ });
142
+ }
143
+
144
+ // Calculate task statistics
145
+ const stats = tasks.reduce((acc, task) => {
146
+ acc.total++;
147
+ acc[task.status] = (acc[task.status] || 0) + 1;
148
+
149
+ // Count subtasks
150
+ if (task.subtasks) {
151
+ task.subtasks.forEach(subtask => {
152
+ acc.subtotalTasks++;
153
+ acc.subtasks = acc.subtasks || {};
154
+ acc.subtasks[subtask.status] = (acc.subtasks[subtask.status] || 0) + 1;
155
+ });
156
+ }
157
+
158
+ return acc;
159
+ }, {
160
+ total: 0,
161
+ subtotalTasks: 0,
162
+ pending: 0,
163
+ 'in-progress': 0,
164
+ done: 0,
165
+ review: 0,
166
+ deferred: 0,
167
+ cancelled: 0,
168
+ subtasks: {}
169
+ });
170
+
171
+ taskMetadata = {
172
+ taskCount: stats.total,
173
+ subtaskCount: stats.subtotalTasks,
174
+ completed: stats.done || 0,
175
+ pending: stats.pending || 0,
176
+ inProgress: stats['in-progress'] || 0,
177
+ review: stats.review || 0,
178
+ completionPercentage: stats.total > 0 ? Math.round((stats.done / stats.total) * 100) : 0,
179
+ lastModified: (await fs.stat(tasksPath)).mtime.toISOString()
180
+ };
181
+ } catch (parseError) {
182
+ console.warn('Failed to parse tasks.json:', parseError.message);
183
+ taskMetadata = { error: 'Failed to parse tasks.json' };
184
+ }
185
+ }
186
+
187
+ return {
188
+ hasTaskmaster: true,
189
+ hasEssentialFiles,
190
+ files: fileStatus,
191
+ metadata: taskMetadata,
192
+ path: taskMasterPath
193
+ };
194
+
195
+ } catch (error) {
196
+ console.error('Error detecting TaskMaster folder:', error);
197
+ return {
198
+ hasTaskmaster: false,
199
+ reason: `Error checking directory: ${error.message}`
200
+ };
201
+ }
202
+ }
203
+
204
+ // Cache for extracted project directories
205
+ const projectDirectoryCache = new Map();
206
+
207
+ // Clear cache when needed (called when project files change)
208
+ function clearProjectDirectoryCache() {
209
+ projectDirectoryCache.clear();
210
+ }
211
+
212
+ // Load project configuration file
213
+ async function loadProjectConfig() {
214
+ const configPath = path.join(os.homedir(), '.claude', 'project-config.json');
215
+ try {
216
+ const configData = await fs.readFile(configPath, 'utf8');
217
+ return JSON.parse(configData);
218
+ } catch (error) {
219
+ // Return empty config if file doesn't exist
220
+ return {};
221
+ }
222
+ }
223
+
224
+ // Save project configuration file
225
+ async function saveProjectConfig(config) {
226
+ const claudeDir = path.join(os.homedir(), '.claude');
227
+ const configPath = path.join(claudeDir, 'project-config.json');
228
+
229
+ // Ensure the .claude directory exists
230
+ try {
231
+ await fs.mkdir(claudeDir, { recursive: true });
232
+ } catch (error) {
233
+ if (error.code !== 'EEXIST') {
234
+ throw error;
235
+ }
236
+ }
237
+
238
+ await fs.writeFile(configPath, JSON.stringify(config, null, 2), 'utf8');
239
+ }
240
+
241
+ // Generate better display name from path
242
+ async function generateDisplayName(projectName, actualProjectDir = null) {
243
+ // Use actual project directory if provided, otherwise decode from project name
244
+ let projectPath = actualProjectDir || projectName.replace(/-/g, '/');
245
+
246
+ // Try to read package.json from the project path
247
+ try {
248
+ const packageJsonPath = path.join(projectPath, 'package.json');
249
+ const packageData = await fs.readFile(packageJsonPath, 'utf8');
250
+ const packageJson = JSON.parse(packageData);
251
+
252
+ // Return the name from package.json if it exists
253
+ if (packageJson.name) {
254
+ return packageJson.name;
255
+ }
256
+ } catch (error) {
257
+ // Fall back to path-based naming if package.json doesn't exist or can't be read
258
+ }
259
+
260
+ // If it starts with /, it's an absolute path
261
+ if (projectPath.startsWith('/')) {
262
+ const parts = projectPath.split('/').filter(Boolean);
263
+ // Return only the last folder name
264
+ return parts[parts.length - 1] || projectPath;
265
+ }
266
+
267
+ return projectPath;
268
+ }
269
+
270
+ // Extract the actual project directory from JSONL sessions (with caching)
271
+ async function extractProjectDirectory(projectName) {
272
+ // Check cache first
273
+ if (projectDirectoryCache.has(projectName)) {
274
+ return projectDirectoryCache.get(projectName);
275
+ }
276
+
277
+ // Check project config for originalPath (manually added projects via UI or platform)
278
+ // This handles projects with dashes in their directory names correctly
279
+ const config = await loadProjectConfig();
280
+ if (config[projectName]?.originalPath) {
281
+ const originalPath = config[projectName].originalPath;
282
+ projectDirectoryCache.set(projectName, originalPath);
283
+ return originalPath;
284
+ }
285
+
286
+ const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
287
+ const cwdCounts = new Map();
288
+ let latestTimestamp = 0;
289
+ let latestCwd = null;
290
+ let extractedPath;
291
+
292
+ try {
293
+ // Check if the project directory exists
294
+ await fs.access(projectDir);
295
+
296
+ const files = await fs.readdir(projectDir);
297
+ const jsonlFiles = files.filter(file => file.endsWith('.jsonl'));
298
+
299
+ if (jsonlFiles.length === 0) {
300
+ // Fall back to decoded project name if no sessions
301
+ extractedPath = projectName.replace(/-/g, '/');
302
+ } else {
303
+ // Process all JSONL files to collect cwd values
304
+ for (const file of jsonlFiles) {
305
+ const jsonlFile = path.join(projectDir, file);
306
+ const fileStream = fsSync.createReadStream(jsonlFile);
307
+ const rl = readline.createInterface({
308
+ input: fileStream,
309
+ crlfDelay: Infinity
310
+ });
311
+
312
+ for await (const line of rl) {
313
+ if (line.trim()) {
314
+ try {
315
+ const entry = JSON.parse(line);
316
+
317
+ if (entry.cwd) {
318
+ // Count occurrences of each cwd
319
+ cwdCounts.set(entry.cwd, (cwdCounts.get(entry.cwd) || 0) + 1);
320
+
321
+ // Track the most recent cwd
322
+ const timestamp = new Date(entry.timestamp || 0).getTime();
323
+ if (timestamp > latestTimestamp) {
324
+ latestTimestamp = timestamp;
325
+ latestCwd = entry.cwd;
326
+ }
327
+ }
328
+ } catch (parseError) {
329
+ // Skip malformed lines
330
+ }
331
+ }
332
+ }
333
+ }
334
+
335
+ // Determine the best cwd to use
336
+ if (cwdCounts.size === 0) {
337
+ // No cwd found, fall back to decoded project name
338
+ extractedPath = projectName.replace(/-/g, '/');
339
+ } else if (cwdCounts.size === 1) {
340
+ // Only one cwd, use it
341
+ extractedPath = Array.from(cwdCounts.keys())[0];
342
+ } else {
343
+ // Multiple cwd values - prefer the most recent one if it has reasonable usage
344
+ const mostRecentCount = cwdCounts.get(latestCwd) || 0;
345
+ const maxCount = Math.max(...cwdCounts.values());
346
+
347
+ // Use most recent if it has at least 25% of the max count
348
+ if (mostRecentCount >= maxCount * 0.25) {
349
+ extractedPath = latestCwd;
350
+ } else {
351
+ // Otherwise use the most frequently used cwd
352
+ for (const [cwd, count] of cwdCounts.entries()) {
353
+ if (count === maxCount) {
354
+ extractedPath = cwd;
355
+ break;
356
+ }
357
+ }
358
+ }
359
+
360
+ // Fallback (shouldn't reach here)
361
+ if (!extractedPath) {
362
+ extractedPath = latestCwd || projectName.replace(/-/g, '/');
363
+ }
364
+ }
365
+ }
366
+
367
+ // Cache the result
368
+ projectDirectoryCache.set(projectName, extractedPath);
369
+
370
+ return extractedPath;
371
+
372
+ } catch (error) {
373
+ // If the directory doesn't exist, just use the decoded project name
374
+ if (error.code === 'ENOENT') {
375
+ extractedPath = projectName.replace(/-/g, '/');
376
+ } else {
377
+ console.error(`Error extracting project directory for ${projectName}:`, error);
378
+ // Fall back to decoded project name for other errors
379
+ extractedPath = projectName.replace(/-/g, '/');
380
+ }
381
+
382
+ // Cache the fallback result too
383
+ projectDirectoryCache.set(projectName, extractedPath);
384
+
385
+ return extractedPath;
386
+ }
387
+ }
388
+
389
+ async function getProjects(progressCallback = null) {
390
+ // Wrap with a 10s timeout to prevent hanging on slow filesystems
391
+ const timeoutMs = 10000;
392
+ const result = await Promise.race([
393
+ _getProjectsImpl(progressCallback),
394
+ new Promise((_, reject) => setTimeout(() => reject(new Error('Projects scan timed out')), timeoutMs))
395
+ ]).catch(err => {
396
+ console.warn(`[WARN] getProjects failed: ${err.message}. Returning empty list.`);
397
+ return [];
398
+ });
399
+ return result;
400
+ }
401
+
402
+ async function _getProjectsImpl(progressCallback = null) {
403
+ const claudeDir = path.join(os.homedir(), '.claude', 'projects');
404
+ const config = await loadProjectConfig();
405
+ const projects = [];
406
+ const existingProjects = new Set();
407
+ const codexSessionsIndexRef = { sessionsByProject: null };
408
+ let totalProjects = 0;
409
+ let processedProjects = 0;
410
+ let directories = [];
411
+
412
+ try {
413
+ // Check if the .claude/projects directory exists
414
+ await fs.access(claudeDir);
415
+
416
+ // First, get existing Claude projects from the file system
417
+ const entries = await fs.readdir(claudeDir, { withFileTypes: true });
418
+ directories = entries.filter(e => e.isDirectory());
419
+
420
+ // Build set of existing project names for later
421
+ directories.forEach(e => existingProjects.add(e.name));
422
+
423
+ // Count manual projects not already in directories
424
+ const manualProjectsCount = Object.entries(config)
425
+ .filter(([name, cfg]) => cfg.manuallyAdded && !existingProjects.has(name))
426
+ .length;
427
+
428
+ totalProjects = directories.length + manualProjectsCount;
429
+
430
+ for (const entry of directories) {
431
+ processedProjects++;
432
+
433
+ // Emit progress
434
+ if (progressCallback) {
435
+ progressCallback({
436
+ phase: 'loading',
437
+ current: processedProjects,
438
+ total: totalProjects,
439
+ currentProject: entry.name
440
+ });
441
+ }
442
+
443
+ // Extract actual project directory from JSONL sessions
444
+ const actualProjectDir = await extractProjectDirectory(entry.name);
445
+
446
+ // Get display name from config or generate one
447
+ const customName = config[entry.name]?.displayName;
448
+ const autoDisplayName = await generateDisplayName(entry.name, actualProjectDir);
449
+ const fullPath = actualProjectDir;
450
+
451
+ const project = {
452
+ name: entry.name,
453
+ path: actualProjectDir,
454
+ displayName: customName || autoDisplayName,
455
+ fullPath: fullPath,
456
+ isCustomName: !!customName,
457
+ sessions: [],
458
+ sessionMeta: {
459
+ hasMore: false,
460
+ total: 0
461
+ }
462
+ };
463
+
464
+ // Try to get sessions for this project (just first 5 for performance)
465
+ try {
466
+ const sessionResult = await getSessions(entry.name, 5, 0);
467
+ project.sessions = sessionResult.sessions || [];
468
+ project.sessionMeta = {
469
+ hasMore: sessionResult.hasMore,
470
+ total: sessionResult.total
471
+ };
472
+ } catch (e) {
473
+ console.warn(`Could not load sessions for project ${entry.name}:`, e.message);
474
+ project.sessionMeta = {
475
+ hasMore: false,
476
+ total: 0
477
+ };
478
+ }
479
+
480
+ // Also fetch Cursor sessions for this project
481
+ try {
482
+ project.cursorSessions = await getCursorSessions(actualProjectDir);
483
+ } catch (e) {
484
+ console.warn(`Could not load Cursor sessions for project ${entry.name}:`, e.message);
485
+ project.cursorSessions = [];
486
+ }
487
+
488
+ // Also fetch Codex sessions for this project
489
+ try {
490
+ project.codexSessions = await getCodexSessions(actualProjectDir, {
491
+ indexRef: codexSessionsIndexRef,
492
+ });
493
+ } catch (e) {
494
+ console.warn(`Could not load Codex sessions for project ${entry.name}:`, e.message);
495
+ project.codexSessions = [];
496
+ }
497
+
498
+ // Add TaskMaster detection
499
+ try {
500
+ const taskMasterResult = await detectTaskMasterFolder(actualProjectDir);
501
+ project.taskmaster = {
502
+ hasTaskmaster: taskMasterResult.hasTaskmaster,
503
+ hasEssentialFiles: taskMasterResult.hasEssentialFiles,
504
+ metadata: taskMasterResult.metadata,
505
+ status: taskMasterResult.hasTaskmaster && taskMasterResult.hasEssentialFiles ? 'configured' : 'not-configured'
506
+ };
507
+ } catch (e) {
508
+ console.warn(`Could not detect TaskMaster for project ${entry.name}:`, e.message);
509
+ project.taskmaster = {
510
+ hasTaskmaster: false,
511
+ hasEssentialFiles: false,
512
+ metadata: null,
513
+ status: 'error'
514
+ };
515
+ }
516
+
517
+ projects.push(project);
518
+ }
519
+ } catch (error) {
520
+ // If the directory doesn't exist (ENOENT), that's okay - just continue with empty projects
521
+ if (error.code !== 'ENOENT') {
522
+ console.error('Error reading projects directory:', error);
523
+ }
524
+ // Calculate total for manual projects only (no directories exist)
525
+ totalProjects = Object.entries(config)
526
+ .filter(([name, cfg]) => cfg.manuallyAdded)
527
+ .length;
528
+ }
529
+
530
+ // Add manually configured projects that don't exist as folders yet
531
+ for (const [projectName, projectConfig] of Object.entries(config)) {
532
+ if (!existingProjects.has(projectName) && projectConfig.manuallyAdded) {
533
+ processedProjects++;
534
+
535
+ // Emit progress for manual projects
536
+ if (progressCallback) {
537
+ progressCallback({
538
+ phase: 'loading',
539
+ current: processedProjects,
540
+ total: totalProjects,
541
+ currentProject: projectName
542
+ });
543
+ }
544
+
545
+ // Use the original path if available, otherwise extract from potential sessions
546
+ let actualProjectDir = projectConfig.originalPath;
547
+
548
+ if (!actualProjectDir) {
549
+ try {
550
+ actualProjectDir = await extractProjectDirectory(projectName);
551
+ } catch (error) {
552
+ // Fall back to decoded project name
553
+ actualProjectDir = projectName.replace(/-/g, '/');
554
+ }
555
+ }
556
+
557
+ const project = {
558
+ name: projectName,
559
+ path: actualProjectDir,
560
+ displayName: projectConfig.displayName || await generateDisplayName(projectName, actualProjectDir),
561
+ fullPath: actualProjectDir,
562
+ isCustomName: !!projectConfig.displayName,
563
+ isManuallyAdded: true,
564
+ sessions: [],
565
+ sessionMeta: {
566
+ hasMore: false,
567
+ total: 0
568
+ },
569
+ cursorSessions: [],
570
+ codexSessions: []
571
+ };
572
+
573
+ // Try to fetch Cursor sessions for manual projects too
574
+ try {
575
+ project.cursorSessions = await getCursorSessions(actualProjectDir);
576
+ } catch (e) {
577
+ console.warn(`Could not load Cursor sessions for manual project ${projectName}:`, e.message);
578
+ }
579
+
580
+ // Try to fetch Codex sessions for manual projects too
581
+ try {
582
+ project.codexSessions = await getCodexSessions(actualProjectDir, {
583
+ indexRef: codexSessionsIndexRef,
584
+ });
585
+ } catch (e) {
586
+ console.warn(`Could not load Codex sessions for manual project ${projectName}:`, e.message);
587
+ }
588
+
589
+ // Add TaskMaster detection for manual projects
590
+ try {
591
+ const taskMasterResult = await detectTaskMasterFolder(actualProjectDir);
592
+
593
+ // Determine TaskMaster status
594
+ let taskMasterStatus = 'not-configured';
595
+ if (taskMasterResult.hasTaskmaster && taskMasterResult.hasEssentialFiles) {
596
+ taskMasterStatus = 'taskmaster-only'; // We don't check MCP for manual projects in bulk
597
+ }
598
+
599
+ project.taskmaster = {
600
+ status: taskMasterStatus,
601
+ hasTaskmaster: taskMasterResult.hasTaskmaster,
602
+ hasEssentialFiles: taskMasterResult.hasEssentialFiles,
603
+ metadata: taskMasterResult.metadata
604
+ };
605
+ } catch (error) {
606
+ console.warn(`TaskMaster detection failed for manual project ${projectName}:`, error.message);
607
+ project.taskmaster = {
608
+ status: 'error',
609
+ hasTaskmaster: false,
610
+ hasEssentialFiles: false,
611
+ error: error.message
612
+ };
613
+ }
614
+
615
+ projects.push(project);
616
+ }
617
+ }
618
+
619
+ // Emit completion after all projects (including manual) are processed
620
+ if (progressCallback) {
621
+ progressCallback({
622
+ phase: 'complete',
623
+ current: totalProjects,
624
+ total: totalProjects
625
+ });
626
+ }
627
+
628
+ return projects;
629
+ }
630
+
631
+ async function getSessions(projectName, limit = 5, offset = 0) {
632
+ const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
633
+
634
+ try {
635
+ const files = await fs.readdir(projectDir);
636
+ // agent-*.jsonl files contain session start data at this point. This needs to be revisited
637
+ // periodically to make sure only accurate data is there and no new functionality is added there
638
+ const jsonlFiles = files.filter(file => file.endsWith('.jsonl') && !file.startsWith('agent-'));
639
+
640
+ if (jsonlFiles.length === 0) {
641
+ return { sessions: [], hasMore: false, total: 0 };
642
+ }
643
+
644
+ // Sort files by modification time (newest first)
645
+ const filesWithStats = await Promise.all(
646
+ jsonlFiles.map(async (file) => {
647
+ const filePath = path.join(projectDir, file);
648
+ const stats = await fs.stat(filePath);
649
+ return { file, mtime: stats.mtime };
650
+ })
651
+ );
652
+ filesWithStats.sort((a, b) => b.mtime - a.mtime);
653
+
654
+ const allSessions = new Map();
655
+ const allEntries = [];
656
+ const uuidToSessionMap = new Map();
657
+
658
+ // Collect all sessions and entries from all files
659
+ for (const { file } of filesWithStats) {
660
+ const jsonlFile = path.join(projectDir, file);
661
+ const result = await parseJsonlSessions(jsonlFile);
662
+
663
+ result.sessions.forEach(session => {
664
+ if (!allSessions.has(session.id)) {
665
+ allSessions.set(session.id, session);
666
+ }
667
+ });
668
+
669
+ allEntries.push(...result.entries);
670
+
671
+ // Early exit optimization for large projects
672
+ if (allSessions.size >= (limit + offset) * 2 && allEntries.length >= Math.min(3, filesWithStats.length)) {
673
+ break;
674
+ }
675
+ }
676
+
677
+ // Build UUID-to-session mapping for timeline detection
678
+ allEntries.forEach(entry => {
679
+ if (entry.uuid && entry.sessionId) {
680
+ uuidToSessionMap.set(entry.uuid, entry.sessionId);
681
+ }
682
+ });
683
+
684
+ // Group sessions by first user message ID
685
+ const sessionGroups = new Map(); // firstUserMsgId -> { latestSession, allSessions[] }
686
+ const sessionToFirstUserMsgId = new Map(); // sessionId -> firstUserMsgId
687
+
688
+ // Find the first user message for each session
689
+ allEntries.forEach(entry => {
690
+ if (entry.sessionId && entry.type === 'user' && entry.parentUuid === null && entry.uuid) {
691
+ // This is a first user message in a session (parentUuid is null)
692
+ const firstUserMsgId = entry.uuid;
693
+
694
+ if (!sessionToFirstUserMsgId.has(entry.sessionId)) {
695
+ sessionToFirstUserMsgId.set(entry.sessionId, firstUserMsgId);
696
+
697
+ const session = allSessions.get(entry.sessionId);
698
+ if (session) {
699
+ if (!sessionGroups.has(firstUserMsgId)) {
700
+ sessionGroups.set(firstUserMsgId, {
701
+ latestSession: session,
702
+ allSessions: [session]
703
+ });
704
+ } else {
705
+ const group = sessionGroups.get(firstUserMsgId);
706
+ group.allSessions.push(session);
707
+
708
+ // Update latest session if this one is more recent
709
+ if (new Date(session.lastActivity) > new Date(group.latestSession.lastActivity)) {
710
+ group.latestSession = session;
711
+ }
712
+ }
713
+ }
714
+ }
715
+ }
716
+ });
717
+
718
+ // Collect all sessions that don't belong to any group (standalone sessions)
719
+ const groupedSessionIds = new Set();
720
+ sessionGroups.forEach(group => {
721
+ group.allSessions.forEach(session => groupedSessionIds.add(session.id));
722
+ });
723
+
724
+ const standaloneSessionsArray = Array.from(allSessions.values())
725
+ .filter(session => !groupedSessionIds.has(session.id));
726
+
727
+ // Combine grouped sessions (only show latest from each group) + standalone sessions
728
+ const latestFromGroups = Array.from(sessionGroups.values()).map(group => {
729
+ const session = { ...group.latestSession };
730
+ // Add metadata about grouping
731
+ if (group.allSessions.length > 1) {
732
+ session.isGrouped = true;
733
+ session.groupSize = group.allSessions.length;
734
+ session.groupSessions = group.allSessions.map(s => s.id);
735
+ }
736
+ return session;
737
+ });
738
+ const visibleSessions = [...latestFromGroups, ...standaloneSessionsArray]
739
+ .filter(session => !session.summary.startsWith('{ "'))
740
+ .sort((a, b) => new Date(b.lastActivity) - new Date(a.lastActivity));
741
+
742
+ const total = visibleSessions.length;
743
+ const paginatedSessions = visibleSessions.slice(offset, offset + limit);
744
+ const hasMore = offset + limit < total;
745
+
746
+ return {
747
+ sessions: paginatedSessions,
748
+ hasMore,
749
+ total,
750
+ offset,
751
+ limit
752
+ };
753
+ } catch (error) {
754
+ console.error(`Error reading sessions for project ${projectName}:`, error);
755
+ return { sessions: [], hasMore: false, total: 0 };
756
+ }
757
+ }
758
+
759
+ async function parseJsonlSessions(filePath) {
760
+ const sessions = new Map();
761
+ const entries = [];
762
+ const pendingSummaries = new Map(); // leafUuid -> summary for entries without sessionId
763
+
764
+ try {
765
+ const fileStream = fsSync.createReadStream(filePath);
766
+ const rl = readline.createInterface({
767
+ input: fileStream,
768
+ crlfDelay: Infinity
769
+ });
770
+
771
+ for await (const line of rl) {
772
+ if (line.trim()) {
773
+ try {
774
+ const entry = JSON.parse(line);
775
+ entries.push(entry);
776
+
777
+ // Handle summary entries that don't have sessionId yet
778
+ if (entry.type === 'summary' && entry.summary && !entry.sessionId && entry.leafUuid) {
779
+ pendingSummaries.set(entry.leafUuid, entry.summary);
780
+ }
781
+
782
+ if (entry.sessionId) {
783
+ if (!sessions.has(entry.sessionId)) {
784
+ sessions.set(entry.sessionId, {
785
+ id: entry.sessionId,
786
+ summary: 'New Session',
787
+ messageCount: 0,
788
+ lastActivity: new Date(),
789
+ cwd: entry.cwd || '',
790
+ lastUserMessage: null,
791
+ lastAssistantMessage: null
792
+ });
793
+ }
794
+
795
+ const session = sessions.get(entry.sessionId);
796
+
797
+ // Apply pending summary if this entry has a parentUuid that matches a pending summary
798
+ if (session.summary === 'New Session' && entry.parentUuid && pendingSummaries.has(entry.parentUuid)) {
799
+ session.summary = pendingSummaries.get(entry.parentUuid);
800
+ }
801
+
802
+ // Update summary from summary entries with sessionId
803
+ if (entry.type === 'summary' && entry.summary) {
804
+ session.summary = entry.summary;
805
+ }
806
+
807
+ // Track last user and assistant messages (skip system messages)
808
+ if (entry.message?.role === 'user' && entry.message?.content) {
809
+ const content = entry.message.content;
810
+
811
+ // Extract text from array format if needed
812
+ let textContent = content;
813
+ if (Array.isArray(content) && content.length > 0 && content[0].type === 'text') {
814
+ textContent = content[0].text;
815
+ }
816
+
817
+ const isSystemMessage = typeof textContent === 'string' && (
818
+ textContent.startsWith('<command-name>') ||
819
+ textContent.startsWith('<command-message>') ||
820
+ textContent.startsWith('<command-args>') ||
821
+ textContent.startsWith('<local-command-stdout>') ||
822
+ textContent.startsWith('<system-reminder>') ||
823
+ textContent.startsWith('Caveat:') ||
824
+ textContent.startsWith('This session is being continued from a previous') ||
825
+ textContent.startsWith('Invalid API key') ||
826
+ textContent.includes('{"subtasks":') || // Filter Task Master prompts
827
+ textContent.includes('CRITICAL: You MUST respond with ONLY a JSON') || // Filter Task Master system prompts
828
+ textContent === 'Warmup' // Explicitly filter out "Warmup"
829
+ );
830
+
831
+ if (typeof textContent === 'string' && textContent.length > 0 && !isSystemMessage) {
832
+ session.lastUserMessage = textContent;
833
+ }
834
+ } else if (entry.message?.role === 'assistant' && entry.message?.content) {
835
+ // Skip API error messages using the isApiErrorMessage flag
836
+ if (entry.isApiErrorMessage === true) {
837
+ // Skip this message entirely
838
+ } else {
839
+ // Track last assistant text message
840
+ let assistantText = null;
841
+
842
+ if (Array.isArray(entry.message.content)) {
843
+ for (const part of entry.message.content) {
844
+ if (part.type === 'text' && part.text) {
845
+ assistantText = part.text;
846
+ }
847
+ }
848
+ } else if (typeof entry.message.content === 'string') {
849
+ assistantText = entry.message.content;
850
+ }
851
+
852
+ // Additional filter for assistant messages with system content
853
+ const isSystemAssistantMessage = typeof assistantText === 'string' && (
854
+ assistantText.startsWith('Invalid API key') ||
855
+ assistantText.includes('{"subtasks":') ||
856
+ assistantText.includes('CRITICAL: You MUST respond with ONLY a JSON')
857
+ );
858
+
859
+ if (assistantText && !isSystemAssistantMessage) {
860
+ session.lastAssistantMessage = assistantText;
861
+ }
862
+ }
863
+ }
864
+
865
+ session.messageCount++;
866
+
867
+ if (entry.timestamp) {
868
+ session.lastActivity = new Date(entry.timestamp);
869
+ }
870
+ }
871
+ } catch (parseError) {
872
+ // Skip malformed lines silently
873
+ }
874
+ }
875
+ }
876
+
877
+ // After processing all entries, set final summary based on last message if no summary exists
878
+ for (const session of sessions.values()) {
879
+ if (session.summary === 'New Session') {
880
+ // Prefer last user message, fall back to last assistant message
881
+ const lastMessage = session.lastUserMessage || session.lastAssistantMessage;
882
+ if (lastMessage) {
883
+ session.summary = lastMessage.length > 50 ? lastMessage.substring(0, 50) + '...' : lastMessage;
884
+ }
885
+ }
886
+ }
887
+
888
+ // Filter out sessions that contain JSON responses (Task Master errors)
889
+ const allSessions = Array.from(sessions.values());
890
+ const filteredSessions = allSessions.filter(session => {
891
+ const shouldFilter = session.summary.startsWith('{ "');
892
+ if (shouldFilter) {
893
+ }
894
+ // Log a sample of summaries to debug
895
+ if (Math.random() < 0.01) { // Log 1% of sessions
896
+ }
897
+ return !shouldFilter;
898
+ });
899
+
900
+
901
+ return {
902
+ sessions: filteredSessions,
903
+ entries: entries
904
+ };
905
+
906
+ } catch (error) {
907
+ console.error('Error reading JSONL file:', error);
908
+ return { sessions: [], entries: [] };
909
+ }
910
+ }
911
+
912
+ // Parse an agent JSONL file and extract tool uses
913
+ async function parseAgentTools(filePath) {
914
+ const tools = [];
915
+
916
+ try {
917
+ const fileStream = fsSync.createReadStream(filePath);
918
+ const rl = readline.createInterface({
919
+ input: fileStream,
920
+ crlfDelay: Infinity
921
+ });
922
+
923
+ for await (const line of rl) {
924
+ if (line.trim()) {
925
+ try {
926
+ const entry = JSON.parse(line);
927
+ // Look for assistant messages with tool_use
928
+ if (entry.message?.role === 'assistant' && Array.isArray(entry.message?.content)) {
929
+ for (const part of entry.message.content) {
930
+ if (part.type === 'tool_use') {
931
+ tools.push({
932
+ toolId: part.id,
933
+ toolName: part.name,
934
+ toolInput: part.input,
935
+ timestamp: entry.timestamp
936
+ });
937
+ }
938
+ }
939
+ }
940
+ // Look for tool results
941
+ if (entry.message?.role === 'user' && Array.isArray(entry.message?.content)) {
942
+ for (const part of entry.message.content) {
943
+ if (part.type === 'tool_result') {
944
+ // Find the matching tool and add result
945
+ const tool = tools.find(t => t.toolId === part.tool_use_id);
946
+ if (tool) {
947
+ tool.toolResult = {
948
+ content: typeof part.content === 'string' ? part.content :
949
+ Array.isArray(part.content) ? part.content.map(c => c.text || '').join('\n') :
950
+ JSON.stringify(part.content),
951
+ isError: Boolean(part.is_error)
952
+ };
953
+ }
954
+ }
955
+ }
956
+ }
957
+ } catch (parseError) {
958
+ // Skip malformed lines
959
+ }
960
+ }
961
+ }
962
+ } catch (error) {
963
+ console.warn(`Error parsing agent file ${filePath}:`, error.message);
964
+ }
965
+
966
+ return tools;
967
+ }
968
+
969
+ // Get messages for a specific session with pagination support
970
+ async function getSessionMessages(projectName, sessionId, limit = null, offset = 0) {
971
+ const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
972
+
973
+ try {
974
+ const files = await fs.readdir(projectDir);
975
+ // agent-*.jsonl files contain subagent tool history - we'll process them separately
976
+ const jsonlFiles = files.filter(file => file.endsWith('.jsonl') && !file.startsWith('agent-'));
977
+ const agentFiles = files.filter(file => file.endsWith('.jsonl') && file.startsWith('agent-'));
978
+
979
+ if (jsonlFiles.length === 0) {
980
+ return { messages: [], total: 0, hasMore: false };
981
+ }
982
+
983
+ const messages = [];
984
+ // Map of agentId -> tools for subagent tool grouping
985
+ const agentToolsCache = new Map();
986
+
987
+ // Process all JSONL files to find messages for this session
988
+ for (const file of jsonlFiles) {
989
+ const jsonlFile = path.join(projectDir, file);
990
+ const fileStream = fsSync.createReadStream(jsonlFile);
991
+ const rl = readline.createInterface({
992
+ input: fileStream,
993
+ crlfDelay: Infinity
994
+ });
995
+
996
+ for await (const line of rl) {
997
+ if (line.trim()) {
998
+ try {
999
+ const entry = JSON.parse(line);
1000
+ if (entry.sessionId === sessionId) {
1001
+ messages.push(entry);
1002
+ }
1003
+ } catch (parseError) {
1004
+ console.warn('Error parsing line:', parseError.message);
1005
+ }
1006
+ }
1007
+ }
1008
+ }
1009
+
1010
+ // Collect agentIds from Task tool results
1011
+ const agentIds = new Set();
1012
+ for (const message of messages) {
1013
+ if (message.toolUseResult?.agentId) {
1014
+ agentIds.add(message.toolUseResult.agentId);
1015
+ }
1016
+ }
1017
+
1018
+ // Load agent tools for each agentId found
1019
+ for (const agentId of agentIds) {
1020
+ const agentFileName = `agent-${agentId}.jsonl`;
1021
+ if (agentFiles.includes(agentFileName)) {
1022
+ const agentFilePath = path.join(projectDir, agentFileName);
1023
+ const tools = await parseAgentTools(agentFilePath);
1024
+ agentToolsCache.set(agentId, tools);
1025
+ }
1026
+ }
1027
+
1028
+ // Attach agent tools to their parent Task messages
1029
+ for (const message of messages) {
1030
+ if (message.toolUseResult?.agentId) {
1031
+ const agentId = message.toolUseResult.agentId;
1032
+ const agentTools = agentToolsCache.get(agentId);
1033
+ if (agentTools && agentTools.length > 0) {
1034
+ message.subagentTools = agentTools;
1035
+ }
1036
+ }
1037
+ }
1038
+
1039
+ // Sort messages by timestamp
1040
+ const sortedMessages = messages.sort((a, b) =>
1041
+ new Date(a.timestamp || 0) - new Date(b.timestamp || 0)
1042
+ );
1043
+
1044
+ const total = sortedMessages.length;
1045
+
1046
+ // If no limit is specified, return all messages (backward compatibility)
1047
+ if (limit === null) {
1048
+ return sortedMessages;
1049
+ }
1050
+
1051
+ // Apply pagination - for recent messages, we need to slice from the end
1052
+ // offset 0 should give us the most recent messages
1053
+ const startIndex = Math.max(0, total - offset - limit);
1054
+ const endIndex = total - offset;
1055
+ const paginatedMessages = sortedMessages.slice(startIndex, endIndex);
1056
+ const hasMore = startIndex > 0;
1057
+
1058
+ return {
1059
+ messages: paginatedMessages,
1060
+ total,
1061
+ hasMore,
1062
+ offset,
1063
+ limit
1064
+ };
1065
+ } catch (error) {
1066
+ console.error(`Error reading messages for session ${sessionId}:`, error);
1067
+ return limit === null ? [] : { messages: [], total: 0, hasMore: false };
1068
+ }
1069
+ }
1070
+
1071
+ // Rename a project's display name
1072
+ async function renameProject(projectName, newDisplayName) {
1073
+ const config = await loadProjectConfig();
1074
+
1075
+ if (!newDisplayName || newDisplayName.trim() === '') {
1076
+ // Remove custom name if empty, will fall back to auto-generated
1077
+ delete config[projectName];
1078
+ } else {
1079
+ // Set custom display name
1080
+ config[projectName] = {
1081
+ displayName: newDisplayName.trim()
1082
+ };
1083
+ }
1084
+
1085
+ await saveProjectConfig(config);
1086
+ return true;
1087
+ }
1088
+
1089
+ // Delete a session from a project
1090
+ async function deleteSession(projectName, sessionId) {
1091
+ const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
1092
+
1093
+ try {
1094
+ const files = await fs.readdir(projectDir);
1095
+ const jsonlFiles = files.filter(file => file.endsWith('.jsonl'));
1096
+
1097
+ if (jsonlFiles.length === 0) {
1098
+ throw new Error('No session files found for this project');
1099
+ }
1100
+
1101
+ // Check all JSONL files to find which one contains the session
1102
+ for (const file of jsonlFiles) {
1103
+ const jsonlFile = path.join(projectDir, file);
1104
+ const content = await fs.readFile(jsonlFile, 'utf8');
1105
+ const lines = content.split('\n').filter(line => line.trim());
1106
+
1107
+ // Check if this file contains the session
1108
+ const hasSession = lines.some(line => {
1109
+ try {
1110
+ const data = JSON.parse(line);
1111
+ return data.sessionId === sessionId;
1112
+ } catch {
1113
+ return false;
1114
+ }
1115
+ });
1116
+
1117
+ if (hasSession) {
1118
+ // Filter out all entries for this session
1119
+ const filteredLines = lines.filter(line => {
1120
+ try {
1121
+ const data = JSON.parse(line);
1122
+ return data.sessionId !== sessionId;
1123
+ } catch {
1124
+ return true; // Keep malformed lines
1125
+ }
1126
+ });
1127
+
1128
+ // Write back the filtered content
1129
+ await fs.writeFile(jsonlFile, filteredLines.join('\n') + (filteredLines.length > 0 ? '\n' : ''));
1130
+ return true;
1131
+ }
1132
+ }
1133
+
1134
+ throw new Error(`Session ${sessionId} not found in any files`);
1135
+ } catch (error) {
1136
+ console.error(`Error deleting session ${sessionId} from project ${projectName}:`, error);
1137
+ throw error;
1138
+ }
1139
+ }
1140
+
1141
+ // Check if a project is empty (has no sessions)
1142
+ async function isProjectEmpty(projectName) {
1143
+ try {
1144
+ const sessionsResult = await getSessions(projectName, 1, 0);
1145
+ return sessionsResult.total === 0;
1146
+ } catch (error) {
1147
+ console.error(`Error checking if project ${projectName} is empty:`, error);
1148
+ return false;
1149
+ }
1150
+ }
1151
+
1152
+ // Delete a project (force=true to delete even with sessions)
1153
+ async function deleteProject(projectName, force = false) {
1154
+ const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
1155
+
1156
+ try {
1157
+ const isEmpty = await isProjectEmpty(projectName);
1158
+ if (!isEmpty && !force) {
1159
+ throw new Error('Cannot delete project with existing sessions');
1160
+ }
1161
+
1162
+ const config = await loadProjectConfig();
1163
+ let projectPath = config[projectName]?.path || config[projectName]?.originalPath;
1164
+
1165
+ // Fallback to extractProjectDirectory if projectPath is not in config
1166
+ if (!projectPath) {
1167
+ projectPath = await extractProjectDirectory(projectName);
1168
+ }
1169
+
1170
+ // Remove the project directory (includes all Claude sessions)
1171
+ await fs.rm(projectDir, { recursive: true, force: true });
1172
+
1173
+ // Delete all Codex sessions associated with this project
1174
+ if (projectPath) {
1175
+ try {
1176
+ const codexSessions = await getCodexSessions(projectPath, { limit: 0 });
1177
+ for (const session of codexSessions) {
1178
+ try {
1179
+ await deleteCodexSession(session.id);
1180
+ } catch (err) {
1181
+ console.warn(`Failed to delete Codex session ${session.id}:`, err.message);
1182
+ }
1183
+ }
1184
+ } catch (err) {
1185
+ console.warn('Failed to delete Codex sessions:', err.message);
1186
+ }
1187
+
1188
+ // Delete Cursor sessions directory if it exists
1189
+ try {
1190
+ const hash = crypto.createHash('md5').update(projectPath).digest('hex');
1191
+ const cursorProjectDir = path.join(os.homedir(), '.cursor', 'chats', hash);
1192
+ await fs.rm(cursorProjectDir, { recursive: true, force: true });
1193
+ } catch (err) {
1194
+ // Cursor dir may not exist, ignore
1195
+ }
1196
+ }
1197
+
1198
+ // Remove from project config
1199
+ delete config[projectName];
1200
+ await saveProjectConfig(config);
1201
+
1202
+ return true;
1203
+ } catch (error) {
1204
+ console.error(`Error deleting project ${projectName}:`, error);
1205
+ throw error;
1206
+ }
1207
+ }
1208
+
1209
+ // Add a project manually to the config (without creating folders)
1210
+ async function addProjectManually(projectPath, displayName = null) {
1211
+ const absolutePath = path.resolve(projectPath);
1212
+
1213
+ try {
1214
+ // Check if the path exists
1215
+ await fs.access(absolutePath);
1216
+ } catch (error) {
1217
+ throw new Error(`Path does not exist: ${absolutePath}`);
1218
+ }
1219
+
1220
+ // Generate project name (encode path for use as directory name)
1221
+ const projectName = absolutePath.replace(/[\\/:\s~_]/g, '-');
1222
+
1223
+ // Check if project already exists in config
1224
+ const config = await loadProjectConfig();
1225
+ const projectDir = path.join(os.homedir(), '.claude', 'projects', projectName);
1226
+
1227
+ if (config[projectName]) {
1228
+ throw new Error(`Project already configured for path: ${absolutePath}`);
1229
+ }
1230
+
1231
+ // Allow adding projects even if the directory exists - this enables tracking
1232
+ // existing AI assistant projects (Claude, Cursor, Codex, etc.) in the UI
1233
+
1234
+ // Add to config as manually added project
1235
+ config[projectName] = {
1236
+ manuallyAdded: true,
1237
+ originalPath: absolutePath
1238
+ };
1239
+
1240
+ if (displayName) {
1241
+ config[projectName].displayName = displayName;
1242
+ }
1243
+
1244
+ await saveProjectConfig(config);
1245
+
1246
+
1247
+ return {
1248
+ name: projectName,
1249
+ path: absolutePath,
1250
+ fullPath: absolutePath,
1251
+ displayName: displayName || await generateDisplayName(projectName, absolutePath),
1252
+ isManuallyAdded: true,
1253
+ sessions: [],
1254
+ cursorSessions: []
1255
+ };
1256
+ }
1257
+
1258
+ // Fetch Cursor sessions for a given project path
1259
+ async function getCursorSessions(projectPath) {
1260
+ try {
1261
+ // Calculate cwdID hash for the project path (Cursor uses MD5 hash)
1262
+ const cwdId = crypto.createHash('md5').update(projectPath).digest('hex');
1263
+ const cursorChatsPath = path.join(os.homedir(), '.cursor', 'chats', cwdId);
1264
+
1265
+ // Check if the directory exists
1266
+ try {
1267
+ await fs.access(cursorChatsPath);
1268
+ } catch (error) {
1269
+ // No sessions for this project
1270
+ return [];
1271
+ }
1272
+
1273
+ // List all session directories
1274
+ const sessionDirs = await fs.readdir(cursorChatsPath);
1275
+ const sessions = [];
1276
+
1277
+ for (const sessionId of sessionDirs) {
1278
+ const sessionPath = path.join(cursorChatsPath, sessionId);
1279
+ const storeDbPath = path.join(sessionPath, 'store.db');
1280
+
1281
+ try {
1282
+ // Check if store.db exists
1283
+ await fs.access(storeDbPath);
1284
+
1285
+ // Capture store.db mtime as a reliable fallback timestamp
1286
+ let dbStatMtimeMs = null;
1287
+ try {
1288
+ const stat = await fs.stat(storeDbPath);
1289
+ dbStatMtimeMs = stat.mtimeMs;
1290
+ } catch (_) {}
1291
+
1292
+ // Open SQLite database (requires native sqlite3 module)
1293
+ if (!sqliteOpen || !sqlite3) {
1294
+ continue; // Skip on Vercel where native modules aren't available
1295
+ }
1296
+ const db = await sqliteOpen({
1297
+ filename: storeDbPath,
1298
+ driver: sqlite3.Database,
1299
+ mode: sqlite3.OPEN_READONLY
1300
+ });
1301
+
1302
+ // Get metadata from meta table
1303
+ const metaRows = await db.all(`
1304
+ SELECT key, value FROM meta
1305
+ `);
1306
+
1307
+ // Parse metadata
1308
+ let metadata = {};
1309
+ for (const row of metaRows) {
1310
+ if (row.value) {
1311
+ try {
1312
+ // Try to decode as hex-encoded JSON
1313
+ const hexMatch = row.value.toString().match(/^[0-9a-fA-F]+$/);
1314
+ if (hexMatch) {
1315
+ const jsonStr = Buffer.from(row.value, 'hex').toString('utf8');
1316
+ metadata[row.key] = JSON.parse(jsonStr);
1317
+ } else {
1318
+ metadata[row.key] = row.value.toString();
1319
+ }
1320
+ } catch (e) {
1321
+ metadata[row.key] = row.value.toString();
1322
+ }
1323
+ }
1324
+ }
1325
+
1326
+ // Get message count
1327
+ const messageCountResult = await db.get(`
1328
+ SELECT COUNT(*) as count FROM blobs
1329
+ `);
1330
+
1331
+ await db.close();
1332
+
1333
+ // Extract session info
1334
+ const sessionName = metadata.title || metadata.sessionTitle || 'Untitled Session';
1335
+
1336
+ // Determine timestamp - prefer createdAt from metadata, fall back to db file mtime
1337
+ let createdAt = null;
1338
+ if (metadata.createdAt) {
1339
+ createdAt = new Date(metadata.createdAt).toISOString();
1340
+ } else if (dbStatMtimeMs) {
1341
+ createdAt = new Date(dbStatMtimeMs).toISOString();
1342
+ } else {
1343
+ createdAt = new Date().toISOString();
1344
+ }
1345
+
1346
+ sessions.push({
1347
+ id: sessionId,
1348
+ name: sessionName,
1349
+ createdAt: createdAt,
1350
+ lastActivity: createdAt, // For compatibility with Claude sessions
1351
+ messageCount: messageCountResult.count || 0,
1352
+ projectPath: projectPath
1353
+ });
1354
+
1355
+ } catch (error) {
1356
+ console.warn(`Could not read Cursor session ${sessionId}:`, error.message);
1357
+ }
1358
+ }
1359
+
1360
+ // Sort sessions by creation time (newest first)
1361
+ sessions.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt));
1362
+
1363
+ // Return only the first 5 sessions for performance
1364
+ return sessions.slice(0, 5);
1365
+
1366
+ } catch (error) {
1367
+ console.error('Error fetching Cursor sessions:', error);
1368
+ return [];
1369
+ }
1370
+ }
1371
+
1372
+
1373
+ function normalizeComparablePath(inputPath) {
1374
+ if (!inputPath || typeof inputPath !== 'string') {
1375
+ return '';
1376
+ }
1377
+
1378
+ const withoutLongPathPrefix = inputPath.startsWith('\\\\?\\')
1379
+ ? inputPath.slice(4)
1380
+ : inputPath;
1381
+ const normalized = path.normalize(withoutLongPathPrefix.trim());
1382
+
1383
+ if (!normalized) {
1384
+ return '';
1385
+ }
1386
+
1387
+ const resolved = path.resolve(normalized);
1388
+ return process.platform === 'win32' ? resolved.toLowerCase() : resolved;
1389
+ }
1390
+
1391
+ async function findCodexJsonlFiles(dir) {
1392
+ const files = [];
1393
+
1394
+ try {
1395
+ const entries = await fs.readdir(dir, { withFileTypes: true });
1396
+ for (const entry of entries) {
1397
+ const fullPath = path.join(dir, entry.name);
1398
+ if (entry.isDirectory()) {
1399
+ files.push(...await findCodexJsonlFiles(fullPath));
1400
+ } else if (entry.name.endsWith('.jsonl')) {
1401
+ files.push(fullPath);
1402
+ }
1403
+ }
1404
+ } catch (error) {
1405
+ // Skip directories we can't read
1406
+ }
1407
+
1408
+ return files;
1409
+ }
1410
+
1411
+ async function buildCodexSessionsIndex() {
1412
+ const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
1413
+ const sessionsByProject = new Map();
1414
+
1415
+ try {
1416
+ await fs.access(codexSessionsDir);
1417
+ } catch (error) {
1418
+ return sessionsByProject;
1419
+ }
1420
+
1421
+ const jsonlFiles = await findCodexJsonlFiles(codexSessionsDir);
1422
+
1423
+ for (const filePath of jsonlFiles) {
1424
+ try {
1425
+ const sessionData = await parseCodexSessionFile(filePath);
1426
+ if (!sessionData || !sessionData.id) {
1427
+ continue;
1428
+ }
1429
+
1430
+ const normalizedProjectPath = normalizeComparablePath(sessionData.cwd);
1431
+ if (!normalizedProjectPath) {
1432
+ continue;
1433
+ }
1434
+
1435
+ const session = {
1436
+ id: sessionData.id,
1437
+ summary: sessionData.summary || 'Codex Session',
1438
+ messageCount: sessionData.messageCount || 0,
1439
+ lastActivity: sessionData.timestamp ? new Date(sessionData.timestamp) : new Date(),
1440
+ cwd: sessionData.cwd,
1441
+ model: sessionData.model,
1442
+ filePath,
1443
+ provider: 'codex',
1444
+ };
1445
+
1446
+ if (!sessionsByProject.has(normalizedProjectPath)) {
1447
+ sessionsByProject.set(normalizedProjectPath, []);
1448
+ }
1449
+
1450
+ sessionsByProject.get(normalizedProjectPath).push(session);
1451
+ } catch (error) {
1452
+ console.warn(`Could not parse Codex session file ${filePath}:`, error.message);
1453
+ }
1454
+ }
1455
+
1456
+ for (const sessions of sessionsByProject.values()) {
1457
+ sessions.sort((a, b) => new Date(b.lastActivity) - new Date(a.lastActivity));
1458
+ }
1459
+
1460
+ return sessionsByProject;
1461
+ }
1462
+
1463
+ // Fetch Codex sessions for a given project path
1464
+ async function getCodexSessions(projectPath, options = {}) {
1465
+ const { limit = 5, indexRef = null } = options;
1466
+ try {
1467
+ const normalizedProjectPath = normalizeComparablePath(projectPath);
1468
+ if (!normalizedProjectPath) {
1469
+ return [];
1470
+ }
1471
+
1472
+ if (indexRef && !indexRef.sessionsByProject) {
1473
+ indexRef.sessionsByProject = await buildCodexSessionsIndex();
1474
+ }
1475
+
1476
+ const sessionsByProject = indexRef?.sessionsByProject || await buildCodexSessionsIndex();
1477
+ const sessions = sessionsByProject.get(normalizedProjectPath) || [];
1478
+
1479
+ // Return limited sessions for performance (0 = unlimited for deletion)
1480
+ return limit > 0 ? sessions.slice(0, limit) : [...sessions];
1481
+
1482
+ } catch (error) {
1483
+ console.error('Error fetching Codex sessions:', error);
1484
+ return [];
1485
+ }
1486
+ }
1487
+
1488
+ // Parse a Codex session JSONL file to extract metadata
1489
+ async function parseCodexSessionFile(filePath) {
1490
+ try {
1491
+ const fileStream = fsSync.createReadStream(filePath);
1492
+ const rl = readline.createInterface({
1493
+ input: fileStream,
1494
+ crlfDelay: Infinity
1495
+ });
1496
+
1497
+ let sessionMeta = null;
1498
+ let lastTimestamp = null;
1499
+ let lastUserMessage = null;
1500
+ let messageCount = 0;
1501
+
1502
+ for await (const line of rl) {
1503
+ if (line.trim()) {
1504
+ try {
1505
+ const entry = JSON.parse(line);
1506
+
1507
+ // Track timestamp
1508
+ if (entry.timestamp) {
1509
+ lastTimestamp = entry.timestamp;
1510
+ }
1511
+
1512
+ // Extract session metadata
1513
+ if (entry.type === 'session_meta' && entry.payload) {
1514
+ sessionMeta = {
1515
+ id: entry.payload.id,
1516
+ cwd: entry.payload.cwd,
1517
+ model: entry.payload.model || entry.payload.model_provider,
1518
+ timestamp: entry.timestamp,
1519
+ git: entry.payload.git
1520
+ };
1521
+ }
1522
+
1523
+ // Count messages and extract user messages for summary
1524
+ if (entry.type === 'event_msg' && entry.payload?.type === 'user_message') {
1525
+ messageCount++;
1526
+ if (entry.payload.message) {
1527
+ lastUserMessage = entry.payload.message;
1528
+ }
1529
+ }
1530
+
1531
+ if (entry.type === 'response_item' && entry.payload?.type === 'message' && entry.payload.role === 'assistant') {
1532
+ messageCount++;
1533
+ }
1534
+
1535
+ } catch (parseError) {
1536
+ // Skip malformed lines
1537
+ }
1538
+ }
1539
+ }
1540
+
1541
+ if (sessionMeta) {
1542
+ return {
1543
+ ...sessionMeta,
1544
+ timestamp: lastTimestamp || sessionMeta.timestamp,
1545
+ summary: lastUserMessage ?
1546
+ (lastUserMessage.length > 50 ? lastUserMessage.substring(0, 50) + '...' : lastUserMessage) :
1547
+ 'Codex Session',
1548
+ messageCount
1549
+ };
1550
+ }
1551
+
1552
+ return null;
1553
+
1554
+ } catch (error) {
1555
+ console.error('Error parsing Codex session file:', error);
1556
+ return null;
1557
+ }
1558
+ }
1559
+
1560
+ // Get messages for a specific Codex session
1561
+ async function getCodexSessionMessages(sessionId, limit = null, offset = 0) {
1562
+ try {
1563
+ const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
1564
+
1565
+ // Find the session file by searching for the session ID
1566
+ const findSessionFile = async (dir) => {
1567
+ try {
1568
+ const entries = await fs.readdir(dir, { withFileTypes: true });
1569
+ for (const entry of entries) {
1570
+ const fullPath = path.join(dir, entry.name);
1571
+ if (entry.isDirectory()) {
1572
+ const found = await findSessionFile(fullPath);
1573
+ if (found) return found;
1574
+ } else if (entry.name.includes(sessionId) && entry.name.endsWith('.jsonl')) {
1575
+ return fullPath;
1576
+ }
1577
+ }
1578
+ } catch (error) {
1579
+ // Skip directories we can't read
1580
+ }
1581
+ return null;
1582
+ };
1583
+
1584
+ const sessionFilePath = await findSessionFile(codexSessionsDir);
1585
+
1586
+ if (!sessionFilePath) {
1587
+ console.warn(`Codex session file not found for session ${sessionId}`);
1588
+ return { messages: [], total: 0, hasMore: false };
1589
+ }
1590
+
1591
+ const messages = [];
1592
+ let tokenUsage = null;
1593
+ const fileStream = fsSync.createReadStream(sessionFilePath);
1594
+ const rl = readline.createInterface({
1595
+ input: fileStream,
1596
+ crlfDelay: Infinity
1597
+ });
1598
+
1599
+ // Helper to extract text from Codex content array
1600
+ const extractText = (content) => {
1601
+ if (!Array.isArray(content)) return content;
1602
+ return content
1603
+ .map(item => {
1604
+ if (item.type === 'input_text' || item.type === 'output_text') {
1605
+ return item.text;
1606
+ }
1607
+ if (item.type === 'text') {
1608
+ return item.text;
1609
+ }
1610
+ return '';
1611
+ })
1612
+ .filter(Boolean)
1613
+ .join('\n');
1614
+ };
1615
+
1616
+ for await (const line of rl) {
1617
+ if (line.trim()) {
1618
+ try {
1619
+ const entry = JSON.parse(line);
1620
+
1621
+ // Extract token usage from token_count events (keep latest)
1622
+ if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload?.info) {
1623
+ const info = entry.payload.info;
1624
+ if (info.total_token_usage) {
1625
+ tokenUsage = {
1626
+ used: info.total_token_usage.total_tokens || 0,
1627
+ total: info.model_context_window || 200000
1628
+ };
1629
+ }
1630
+ }
1631
+
1632
+ // Extract messages from response_item
1633
+ if (entry.type === 'response_item' && entry.payload?.type === 'message') {
1634
+ const content = entry.payload.content;
1635
+ const role = entry.payload.role || 'assistant';
1636
+ const textContent = extractText(content);
1637
+
1638
+ // Skip system context messages (environment_context)
1639
+ if (textContent?.includes('<environment_context>')) {
1640
+ continue;
1641
+ }
1642
+
1643
+ // Only add if there's actual content
1644
+ if (textContent?.trim()) {
1645
+ messages.push({
1646
+ type: role === 'user' ? 'user' : 'assistant',
1647
+ timestamp: entry.timestamp,
1648
+ message: {
1649
+ role: role,
1650
+ content: textContent
1651
+ }
1652
+ });
1653
+ }
1654
+ }
1655
+
1656
+ if (entry.type === 'response_item' && entry.payload?.type === 'reasoning') {
1657
+ const summaryText = entry.payload.summary
1658
+ ?.map(s => s.text)
1659
+ .filter(Boolean)
1660
+ .join('\n');
1661
+ if (summaryText?.trim()) {
1662
+ messages.push({
1663
+ type: 'thinking',
1664
+ timestamp: entry.timestamp,
1665
+ message: {
1666
+ role: 'assistant',
1667
+ content: summaryText
1668
+ }
1669
+ });
1670
+ }
1671
+ }
1672
+
1673
+ if (entry.type === 'response_item' && entry.payload?.type === 'function_call') {
1674
+ let toolName = entry.payload.name;
1675
+ let toolInput = entry.payload.arguments;
1676
+
1677
+ // Map Codex tool names to Claude equivalents
1678
+ if (toolName === 'shell_command') {
1679
+ toolName = 'Bash';
1680
+ try {
1681
+ const args = JSON.parse(entry.payload.arguments);
1682
+ toolInput = JSON.stringify({ command: args.command });
1683
+ } catch (e) {
1684
+ // Keep original if parsing fails
1685
+ }
1686
+ }
1687
+
1688
+ messages.push({
1689
+ type: 'tool_use',
1690
+ timestamp: entry.timestamp,
1691
+ toolName: toolName,
1692
+ toolInput: toolInput,
1693
+ toolCallId: entry.payload.call_id
1694
+ });
1695
+ }
1696
+
1697
+ if (entry.type === 'response_item' && entry.payload?.type === 'function_call_output') {
1698
+ messages.push({
1699
+ type: 'tool_result',
1700
+ timestamp: entry.timestamp,
1701
+ toolCallId: entry.payload.call_id,
1702
+ output: entry.payload.output
1703
+ });
1704
+ }
1705
+
1706
+ if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call') {
1707
+ const toolName = entry.payload.name || 'custom_tool';
1708
+ const input = entry.payload.input || '';
1709
+
1710
+ if (toolName === 'apply_patch') {
1711
+ // Parse Codex patch format and convert to Claude Edit format
1712
+ const fileMatch = input.match(/\*\*\* Update File: (.+)/);
1713
+ const filePath = fileMatch ? fileMatch[1].trim() : 'unknown';
1714
+
1715
+ // Extract old and new content from patch
1716
+ const lines = input.split('\n');
1717
+ const oldLines = [];
1718
+ const newLines = [];
1719
+
1720
+ for (const line of lines) {
1721
+ if (line.startsWith('-') && !line.startsWith('---')) {
1722
+ oldLines.push(line.substring(1));
1723
+ } else if (line.startsWith('+') && !line.startsWith('+++')) {
1724
+ newLines.push(line.substring(1));
1725
+ }
1726
+ }
1727
+
1728
+ messages.push({
1729
+ type: 'tool_use',
1730
+ timestamp: entry.timestamp,
1731
+ toolName: 'Edit',
1732
+ toolInput: JSON.stringify({
1733
+ file_path: filePath,
1734
+ old_string: oldLines.join('\n'),
1735
+ new_string: newLines.join('\n')
1736
+ }),
1737
+ toolCallId: entry.payload.call_id
1738
+ });
1739
+ } else {
1740
+ messages.push({
1741
+ type: 'tool_use',
1742
+ timestamp: entry.timestamp,
1743
+ toolName: toolName,
1744
+ toolInput: input,
1745
+ toolCallId: entry.payload.call_id
1746
+ });
1747
+ }
1748
+ }
1749
+
1750
+ if (entry.type === 'response_item' && entry.payload?.type === 'custom_tool_call_output') {
1751
+ messages.push({
1752
+ type: 'tool_result',
1753
+ timestamp: entry.timestamp,
1754
+ toolCallId: entry.payload.call_id,
1755
+ output: entry.payload.output || ''
1756
+ });
1757
+ }
1758
+
1759
+ } catch (parseError) {
1760
+ // Skip malformed lines
1761
+ }
1762
+ }
1763
+ }
1764
+
1765
+ // Sort by timestamp
1766
+ messages.sort((a, b) => new Date(a.timestamp || 0) - new Date(b.timestamp || 0));
1767
+
1768
+ const total = messages.length;
1769
+
1770
+ // Apply pagination if limit is specified
1771
+ if (limit !== null) {
1772
+ const startIndex = Math.max(0, total - offset - limit);
1773
+ const endIndex = total - offset;
1774
+ const paginatedMessages = messages.slice(startIndex, endIndex);
1775
+ const hasMore = startIndex > 0;
1776
+
1777
+ return {
1778
+ messages: paginatedMessages,
1779
+ total,
1780
+ hasMore,
1781
+ offset,
1782
+ limit,
1783
+ tokenUsage
1784
+ };
1785
+ }
1786
+
1787
+ return { messages, tokenUsage };
1788
+
1789
+ } catch (error) {
1790
+ console.error(`Error reading Codex session messages for ${sessionId}:`, error);
1791
+ return { messages: [], total: 0, hasMore: false };
1792
+ }
1793
+ }
1794
+
1795
+ async function deleteCodexSession(sessionId) {
1796
+ try {
1797
+ const codexSessionsDir = path.join(os.homedir(), '.codex', 'sessions');
1798
+
1799
+ const findJsonlFiles = async (dir) => {
1800
+ const files = [];
1801
+ try {
1802
+ const entries = await fs.readdir(dir, { withFileTypes: true });
1803
+ for (const entry of entries) {
1804
+ const fullPath = path.join(dir, entry.name);
1805
+ if (entry.isDirectory()) {
1806
+ files.push(...await findJsonlFiles(fullPath));
1807
+ } else if (entry.name.endsWith('.jsonl')) {
1808
+ files.push(fullPath);
1809
+ }
1810
+ }
1811
+ } catch (error) {}
1812
+ return files;
1813
+ };
1814
+
1815
+ const jsonlFiles = await findJsonlFiles(codexSessionsDir);
1816
+
1817
+ for (const filePath of jsonlFiles) {
1818
+ const sessionData = await parseCodexSessionFile(filePath);
1819
+ if (sessionData && sessionData.id === sessionId) {
1820
+ await fs.unlink(filePath);
1821
+ return true;
1822
+ }
1823
+ }
1824
+
1825
+ throw new Error(`Codex session file not found for session ${sessionId}`);
1826
+ } catch (error) {
1827
+ console.error(`Error deleting Codex session ${sessionId}:`, error);
1828
+ throw error;
1829
+ }
1830
+ }
1831
+
1832
+ export {
1833
+ getProjects,
1834
+ getSessions,
1835
+ getSessionMessages,
1836
+ parseJsonlSessions,
1837
+ renameProject,
1838
+ deleteSession,
1839
+ isProjectEmpty,
1840
+ deleteProject,
1841
+ addProjectManually,
1842
+ loadProjectConfig,
1843
+ saveProjectConfig,
1844
+ extractProjectDirectory,
1845
+ clearProjectDirectoryCache,
1846
+ getCodexSessions,
1847
+ getCodexSessionMessages,
1848
+ deleteCodexSession
1849
+ };