@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,2325 @@
1
+ #!/usr/bin/env node
2
+ // Load environment variables before other imports execute
3
+ import './load-env.js';
4
+ import fs from 'fs';
5
+ import path from 'path';
6
+ import { findAppRoot, getModuleDir } from './utils/runtime-paths.js';
7
+ import { AppError, createNormalizedMessage } from './shared/utils.js';
8
+ const __dirname = getModuleDir(import.meta.url);
9
+ // The server source runs from /server, while the compiled output runs from /dist-server/server.
10
+ // Resolving the app root once keeps every repo-level lookup below aligned across both layouts.
11
+ const APP_ROOT = findAppRoot(__dirname);
12
+ const installMode = fs.existsSync(path.join(APP_ROOT, '.git')) ? 'git' : 'npm';
13
+ const DAEMON_COMMAND_CONTEXT = {
14
+ appRoot: APP_ROOT,
15
+ cliEntry: path.join(APP_ROOT, 'server', 'cli.js'),
16
+ nodeExecPath: process.execPath,
17
+ };
18
+ import { c } from './utils/colors.js';
19
+ console.log('SERVER_PORT from env:', process.env.SERVER_PORT);
20
+ import express from 'express';
21
+ import { WebSocketServer, WebSocket } from 'ws';
22
+ import os from 'os';
23
+ import http from 'http';
24
+ import net from 'node:net';
25
+ import cors from 'cors';
26
+ import { promises as fsPromises } from 'fs';
27
+ import { spawn } from 'child_process';
28
+ import pty from 'node-pty';
29
+ import mime from 'mime-types';
30
+ import { getProjects, getSessions, renameProject, deleteSession, deleteProject, extractProjectDirectory, clearProjectDirectoryCache, searchConversations } from './projects.js';
31
+ import { queryClaudeSDK, abortClaudeSDKSession, isClaudeSDKSessionActive, getActiveClaudeSDKSessions, resolveToolApproval, getPendingApprovalsForSession, reconnectSessionWriter } from './claude-sdk.js';
32
+ import { spawnCursor, abortCursorSession, isCursorSessionActive, getActiveCursorSessions } from './cursor-cli.js';
33
+ import { queryCodex, abortCodexSession, isCodexSessionActive, getActiveCodexSessions } from './openai-codex.js';
34
+ import { spawnGemini, abortGeminiSession, isGeminiSessionActive, getActiveGeminiSessions } from './gemini-cli.js';
35
+ import sessionManager from './sessionManager.js';
36
+ import gitRoutes from './routes/git.js';
37
+ import authRoutes from './routes/auth.js';
38
+ import cursorRoutes from './routes/cursor.js';
39
+ import taskmasterRoutes from './routes/taskmaster.js';
40
+ import mcpUtilsRoutes from './routes/mcp-utils.js';
41
+ import commandsRoutes from './routes/commands.js';
42
+ import settingsRoutes from './routes/settings.js';
43
+ import agentRoutes from './routes/agent.js';
44
+ import projectsRoutes, { WORKSPACES_ROOT, WORKSPACES_BASE, validateWorkspacePath, normalizeWorkspacePath, } from './routes/projects.js';
45
+ import cliAuthRoutes from './routes/cli-auth.js';
46
+ import userRoutes from './routes/user.js';
47
+ import codexRoutes from './routes/codex.js';
48
+ import geminiRoutes from './routes/gemini.js';
49
+ import pluginsRoutes from './routes/plugins.js';
50
+ import messagesRoutes from './routes/messages.js';
51
+ import providerRoutes from './modules/providers/provider.routes.js';
52
+ import { startEnabledPluginServers, stopAllPlugins, getPluginPort } from './utils/plugin-process-manager.js';
53
+ import { initializeDatabase, sessionNamesDb, applyCustomSessionNames } from './database/db.js';
54
+ import { configureWebPush } from './services/vapid-keys.js';
55
+ import { validateApiKey, authenticateToken, authenticateWebSocket } from './middleware/auth.js';
56
+ import { IS_PLATFORM } from './constants/config.js';
57
+ import { getConnectableHost } from '../shared/networkHosts.js';
58
+ import { buildDaemonCliCommand, handleDaemonCommand } from './daemon-manager.js';
59
+ const VALID_PROVIDERS = ['claude', 'codex', 'cursor', 'gemini'];
60
+ // File system watchers for provider project/session folders
61
+ const PROVIDER_WATCH_PATHS = [
62
+ { provider: 'claude', rootPath: path.join(os.homedir(), '.claude', 'projects') },
63
+ { provider: 'cursor', rootPath: path.join(os.homedir(), '.cursor', 'chats') },
64
+ { provider: 'codex', rootPath: path.join(os.homedir(), '.codex', 'sessions') },
65
+ { provider: 'gemini', rootPath: path.join(os.homedir(), '.gemini', 'projects') },
66
+ { provider: 'gemini_sessions', rootPath: path.join(os.homedir(), '.gemini', 'sessions') },
67
+ { provider: 'gemini_cli', rootPath: path.join(os.homedir(), '.gemini', 'tmp') },
68
+ ];
69
+ const WATCHER_IGNORED_PATTERNS = [
70
+ '**/node_modules/**',
71
+ '**/.git/**',
72
+ '**/dist/**',
73
+ '**/build/**',
74
+ '**/*.tmp',
75
+ '**/*.swp',
76
+ '**/.DS_Store'
77
+ ];
78
+ const WATCHER_DEBOUNCE_MS = 300;
79
+ let projectsWatchers = [];
80
+ let projectsWatcherDebounceTimer = null;
81
+ const connectedClients = new Set();
82
+ let isGetProjectsRunning = false; // Flag to prevent reentrant calls
83
+ // Broadcast progress to all connected WebSocket clients
84
+ function broadcastProgress(progress) {
85
+ const message = JSON.stringify({
86
+ type: 'loading_progress',
87
+ ...progress
88
+ });
89
+ connectedClients.forEach(client => {
90
+ if (client.readyState === WebSocket.OPEN) {
91
+ client.send(message);
92
+ }
93
+ });
94
+ }
95
+ // Setup file system watchers for Claude, Cursor, and Codex project/session folders
96
+ async function setupProjectsWatcher() {
97
+ const chokidar = (await import('chokidar')).default;
98
+ if (projectsWatcherDebounceTimer) {
99
+ clearTimeout(projectsWatcherDebounceTimer);
100
+ projectsWatcherDebounceTimer = null;
101
+ }
102
+ await Promise.all(projectsWatchers.map(async (watcher) => {
103
+ try {
104
+ await watcher.close();
105
+ }
106
+ catch (error) {
107
+ console.error('[WARN] Failed to close watcher:', error);
108
+ }
109
+ }));
110
+ projectsWatchers = [];
111
+ const debouncedUpdate = (eventType, filePath, provider, rootPath) => {
112
+ if (projectsWatcherDebounceTimer) {
113
+ clearTimeout(projectsWatcherDebounceTimer);
114
+ }
115
+ projectsWatcherDebounceTimer = setTimeout(async () => {
116
+ // Prevent reentrant calls
117
+ if (isGetProjectsRunning) {
118
+ return;
119
+ }
120
+ try {
121
+ isGetProjectsRunning = true;
122
+ // Clear project directory cache when files change
123
+ clearProjectDirectoryCache();
124
+ // Get updated projects list
125
+ const updatedProjects = await getProjects(broadcastProgress);
126
+ // Notify all connected clients about the project changes
127
+ const updateMessage = JSON.stringify({
128
+ type: 'projects_updated',
129
+ projects: updatedProjects,
130
+ timestamp: new Date().toISOString(),
131
+ changeType: eventType,
132
+ changedFile: path.relative(rootPath, filePath),
133
+ watchProvider: provider
134
+ });
135
+ connectedClients.forEach(client => {
136
+ if (client.readyState === WebSocket.OPEN) {
137
+ client.send(updateMessage);
138
+ }
139
+ });
140
+ }
141
+ catch (error) {
142
+ console.error('[ERROR] Error handling project changes:', error);
143
+ }
144
+ finally {
145
+ isGetProjectsRunning = false;
146
+ }
147
+ }, WATCHER_DEBOUNCE_MS);
148
+ };
149
+ for (const { provider, rootPath } of PROVIDER_WATCH_PATHS) {
150
+ try {
151
+ // chokidar v4 emits ENOENT via the "error" event for missing roots and will not auto-recover.
152
+ // Ensure provider folders exist before creating the watcher so watching stays active.
153
+ await fsPromises.mkdir(rootPath, { recursive: true });
154
+ // Initialize chokidar watcher with optimized settings
155
+ const watcher = chokidar.watch(rootPath, {
156
+ ignored: WATCHER_IGNORED_PATTERNS,
157
+ persistent: true,
158
+ ignoreInitial: true, // Don't fire events for existing files on startup
159
+ followSymlinks: false,
160
+ depth: 10, // Reasonable depth limit
161
+ awaitWriteFinish: {
162
+ stabilityThreshold: 100, // Wait 100ms for file to stabilize
163
+ pollInterval: 50
164
+ }
165
+ });
166
+ // Set up event listeners
167
+ watcher
168
+ .on('add', (filePath) => debouncedUpdate('add', filePath, provider, rootPath))
169
+ .on('change', (filePath) => debouncedUpdate('change', filePath, provider, rootPath))
170
+ .on('unlink', (filePath) => debouncedUpdate('unlink', filePath, provider, rootPath))
171
+ .on('addDir', (dirPath) => debouncedUpdate('addDir', dirPath, provider, rootPath))
172
+ .on('unlinkDir', (dirPath) => debouncedUpdate('unlinkDir', dirPath, provider, rootPath))
173
+ .on('error', (error) => {
174
+ console.error(`[ERROR] ${provider} watcher error:`, error);
175
+ })
176
+ .on('ready', () => {
177
+ });
178
+ projectsWatchers.push(watcher);
179
+ }
180
+ catch (error) {
181
+ console.error(`[ERROR] Failed to setup ${provider} watcher for ${rootPath}:`, error);
182
+ }
183
+ }
184
+ if (projectsWatchers.length === 0) {
185
+ console.error('[ERROR] Failed to setup any provider watchers');
186
+ }
187
+ }
188
+ const app = express();
189
+ const server = http.createServer(app);
190
+ const ptySessionsMap = new Map();
191
+ const PTY_SESSION_TIMEOUT = 30 * 60 * 1000;
192
+ const SHELL_URL_PARSE_BUFFER_LIMIT = 32768;
193
+ import { stripAnsiSequences, normalizeDetectedUrl, extractUrlsFromText, shouldAutoOpenUrlFromOutput } from './utils/url-detection.js';
194
+ // Single WebSocket server that handles both paths
195
+ const wss = new WebSocketServer({
196
+ server,
197
+ verifyClient: (info) => {
198
+ console.log('WebSocket connection attempt to:', info.req.url);
199
+ // Platform mode: always allow connection
200
+ if (IS_PLATFORM) {
201
+ const user = authenticateWebSocket(null); // Will return first user
202
+ if (!user) {
203
+ console.log('[WARN] Platform mode: No user found in database');
204
+ return false;
205
+ }
206
+ info.req.user = user;
207
+ console.log('[OK] Platform mode WebSocket authenticated for user:', user.username);
208
+ return true;
209
+ }
210
+ // Normal mode: verify token
211
+ // Extract token from query parameters or headers
212
+ const url = new URL(info.req.url, 'http://localhost');
213
+ const token = url.searchParams.get('token') ||
214
+ info.req.headers.authorization?.split(' ')[1];
215
+ // Verify token
216
+ const user = authenticateWebSocket(token);
217
+ if (!user) {
218
+ console.log('[WARN] WebSocket authentication failed');
219
+ return false;
220
+ }
221
+ // Store user info in the request for later use
222
+ info.req.user = user;
223
+ console.log('[OK] WebSocket authenticated for user:', user.username);
224
+ return true;
225
+ }
226
+ });
227
+ // Make WebSocket server available to routes
228
+ app.locals.wss = wss;
229
+ app.use(cors({ exposedHeaders: ['X-Refreshed-Token'] }));
230
+ app.use(express.json({
231
+ limit: '50mb',
232
+ type: (req) => {
233
+ // Skip multipart/form-data requests (for file uploads like images)
234
+ const contentType = req.headers['content-type'] || '';
235
+ if (contentType.includes('multipart/form-data')) {
236
+ return false;
237
+ }
238
+ return contentType.includes('json');
239
+ }
240
+ }));
241
+ app.use(express.urlencoded({ limit: '50mb', extended: true }));
242
+ // Public health check endpoint (no authentication required)
243
+ app.get('/health', (req, res) => {
244
+ res.json({
245
+ status: 'ok',
246
+ timestamp: new Date().toISOString(),
247
+ installMode
248
+ });
249
+ });
250
+ // Optional API key validation (if configured)
251
+ app.use('/api', validateApiKey);
252
+ // Authentication routes (public)
253
+ app.use('/api/auth', authRoutes);
254
+ // Projects API Routes (protected)
255
+ app.use('/api/projects', authenticateToken, projectsRoutes);
256
+ // Git API Routes (protected)
257
+ app.use('/api/git', authenticateToken, gitRoutes);
258
+ // Cursor API Routes (protected)
259
+ app.use('/api/cursor', authenticateToken, cursorRoutes);
260
+ // TaskMaster API Routes (protected)
261
+ app.use('/api/taskmaster', authenticateToken, taskmasterRoutes);
262
+ // MCP utilities
263
+ app.use('/api/mcp-utils', authenticateToken, mcpUtilsRoutes);
264
+ // Commands API Routes (protected)
265
+ app.use('/api/commands', authenticateToken, commandsRoutes);
266
+ // Settings API Routes (protected)
267
+ app.use('/api/settings', authenticateToken, settingsRoutes);
268
+ // User API Routes (protected)
269
+ app.use('/api/user', authenticateToken, userRoutes);
270
+ // Codex API Routes (protected)
271
+ app.use('/api/codex', authenticateToken, codexRoutes);
272
+ // Gemini API Routes (protected)
273
+ app.use('/api/gemini', authenticateToken, geminiRoutes);
274
+ // Plugins API Routes (protected)
275
+ app.use('/api/plugins', authenticateToken, pluginsRoutes);
276
+ // Unified session messages route (protected)
277
+ app.use('/api/sessions', authenticateToken, messagesRoutes);
278
+ // Unified provider MCP routes (protected)
279
+ app.use('/api/providers', authenticateToken, providerRoutes);
280
+ // Agent API Routes (uses API key authentication)
281
+ app.use('/api/agent', agentRoutes);
282
+ // Serve public files (like api-docs.html)
283
+ app.use(express.static(path.join(APP_ROOT, 'public')));
284
+ // Static files served after API routes
285
+ // Add cache control: HTML files should not be cached, but assets can be cached
286
+ app.use(express.static(path.join(APP_ROOT, 'dist'), {
287
+ setHeaders: (res, filePath) => {
288
+ if (filePath.endsWith('.html')) {
289
+ // Prevent HTML caching to avoid service worker issues after builds
290
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
291
+ res.setHeader('Pragma', 'no-cache');
292
+ res.setHeader('Expires', '0');
293
+ }
294
+ else if (filePath.match(/\.(js|css|woff2?|ttf|eot|svg|png|jpg|jpeg|gif|ico)$/)) {
295
+ // Cache static assets for 1 year (they have hashed names)
296
+ res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
297
+ }
298
+ }
299
+ }));
300
+ // API Routes (protected)
301
+ // /api/config endpoint removed - no longer needed
302
+ // Frontend now uses window.location for WebSocket URLs
303
+ // System update endpoint
304
+ app.post('/api/system/update', authenticateToken, async (req, res) => {
305
+ try {
306
+ // Get the project root directory (parent of server directory)
307
+ const projectRoot = APP_ROOT;
308
+ console.log('Starting system update from directory:', projectRoot);
309
+ // Platform deployments use their own update workflow from the project root.
310
+ const updateCommand = IS_PLATFORM
311
+ // In platform, husky and dev dependencies are not needed
312
+ ? 'npm run update:platform'
313
+ : installMode === 'git'
314
+ ? 'git checkout main && git pull && npm install'
315
+ : 'npm install -g @pixelbyte-software/pixcode@latest';
316
+ const updateCwd = IS_PLATFORM || installMode === 'git'
317
+ ? projectRoot
318
+ : os.homedir();
319
+ const child = spawn('sh', ['-c', updateCommand], {
320
+ cwd: updateCwd,
321
+ env: process.env
322
+ });
323
+ let output = '';
324
+ let errorOutput = '';
325
+ child.stdout.on('data', (data) => {
326
+ const text = data.toString();
327
+ output += text;
328
+ console.log('Update output:', text);
329
+ });
330
+ child.stderr.on('data', (data) => {
331
+ const text = data.toString();
332
+ errorOutput += text;
333
+ console.error('Update error:', text);
334
+ });
335
+ child.on('close', (code) => {
336
+ if (code === 0) {
337
+ res.json({
338
+ success: true,
339
+ output: output || 'Update completed successfully',
340
+ message: 'Update completed. Please restart the server to apply changes.'
341
+ });
342
+ }
343
+ else {
344
+ res.status(500).json({
345
+ success: false,
346
+ error: 'Update command failed',
347
+ output: output,
348
+ errorOutput: errorOutput
349
+ });
350
+ }
351
+ });
352
+ child.on('error', (error) => {
353
+ console.error('Update process error:', error);
354
+ res.status(500).json({
355
+ success: false,
356
+ error: error.message
357
+ });
358
+ });
359
+ }
360
+ catch (error) {
361
+ console.error('System update error:', error);
362
+ res.status(500).json({
363
+ success: false,
364
+ error: error.message
365
+ });
366
+ }
367
+ });
368
+ app.get('/api/projects', authenticateToken, async (req, res) => {
369
+ try {
370
+ const projects = await getProjects(broadcastProgress);
371
+ res.json(projects);
372
+ }
373
+ catch (error) {
374
+ res.status(500).json({ error: error.message });
375
+ }
376
+ });
377
+ app.get('/api/projects/:projectName/sessions', authenticateToken, async (req, res) => {
378
+ try {
379
+ const { limit = 5, offset = 0 } = req.query;
380
+ const result = await getSessions(req.params.projectName, parseInt(limit), parseInt(offset));
381
+ applyCustomSessionNames(result.sessions, 'claude');
382
+ res.json(result);
383
+ }
384
+ catch (error) {
385
+ res.status(500).json({ error: error.message });
386
+ }
387
+ });
388
+ // Rename project endpoint
389
+ app.put('/api/projects/:projectName/rename', authenticateToken, async (req, res) => {
390
+ try {
391
+ const { displayName } = req.body;
392
+ await renameProject(req.params.projectName, displayName);
393
+ res.json({ success: true });
394
+ }
395
+ catch (error) {
396
+ res.status(500).json({ error: error.message });
397
+ }
398
+ });
399
+ // Delete session endpoint
400
+ app.delete('/api/projects/:projectName/sessions/:sessionId', authenticateToken, async (req, res) => {
401
+ try {
402
+ const { projectName, sessionId } = req.params;
403
+ console.log(`[API] Deleting session: ${sessionId} from project: ${projectName}`);
404
+ await deleteSession(projectName, sessionId);
405
+ sessionNamesDb.deleteName(sessionId, 'claude');
406
+ console.log(`[API] Session ${sessionId} deleted successfully`);
407
+ res.json({ success: true });
408
+ }
409
+ catch (error) {
410
+ console.error(`[API] Error deleting session ${req.params.sessionId}:`, error);
411
+ res.status(500).json({ error: error.message });
412
+ }
413
+ });
414
+ // Rename session endpoint
415
+ app.put('/api/sessions/:sessionId/rename', authenticateToken, async (req, res) => {
416
+ try {
417
+ const { sessionId } = req.params;
418
+ const safeSessionId = String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '');
419
+ if (!safeSessionId || safeSessionId !== String(sessionId)) {
420
+ return res.status(400).json({ error: 'Invalid sessionId' });
421
+ }
422
+ const { summary, provider } = req.body;
423
+ if (!summary || typeof summary !== 'string' || summary.trim() === '') {
424
+ return res.status(400).json({ error: 'Summary is required' });
425
+ }
426
+ if (summary.trim().length > 500) {
427
+ return res.status(400).json({ error: 'Summary must not exceed 500 characters' });
428
+ }
429
+ if (!provider || !VALID_PROVIDERS.includes(provider)) {
430
+ return res.status(400).json({ error: `Provider must be one of: ${VALID_PROVIDERS.join(', ')}` });
431
+ }
432
+ sessionNamesDb.setName(safeSessionId, provider, summary.trim());
433
+ res.json({ success: true });
434
+ }
435
+ catch (error) {
436
+ console.error(`[API] Error renaming session ${req.params.sessionId}:`, error);
437
+ res.status(500).json({ error: error.message });
438
+ }
439
+ });
440
+ // Delete project endpoint
441
+ // force=true to allow removal even when sessions exist
442
+ // deleteData=true to also delete session/memory files on disk (destructive)
443
+ app.delete('/api/projects/:projectName', authenticateToken, async (req, res) => {
444
+ try {
445
+ const { projectName } = req.params;
446
+ const force = req.query.force === 'true';
447
+ const deleteData = req.query.deleteData === 'true';
448
+ await deleteProject(projectName, force, deleteData);
449
+ res.json({ success: true });
450
+ }
451
+ catch (error) {
452
+ res.status(500).json({ error: error.message });
453
+ }
454
+ });
455
+ // Search conversations content (SSE streaming)
456
+ app.get('/api/search/conversations', authenticateToken, async (req, res) => {
457
+ const query = typeof req.query.q === 'string' ? req.query.q.trim() : '';
458
+ const parsedLimit = Number.parseInt(String(req.query.limit), 10);
459
+ const limit = Number.isNaN(parsedLimit) ? 50 : Math.max(1, Math.min(parsedLimit, 100));
460
+ if (query.length < 2) {
461
+ return res.status(400).json({ error: 'Query must be at least 2 characters' });
462
+ }
463
+ res.writeHead(200, {
464
+ 'Content-Type': 'text/event-stream',
465
+ 'Cache-Control': 'no-cache',
466
+ 'Connection': 'keep-alive',
467
+ 'X-Accel-Buffering': 'no',
468
+ });
469
+ let closed = false;
470
+ const abortController = new AbortController();
471
+ req.on('close', () => { closed = true; abortController.abort(); });
472
+ try {
473
+ await searchConversations(query, limit, ({ projectResult, totalMatches, scannedProjects, totalProjects }) => {
474
+ if (closed)
475
+ return;
476
+ if (projectResult) {
477
+ res.write(`event: result\ndata: ${JSON.stringify({ projectResult, totalMatches, scannedProjects, totalProjects })}\n\n`);
478
+ }
479
+ else {
480
+ res.write(`event: progress\ndata: ${JSON.stringify({ totalMatches, scannedProjects, totalProjects })}\n\n`);
481
+ }
482
+ }, abortController.signal);
483
+ if (!closed) {
484
+ res.write(`event: done\ndata: {}\n\n`);
485
+ }
486
+ }
487
+ catch (error) {
488
+ console.error('Error searching conversations:', error);
489
+ if (!closed) {
490
+ res.write(`event: error\ndata: ${JSON.stringify({ error: 'Search failed' })}\n\n`);
491
+ }
492
+ }
493
+ finally {
494
+ if (!closed) {
495
+ res.end();
496
+ }
497
+ }
498
+ });
499
+ const expandWorkspacePath = (inputPath) => {
500
+ if (!inputPath)
501
+ return WORKSPACES_BASE;
502
+ return normalizeWorkspacePath(inputPath);
503
+ };
504
+ // Browse filesystem endpoint for project suggestions - uses existing getFileTree
505
+ app.get('/api/browse-filesystem', authenticateToken, async (req, res) => {
506
+ try {
507
+ const { path: dirPath } = req.query;
508
+ console.log('[API] Browse filesystem request for path:', dirPath);
509
+ console.log('[API] WORKSPACES_ROOT is:', WORKSPACES_ROOT);
510
+ console.log('[API] WORKSPACES_BASE is:', WORKSPACES_BASE);
511
+ // Default to home directory if no path provided
512
+ const defaultRoot = WORKSPACES_BASE;
513
+ let targetPath = dirPath ? expandWorkspacePath(dirPath) : defaultRoot;
514
+ // Security check - ensure path is within allowed workspace root
515
+ let validation = await validateWorkspacePath(targetPath);
516
+ if (!validation.valid) {
517
+ // Keep the browser functional by returning to the safe base on invalid navigation.
518
+ const fallbackValidation = await validateWorkspacePath(defaultRoot);
519
+ if (!fallbackValidation.valid) {
520
+ return res.status(403).json({ error: validation.error });
521
+ }
522
+ validation = fallbackValidation;
523
+ }
524
+ const resolvedPath = validation.resolvedPath || targetPath;
525
+ // Security check - ensure path is accessible
526
+ try {
527
+ if (resolvedPath === defaultRoot) {
528
+ await fs.promises.mkdir(resolvedPath, { recursive: true });
529
+ }
530
+ await fs.promises.access(resolvedPath);
531
+ const stats = await fs.promises.stat(resolvedPath);
532
+ if (!stats.isDirectory()) {
533
+ return res.status(400).json({ error: 'Path is not a directory' });
534
+ }
535
+ }
536
+ catch (err) {
537
+ return res.status(404).json({ error: 'Directory not accessible' });
538
+ }
539
+ // Use existing getFileTree function with shallow depth (only direct children)
540
+ const fileTree = await getFileTree(resolvedPath, 1, 0, false); // maxDepth=1, showHidden=false
541
+ // Filter only directories and format for suggestions
542
+ const directories = fileTree
543
+ .filter(item => item.type === 'directory')
544
+ .map(item => ({
545
+ path: item.path,
546
+ name: item.name,
547
+ type: 'directory'
548
+ }))
549
+ .sort((a, b) => {
550
+ const aHidden = a.name.startsWith('.');
551
+ const bHidden = b.name.startsWith('.');
552
+ if (aHidden && !bHidden)
553
+ return 1;
554
+ if (!aHidden && bHidden)
555
+ return -1;
556
+ return a.name.localeCompare(b.name);
557
+ });
558
+ // Add common directories if browsing home directory
559
+ const suggestions = [];
560
+ let resolvedWorkspaceBase = defaultRoot;
561
+ try {
562
+ resolvedWorkspaceBase = await fsPromises.realpath(defaultRoot);
563
+ }
564
+ catch (error) {
565
+ // Use default root as-is if realpath fails
566
+ }
567
+ if (resolvedPath === resolvedWorkspaceBase) {
568
+ const commonDirs = ['Desktop', 'Documents', 'Projects', 'Development', 'Dev', 'Code', 'workspace'];
569
+ const existingCommon = directories.filter(dir => commonDirs.includes(dir.name));
570
+ const otherDirs = directories.filter(dir => !commonDirs.includes(dir.name));
571
+ suggestions.push(...existingCommon, ...otherDirs);
572
+ }
573
+ else {
574
+ suggestions.push(...directories);
575
+ }
576
+ res.json({
577
+ path: resolvedPath,
578
+ rootPath: resolvedWorkspaceBase,
579
+ suggestions: suggestions
580
+ });
581
+ }
582
+ catch (error) {
583
+ console.error('Error browsing filesystem:', error);
584
+ res.status(500).json({ error: 'Failed to browse filesystem' });
585
+ }
586
+ });
587
+ app.post('/api/create-folder', authenticateToken, async (req, res) => {
588
+ try {
589
+ const { path: folderPath } = req.body;
590
+ if (!folderPath) {
591
+ return res.status(400).json({ error: 'Path is required' });
592
+ }
593
+ const expandedPath = expandWorkspacePath(folderPath);
594
+ const resolvedInput = path.resolve(expandedPath);
595
+ const validation = await validateWorkspacePath(resolvedInput);
596
+ if (!validation.valid) {
597
+ return res.status(403).json({ error: validation.error });
598
+ }
599
+ const targetPath = validation.resolvedPath || resolvedInput;
600
+ const parentDir = path.dirname(targetPath);
601
+ try {
602
+ await fs.promises.access(parentDir);
603
+ }
604
+ catch (err) {
605
+ return res.status(404).json({ error: 'Parent directory does not exist' });
606
+ }
607
+ try {
608
+ await fs.promises.access(targetPath);
609
+ return res.status(409).json({ error: 'Folder already exists' });
610
+ }
611
+ catch (err) {
612
+ // Folder doesn't exist, which is what we want
613
+ }
614
+ try {
615
+ await fs.promises.mkdir(targetPath, { recursive: false });
616
+ res.json({ success: true, path: targetPath });
617
+ }
618
+ catch (mkdirError) {
619
+ if (mkdirError.code === 'EEXIST') {
620
+ return res.status(409).json({ error: 'Folder already exists' });
621
+ }
622
+ throw mkdirError;
623
+ }
624
+ }
625
+ catch (error) {
626
+ console.error('Error creating folder:', error);
627
+ res.status(500).json({ error: 'Failed to create folder' });
628
+ }
629
+ });
630
+ // Read file content endpoint
631
+ app.get('/api/projects/:projectName/file', authenticateToken, async (req, res) => {
632
+ try {
633
+ const { projectName } = req.params;
634
+ const { filePath } = req.query;
635
+ // Security: ensure the requested path is inside the project root
636
+ if (!filePath) {
637
+ return res.status(400).json({ error: 'Invalid file path' });
638
+ }
639
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
640
+ if (!projectRoot) {
641
+ return res.status(404).json({ error: 'Project not found' });
642
+ }
643
+ // Handle both absolute and relative paths
644
+ const resolved = path.isAbsolute(filePath)
645
+ ? path.resolve(filePath)
646
+ : path.resolve(projectRoot, filePath);
647
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
648
+ if (!resolved.startsWith(normalizedRoot)) {
649
+ return res.status(403).json({ error: 'Path must be under project root' });
650
+ }
651
+ const content = await fsPromises.readFile(resolved, 'utf8');
652
+ res.json({ content, path: resolved });
653
+ }
654
+ catch (error) {
655
+ console.error('Error reading file:', error);
656
+ if (error.code === 'ENOENT') {
657
+ res.status(404).json({ error: 'File not found' });
658
+ }
659
+ else if (error.code === 'EACCES') {
660
+ res.status(403).json({ error: 'Permission denied' });
661
+ }
662
+ else {
663
+ res.status(500).json({ error: error.message });
664
+ }
665
+ }
666
+ });
667
+ // Serve raw file bytes for previews and downloads.
668
+ app.get('/api/projects/:projectName/files/content', authenticateToken, async (req, res) => {
669
+ try {
670
+ const { projectName } = req.params;
671
+ const { path: filePath } = req.query;
672
+ // Security: ensure the requested path is inside the project root
673
+ if (!filePath) {
674
+ return res.status(400).json({ error: 'Invalid file path' });
675
+ }
676
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
677
+ if (!projectRoot) {
678
+ return res.status(404).json({ error: 'Project not found' });
679
+ }
680
+ // Match the text reader endpoint so callers can pass either project-relative
681
+ // or absolute paths without changing how the bytes are served.
682
+ const resolved = path.isAbsolute(filePath)
683
+ ? path.resolve(filePath)
684
+ : path.resolve(projectRoot, filePath);
685
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
686
+ if (!resolved.startsWith(normalizedRoot)) {
687
+ return res.status(403).json({ error: 'Path must be under project root' });
688
+ }
689
+ // Check if file exists
690
+ try {
691
+ await fsPromises.access(resolved);
692
+ }
693
+ catch (error) {
694
+ return res.status(404).json({ error: 'File not found' });
695
+ }
696
+ // Get file extension and set appropriate content type
697
+ const mimeType = mime.lookup(resolved) || 'application/octet-stream';
698
+ res.setHeader('Content-Type', mimeType);
699
+ // Stream the file
700
+ const fileStream = fs.createReadStream(resolved);
701
+ fileStream.pipe(res);
702
+ fileStream.on('error', (error) => {
703
+ console.error('Error streaming file:', error);
704
+ if (!res.headersSent) {
705
+ res.status(500).json({ error: 'Error reading file' });
706
+ }
707
+ });
708
+ }
709
+ catch (error) {
710
+ console.error('Error serving binary file:', error);
711
+ if (!res.headersSent) {
712
+ res.status(500).json({ error: error.message });
713
+ }
714
+ }
715
+ });
716
+ // Save file content endpoint
717
+ app.put('/api/projects/:projectName/file', authenticateToken, async (req, res) => {
718
+ try {
719
+ const { projectName } = req.params;
720
+ const { filePath, content } = req.body;
721
+ // Security: ensure the requested path is inside the project root
722
+ if (!filePath) {
723
+ return res.status(400).json({ error: 'Invalid file path' });
724
+ }
725
+ if (content === undefined) {
726
+ return res.status(400).json({ error: 'Content is required' });
727
+ }
728
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
729
+ if (!projectRoot) {
730
+ return res.status(404).json({ error: 'Project not found' });
731
+ }
732
+ // Handle both absolute and relative paths
733
+ const resolved = path.isAbsolute(filePath)
734
+ ? path.resolve(filePath)
735
+ : path.resolve(projectRoot, filePath);
736
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
737
+ if (!resolved.startsWith(normalizedRoot)) {
738
+ return res.status(403).json({ error: 'Path must be under project root' });
739
+ }
740
+ // Write the new content
741
+ await fsPromises.writeFile(resolved, content, 'utf8');
742
+ res.json({
743
+ success: true,
744
+ path: resolved,
745
+ message: 'File saved successfully'
746
+ });
747
+ }
748
+ catch (error) {
749
+ console.error('Error saving file:', error);
750
+ if (error.code === 'ENOENT') {
751
+ res.status(404).json({ error: 'File or directory not found' });
752
+ }
753
+ else if (error.code === 'EACCES') {
754
+ res.status(403).json({ error: 'Permission denied' });
755
+ }
756
+ else {
757
+ res.status(500).json({ error: error.message });
758
+ }
759
+ }
760
+ });
761
+ app.get('/api/projects/:projectName/files', authenticateToken, async (req, res) => {
762
+ try {
763
+ // Using fsPromises from import
764
+ // Use extractProjectDirectory to get the actual project path
765
+ let actualPath;
766
+ try {
767
+ actualPath = await extractProjectDirectory(req.params.projectName);
768
+ }
769
+ catch (error) {
770
+ console.error('Error extracting project directory:', error);
771
+ // Fallback to simple dash replacement
772
+ actualPath = req.params.projectName.replace(/-/g, '/');
773
+ }
774
+ // Check if path exists
775
+ try {
776
+ await fsPromises.access(actualPath);
777
+ }
778
+ catch (e) {
779
+ return res.status(404).json({ error: `Project path not found: ${actualPath}` });
780
+ }
781
+ const files = await getFileTree(actualPath, 10, 0, true);
782
+ res.json(files);
783
+ }
784
+ catch (error) {
785
+ console.error('[ERROR] File tree error:', error.message);
786
+ res.status(500).json({ error: error.message });
787
+ }
788
+ });
789
+ // ============================================================================
790
+ // FILE OPERATIONS API ENDPOINTS
791
+ // ============================================================================
792
+ /**
793
+ * Validate that a path is within the project root
794
+ * @param {string} projectRoot - The project root path
795
+ * @param {string} targetPath - The path to validate
796
+ * @returns {{ valid: boolean, resolved?: string, error?: string }}
797
+ */
798
+ function validatePathInProject(projectRoot, targetPath) {
799
+ const resolved = path.isAbsolute(targetPath)
800
+ ? path.resolve(targetPath)
801
+ : path.resolve(projectRoot, targetPath);
802
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
803
+ if (!resolved.startsWith(normalizedRoot)) {
804
+ return { valid: false, error: 'Path must be under project root' };
805
+ }
806
+ return { valid: true, resolved };
807
+ }
808
+ /**
809
+ * Validate filename - check for invalid characters
810
+ * @param {string} name - The filename to validate
811
+ * @returns {{ valid: boolean, error?: string }}
812
+ */
813
+ function validateFilename(name) {
814
+ if (!name || !name.trim()) {
815
+ return { valid: false, error: 'Filename cannot be empty' };
816
+ }
817
+ // Check for invalid characters (Windows + Unix)
818
+ const invalidChars = /[<>:"/\\|?*\x00-\x1f]/;
819
+ if (invalidChars.test(name)) {
820
+ return { valid: false, error: 'Filename contains invalid characters' };
821
+ }
822
+ // Check for reserved names (Windows)
823
+ const reserved = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
824
+ if (reserved.test(name)) {
825
+ return { valid: false, error: 'Filename is a reserved name' };
826
+ }
827
+ // Check for dots only
828
+ if (/^\.+$/.test(name)) {
829
+ return { valid: false, error: 'Filename cannot be only dots' };
830
+ }
831
+ return { valid: true };
832
+ }
833
+ // POST /api/projects/:projectName/files/create - Create new file or directory
834
+ app.post('/api/projects/:projectName/files/create', authenticateToken, async (req, res) => {
835
+ try {
836
+ const { projectName } = req.params;
837
+ const { path: parentPath, type, name } = req.body;
838
+ // Validate input
839
+ if (!name || !type) {
840
+ return res.status(400).json({ error: 'Name and type are required' });
841
+ }
842
+ if (!['file', 'directory'].includes(type)) {
843
+ return res.status(400).json({ error: 'Type must be "file" or "directory"' });
844
+ }
845
+ const nameValidation = validateFilename(name);
846
+ if (!nameValidation.valid) {
847
+ return res.status(400).json({ error: nameValidation.error });
848
+ }
849
+ // Get project root
850
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
851
+ if (!projectRoot) {
852
+ return res.status(404).json({ error: 'Project not found' });
853
+ }
854
+ // Build and validate target path
855
+ const targetDir = parentPath || '';
856
+ const targetPath = targetDir ? path.join(targetDir, name) : name;
857
+ const validation = validatePathInProject(projectRoot, targetPath);
858
+ if (!validation.valid) {
859
+ return res.status(403).json({ error: validation.error });
860
+ }
861
+ const resolvedPath = validation.resolved;
862
+ // Check if already exists
863
+ try {
864
+ await fsPromises.access(resolvedPath);
865
+ return res.status(409).json({ error: `${type === 'file' ? 'File' : 'Directory'} already exists` });
866
+ }
867
+ catch {
868
+ // Doesn't exist, which is what we want
869
+ }
870
+ // Create file or directory
871
+ if (type === 'directory') {
872
+ await fsPromises.mkdir(resolvedPath, { recursive: false });
873
+ }
874
+ else {
875
+ // Ensure parent directory exists
876
+ const parentDir = path.dirname(resolvedPath);
877
+ try {
878
+ await fsPromises.access(parentDir);
879
+ }
880
+ catch {
881
+ await fsPromises.mkdir(parentDir, { recursive: true });
882
+ }
883
+ await fsPromises.writeFile(resolvedPath, '', 'utf8');
884
+ }
885
+ res.json({
886
+ success: true,
887
+ path: resolvedPath,
888
+ name,
889
+ type,
890
+ message: `${type === 'file' ? 'File' : 'Directory'} created successfully`
891
+ });
892
+ }
893
+ catch (error) {
894
+ console.error('Error creating file/directory:', error);
895
+ if (error.code === 'EACCES') {
896
+ res.status(403).json({ error: 'Permission denied' });
897
+ }
898
+ else if (error.code === 'ENOENT') {
899
+ res.status(404).json({ error: 'Parent directory not found' });
900
+ }
901
+ else {
902
+ res.status(500).json({ error: error.message });
903
+ }
904
+ }
905
+ });
906
+ // PUT /api/projects/:projectName/files/rename - Rename file or directory
907
+ app.put('/api/projects/:projectName/files/rename', authenticateToken, async (req, res) => {
908
+ try {
909
+ const { projectName } = req.params;
910
+ const { oldPath, newName } = req.body;
911
+ // Validate input
912
+ if (!oldPath || !newName) {
913
+ return res.status(400).json({ error: 'oldPath and newName are required' });
914
+ }
915
+ const nameValidation = validateFilename(newName);
916
+ if (!nameValidation.valid) {
917
+ return res.status(400).json({ error: nameValidation.error });
918
+ }
919
+ // Get project root
920
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
921
+ if (!projectRoot) {
922
+ return res.status(404).json({ error: 'Project not found' });
923
+ }
924
+ // Validate old path
925
+ const oldValidation = validatePathInProject(projectRoot, oldPath);
926
+ if (!oldValidation.valid) {
927
+ return res.status(403).json({ error: oldValidation.error });
928
+ }
929
+ const resolvedOldPath = oldValidation.resolved;
930
+ // Check if old path exists
931
+ try {
932
+ await fsPromises.access(resolvedOldPath);
933
+ }
934
+ catch {
935
+ return res.status(404).json({ error: 'File or directory not found' });
936
+ }
937
+ // Build and validate new path
938
+ const parentDir = path.dirname(resolvedOldPath);
939
+ const resolvedNewPath = path.join(parentDir, newName);
940
+ const newValidation = validatePathInProject(projectRoot, resolvedNewPath);
941
+ if (!newValidation.valid) {
942
+ return res.status(403).json({ error: newValidation.error });
943
+ }
944
+ // Check if new path already exists
945
+ try {
946
+ await fsPromises.access(resolvedNewPath);
947
+ return res.status(409).json({ error: 'A file or directory with this name already exists' });
948
+ }
949
+ catch {
950
+ // Doesn't exist, which is what we want
951
+ }
952
+ // Rename
953
+ await fsPromises.rename(resolvedOldPath, resolvedNewPath);
954
+ res.json({
955
+ success: true,
956
+ oldPath: resolvedOldPath,
957
+ newPath: resolvedNewPath,
958
+ newName,
959
+ message: 'Renamed successfully'
960
+ });
961
+ }
962
+ catch (error) {
963
+ console.error('Error renaming file/directory:', error);
964
+ if (error.code === 'EACCES') {
965
+ res.status(403).json({ error: 'Permission denied' });
966
+ }
967
+ else if (error.code === 'ENOENT') {
968
+ res.status(404).json({ error: 'File or directory not found' });
969
+ }
970
+ else if (error.code === 'EXDEV') {
971
+ res.status(400).json({ error: 'Cannot move across different filesystems' });
972
+ }
973
+ else {
974
+ res.status(500).json({ error: error.message });
975
+ }
976
+ }
977
+ });
978
+ // DELETE /api/projects/:projectName/files - Delete file or directory
979
+ app.delete('/api/projects/:projectName/files', authenticateToken, async (req, res) => {
980
+ try {
981
+ const { projectName } = req.params;
982
+ const { path: targetPath, type } = req.body;
983
+ // Validate input
984
+ if (!targetPath) {
985
+ return res.status(400).json({ error: 'Path is required' });
986
+ }
987
+ // Get project root
988
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
989
+ if (!projectRoot) {
990
+ return res.status(404).json({ error: 'Project not found' });
991
+ }
992
+ // Validate path
993
+ const validation = validatePathInProject(projectRoot, targetPath);
994
+ if (!validation.valid) {
995
+ return res.status(403).json({ error: validation.error });
996
+ }
997
+ const resolvedPath = validation.resolved;
998
+ // Check if path exists and get stats
999
+ let stats;
1000
+ try {
1001
+ stats = await fsPromises.stat(resolvedPath);
1002
+ }
1003
+ catch {
1004
+ return res.status(404).json({ error: 'File or directory not found' });
1005
+ }
1006
+ // Prevent deleting the project root itself
1007
+ if (resolvedPath === path.resolve(projectRoot)) {
1008
+ return res.status(403).json({ error: 'Cannot delete project root directory' });
1009
+ }
1010
+ // Delete based on type
1011
+ if (stats.isDirectory()) {
1012
+ await fsPromises.rm(resolvedPath, { recursive: true, force: true });
1013
+ }
1014
+ else {
1015
+ await fsPromises.unlink(resolvedPath);
1016
+ }
1017
+ res.json({
1018
+ success: true,
1019
+ path: resolvedPath,
1020
+ type: stats.isDirectory() ? 'directory' : 'file',
1021
+ message: 'Deleted successfully'
1022
+ });
1023
+ }
1024
+ catch (error) {
1025
+ console.error('Error deleting file/directory:', error);
1026
+ if (error.code === 'EACCES') {
1027
+ res.status(403).json({ error: 'Permission denied' });
1028
+ }
1029
+ else if (error.code === 'ENOENT') {
1030
+ res.status(404).json({ error: 'File or directory not found' });
1031
+ }
1032
+ else if (error.code === 'ENOTEMPTY') {
1033
+ res.status(400).json({ error: 'Directory is not empty' });
1034
+ }
1035
+ else {
1036
+ res.status(500).json({ error: error.message });
1037
+ }
1038
+ }
1039
+ });
1040
+ // POST /api/projects/:projectName/files/upload - Upload files
1041
+ // Dynamic import of multer for file uploads
1042
+ const uploadFilesHandler = async (req, res) => {
1043
+ // Dynamic import of multer
1044
+ const multer = (await import('multer')).default;
1045
+ const uploadMiddleware = multer({
1046
+ storage: multer.diskStorage({
1047
+ destination: (req, file, cb) => {
1048
+ cb(null, os.tmpdir());
1049
+ },
1050
+ filename: (req, file, cb) => {
1051
+ // Use a unique temp name, but preserve original name in file.originalname
1052
+ // Note: file.originalname may contain path separators for folder uploads
1053
+ const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
1054
+ // For temp file, just use a safe unique name without the path
1055
+ cb(null, `upload-${uniqueSuffix}`);
1056
+ }
1057
+ }),
1058
+ limits: {
1059
+ fileSize: 50 * 1024 * 1024, // 50MB limit
1060
+ files: 20 // Max 20 files at once
1061
+ }
1062
+ });
1063
+ // Use multer middleware
1064
+ uploadMiddleware.array('files', 20)(req, res, async (err) => {
1065
+ if (err) {
1066
+ console.error('Multer error:', err);
1067
+ if (err.code === 'LIMIT_FILE_SIZE') {
1068
+ return res.status(400).json({ error: 'File too large. Maximum size is 50MB.' });
1069
+ }
1070
+ if (err.code === 'LIMIT_FILE_COUNT') {
1071
+ return res.status(400).json({ error: 'Too many files. Maximum is 20 files.' });
1072
+ }
1073
+ return res.status(500).json({ error: err.message });
1074
+ }
1075
+ try {
1076
+ const { projectName } = req.params;
1077
+ const { targetPath, relativePaths } = req.body;
1078
+ // Parse relative paths if provided (for folder uploads)
1079
+ let filePaths = [];
1080
+ if (relativePaths) {
1081
+ try {
1082
+ filePaths = JSON.parse(relativePaths);
1083
+ }
1084
+ catch (e) {
1085
+ console.log('[DEBUG] Failed to parse relativePaths:', relativePaths);
1086
+ }
1087
+ }
1088
+ console.log('[DEBUG] File upload request:', {
1089
+ projectName,
1090
+ targetPath: JSON.stringify(targetPath),
1091
+ targetPathType: typeof targetPath,
1092
+ filesCount: req.files?.length,
1093
+ relativePaths: filePaths
1094
+ });
1095
+ if (!req.files || req.files.length === 0) {
1096
+ return res.status(400).json({ error: 'No files provided' });
1097
+ }
1098
+ // Get project root
1099
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
1100
+ if (!projectRoot) {
1101
+ return res.status(404).json({ error: 'Project not found' });
1102
+ }
1103
+ console.log('[DEBUG] Project root:', projectRoot);
1104
+ // Validate and resolve target path
1105
+ // If targetPath is empty or '.', use project root directly
1106
+ const targetDir = targetPath || '';
1107
+ let resolvedTargetDir;
1108
+ console.log('[DEBUG] Target dir:', JSON.stringify(targetDir));
1109
+ if (!targetDir || targetDir === '.' || targetDir === './') {
1110
+ // Empty path means upload to project root
1111
+ resolvedTargetDir = path.resolve(projectRoot);
1112
+ console.log('[DEBUG] Using project root as target:', resolvedTargetDir);
1113
+ }
1114
+ else {
1115
+ const validation = validatePathInProject(projectRoot, targetDir);
1116
+ if (!validation.valid) {
1117
+ console.log('[DEBUG] Path validation failed:', validation.error);
1118
+ return res.status(403).json({ error: validation.error });
1119
+ }
1120
+ resolvedTargetDir = validation.resolved;
1121
+ console.log('[DEBUG] Resolved target dir:', resolvedTargetDir);
1122
+ }
1123
+ // Ensure target directory exists
1124
+ try {
1125
+ await fsPromises.access(resolvedTargetDir);
1126
+ }
1127
+ catch {
1128
+ await fsPromises.mkdir(resolvedTargetDir, { recursive: true });
1129
+ }
1130
+ // Move uploaded files from temp to target directory
1131
+ const uploadedFiles = [];
1132
+ console.log('[DEBUG] Processing files:', req.files.map(f => ({ originalname: f.originalname, path: f.path })));
1133
+ for (let i = 0; i < req.files.length; i++) {
1134
+ const file = req.files[i];
1135
+ // Use relative path if provided (for folder uploads), otherwise use originalname
1136
+ const fileName = (filePaths && filePaths[i]) ? filePaths[i] : file.originalname;
1137
+ console.log('[DEBUG] Processing file:', fileName, '(originalname:', file.originalname + ')');
1138
+ const destPath = path.join(resolvedTargetDir, fileName);
1139
+ // Validate destination path
1140
+ const destValidation = validatePathInProject(projectRoot, destPath);
1141
+ if (!destValidation.valid) {
1142
+ console.log('[DEBUG] Destination validation failed for:', destPath);
1143
+ // Clean up temp file
1144
+ await fsPromises.unlink(file.path).catch(() => { });
1145
+ continue;
1146
+ }
1147
+ // Ensure parent directory exists (for nested files from folder upload)
1148
+ const parentDir = path.dirname(destPath);
1149
+ try {
1150
+ await fsPromises.access(parentDir);
1151
+ }
1152
+ catch {
1153
+ await fsPromises.mkdir(parentDir, { recursive: true });
1154
+ }
1155
+ // Move file (copy + unlink to handle cross-device scenarios)
1156
+ await fsPromises.copyFile(file.path, destPath);
1157
+ await fsPromises.unlink(file.path);
1158
+ uploadedFiles.push({
1159
+ name: fileName,
1160
+ path: destPath,
1161
+ size: file.size,
1162
+ mimeType: file.mimetype
1163
+ });
1164
+ }
1165
+ res.json({
1166
+ success: true,
1167
+ files: uploadedFiles,
1168
+ targetPath: resolvedTargetDir,
1169
+ message: `Uploaded ${uploadedFiles.length} file(s) successfully`
1170
+ });
1171
+ }
1172
+ catch (error) {
1173
+ console.error('Error uploading files:', error);
1174
+ // Clean up any remaining temp files
1175
+ if (req.files) {
1176
+ for (const file of req.files) {
1177
+ await fsPromises.unlink(file.path).catch(() => { });
1178
+ }
1179
+ }
1180
+ if (error.code === 'EACCES') {
1181
+ res.status(403).json({ error: 'Permission denied' });
1182
+ }
1183
+ else {
1184
+ res.status(500).json({ error: error.message });
1185
+ }
1186
+ }
1187
+ });
1188
+ };
1189
+ app.post('/api/projects/:projectName/files/upload', authenticateToken, uploadFilesHandler);
1190
+ /**
1191
+ * Proxy an authenticated client WebSocket to a plugin's internal WS server.
1192
+ * Auth is enforced by verifyClient before this function is reached.
1193
+ */
1194
+ function handlePluginWsProxy(clientWs, pathname) {
1195
+ const pluginName = pathname.replace('/plugin-ws/', '');
1196
+ if (!pluginName || /[^a-zA-Z0-9_-]/.test(pluginName)) {
1197
+ clientWs.close(4400, 'Invalid plugin name');
1198
+ return;
1199
+ }
1200
+ const port = getPluginPort(pluginName);
1201
+ if (!port) {
1202
+ clientWs.close(4404, 'Plugin not running');
1203
+ return;
1204
+ }
1205
+ const upstream = new WebSocket(`ws://127.0.0.1:${port}/ws`);
1206
+ upstream.on('open', () => {
1207
+ console.log(`[Plugins] WS proxy connected to "${pluginName}" on port ${port}`);
1208
+ });
1209
+ // Relay messages bidirectionally
1210
+ upstream.on('message', (data) => {
1211
+ if (clientWs.readyState === WebSocket.OPEN)
1212
+ clientWs.send(data);
1213
+ });
1214
+ clientWs.on('message', (data) => {
1215
+ if (upstream.readyState === WebSocket.OPEN)
1216
+ upstream.send(data);
1217
+ });
1218
+ // Propagate close in both directions
1219
+ upstream.on('close', () => { if (clientWs.readyState === WebSocket.OPEN)
1220
+ clientWs.close(); });
1221
+ clientWs.on('close', () => { if (upstream.readyState === WebSocket.OPEN)
1222
+ upstream.close(); });
1223
+ upstream.on('error', (err) => {
1224
+ console.error(`[Plugins] WS proxy error for "${pluginName}":`, err.message);
1225
+ if (clientWs.readyState === WebSocket.OPEN)
1226
+ clientWs.close(4502, 'Upstream error');
1227
+ });
1228
+ clientWs.on('error', () => {
1229
+ if (upstream.readyState === WebSocket.OPEN)
1230
+ upstream.close();
1231
+ });
1232
+ }
1233
+ // WebSocket connection handler that routes based on URL path
1234
+ wss.on('connection', (ws, request) => {
1235
+ const url = request.url;
1236
+ console.log('[INFO] Client connected to:', url);
1237
+ // Parse URL to get pathname without query parameters
1238
+ const urlObj = new URL(url, 'http://localhost');
1239
+ const pathname = urlObj.pathname;
1240
+ if (pathname === '/shell') {
1241
+ handleShellConnection(ws);
1242
+ }
1243
+ else if (pathname === '/ws') {
1244
+ handleChatConnection(ws, request);
1245
+ }
1246
+ else if (pathname.startsWith('/plugin-ws/')) {
1247
+ handlePluginWsProxy(ws, pathname);
1248
+ }
1249
+ else {
1250
+ console.log('[WARN] Unknown WebSocket path:', pathname);
1251
+ ws.close();
1252
+ }
1253
+ });
1254
+ /**
1255
+ * WebSocket Writer - Wrapper for WebSocket to match SSEStreamWriter interface
1256
+ *
1257
+ * Provider files use `createNormalizedMessage()` from `shared/utils.js` and
1258
+ * adapter `normalizeMessage()` to produce unified NormalizedMessage events.
1259
+ * The writer simply serialises and sends.
1260
+ */
1261
+ class WebSocketWriter {
1262
+ constructor(ws, userId = null) {
1263
+ this.ws = ws;
1264
+ this.sessionId = null;
1265
+ this.userId = userId;
1266
+ this.isWebSocketWriter = true; // Marker for transport detection
1267
+ }
1268
+ send(data) {
1269
+ if (this.ws.readyState === 1) { // WebSocket.OPEN
1270
+ this.ws.send(JSON.stringify(data));
1271
+ }
1272
+ }
1273
+ updateWebSocket(newRawWs) {
1274
+ this.ws = newRawWs;
1275
+ }
1276
+ setSessionId(sessionId) {
1277
+ this.sessionId = sessionId;
1278
+ }
1279
+ getSessionId() {
1280
+ return this.sessionId;
1281
+ }
1282
+ }
1283
+ // Handle chat WebSocket connections
1284
+ function handleChatConnection(ws, request) {
1285
+ console.log('[INFO] Chat WebSocket connected');
1286
+ // Add to connected clients for project updates
1287
+ connectedClients.add(ws);
1288
+ // Wrap WebSocket with writer for consistent interface with SSEStreamWriter
1289
+ const writer = new WebSocketWriter(ws, request?.user?.id ?? request?.user?.userId ?? null);
1290
+ ws.on('message', async (message) => {
1291
+ try {
1292
+ const data = JSON.parse(message);
1293
+ if (data.type === 'claude-command') {
1294
+ console.log('[DEBUG] User message:', data.command || '[Continue/Resume]');
1295
+ console.log('📁 Project:', data.options?.projectPath || 'Unknown');
1296
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
1297
+ // Use Claude Agents SDK
1298
+ await queryClaudeSDK(data.command, data.options, writer);
1299
+ }
1300
+ else if (data.type === 'cursor-command') {
1301
+ console.log('[DEBUG] Cursor message:', data.command || '[Continue/Resume]');
1302
+ console.log('📁 Project:', data.options?.cwd || 'Unknown');
1303
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
1304
+ console.log('🤖 Model:', data.options?.model || 'default');
1305
+ await spawnCursor(data.command, data.options, writer);
1306
+ }
1307
+ else if (data.type === 'codex-command') {
1308
+ console.log('[DEBUG] Codex message:', data.command || '[Continue/Resume]');
1309
+ console.log('📁 Project:', data.options?.projectPath || data.options?.cwd || 'Unknown');
1310
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
1311
+ console.log('🤖 Model:', data.options?.model || 'default');
1312
+ await queryCodex(data.command, data.options, writer);
1313
+ }
1314
+ else if (data.type === 'gemini-command') {
1315
+ console.log('[DEBUG] Gemini message:', data.command || '[Continue/Resume]');
1316
+ console.log('📁 Project:', data.options?.projectPath || data.options?.cwd || 'Unknown');
1317
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
1318
+ console.log('🤖 Model:', data.options?.model || 'default');
1319
+ await spawnGemini(data.command, data.options, writer);
1320
+ }
1321
+ else if (data.type === 'cursor-resume') {
1322
+ // Backward compatibility: treat as cursor-command with resume and no prompt
1323
+ console.log('[DEBUG] Cursor resume session (compat):', data.sessionId);
1324
+ await spawnCursor('', {
1325
+ sessionId: data.sessionId,
1326
+ resume: true,
1327
+ cwd: data.options?.cwd
1328
+ }, writer);
1329
+ }
1330
+ else if (data.type === 'abort-session') {
1331
+ console.log('[DEBUG] Abort session request:', data.sessionId);
1332
+ const provider = data.provider || 'claude';
1333
+ let success;
1334
+ if (provider === 'cursor') {
1335
+ success = abortCursorSession(data.sessionId);
1336
+ }
1337
+ else if (provider === 'codex') {
1338
+ success = abortCodexSession(data.sessionId);
1339
+ }
1340
+ else if (provider === 'gemini') {
1341
+ success = abortGeminiSession(data.sessionId);
1342
+ }
1343
+ else {
1344
+ // Use Claude Agents SDK
1345
+ success = await abortClaudeSDKSession(data.sessionId);
1346
+ }
1347
+ writer.send(createNormalizedMessage({ kind: 'complete', exitCode: success ? 0 : 1, aborted: true, success, sessionId: data.sessionId, provider }));
1348
+ }
1349
+ else if (data.type === 'claude-permission-response') {
1350
+ // Relay UI approval decisions back into the SDK control flow.
1351
+ // This does not persist permissions; it only resolves the in-flight request,
1352
+ // introduced so the SDK can resume once the user clicks Allow/Deny.
1353
+ if (data.requestId) {
1354
+ resolveToolApproval(data.requestId, {
1355
+ allow: Boolean(data.allow),
1356
+ updatedInput: data.updatedInput,
1357
+ message: data.message,
1358
+ rememberEntry: data.rememberEntry
1359
+ });
1360
+ }
1361
+ }
1362
+ else if (data.type === 'cursor-abort') {
1363
+ console.log('[DEBUG] Abort Cursor session:', data.sessionId);
1364
+ const success = abortCursorSession(data.sessionId);
1365
+ writer.send(createNormalizedMessage({ kind: 'complete', exitCode: success ? 0 : 1, aborted: true, success, sessionId: data.sessionId, provider: 'cursor' }));
1366
+ }
1367
+ else if (data.type === 'check-session-status') {
1368
+ // Check if a specific session is currently processing
1369
+ const provider = data.provider || 'claude';
1370
+ const sessionId = data.sessionId;
1371
+ let isActive;
1372
+ if (provider === 'cursor') {
1373
+ isActive = isCursorSessionActive(sessionId);
1374
+ }
1375
+ else if (provider === 'codex') {
1376
+ isActive = isCodexSessionActive(sessionId);
1377
+ }
1378
+ else if (provider === 'gemini') {
1379
+ isActive = isGeminiSessionActive(sessionId);
1380
+ }
1381
+ else {
1382
+ // Use Claude Agents SDK
1383
+ isActive = isClaudeSDKSessionActive(sessionId);
1384
+ if (isActive) {
1385
+ // Reconnect the session's writer to the new WebSocket so
1386
+ // subsequent SDK output flows to the refreshed client.
1387
+ reconnectSessionWriter(sessionId, ws);
1388
+ }
1389
+ }
1390
+ writer.send({
1391
+ type: 'session-status',
1392
+ sessionId,
1393
+ provider,
1394
+ isProcessing: isActive
1395
+ });
1396
+ }
1397
+ else if (data.type === 'get-pending-permissions') {
1398
+ // Return pending permission requests for a session
1399
+ const sessionId = data.sessionId;
1400
+ if (sessionId && isClaudeSDKSessionActive(sessionId)) {
1401
+ const pending = getPendingApprovalsForSession(sessionId);
1402
+ writer.send({
1403
+ type: 'pending-permissions-response',
1404
+ sessionId,
1405
+ data: pending
1406
+ });
1407
+ }
1408
+ }
1409
+ else if (data.type === 'get-active-sessions') {
1410
+ // Get all currently active sessions
1411
+ const activeSessions = {
1412
+ claude: getActiveClaudeSDKSessions(),
1413
+ cursor: getActiveCursorSessions(),
1414
+ codex: getActiveCodexSessions(),
1415
+ gemini: getActiveGeminiSessions()
1416
+ };
1417
+ writer.send({
1418
+ type: 'active-sessions',
1419
+ sessions: activeSessions
1420
+ });
1421
+ }
1422
+ }
1423
+ catch (error) {
1424
+ console.error('[ERROR] Chat WebSocket error:', error.message);
1425
+ writer.send({
1426
+ type: 'error',
1427
+ error: error.message
1428
+ });
1429
+ }
1430
+ });
1431
+ ws.on('close', () => {
1432
+ console.log('🔌 Chat client disconnected');
1433
+ // Remove from connected clients
1434
+ connectedClients.delete(ws);
1435
+ });
1436
+ }
1437
+ // Handle shell WebSocket connections
1438
+ function handleShellConnection(ws) {
1439
+ console.log('🐚 Shell client connected');
1440
+ let shellProcess = null;
1441
+ let ptySessionKey = null;
1442
+ let urlDetectionBuffer = '';
1443
+ const announcedAuthUrls = new Set();
1444
+ ws.on('message', async (message) => {
1445
+ try {
1446
+ const data = JSON.parse(message);
1447
+ console.log('📨 Shell message received:', data.type);
1448
+ if (data.type === 'init') {
1449
+ const projectPath = data.projectPath || process.cwd();
1450
+ const sessionId = data.sessionId;
1451
+ const hasSession = data.hasSession;
1452
+ const provider = data.provider || 'claude';
1453
+ const initialCommand = data.initialCommand;
1454
+ const isPlainShell = data.isPlainShell || (!!initialCommand && !hasSession) || provider === 'plain-shell';
1455
+ urlDetectionBuffer = '';
1456
+ announcedAuthUrls.clear();
1457
+ // Login commands (Claude/Cursor auth) should never reuse cached sessions
1458
+ const isLoginCommand = initialCommand && (initialCommand.includes('setup-token') ||
1459
+ initialCommand.includes('cursor-agent login') ||
1460
+ initialCommand.includes('auth login'));
1461
+ // Include command hash in session key so different commands get separate sessions
1462
+ const commandSuffix = isPlainShell && initialCommand
1463
+ ? `_cmd_${Buffer.from(initialCommand).toString('base64').slice(0, 16)}`
1464
+ : '';
1465
+ ptySessionKey = `${projectPath}_${sessionId || 'default'}${commandSuffix}`;
1466
+ // Kill any existing login session before starting fresh
1467
+ if (isLoginCommand) {
1468
+ const oldSession = ptySessionsMap.get(ptySessionKey);
1469
+ if (oldSession) {
1470
+ console.log('🧹 Cleaning up existing login session:', ptySessionKey);
1471
+ if (oldSession.timeoutId)
1472
+ clearTimeout(oldSession.timeoutId);
1473
+ if (oldSession.pty && oldSession.pty.kill)
1474
+ oldSession.pty.kill();
1475
+ ptySessionsMap.delete(ptySessionKey);
1476
+ }
1477
+ }
1478
+ const existingSession = isLoginCommand ? null : ptySessionsMap.get(ptySessionKey);
1479
+ if (existingSession) {
1480
+ console.log('♻️ Reconnecting to existing PTY session:', ptySessionKey);
1481
+ shellProcess = existingSession.pty;
1482
+ clearTimeout(existingSession.timeoutId);
1483
+ ws.send(JSON.stringify({
1484
+ type: 'output',
1485
+ data: `\x1b[36m[Reconnected to existing session]\x1b[0m\r\n`
1486
+ }));
1487
+ if (existingSession.buffer && existingSession.buffer.length > 0) {
1488
+ console.log(`📜 Sending ${existingSession.buffer.length} buffered messages`);
1489
+ existingSession.buffer.forEach(bufferedData => {
1490
+ ws.send(JSON.stringify({
1491
+ type: 'output',
1492
+ data: bufferedData
1493
+ }));
1494
+ });
1495
+ }
1496
+ existingSession.ws = ws;
1497
+ return;
1498
+ }
1499
+ console.log('[INFO] Starting shell in:', projectPath);
1500
+ console.log('📋 Session info:', hasSession ? `Resume session ${sessionId}` : (isPlainShell ? 'Plain shell mode' : 'New session'));
1501
+ console.log('🤖 Provider:', isPlainShell ? 'plain-shell' : provider);
1502
+ if (initialCommand) {
1503
+ console.log('⚡ Initial command:', initialCommand);
1504
+ }
1505
+ // First send a welcome message
1506
+ let welcomeMsg;
1507
+ if (isPlainShell) {
1508
+ welcomeMsg = `\x1b[36mStarting terminal in: ${projectPath}\x1b[0m\r\n`;
1509
+ }
1510
+ else {
1511
+ const providerName = provider === 'cursor' ? 'Cursor' : (provider === 'codex' ? 'Codex' : (provider === 'gemini' ? 'Gemini' : 'Claude'));
1512
+ welcomeMsg = hasSession ?
1513
+ `\x1b[36mResuming ${providerName} session ${sessionId} in: ${projectPath}\x1b[0m\r\n` :
1514
+ `\x1b[36mStarting new ${providerName} session in: ${projectPath}\x1b[0m\r\n`;
1515
+ }
1516
+ ws.send(JSON.stringify({
1517
+ type: 'output',
1518
+ data: welcomeMsg
1519
+ }));
1520
+ try {
1521
+ // Validate projectPath — resolve to absolute and verify it exists
1522
+ const resolvedProjectPath = path.resolve(projectPath);
1523
+ try {
1524
+ const stats = fs.statSync(resolvedProjectPath);
1525
+ if (!stats.isDirectory()) {
1526
+ throw new Error('Not a directory');
1527
+ }
1528
+ }
1529
+ catch (pathErr) {
1530
+ ws.send(JSON.stringify({ type: 'error', message: 'Invalid project path' }));
1531
+ return;
1532
+ }
1533
+ // Validate sessionId — only allow safe characters
1534
+ const safeSessionIdPattern = /^[a-zA-Z0-9_.\-:]+$/;
1535
+ if (sessionId && !safeSessionIdPattern.test(sessionId)) {
1536
+ ws.send(JSON.stringify({ type: 'error', message: 'Invalid session ID' }));
1537
+ return;
1538
+ }
1539
+ // Build shell command — use cwd for project path (never interpolate into shell string)
1540
+ let shellCommand;
1541
+ if (isPlainShell) {
1542
+ // Plain shell mode - run the initial command in the project directory
1543
+ shellCommand = initialCommand;
1544
+ }
1545
+ else if (provider === 'cursor') {
1546
+ if (hasSession && sessionId) {
1547
+ shellCommand = `cursor-agent --resume="${sessionId}"`;
1548
+ }
1549
+ else {
1550
+ shellCommand = 'cursor-agent';
1551
+ }
1552
+ }
1553
+ else if (provider === 'codex') {
1554
+ // Use codex command; attempt to resume and fall back to a new session when the resume fails.
1555
+ if (hasSession && sessionId) {
1556
+ if (os.platform() === 'win32') {
1557
+ // PowerShell syntax for fallback
1558
+ shellCommand = `codex resume "${sessionId}"; if ($LASTEXITCODE -ne 0) { codex }`;
1559
+ }
1560
+ else {
1561
+ shellCommand = `codex resume "${sessionId}" || codex`;
1562
+ }
1563
+ }
1564
+ else {
1565
+ shellCommand = 'codex';
1566
+ }
1567
+ }
1568
+ else if (provider === 'gemini') {
1569
+ const command = initialCommand || 'gemini';
1570
+ let resumeId = sessionId;
1571
+ if (hasSession && sessionId) {
1572
+ try {
1573
+ // Gemini CLI enforces its own native session IDs, unlike other agents that accept arbitrary string names.
1574
+ // The UI only knows about its internal generated `sessionId` (e.g. gemini_1234).
1575
+ // We must fetch the mapping from the backend session manager to pass the native `cliSessionId` to the shell.
1576
+ const sess = sessionManager.getSession(sessionId);
1577
+ if (sess && sess.cliSessionId) {
1578
+ resumeId = sess.cliSessionId;
1579
+ // Validate the looked-up CLI session ID too
1580
+ if (!safeSessionIdPattern.test(resumeId)) {
1581
+ resumeId = null;
1582
+ }
1583
+ }
1584
+ }
1585
+ catch (err) {
1586
+ console.error('Failed to get Gemini CLI session ID:', err);
1587
+ }
1588
+ }
1589
+ if (hasSession && resumeId) {
1590
+ shellCommand = `${command} --resume "${resumeId}"`;
1591
+ }
1592
+ else {
1593
+ shellCommand = command;
1594
+ }
1595
+ }
1596
+ else {
1597
+ // Claude (default provider)
1598
+ const command = initialCommand || 'claude';
1599
+ if (hasSession && sessionId) {
1600
+ if (os.platform() === 'win32') {
1601
+ shellCommand = `claude --resume "${sessionId}"; if ($LASTEXITCODE -ne 0) { claude }`;
1602
+ }
1603
+ else {
1604
+ shellCommand = `claude --resume "${sessionId}" || claude`;
1605
+ }
1606
+ }
1607
+ else {
1608
+ shellCommand = command;
1609
+ }
1610
+ }
1611
+ console.log('🔧 Executing shell command:', shellCommand);
1612
+ // Use appropriate shell based on platform
1613
+ const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';
1614
+ const shellArgs = os.platform() === 'win32' ? ['-Command', shellCommand] : ['-c', shellCommand];
1615
+ // Use terminal dimensions from client if provided, otherwise use defaults
1616
+ const termCols = data.cols || 80;
1617
+ const termRows = data.rows || 24;
1618
+ console.log('📐 Using terminal dimensions:', termCols, 'x', termRows);
1619
+ shellProcess = pty.spawn(shell, shellArgs, {
1620
+ name: 'xterm-256color',
1621
+ cols: termCols,
1622
+ rows: termRows,
1623
+ cwd: resolvedProjectPath,
1624
+ env: {
1625
+ ...process.env,
1626
+ TERM: 'xterm-256color',
1627
+ COLORTERM: 'truecolor',
1628
+ FORCE_COLOR: '3'
1629
+ }
1630
+ });
1631
+ console.log('🟢 Shell process started with PTY, PID:', shellProcess.pid);
1632
+ ptySessionsMap.set(ptySessionKey, {
1633
+ pty: shellProcess,
1634
+ ws: ws,
1635
+ buffer: [],
1636
+ timeoutId: null,
1637
+ projectPath,
1638
+ sessionId
1639
+ });
1640
+ // Handle data output
1641
+ shellProcess.onData((data) => {
1642
+ const session = ptySessionsMap.get(ptySessionKey);
1643
+ if (!session)
1644
+ return;
1645
+ if (session.buffer.length < 5000) {
1646
+ session.buffer.push(data);
1647
+ }
1648
+ else {
1649
+ session.buffer.shift();
1650
+ session.buffer.push(data);
1651
+ }
1652
+ if (session.ws && session.ws.readyState === WebSocket.OPEN) {
1653
+ let outputData = data;
1654
+ const cleanChunk = stripAnsiSequences(data);
1655
+ urlDetectionBuffer = `${urlDetectionBuffer}${cleanChunk}`.slice(-SHELL_URL_PARSE_BUFFER_LIMIT);
1656
+ outputData = outputData.replace(/OPEN_URL:\s*(https?:\/\/[^\s\x1b\x07]+)/g, '[INFO] Opening in browser: $1');
1657
+ const emitAuthUrl = (detectedUrl, autoOpen = false) => {
1658
+ const normalizedUrl = normalizeDetectedUrl(detectedUrl);
1659
+ if (!normalizedUrl)
1660
+ return;
1661
+ const isNewUrl = !announcedAuthUrls.has(normalizedUrl);
1662
+ if (isNewUrl) {
1663
+ announcedAuthUrls.add(normalizedUrl);
1664
+ session.ws.send(JSON.stringify({
1665
+ type: 'auth_url',
1666
+ url: normalizedUrl,
1667
+ autoOpen
1668
+ }));
1669
+ }
1670
+ };
1671
+ const normalizedDetectedUrls = extractUrlsFromText(urlDetectionBuffer)
1672
+ .map((url) => normalizeDetectedUrl(url))
1673
+ .filter(Boolean);
1674
+ // Prefer the most complete URL if shorter prefix variants are also present.
1675
+ const dedupedDetectedUrls = Array.from(new Set(normalizedDetectedUrls)).filter((url, _, urls) => !urls.some((otherUrl) => otherUrl !== url && otherUrl.startsWith(url)));
1676
+ dedupedDetectedUrls.forEach((url) => emitAuthUrl(url, false));
1677
+ if (shouldAutoOpenUrlFromOutput(cleanChunk) && dedupedDetectedUrls.length > 0) {
1678
+ const bestUrl = dedupedDetectedUrls.reduce((longest, current) => current.length > longest.length ? current : longest);
1679
+ emitAuthUrl(bestUrl, true);
1680
+ }
1681
+ // Send regular output
1682
+ session.ws.send(JSON.stringify({
1683
+ type: 'output',
1684
+ data: outputData
1685
+ }));
1686
+ }
1687
+ });
1688
+ // Handle process exit
1689
+ shellProcess.onExit((exitCode) => {
1690
+ console.log('🔚 Shell process exited with code:', exitCode.exitCode, 'signal:', exitCode.signal);
1691
+ const session = ptySessionsMap.get(ptySessionKey);
1692
+ if (session && session.ws && session.ws.readyState === WebSocket.OPEN) {
1693
+ session.ws.send(JSON.stringify({
1694
+ type: 'output',
1695
+ data: `\r\n\x1b[33mProcess exited with code ${exitCode.exitCode}${exitCode.signal ? ` (${exitCode.signal})` : ''}\x1b[0m\r\n`
1696
+ }));
1697
+ }
1698
+ if (session && session.timeoutId) {
1699
+ clearTimeout(session.timeoutId);
1700
+ }
1701
+ ptySessionsMap.delete(ptySessionKey);
1702
+ shellProcess = null;
1703
+ });
1704
+ }
1705
+ catch (spawnError) {
1706
+ console.error('[ERROR] Error spawning process:', spawnError);
1707
+ ws.send(JSON.stringify({
1708
+ type: 'output',
1709
+ data: `\r\n\x1b[31mError: ${spawnError.message}\x1b[0m\r\n`
1710
+ }));
1711
+ }
1712
+ }
1713
+ else if (data.type === 'input') {
1714
+ // Send input to shell process
1715
+ if (shellProcess && shellProcess.write) {
1716
+ try {
1717
+ shellProcess.write(data.data);
1718
+ }
1719
+ catch (error) {
1720
+ console.error('Error writing to shell:', error);
1721
+ }
1722
+ }
1723
+ else {
1724
+ console.warn('No active shell process to send input to');
1725
+ }
1726
+ }
1727
+ else if (data.type === 'resize') {
1728
+ // Handle terminal resize
1729
+ if (shellProcess && shellProcess.resize) {
1730
+ console.log('Terminal resize requested:', data.cols, 'x', data.rows);
1731
+ shellProcess.resize(data.cols, data.rows);
1732
+ }
1733
+ }
1734
+ }
1735
+ catch (error) {
1736
+ console.error('[ERROR] Shell WebSocket error:', error.message);
1737
+ if (ws.readyState === WebSocket.OPEN) {
1738
+ ws.send(JSON.stringify({
1739
+ type: 'output',
1740
+ data: `\r\n\x1b[31mError: ${error.message}\x1b[0m\r\n`
1741
+ }));
1742
+ }
1743
+ }
1744
+ });
1745
+ ws.on('close', () => {
1746
+ console.log('🔌 Shell client disconnected');
1747
+ if (ptySessionKey) {
1748
+ const session = ptySessionsMap.get(ptySessionKey);
1749
+ if (session) {
1750
+ console.log('⏳ PTY session kept alive, will timeout in 30 minutes:', ptySessionKey);
1751
+ session.ws = null;
1752
+ session.timeoutId = setTimeout(() => {
1753
+ console.log('⏰ PTY session timeout, killing process:', ptySessionKey);
1754
+ if (session.pty && session.pty.kill) {
1755
+ session.pty.kill();
1756
+ }
1757
+ ptySessionsMap.delete(ptySessionKey);
1758
+ }, PTY_SESSION_TIMEOUT);
1759
+ }
1760
+ }
1761
+ });
1762
+ ws.on('error', (error) => {
1763
+ console.error('[ERROR] Shell WebSocket error:', error);
1764
+ });
1765
+ }
1766
+ // Image upload endpoint
1767
+ app.post('/api/projects/:projectName/upload-images', authenticateToken, async (req, res) => {
1768
+ try {
1769
+ const multer = (await import('multer')).default;
1770
+ const path = (await import('path')).default;
1771
+ const fs = (await import('fs')).promises;
1772
+ const os = (await import('os')).default;
1773
+ // Configure multer for image uploads
1774
+ const storage = multer.diskStorage({
1775
+ destination: async (req, file, cb) => {
1776
+ const uploadDir = path.join(os.tmpdir(), 'claude-ui-uploads', String(req.user.id));
1777
+ await fs.mkdir(uploadDir, { recursive: true });
1778
+ cb(null, uploadDir);
1779
+ },
1780
+ filename: (req, file, cb) => {
1781
+ const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
1782
+ const sanitizedName = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '_');
1783
+ cb(null, uniqueSuffix + '-' + sanitizedName);
1784
+ }
1785
+ });
1786
+ const fileFilter = (req, file, cb) => {
1787
+ const allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
1788
+ if (allowedMimes.includes(file.mimetype)) {
1789
+ cb(null, true);
1790
+ }
1791
+ else {
1792
+ cb(new Error('Invalid file type. Only JPEG, PNG, GIF, WebP, and SVG are allowed.'));
1793
+ }
1794
+ };
1795
+ const upload = multer({
1796
+ storage,
1797
+ fileFilter,
1798
+ limits: {
1799
+ fileSize: 5 * 1024 * 1024, // 5MB
1800
+ files: 5
1801
+ }
1802
+ });
1803
+ // Handle multipart form data
1804
+ upload.array('images', 5)(req, res, async (err) => {
1805
+ if (err) {
1806
+ return res.status(400).json({ error: err.message });
1807
+ }
1808
+ if (!req.files || req.files.length === 0) {
1809
+ return res.status(400).json({ error: 'No image files provided' });
1810
+ }
1811
+ try {
1812
+ // Process uploaded images
1813
+ const processedImages = await Promise.all(req.files.map(async (file) => {
1814
+ // Read file and convert to base64
1815
+ const buffer = await fs.readFile(file.path);
1816
+ const base64 = buffer.toString('base64');
1817
+ const mimeType = file.mimetype;
1818
+ // Clean up temp file immediately
1819
+ await fs.unlink(file.path);
1820
+ return {
1821
+ name: file.originalname,
1822
+ data: `data:${mimeType};base64,${base64}`,
1823
+ size: file.size,
1824
+ mimeType: mimeType
1825
+ };
1826
+ }));
1827
+ res.json({ images: processedImages });
1828
+ }
1829
+ catch (error) {
1830
+ console.error('Error processing images:', error);
1831
+ // Clean up any remaining files
1832
+ await Promise.all(req.files.map(f => fs.unlink(f.path).catch(() => { })));
1833
+ res.status(500).json({ error: 'Failed to process images' });
1834
+ }
1835
+ });
1836
+ }
1837
+ catch (error) {
1838
+ console.error('Error in image upload endpoint:', error);
1839
+ res.status(500).json({ error: 'Internal server error' });
1840
+ }
1841
+ });
1842
+ // Get token usage for a specific session
1843
+ app.get('/api/projects/:projectName/sessions/:sessionId/token-usage', authenticateToken, async (req, res) => {
1844
+ try {
1845
+ const { projectName, sessionId } = req.params;
1846
+ const { provider = 'claude' } = req.query;
1847
+ const homeDir = os.homedir();
1848
+ // Allow only safe characters in sessionId
1849
+ const safeSessionId = String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '');
1850
+ if (!safeSessionId || safeSessionId !== String(sessionId)) {
1851
+ return res.status(400).json({ error: 'Invalid sessionId' });
1852
+ }
1853
+ // Handle Cursor sessions - they use SQLite and don't have token usage info
1854
+ if (provider === 'cursor') {
1855
+ return res.json({
1856
+ used: 0,
1857
+ total: 0,
1858
+ breakdown: { input: 0, cacheCreation: 0, cacheRead: 0 },
1859
+ unsupported: true,
1860
+ message: 'Token usage tracking not available for Cursor sessions'
1861
+ });
1862
+ }
1863
+ // Handle Gemini sessions - they are raw logs in our current setup
1864
+ if (provider === 'gemini') {
1865
+ return res.json({
1866
+ used: 0,
1867
+ total: 0,
1868
+ breakdown: { input: 0, cacheCreation: 0, cacheRead: 0 },
1869
+ unsupported: true,
1870
+ message: 'Token usage tracking not available for Gemini sessions'
1871
+ });
1872
+ }
1873
+ // Handle Codex sessions
1874
+ if (provider === 'codex') {
1875
+ const codexSessionsDir = path.join(homeDir, '.codex', 'sessions');
1876
+ // Find the session file by searching for the session ID
1877
+ const findSessionFile = async (dir) => {
1878
+ try {
1879
+ const entries = await fsPromises.readdir(dir, { withFileTypes: true });
1880
+ for (const entry of entries) {
1881
+ const fullPath = path.join(dir, entry.name);
1882
+ if (entry.isDirectory()) {
1883
+ const found = await findSessionFile(fullPath);
1884
+ if (found)
1885
+ return found;
1886
+ }
1887
+ else if (entry.name.includes(safeSessionId) && entry.name.endsWith('.jsonl')) {
1888
+ return fullPath;
1889
+ }
1890
+ }
1891
+ }
1892
+ catch (error) {
1893
+ // Skip directories we can't read
1894
+ }
1895
+ return null;
1896
+ };
1897
+ const sessionFilePath = await findSessionFile(codexSessionsDir);
1898
+ if (!sessionFilePath) {
1899
+ return res.status(404).json({ error: 'Codex session file not found', sessionId: safeSessionId });
1900
+ }
1901
+ // Read and parse the Codex JSONL file
1902
+ let fileContent;
1903
+ try {
1904
+ fileContent = await fsPromises.readFile(sessionFilePath, 'utf8');
1905
+ }
1906
+ catch (error) {
1907
+ if (error.code === 'ENOENT') {
1908
+ return res.status(404).json({ error: 'Session file not found', path: sessionFilePath });
1909
+ }
1910
+ throw error;
1911
+ }
1912
+ const lines = fileContent.trim().split('\n');
1913
+ let totalTokens = 0;
1914
+ let contextWindow = 200000; // Default for Codex/OpenAI
1915
+ // Find the latest token_count event with info (scan from end)
1916
+ for (let i = lines.length - 1; i >= 0; i--) {
1917
+ try {
1918
+ const entry = JSON.parse(lines[i]);
1919
+ // Codex stores token info in event_msg with type: "token_count"
1920
+ if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload?.info) {
1921
+ const tokenInfo = entry.payload.info;
1922
+ if (tokenInfo.total_token_usage) {
1923
+ totalTokens = tokenInfo.total_token_usage.total_tokens || 0;
1924
+ }
1925
+ if (tokenInfo.model_context_window) {
1926
+ contextWindow = tokenInfo.model_context_window;
1927
+ }
1928
+ break; // Stop after finding the latest token count
1929
+ }
1930
+ }
1931
+ catch (parseError) {
1932
+ // Skip lines that can't be parsed
1933
+ continue;
1934
+ }
1935
+ }
1936
+ return res.json({
1937
+ used: totalTokens,
1938
+ total: contextWindow
1939
+ });
1940
+ }
1941
+ // Handle Claude sessions (default)
1942
+ // Extract actual project path
1943
+ let projectPath;
1944
+ try {
1945
+ projectPath = await extractProjectDirectory(projectName);
1946
+ }
1947
+ catch (error) {
1948
+ console.error('Error extracting project directory:', error);
1949
+ return res.status(500).json({ error: 'Failed to determine project path' });
1950
+ }
1951
+ // Construct the JSONL file path
1952
+ // Claude stores session files in ~/.claude/projects/[encoded-project-path]/[session-id].jsonl
1953
+ // The encoding replaces any non-alphanumeric character (except -) with -
1954
+ const encodedPath = projectPath.replace(/[^a-zA-Z0-9-]/g, '-');
1955
+ const projectDir = path.join(homeDir, '.claude', 'projects', encodedPath);
1956
+ const jsonlPath = path.join(projectDir, `${safeSessionId}.jsonl`);
1957
+ // Constrain to projectDir
1958
+ const rel = path.relative(path.resolve(projectDir), path.resolve(jsonlPath));
1959
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
1960
+ return res.status(400).json({ error: 'Invalid path' });
1961
+ }
1962
+ // Read and parse the JSONL file
1963
+ let fileContent;
1964
+ try {
1965
+ fileContent = await fsPromises.readFile(jsonlPath, 'utf8');
1966
+ }
1967
+ catch (error) {
1968
+ if (error.code === 'ENOENT') {
1969
+ return res.status(404).json({ error: 'Session file not found', path: jsonlPath });
1970
+ }
1971
+ throw error; // Re-throw other errors to be caught by outer try-catch
1972
+ }
1973
+ const lines = fileContent.trim().split('\n');
1974
+ const parsedContextWindow = parseInt(process.env.CONTEXT_WINDOW, 10);
1975
+ const contextWindow = Number.isFinite(parsedContextWindow) ? parsedContextWindow : 160000;
1976
+ let inputTokens = 0;
1977
+ let cacheCreationTokens = 0;
1978
+ let cacheReadTokens = 0;
1979
+ // Find the latest assistant message with usage data (scan from end)
1980
+ for (let i = lines.length - 1; i >= 0; i--) {
1981
+ try {
1982
+ const entry = JSON.parse(lines[i]);
1983
+ // Only count assistant messages which have usage data
1984
+ if (entry.type === 'assistant' && entry.message?.usage) {
1985
+ const usage = entry.message.usage;
1986
+ // Use token counts from latest assistant message only
1987
+ inputTokens = usage.input_tokens || 0;
1988
+ cacheCreationTokens = usage.cache_creation_input_tokens || 0;
1989
+ cacheReadTokens = usage.cache_read_input_tokens || 0;
1990
+ break; // Stop after finding the latest assistant message
1991
+ }
1992
+ }
1993
+ catch (parseError) {
1994
+ // Skip lines that can't be parsed
1995
+ continue;
1996
+ }
1997
+ }
1998
+ // Calculate total context usage (excluding output_tokens, as per ccusage)
1999
+ const totalUsed = inputTokens + cacheCreationTokens + cacheReadTokens;
2000
+ res.json({
2001
+ used: totalUsed,
2002
+ total: contextWindow,
2003
+ breakdown: {
2004
+ input: inputTokens,
2005
+ cacheCreation: cacheCreationTokens,
2006
+ cacheRead: cacheReadTokens
2007
+ }
2008
+ });
2009
+ }
2010
+ catch (error) {
2011
+ console.error('Error reading session token usage:', error);
2012
+ res.status(500).json({ error: 'Failed to read session token usage' });
2013
+ }
2014
+ });
2015
+ // Serve React app for all other routes (excluding static files)
2016
+ app.get('*', (req, res) => {
2017
+ // Skip requests for static assets (files with extensions)
2018
+ if (path.extname(req.path)) {
2019
+ return res.status(404).send('Not found');
2020
+ }
2021
+ // Only serve index.html for HTML routes, not for static assets
2022
+ // Static assets should already be handled by express.static middleware above
2023
+ const indexPath = path.join(APP_ROOT, 'dist', 'index.html');
2024
+ // Check if dist/index.html exists (production build available)
2025
+ if (fs.existsSync(indexPath)) {
2026
+ // Set no-cache headers for HTML to prevent service worker issues
2027
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
2028
+ res.setHeader('Pragma', 'no-cache');
2029
+ res.setHeader('Expires', '0');
2030
+ res.sendFile(indexPath);
2031
+ }
2032
+ else {
2033
+ // In development, redirect to Vite dev server only if dist doesn't exist
2034
+ const redirectHost = getConnectableHost(req.hostname);
2035
+ res.redirect(`${req.protocol}://${redirectHost}:${VITE_PORT}`);
2036
+ }
2037
+ });
2038
+ // global error middleware must be last
2039
+ app.use((err, req, res, next) => {
2040
+ if (err instanceof AppError) {
2041
+ return res.status(err.statusCode).json({
2042
+ success: false,
2043
+ error: {
2044
+ code: err.code,
2045
+ message: err.message,
2046
+ details: err.details,
2047
+ },
2048
+ });
2049
+ }
2050
+ console.error(err);
2051
+ return res.status(500).json({
2052
+ success: false,
2053
+ error: {
2054
+ code: 'INTERNAL_ERROR',
2055
+ message: 'Internal server error',
2056
+ },
2057
+ });
2058
+ });
2059
+ // Helper function to convert permissions to rwx format
2060
+ function permToRwx(perm) {
2061
+ const r = perm & 4 ? 'r' : '-';
2062
+ const w = perm & 2 ? 'w' : '-';
2063
+ const x = perm & 1 ? 'x' : '-';
2064
+ return r + w + x;
2065
+ }
2066
+ async function getFileTree(dirPath, maxDepth = 3, currentDepth = 0, showHidden = true) {
2067
+ // Using fsPromises from import
2068
+ const items = [];
2069
+ try {
2070
+ const entries = await fsPromises.readdir(dirPath, { withFileTypes: true });
2071
+ for (const entry of entries) {
2072
+ // Debug: log all entries including hidden files
2073
+ // Skip heavy build directories and VCS directories
2074
+ if (entry.name === 'node_modules' ||
2075
+ entry.name === 'dist' ||
2076
+ entry.name === 'build' ||
2077
+ entry.name === '.git' ||
2078
+ entry.name === '.svn' ||
2079
+ entry.name === '.hg')
2080
+ continue;
2081
+ const itemPath = path.join(dirPath, entry.name);
2082
+ const item = {
2083
+ name: entry.name,
2084
+ path: itemPath,
2085
+ type: entry.isDirectory() ? 'directory' : 'file'
2086
+ };
2087
+ // Get file stats for additional metadata
2088
+ try {
2089
+ const stats = await fsPromises.stat(itemPath);
2090
+ item.size = stats.size;
2091
+ item.modified = stats.mtime.toISOString();
2092
+ // Convert permissions to rwx format
2093
+ const mode = stats.mode;
2094
+ const ownerPerm = (mode >> 6) & 7;
2095
+ const groupPerm = (mode >> 3) & 7;
2096
+ const otherPerm = mode & 7;
2097
+ item.permissions = ((mode >> 6) & 7).toString() + ((mode >> 3) & 7).toString() + (mode & 7).toString();
2098
+ item.permissionsRwx = permToRwx(ownerPerm) + permToRwx(groupPerm) + permToRwx(otherPerm);
2099
+ }
2100
+ catch (statError) {
2101
+ // If stat fails, provide default values
2102
+ item.size = 0;
2103
+ item.modified = null;
2104
+ item.permissions = '000';
2105
+ item.permissionsRwx = '---------';
2106
+ }
2107
+ if (entry.isDirectory() && currentDepth < maxDepth) {
2108
+ // Recursively get subdirectories but limit depth
2109
+ try {
2110
+ // Check if we can access the directory before trying to read it
2111
+ await fsPromises.access(item.path, fs.constants.R_OK);
2112
+ item.children = await getFileTree(item.path, maxDepth, currentDepth + 1, showHidden);
2113
+ }
2114
+ catch (e) {
2115
+ // Silently skip directories we can't access (permission denied, etc.)
2116
+ item.children = [];
2117
+ }
2118
+ }
2119
+ items.push(item);
2120
+ }
2121
+ }
2122
+ catch (error) {
2123
+ // Only log non-permission errors to avoid spam
2124
+ if (error.code !== 'EACCES' && error.code !== 'EPERM') {
2125
+ console.error('Error reading directory:', error);
2126
+ }
2127
+ }
2128
+ return items.sort((a, b) => {
2129
+ if (a.type !== b.type) {
2130
+ return a.type === 'directory' ? -1 : 1;
2131
+ }
2132
+ return a.name.localeCompare(b.name);
2133
+ });
2134
+ }
2135
+ const SERVER_PORT = process.env.SERVER_PORT || 3001;
2136
+ const HOST = process.env.HOST || '0.0.0.0';
2137
+ const DISPLAY_HOST = getConnectableHost(HOST);
2138
+ const VITE_PORT = process.env.VITE_PORT || 5173;
2139
+ async function isPortOpen(port, timeoutMs = 800) {
2140
+ return await new Promise((resolve) => {
2141
+ const socket = net.createConnection({ host: '127.0.0.1', port: Number(port) });
2142
+ let settled = false;
2143
+ const done = (value) => {
2144
+ if (settled)
2145
+ return;
2146
+ settled = true;
2147
+ socket.destroy();
2148
+ resolve(value);
2149
+ };
2150
+ socket.setTimeout(timeoutMs);
2151
+ socket.once('connect', () => done(true));
2152
+ socket.once('timeout', () => done(false));
2153
+ socket.once('error', () => done(false));
2154
+ });
2155
+ }
2156
+ async function waitForPortOpen(port, timeoutMs = 25000) {
2157
+ const deadline = Date.now() + timeoutMs;
2158
+ while (Date.now() < deadline) {
2159
+ if (await isPortOpen(port)) {
2160
+ return true;
2161
+ }
2162
+ await new Promise(resolve => setTimeout(resolve, 1000));
2163
+ }
2164
+ return false;
2165
+ }
2166
+ function printSystemDaemonActiveNotice(port) {
2167
+ const effectivePort = Number(port) || 3001;
2168
+ const statusCommand = buildDaemonCliCommand({ subcommand: 'status', mode: 'system' }, DAEMON_COMMAND_CONTEXT);
2169
+ const stopCommand = buildDaemonCliCommand({ subcommand: 'stop', mode: 'system' }, DAEMON_COMMAND_CONTEXT);
2170
+ const logsCommand = buildDaemonCliCommand({ subcommand: 'logs', mode: 'system' }, DAEMON_COMMAND_CONTEXT);
2171
+ console.log(`${c.ok('[OK]')} System daemon is active and managing Pixcode.`);
2172
+ console.log(`${c.info('[INFO]')} Health URL: ${c.bright(`http://localhost:${effectivePort}/health`)}`);
2173
+ console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
2174
+ console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
2175
+ console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
2176
+ }
2177
+ function printUserDaemonActiveNotice(port, frontendPort) {
2178
+ const effectivePort = Number(port) || 3001;
2179
+ const effectiveFrontendPort = Number(frontendPort) || 5173;
2180
+ const statusCommand = buildDaemonCliCommand({ subcommand: 'status', mode: 'user' }, DAEMON_COMMAND_CONTEXT);
2181
+ const stopCommand = buildDaemonCliCommand({ subcommand: 'stop', mode: 'user' }, DAEMON_COMMAND_CONTEXT);
2182
+ const logsCommand = buildDaemonCliCommand({ subcommand: 'logs', mode: 'user' }, DAEMON_COMMAND_CONTEXT);
2183
+ console.log(`${c.ok('[OK]')} User daemon is active for this account.`);
2184
+ console.log(`${c.info('[INFO]')} Backend: ${c.bright(`http://localhost:${effectivePort}`)}`);
2185
+ console.log(`${c.info('[INFO]')} Frontend: ${c.bright(`http://localhost:${effectiveFrontendPort}`)}`);
2186
+ console.log(`${c.info('[INFO]')} Status: ${c.bright(statusCommand)}`);
2187
+ console.log(`${c.info('[INFO]')} Stop: ${c.bright(stopCommand)}`);
2188
+ console.log(`${c.info('[INFO]')} Logs: ${c.bright(logsCommand)}`);
2189
+ console.log(`${c.tip('[TIP]')} For login/reboot persistence, enable linger once: ${c.bright(`sudo loginctl enable-linger ${os.userInfo().username}`)}`);
2190
+ }
2191
+ function isSystemPermissionError(error) {
2192
+ const message = String(error?.message || error || '');
2193
+ return /(access denied|permission denied|must be root|interactive authentication required|not permitted|failed to connect to bus|operation not permitted|authentication is required|polkit)/i.test(message);
2194
+ }
2195
+ async function maybeAutoDaemonBootstrapFromIndex() {
2196
+ if (process.platform !== 'linux')
2197
+ return false;
2198
+ if (process.env.PIXCODE_DAEMON_MANAGED === '1')
2199
+ return false;
2200
+ if (process.env.PIXCODE_NO_DAEMON === '1')
2201
+ return false;
2202
+ if (process.env.PIXCODE_DAEMON_ATTEMPTED === '1')
2203
+ return false;
2204
+ process.env.PIXCODE_DAEMON_ATTEMPTED = '1';
2205
+ const systemArgs = ['install', '--mode=system', '--port', String(SERVER_PORT), '--frontend-port', String(VITE_PORT)];
2206
+ const userArgs = ['install', '--mode=user', '--port', String(SERVER_PORT), '--frontend-port', String(VITE_PORT)];
2207
+ try {
2208
+ console.log(`${c.info('[INFO]')} Linux detected. Enforcing system daemon mode for Pixcode...`);
2209
+ await handleDaemonCommand(systemArgs, {
2210
+ appRoot: APP_ROOT,
2211
+ defaultPort: String(SERVER_PORT),
2212
+ color: c,
2213
+ cliEntry: path.join(APP_ROOT, 'server', 'cli.js'),
2214
+ });
2215
+ return true;
2216
+ }
2217
+ catch (systemError) {
2218
+ const healthySoon = await waitForPortOpen(SERVER_PORT);
2219
+ if (healthySoon) {
2220
+ console.log(`${c.warn('[WARN]')} System daemon health check was delayed, but port ${SERVER_PORT} is now reachable.`);
2221
+ printSystemDaemonActiveNotice(SERVER_PORT);
2222
+ return true;
2223
+ }
2224
+ if (!isSystemPermissionError(systemError)) {
2225
+ const installSystemCommand = buildDaemonCliCommand({
2226
+ subcommand: 'install',
2227
+ mode: 'system',
2228
+ extraArgs: ['--port', String(SERVER_PORT), '--frontend-port', String(VITE_PORT)],
2229
+ }, DAEMON_COMMAND_CONTEXT);
2230
+ throw new Error(`System daemon bootstrap failed.\n` +
2231
+ `${systemError.message}\n` +
2232
+ `Run with privileges: ${installSystemCommand}`);
2233
+ }
2234
+ console.log(`${c.warn('[WARN]')} System daemon setup requires elevated privileges for this user.`);
2235
+ console.log(`${c.info('[INFO]')} Falling back to user daemon mode for account "${os.userInfo().username}"...`);
2236
+ try {
2237
+ await handleDaemonCommand(userArgs, {
2238
+ appRoot: APP_ROOT,
2239
+ defaultPort: String(SERVER_PORT),
2240
+ color: c,
2241
+ cliEntry: path.join(APP_ROOT, 'server', 'cli.js'),
2242
+ });
2243
+ printUserDaemonActiveNotice(SERVER_PORT, VITE_PORT);
2244
+ return true;
2245
+ }
2246
+ catch (userError) {
2247
+ const userHealthySoon = await waitForPortOpen(SERVER_PORT);
2248
+ if (userHealthySoon) {
2249
+ console.log(`${c.warn('[WARN]')} User daemon health check was delayed, but port ${SERVER_PORT} is now reachable.`);
2250
+ printUserDaemonActiveNotice(SERVER_PORT, VITE_PORT);
2251
+ return true;
2252
+ }
2253
+ const installSystemCommand = buildDaemonCliCommand({
2254
+ subcommand: 'install',
2255
+ mode: 'system',
2256
+ extraArgs: ['--port', String(SERVER_PORT), '--frontend-port', String(VITE_PORT)],
2257
+ }, DAEMON_COMMAND_CONTEXT);
2258
+ const installUserCommand = buildDaemonCliCommand({
2259
+ subcommand: 'install',
2260
+ mode: 'user',
2261
+ extraArgs: ['--port', String(SERVER_PORT), '--frontend-port', String(VITE_PORT)],
2262
+ }, DAEMON_COMMAND_CONTEXT);
2263
+ throw new Error(`System daemon bootstrap failed.\n` +
2264
+ `${systemError.message}\n\n` +
2265
+ `User daemon fallback also failed.\n` +
2266
+ `${userError.message}\n` +
2267
+ `Try one of:\n` +
2268
+ `1) ${installSystemCommand}\n` +
2269
+ `2) ${installUserCommand}`);
2270
+ }
2271
+ }
2272
+ }
2273
+ // Initialize database and start server
2274
+ async function startServer() {
2275
+ try {
2276
+ if (await maybeAutoDaemonBootstrapFromIndex()) {
2277
+ return;
2278
+ }
2279
+ // Initialize authentication database
2280
+ await initializeDatabase();
2281
+ // Configure Web Push (VAPID keys)
2282
+ configureWebPush();
2283
+ // Check if running in production mode (dist folder exists)
2284
+ const distIndexPath = path.join(APP_ROOT, 'dist', 'index.html');
2285
+ const isProduction = fs.existsSync(distIndexPath);
2286
+ // Log Claude implementation mode
2287
+ console.log(`${c.info('[INFO]')} Using Claude Agents SDK for Claude integration`);
2288
+ console.log('');
2289
+ if (isProduction) {
2290
+ console.log(`${c.info('[INFO]')} To run in production mode, go to http://${DISPLAY_HOST}:${SERVER_PORT}`);
2291
+ }
2292
+ console.log(`${c.info('[INFO]')} To run in development mode with hot-module replacement, go to http://${DISPLAY_HOST}:${VITE_PORT}`);
2293
+ server.listen(SERVER_PORT, HOST, async () => {
2294
+ const appInstallPath = APP_ROOT;
2295
+ console.log('');
2296
+ console.log(c.dim('═'.repeat(63)));
2297
+ console.log(` ${c.bright('Pixcode Server - Ready')}`);
2298
+ console.log(c.dim('═'.repeat(63)));
2299
+ console.log('');
2300
+ console.log(`${c.info('[INFO]')} Server URL: ${c.bright('http://' + DISPLAY_HOST + ':' + SERVER_PORT)}`);
2301
+ console.log(`${c.info('[INFO]')} Installed at: ${c.dim(appInstallPath)}`);
2302
+ console.log(`${c.tip('[TIP]')} Run "pixcode status" for full configuration details`);
2303
+ console.log('');
2304
+ // Start watching the projects folder for changes
2305
+ await setupProjectsWatcher();
2306
+ // Start server-side plugin processes for enabled plugins
2307
+ startEnabledPluginServers().catch(err => {
2308
+ console.error('[Plugins] Error during startup:', err.message);
2309
+ });
2310
+ });
2311
+ // Clean up plugin processes on shutdown
2312
+ const shutdownPlugins = async () => {
2313
+ await stopAllPlugins();
2314
+ process.exit(0);
2315
+ };
2316
+ process.on('SIGTERM', () => void shutdownPlugins());
2317
+ process.on('SIGINT', () => void shutdownPlugins());
2318
+ }
2319
+ catch (error) {
2320
+ console.error('[ERROR] Failed to start server:', error);
2321
+ process.exit(1);
2322
+ }
2323
+ }
2324
+ startServer();
2325
+ //# sourceMappingURL=index.js.map