dr-claw 1.1.2

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 (287) hide show
  1. package/LICENSE +1380 -0
  2. package/NOTICE +17 -0
  3. package/README.md +875 -0
  4. package/README.zh-CN.md +857 -0
  5. package/dist/api-docs.html +878 -0
  6. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  7. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  8. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  9. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  10. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  11. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  12. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  13. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  14. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  15. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  16. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  17. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  18. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  19. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  20. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  21. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  22. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  23. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  24. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  25. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  26. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  27. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  28. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  29. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  30. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  31. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  32. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  33. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  34. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  35. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  36. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  37. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  38. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  39. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  40. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  41. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  42. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  43. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  44. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  45. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  46. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  47. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  48. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  49. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  50. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  51. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  52. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  53. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  54. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  55. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  56. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  57. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  58. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  59. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  60. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  61. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  62. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  63. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  64. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  65. package/dist/assets/_basePickBy-C0n1uo4u.js +1 -0
  66. package/dist/assets/_baseUniq-BRNmhFkc.js +1 -0
  67. package/dist/assets/arc-DOMBmC_A.js +1 -0
  68. package/dist/assets/architectureDiagram-VXUJARFQ-CtMWglbD.js +36 -0
  69. package/dist/assets/blockDiagram-VD42YOAC-DK_gTkJy.js +122 -0
  70. package/dist/assets/c4Diagram-YG6GDRKO-DrDAvsn7.js +10 -0
  71. package/dist/assets/channel-BFOE7OyC.js +1 -0
  72. package/dist/assets/chunk-4BX2VUAB-CGbhdZcN.js +1 -0
  73. package/dist/assets/chunk-55IACEB6-sGeFSxen.js +1 -0
  74. package/dist/assets/chunk-B4BG7PRW-RxgHAU_P.js +165 -0
  75. package/dist/assets/chunk-DI55MBZ5-CvHUXZrx.js +220 -0
  76. package/dist/assets/chunk-FMBD7UC4-Sn7cXVNU.js +15 -0
  77. package/dist/assets/chunk-QN33PNHL-bDKOHppN.js +1 -0
  78. package/dist/assets/chunk-QZHKN3VN-B9kN5LGm.js +1 -0
  79. package/dist/assets/chunk-TZMSLE5B-CCBe6len.js +1 -0
  80. package/dist/assets/classDiagram-2ON5EDUG-DQoMNYlY.js +1 -0
  81. package/dist/assets/classDiagram-v2-WZHVMYZB-DQoMNYlY.js +1 -0
  82. package/dist/assets/clone-BulQSblH.js +1 -0
  83. package/dist/assets/cose-bilkent-S5V4N54A-r6sLiHBW.js +1 -0
  84. package/dist/assets/cytoscape.esm-5J0xJHOV.js +321 -0
  85. package/dist/assets/dagre-6UL2VRFP-AbsaR1Oa.js +4 -0
  86. package/dist/assets/defaultLocale-DX6XiGOO.js +1 -0
  87. package/dist/assets/diagram-PSM6KHXK-DjCvdUyy.js +24 -0
  88. package/dist/assets/diagram-QEK2KX5R-CqiocXkH.js +43 -0
  89. package/dist/assets/diagram-S2PKOQOG-D5ALeoII.js +24 -0
  90. package/dist/assets/erDiagram-Q2GNP2WA-C1AeOsiz.js +60 -0
  91. package/dist/assets/flowDiagram-NV44I4VS-C98ve_DO.js +162 -0
  92. package/dist/assets/ganttDiagram-JELNMOA3-3zdLvcxD.js +267 -0
  93. package/dist/assets/gitGraphDiagram-V2S2FVAM-nDuDMsHh.js +65 -0
  94. package/dist/assets/graph-Blm-emkR.js +1 -0
  95. package/dist/assets/index-B8Yutsnm.css +1 -0
  96. package/dist/assets/index-Cf6gyhc3.js +654 -0
  97. package/dist/assets/infoDiagram-HS3SLOUP-CmzE3q0R.js +2 -0
  98. package/dist/assets/init-Gi6I4Gst.js +1 -0
  99. package/dist/assets/journeyDiagram-XKPGCS4Q-CYaW7LrP.js +139 -0
  100. package/dist/assets/kanban-definition-3W4ZIXB7-mkmW7p0j.js +89 -0
  101. package/dist/assets/layout-Ct2kFIId.js +1 -0
  102. package/dist/assets/linear-CKG9EwIJ.js +1 -0
  103. package/dist/assets/mermaid.core-CaKcUnnd.js +250 -0
  104. package/dist/assets/mindmap-definition-VGOIOE7T-Bct-pYin.js +68 -0
  105. package/dist/assets/ordinal-Cboi1Yqb.js +1 -0
  106. package/dist/assets/pieDiagram-ADFJNKIX-C8wFD4Jr.js +30 -0
  107. package/dist/assets/quadrantDiagram-AYHSOK5B-CuiE_f46.js +7 -0
  108. package/dist/assets/requirementDiagram-UZGBJVZJ-C4v1CqU8.js +64 -0
  109. package/dist/assets/sankeyDiagram-TZEHDZUN-keAqqs-Y.js +10 -0
  110. package/dist/assets/sequenceDiagram-WL72ISMW-ClNbvKTB.js +145 -0
  111. package/dist/assets/stateDiagram-FKZM4ZOC-D8We-2vq.js +1 -0
  112. package/dist/assets/stateDiagram-v2-4FDKWEC3-BUURfjrE.js +1 -0
  113. package/dist/assets/timeline-definition-IT6M3QCI-DsvEMT5T.js +61 -0
  114. package/dist/assets/treemap-GDKQZRPO-TJrzN7Bj.js +162 -0
  115. package/dist/assets/vendor-codemirror-ansM-eig.js +33 -0
  116. package/dist/assets/vendor-react-BWF6YQQ3.js +8 -0
  117. package/dist/assets/vendor-xterm-DfcmCpbH.js +66 -0
  118. package/dist/assets/xychartDiagram-PRI3JC2R-BdATmY5F.js +7 -0
  119. package/dist/clear-cache.html +85 -0
  120. package/dist/convert-icons.md +53 -0
  121. package/dist/dr-claw.png +0 -0
  122. package/dist/favicon.png +0 -0
  123. package/dist/generate-icons.js +49 -0
  124. package/dist/icons/claude-ai-icon.svg +1 -0
  125. package/dist/icons/codex-white.svg +3 -0
  126. package/dist/icons/codex.svg +3 -0
  127. package/dist/icons/cursor-white.svg +12 -0
  128. package/dist/icons/cursor.svg +1 -0
  129. package/dist/icons/file.svg +16997 -0
  130. package/dist/icons/generate-icons.md +19 -0
  131. package/dist/icons/icon-128x128.png +0 -0
  132. package/dist/icons/icon-144x144.png +0 -0
  133. package/dist/icons/icon-152x152.png +0 -0
  134. package/dist/icons/icon-192x192.png +0 -0
  135. package/dist/icons/icon-384x384.png +0 -0
  136. package/dist/icons/icon-512x512.png +0 -0
  137. package/dist/icons/icon-72x72.png +0 -0
  138. package/dist/icons/icon-96x96.png +0 -0
  139. package/dist/icons/news/arxiv.svg +1 -0
  140. package/dist/icons/news/huggingface.svg +8 -0
  141. package/dist/icons/news/x-black.png +0 -0
  142. package/dist/icons/news/x-white.png +0 -0
  143. package/dist/icons/news/xiaohongshu.png +0 -0
  144. package/dist/index.html +51 -0
  145. package/dist/leveraged-cognition.png +0 -0
  146. package/dist/manifest.json +61 -0
  147. package/dist/screenshots/chat.png +0 -0
  148. package/dist/screenshots/new_claw.png +0 -0
  149. package/dist/screenshots/news_dashboard.png +0 -0
  150. package/dist/screenshots/project_dashboard.png +0 -0
  151. package/dist/screenshots/research_lab.png +0 -0
  152. package/dist/screenshots/skill_library.png +0 -0
  153. package/dist/screenshots/task_list.png +0 -0
  154. package/dist/screenshots/terminal_example.png +0 -0
  155. package/dist/screenshots/terminal_example1.png +0 -0
  156. package/dist/sw.js +58 -0
  157. package/dist/wechat-group-qr.jpg +0 -0
  158. package/package.json +133 -0
  159. package/public/api-docs.html +878 -0
  160. package/public/clear-cache.html +85 -0
  161. package/public/convert-icons.md +53 -0
  162. package/public/dr-claw.png +0 -0
  163. package/public/favicon.png +0 -0
  164. package/public/generate-icons.js +49 -0
  165. package/public/icons/claude-ai-icon.svg +1 -0
  166. package/public/icons/codex-white.svg +3 -0
  167. package/public/icons/codex.svg +3 -0
  168. package/public/icons/cursor-white.svg +12 -0
  169. package/public/icons/cursor.svg +1 -0
  170. package/public/icons/file.svg +16997 -0
  171. package/public/icons/generate-icons.md +19 -0
  172. package/public/icons/icon-128x128.png +0 -0
  173. package/public/icons/icon-144x144.png +0 -0
  174. package/public/icons/icon-152x152.png +0 -0
  175. package/public/icons/icon-192x192.png +0 -0
  176. package/public/icons/icon-384x384.png +0 -0
  177. package/public/icons/icon-512x512.png +0 -0
  178. package/public/icons/icon-72x72.png +0 -0
  179. package/public/icons/icon-96x96.png +0 -0
  180. package/public/icons/news/arxiv.svg +1 -0
  181. package/public/icons/news/huggingface.svg +8 -0
  182. package/public/icons/news/x-black.png +0 -0
  183. package/public/icons/news/x-white.png +0 -0
  184. package/public/icons/news/xiaohongshu.png +0 -0
  185. package/public/leveraged-cognition.png +0 -0
  186. package/public/manifest.json +61 -0
  187. package/public/screenshots/chat.png +0 -0
  188. package/public/screenshots/new_claw.png +0 -0
  189. package/public/screenshots/news_dashboard.png +0 -0
  190. package/public/screenshots/project_dashboard.png +0 -0
  191. package/public/screenshots/research_lab.png +0 -0
  192. package/public/screenshots/skill_library.png +0 -0
  193. package/public/screenshots/task_list.png +0 -0
  194. package/public/screenshots/terminal_example.png +0 -0
  195. package/public/screenshots/terminal_example1.png +0 -0
  196. package/public/sw.js +58 -0
  197. package/public/wechat-group-qr.jpg +0 -0
  198. package/scripts/export-skills-catalog-v2.mjs +746 -0
  199. package/scripts/fix-node-pty.js +45 -0
  200. package/scripts/gemini_image_core.py +470 -0
  201. package/scripts/install-python-tools.js +64 -0
  202. package/server/AGENTS.md +73 -0
  203. package/server/__tests__/gemini-legacy-thought.test.mjs +88 -0
  204. package/server/__tests__/runtimePorts.test.mjs +115 -0
  205. package/server/__tests__/session-delete.test.mjs +166 -0
  206. package/server/bin/compute-node +70 -0
  207. package/server/claude-sdk.js +799 -0
  208. package/server/cli-chat.js +488 -0
  209. package/server/cli.js +354 -0
  210. package/server/compute-node.js +439 -0
  211. package/server/constants/config.js +5 -0
  212. package/server/cursor-cli.js +340 -0
  213. package/server/database/auth.db +0 -0
  214. package/server/database/db.js +1852 -0
  215. package/server/database/init.sql +194 -0
  216. package/server/gemini-cli.js +1352 -0
  217. package/server/index.js +3154 -0
  218. package/server/load-env.js +71 -0
  219. package/server/local-gpu.js +860 -0
  220. package/server/middleware/auth.js +100 -0
  221. package/server/openai-codex.js +724 -0
  222. package/server/openrouter.js +890 -0
  223. package/server/project-token-usage.js +407 -0
  224. package/server/projects.js +3973 -0
  225. package/server/routes/agent.js +1272 -0
  226. package/server/routes/auth.js +128 -0
  227. package/server/routes/auto-research.js +558 -0
  228. package/server/routes/cli-auth.js +958 -0
  229. package/server/routes/codex.js +344 -0
  230. package/server/routes/commands.js +601 -0
  231. package/server/routes/compute.js +358 -0
  232. package/server/routes/cursor.js +795 -0
  233. package/server/routes/git.js +1348 -0
  234. package/server/routes/mcp-utils.js +48 -0
  235. package/server/routes/mcp.js +618 -0
  236. package/server/routes/news.js +711 -0
  237. package/server/routes/projects.js +633 -0
  238. package/server/routes/references.js +338 -0
  239. package/server/routes/settings.js +285 -0
  240. package/server/routes/skills.js +914 -0
  241. package/server/routes/taskmaster.js +2566 -0
  242. package/server/routes/telemetry.js +89 -0
  243. package/server/routes/user.js +155 -0
  244. package/server/scripts/fix_session_names.js +57 -0
  245. package/server/scripts/research-news/common_words.py +19 -0
  246. package/server/scripts/research-news/link_keywords.py +298 -0
  247. package/server/scripts/research-news/scan_existing_notes.py +266 -0
  248. package/server/scripts/research-news/scoring_utils.py +227 -0
  249. package/server/scripts/research-news/search_arxiv.py +842 -0
  250. package/server/scripts/research-news/search_huggingface.py +438 -0
  251. package/server/scripts/research-news/search_x.py +490 -0
  252. package/server/scripts/research-news/search_xiaohongshu.py +610 -0
  253. package/server/taskmaster-templates/README.md +150 -0
  254. package/server/taskmaster-templates/README.zh-CN.md +150 -0
  255. package/server/taskmaster-templates/ai-research-dataset.json +230 -0
  256. package/server/taskmaster-templates/ai-research-method-model.json +230 -0
  257. package/server/taskmaster-templates/ai-research-position-paper.json +230 -0
  258. package/server/telemetry.js +121 -0
  259. package/server/templates/AGENTS.md +103 -0
  260. package/server/templates/CLAUDE.md +104 -0
  261. package/server/templates/GEMINI.md +103 -0
  262. package/server/templates/cursor-project.md +108 -0
  263. package/server/templates/index.js +37 -0
  264. package/server/utils/__tests__/sessionTokenUsage.test.js +82 -0
  265. package/server/utils/auto-research-mailer.js +57 -0
  266. package/server/utils/cliResolution.js +170 -0
  267. package/server/utils/commandParser.js +303 -0
  268. package/server/utils/cursorCommand.js +61 -0
  269. package/server/utils/geminiApiKey.js +28 -0
  270. package/server/utils/gitConfig.js +24 -0
  271. package/server/utils/imageAttachmentFiles.js +35 -0
  272. package/server/utils/mcp-detector.js +198 -0
  273. package/server/utils/parsers/bibtex-parser.js +207 -0
  274. package/server/utils/permissions.js +100 -0
  275. package/server/utils/runtimePorts.js +212 -0
  276. package/server/utils/sessionFormatting.js +68 -0
  277. package/server/utils/sessionIndex.js +100 -0
  278. package/server/utils/sessionMode.js +95 -0
  279. package/server/utils/sessionTokenUsage.js +105 -0
  280. package/server/utils/taskmaster-websocket.js +129 -0
  281. package/server/utils/zotero-client.js +136 -0
  282. package/shared/errorClassifier.js +102 -0
  283. package/shared/geminiThinkingSupport.d.ts +22 -0
  284. package/shared/geminiThinkingSupport.js +96 -0
  285. package/shared/geminiThoughtParser.d.ts +8 -0
  286. package/shared/geminiThoughtParser.js +30 -0
  287. package/shared/modelConstants.js +139 -0
@@ -0,0 +1,1272 @@
1
+ import express from 'express';
2
+ import { spawn } from 'child_process';
3
+ import path from 'path';
4
+ import os from 'os';
5
+ import { promises as fs } from 'fs';
6
+ import crypto from 'crypto';
7
+ import { userDb, apiKeysDb, githubTokensDb } from '../database/db.js';
8
+ import { addProjectManually } from '../projects.js';
9
+ import { queryClaudeSDK } from '../claude-sdk.js';
10
+ import { spawnCursor } from '../cursor-cli.js';
11
+ import { queryCodex } from '../openai-codex.js';
12
+ import { spawnGemini } from '../gemini-cli.js';
13
+ import { queryOpenRouter } from '../openrouter.js';
14
+ import { queryLocalGPU } from '../local-gpu.js';
15
+ import { Octokit } from '@octokit/rest';
16
+ import { CLAUDE_MODELS, CURSOR_MODELS, CODEX_MODELS, GEMINI_MODELS, LOCAL_MODELS, OPENROUTER_MODELS } from '../../shared/modelConstants.js';
17
+ import { IS_PLATFORM } from '../constants/config.js';
18
+ import { getGeminiApiKeyForUser, withGeminiApiKeyEnv } from '../utils/geminiApiKey.js';
19
+
20
+ const router = express.Router();
21
+
22
+ /**
23
+ * Middleware to authenticate agent API requests.
24
+ *
25
+ * Supports two authentication modes:
26
+ * 1. Platform mode (IS_PLATFORM=true): For managed/hosted deployments where
27
+ * authentication is handled by an external proxy. Requests are trusted and
28
+ * the default user context is used.
29
+ *
30
+ * 2. API key mode (default): For self-hosted deployments where users authenticate
31
+ * via API keys created in the UI. Keys are validated against the local database.
32
+ */
33
+ const validateExternalApiKey = (req, res, next) => {
34
+ // Platform mode: Authentication is handled externally (e.g., by a proxy layer).
35
+ // Trust the request and use the default user context.
36
+ if (IS_PLATFORM) {
37
+ try {
38
+ const user = userDb.getFirstUser();
39
+ if (!user) {
40
+ return res.status(500).json({ error: 'Platform mode: No user found in database' });
41
+ }
42
+ req.user = user;
43
+ return next();
44
+ } catch (error) {
45
+ console.error('Platform mode error:', error);
46
+ return res.status(500).json({ error: 'Platform mode: Failed to fetch user' });
47
+ }
48
+ }
49
+
50
+ // Self-hosted mode: Validate API key from header or query parameter
51
+ const apiKey = req.headers['x-api-key'] || req.query.apiKey;
52
+
53
+ if (!apiKey) {
54
+ return res.status(401).json({ error: 'API key required' });
55
+ }
56
+
57
+ const user = apiKeysDb.validateApiKey(apiKey);
58
+
59
+ if (!user) {
60
+ return res.status(401).json({ error: 'Invalid or inactive API key' });
61
+ }
62
+
63
+ req.user = user;
64
+ next();
65
+ };
66
+
67
+ /**
68
+ * Get the remote URL of a git repository
69
+ * @param {string} repoPath - Path to the git repository
70
+ * @returns {Promise<string>} - Remote URL of the repository
71
+ */
72
+ async function getGitRemoteUrl(repoPath) {
73
+ return new Promise((resolve, reject) => {
74
+ const gitProcess = spawn('git', ['config', '--get', 'remote.origin.url'], {
75
+ cwd: repoPath,
76
+ stdio: ['pipe', 'pipe', 'pipe']
77
+ });
78
+
79
+ let stdout = '';
80
+ let stderr = '';
81
+
82
+ gitProcess.stdout.on('data', (data) => {
83
+ stdout += data.toString();
84
+ });
85
+
86
+ gitProcess.stderr.on('data', (data) => {
87
+ stderr += data.toString();
88
+ });
89
+
90
+ gitProcess.on('close', (code) => {
91
+ if (code === 0) {
92
+ resolve(stdout.trim());
93
+ } else {
94
+ reject(new Error(`Failed to get git remote: ${stderr}`));
95
+ }
96
+ });
97
+
98
+ gitProcess.on('error', (error) => {
99
+ reject(new Error(`Failed to execute git: ${error.message}`));
100
+ });
101
+ });
102
+ }
103
+
104
+ /**
105
+ * Normalize GitHub URLs for comparison
106
+ * @param {string} url - GitHub URL
107
+ * @returns {string} - Normalized URL
108
+ */
109
+ function normalizeGitHubUrl(url) {
110
+ // Remove .git suffix
111
+ let normalized = url.replace(/\.git$/, '');
112
+ // Convert SSH to HTTPS format for comparison
113
+ normalized = normalized.replace(/^git@github\.com:/, 'https://github.com/');
114
+ // Remove trailing slash
115
+ normalized = normalized.replace(/\/$/, '');
116
+ return normalized.toLowerCase();
117
+ }
118
+
119
+ /**
120
+ * Parse GitHub URL to extract owner and repo
121
+ * @param {string} url - GitHub URL (HTTPS or SSH)
122
+ * @returns {{owner: string, repo: string}} - Parsed owner and repo
123
+ */
124
+ function parseGitHubUrl(url) {
125
+ // Handle HTTPS URLs: https://github.com/owner/repo or https://github.com/owner/repo.git
126
+ // Handle SSH URLs: git@github.com:owner/repo or git@github.com:owner/repo.git
127
+ const match = url.match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/);
128
+ if (!match) {
129
+ throw new Error('Invalid GitHub URL format');
130
+ }
131
+ return {
132
+ owner: match[1],
133
+ repo: match[2].replace(/\.git$/, '')
134
+ };
135
+ }
136
+
137
+ /**
138
+ * Auto-generate a branch name from a message
139
+ * @param {string} message - The agent message
140
+ * @returns {string} - Generated branch name
141
+ */
142
+ function autogenerateBranchName(message) {
143
+ // Convert to lowercase, replace spaces/special chars with hyphens
144
+ let branchName = message
145
+ .toLowerCase()
146
+ .replace(/[^a-z0-9\s-]/g, '') // Remove special characters
147
+ .replace(/\s+/g, '-') // Replace spaces with hyphens
148
+ .replace(/-+/g, '-') // Replace multiple hyphens with single
149
+ .replace(/^-|-$/g, ''); // Remove leading/trailing hyphens
150
+
151
+ // Ensure non-empty fallback
152
+ if (!branchName) {
153
+ branchName = 'task';
154
+ }
155
+
156
+ // Generate timestamp suffix (last 6 chars of base36 timestamp)
157
+ const timestamp = Date.now().toString(36).slice(-6);
158
+ const suffix = `-${timestamp}`;
159
+
160
+ // Limit length to ensure total length including suffix fits within 50 characters
161
+ const maxBaseLength = 50 - suffix.length;
162
+ if (branchName.length > maxBaseLength) {
163
+ branchName = branchName.substring(0, maxBaseLength);
164
+ }
165
+
166
+ // Remove any trailing hyphen after truncation and ensure no leading hyphen
167
+ branchName = branchName.replace(/-$/, '').replace(/^-+/, '');
168
+
169
+ // If still empty or starts with hyphen after cleanup, use fallback
170
+ if (!branchName || branchName.startsWith('-')) {
171
+ branchName = 'task';
172
+ }
173
+
174
+ // Combine base name with timestamp suffix
175
+ branchName = `${branchName}${suffix}`;
176
+
177
+ // Final validation: ensure it matches safe pattern
178
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(branchName)) {
179
+ // Fallback to deterministic safe name
180
+ return `branch-${timestamp}`;
181
+ }
182
+
183
+ return branchName;
184
+ }
185
+
186
+ /**
187
+ * Validate a Git branch name
188
+ * @param {string} branchName - Branch name to validate
189
+ * @returns {{valid: boolean, error?: string}} - Validation result
190
+ */
191
+ function validateBranchName(branchName) {
192
+ if (!branchName || branchName.trim() === '') {
193
+ return { valid: false, error: 'Branch name cannot be empty' };
194
+ }
195
+
196
+ // Git branch name rules
197
+ const invalidPatterns = [
198
+ { pattern: /^\./, message: 'Branch name cannot start with a dot' },
199
+ { pattern: /\.$/, message: 'Branch name cannot end with a dot' },
200
+ { pattern: /\.\./, message: 'Branch name cannot contain consecutive dots (..)' },
201
+ { pattern: /\s/, message: 'Branch name cannot contain spaces' },
202
+ { pattern: /[~^:?*\[\\]/, message: 'Branch name cannot contain special characters: ~ ^ : ? * [ \\' },
203
+ { pattern: /@{/, message: 'Branch name cannot contain @{' },
204
+ { pattern: /\/$/, message: 'Branch name cannot end with a slash' },
205
+ { pattern: /^\//, message: 'Branch name cannot start with a slash' },
206
+ { pattern: /\/\//, message: 'Branch name cannot contain consecutive slashes' },
207
+ { pattern: /\.lock$/, message: 'Branch name cannot end with .lock' }
208
+ ];
209
+
210
+ for (const { pattern, message } of invalidPatterns) {
211
+ if (pattern.test(branchName)) {
212
+ return { valid: false, error: message };
213
+ }
214
+ }
215
+
216
+ // Check for ASCII control characters
217
+ if (/[\x00-\x1F\x7F]/.test(branchName)) {
218
+ return { valid: false, error: 'Branch name cannot contain control characters' };
219
+ }
220
+
221
+ return { valid: true };
222
+ }
223
+
224
+ /**
225
+ * Get recent commit messages from a repository
226
+ * @param {string} projectPath - Path to the git repository
227
+ * @param {number} limit - Number of commits to retrieve (default: 5)
228
+ * @returns {Promise<string[]>} - Array of commit messages
229
+ */
230
+ async function getCommitMessages(projectPath, limit = 5) {
231
+ return new Promise((resolve, reject) => {
232
+ const gitProcess = spawn('git', ['log', `-${limit}`, '--pretty=format:%s'], {
233
+ cwd: projectPath,
234
+ stdio: ['pipe', 'pipe', 'pipe']
235
+ });
236
+
237
+ let stdout = '';
238
+ let stderr = '';
239
+
240
+ gitProcess.stdout.on('data', (data) => {
241
+ stdout += data.toString();
242
+ });
243
+
244
+ gitProcess.stderr.on('data', (data) => {
245
+ stderr += data.toString();
246
+ });
247
+
248
+ gitProcess.on('close', (code) => {
249
+ if (code === 0) {
250
+ const messages = stdout.trim().split('\n').filter(msg => msg.length > 0);
251
+ resolve(messages);
252
+ } else {
253
+ reject(new Error(`Failed to get commit messages: ${stderr}`));
254
+ }
255
+ });
256
+
257
+ gitProcess.on('error', (error) => {
258
+ reject(new Error(`Failed to execute git: ${error.message}`));
259
+ });
260
+ });
261
+ }
262
+
263
+ /**
264
+ * Create a new branch on GitHub using the API
265
+ * @param {Octokit} octokit - Octokit instance
266
+ * @param {string} owner - Repository owner
267
+ * @param {string} repo - Repository name
268
+ * @param {string} branchName - Name of the new branch
269
+ * @param {string} baseBranch - Base branch to branch from (default: 'main')
270
+ * @returns {Promise<void>}
271
+ */
272
+ async function createGitHubBranch(octokit, owner, repo, branchName, baseBranch = 'main') {
273
+ try {
274
+ // Get the SHA of the base branch
275
+ const { data: ref } = await octokit.git.getRef({
276
+ owner,
277
+ repo,
278
+ ref: `heads/${baseBranch}`
279
+ });
280
+
281
+ const baseSha = ref.object.sha;
282
+
283
+ // Create the new branch
284
+ await octokit.git.createRef({
285
+ owner,
286
+ repo,
287
+ ref: `refs/heads/${branchName}`,
288
+ sha: baseSha
289
+ });
290
+
291
+ console.log(`✅ Created branch '${branchName}' on GitHub`);
292
+ } catch (error) {
293
+ if (error.status === 422 && error.message.includes('Reference already exists')) {
294
+ console.log(`â„šī¸ Branch '${branchName}' already exists on GitHub`);
295
+ } else {
296
+ throw error;
297
+ }
298
+ }
299
+ }
300
+
301
+ /**
302
+ * Create a pull request on GitHub
303
+ * @param {Octokit} octokit - Octokit instance
304
+ * @param {string} owner - Repository owner
305
+ * @param {string} repo - Repository name
306
+ * @param {string} branchName - Head branch name
307
+ * @param {string} title - PR title
308
+ * @param {string} body - PR body/description
309
+ * @param {string} baseBranch - Base branch (default: 'main')
310
+ * @returns {Promise<{number: number, url: string}>} - PR number and URL
311
+ */
312
+ async function createGitHubPR(octokit, owner, repo, branchName, title, body, baseBranch = 'main') {
313
+ const { data: pr } = await octokit.pulls.create({
314
+ owner,
315
+ repo,
316
+ title,
317
+ head: branchName,
318
+ base: baseBranch,
319
+ body
320
+ });
321
+
322
+ console.log(`✅ Created pull request #${pr.number}: ${pr.html_url}`);
323
+
324
+ return {
325
+ number: pr.number,
326
+ url: pr.html_url
327
+ };
328
+ }
329
+
330
+ /**
331
+ * Clone a GitHub repository to a directory
332
+ * @param {string} githubUrl - GitHub repository URL
333
+ * @param {string} githubToken - Optional GitHub token for private repos
334
+ * @param {string} projectPath - Path for cloning the repository
335
+ * @returns {Promise<string>} - Path to the cloned repository
336
+ */
337
+ async function cloneGitHubRepo(githubUrl, githubToken = null, projectPath) {
338
+ return new Promise(async (resolve, reject) => {
339
+ try {
340
+ // Validate GitHub URL
341
+ if (!githubUrl || !githubUrl.includes('github.com')) {
342
+ throw new Error('Invalid GitHub URL');
343
+ }
344
+
345
+ const cloneDir = path.resolve(projectPath);
346
+
347
+ // Check if directory already exists
348
+ try {
349
+ await fs.access(cloneDir);
350
+ // Directory exists - check if it's a git repo with the same URL
351
+ try {
352
+ const existingUrl = await getGitRemoteUrl(cloneDir);
353
+ const normalizedExisting = normalizeGitHubUrl(existingUrl);
354
+ const normalizedRequested = normalizeGitHubUrl(githubUrl);
355
+
356
+ if (normalizedExisting === normalizedRequested) {
357
+ console.log('✅ Repository already exists at path with correct URL');
358
+ return resolve(cloneDir);
359
+ } else {
360
+ throw new Error(`Directory ${cloneDir} already exists with a different repository (${existingUrl}). Expected: ${githubUrl}`);
361
+ }
362
+ } catch (gitError) {
363
+ throw new Error(`Directory ${cloneDir} already exists but is not a valid git repository or git command failed`);
364
+ }
365
+ } catch (accessError) {
366
+ // Directory doesn't exist - proceed with clone
367
+ }
368
+
369
+ // Ensure parent directory exists
370
+ await fs.mkdir(path.dirname(cloneDir), { recursive: true });
371
+
372
+ // Prepare the git clone URL with authentication if token is provided
373
+ let cloneUrl = githubUrl;
374
+ if (githubToken) {
375
+ // Convert HTTPS URL to authenticated URL
376
+ // Example: https://github.com/user/repo -> https://token@github.com/user/repo
377
+ cloneUrl = githubUrl.replace('https://github.com', `https://${githubToken}@github.com`);
378
+ }
379
+
380
+ console.log('🔄 Cloning repository:', githubUrl);
381
+ console.log('📁 Destination:', cloneDir);
382
+
383
+ // Execute git clone
384
+ const gitProcess = spawn('git', ['clone', '--depth', '1', cloneUrl, cloneDir], {
385
+ stdio: ['pipe', 'pipe', 'pipe']
386
+ });
387
+
388
+ let stdout = '';
389
+ let stderr = '';
390
+
391
+ gitProcess.stdout.on('data', (data) => {
392
+ stdout += data.toString();
393
+ });
394
+
395
+ gitProcess.stderr.on('data', (data) => {
396
+ stderr += data.toString();
397
+ console.log('Git stderr:', data.toString());
398
+ });
399
+
400
+ gitProcess.on('close', (code) => {
401
+ if (code === 0) {
402
+ console.log('✅ Repository cloned successfully');
403
+ resolve(cloneDir);
404
+ } else {
405
+ console.error('❌ Git clone failed:', stderr);
406
+ reject(new Error(`Git clone failed: ${stderr}`));
407
+ }
408
+ });
409
+
410
+ gitProcess.on('error', (error) => {
411
+ reject(new Error(`Failed to execute git: ${error.message}`));
412
+ });
413
+ } catch (error) {
414
+ reject(error);
415
+ }
416
+ });
417
+ }
418
+
419
+ /**
420
+ * Clean up a temporary project directory and its Claude session
421
+ * @param {string} projectPath - Path to the project directory
422
+ * @param {string} sessionId - Session ID to clean up
423
+ */
424
+ async function cleanupProject(projectPath, sessionId = null) {
425
+ try {
426
+ // Only clean up projects in the external-projects directory
427
+ if (!projectPath.includes('.claude/external-projects')) {
428
+ console.warn('âš ī¸ Refusing to clean up non-external project:', projectPath);
429
+ return;
430
+ }
431
+
432
+ console.log('🧹 Cleaning up project:', projectPath);
433
+ await fs.rm(projectPath, { recursive: true, force: true });
434
+ console.log('✅ Project cleaned up');
435
+
436
+ // Also clean up the Claude session directory if sessionId provided
437
+ if (sessionId) {
438
+ try {
439
+ const sessionPath = path.join(os.homedir(), '.claude', 'sessions', sessionId);
440
+ console.log('🧹 Cleaning up session directory:', sessionPath);
441
+ await fs.rm(sessionPath, { recursive: true, force: true });
442
+ console.log('✅ Session directory cleaned up');
443
+ } catch (error) {
444
+ console.error('âš ī¸ Failed to clean up session directory:', error.message);
445
+ }
446
+ }
447
+ } catch (error) {
448
+ console.error('❌ Failed to clean up project:', error);
449
+ }
450
+ }
451
+
452
+ /**
453
+ * SSE Stream Writer - Adapts SDK/CLI output to Server-Sent Events
454
+ */
455
+ class SSEStreamWriter {
456
+ constructor(res) {
457
+ this.res = res;
458
+ this.sessionId = null;
459
+ this.isSSEStreamWriter = true; // Marker for transport detection
460
+ }
461
+
462
+ send(data) {
463
+ if (this.res.writableEnded) {
464
+ return;
465
+ }
466
+
467
+ // Format as SSE - providers send raw objects, we stringify
468
+ this.res.write(`data: ${JSON.stringify(data)}\n\n`);
469
+ }
470
+
471
+ end() {
472
+ if (!this.res.writableEnded) {
473
+ this.res.write('data: {"type":"done"}\n\n');
474
+ this.res.end();
475
+ }
476
+ }
477
+
478
+ setSessionId(sessionId) {
479
+ this.sessionId = sessionId;
480
+ }
481
+
482
+ getSessionId() {
483
+ return this.sessionId;
484
+ }
485
+ }
486
+
487
+ /**
488
+ * Non-streaming response collector
489
+ */
490
+ class ResponseCollector {
491
+ constructor() {
492
+ this.messages = [];
493
+ this.sessionId = null;
494
+ }
495
+
496
+ send(data) {
497
+ // Store ALL messages for now - we'll filter when returning
498
+ this.messages.push(data);
499
+
500
+ // Extract sessionId if present
501
+ if (typeof data === 'string') {
502
+ try {
503
+ const parsed = JSON.parse(data);
504
+ if (parsed.sessionId) {
505
+ this.sessionId = parsed.sessionId;
506
+ }
507
+ } catch (e) {
508
+ // Not JSON, ignore
509
+ }
510
+ } else if (data && data.sessionId) {
511
+ this.sessionId = data.sessionId;
512
+ }
513
+ }
514
+
515
+ end() {
516
+ // Do nothing - we'll collect all messages
517
+ }
518
+
519
+ setSessionId(sessionId) {
520
+ this.sessionId = sessionId;
521
+ }
522
+
523
+ getSessionId() {
524
+ return this.sessionId;
525
+ }
526
+
527
+ getMessages() {
528
+ return this.messages;
529
+ }
530
+
531
+ /**
532
+ * Get filtered assistant messages only
533
+ */
534
+ getAssistantMessages() {
535
+ const assistantMessages = [];
536
+
537
+ for (const msg of this.messages) {
538
+ // Skip initial status message
539
+ if (msg && msg.type === 'status') {
540
+ continue;
541
+ }
542
+
543
+ // Handle JSON strings
544
+ if (typeof msg === 'string') {
545
+ try {
546
+ const parsed = JSON.parse(msg);
547
+ // Only include claude-response messages with assistant type
548
+ if (parsed.type === 'claude-response' && parsed.data && parsed.data.type === 'assistant') {
549
+ assistantMessages.push(parsed.data);
550
+ }
551
+ } catch (e) {
552
+ // Not JSON, skip
553
+ }
554
+ }
555
+ }
556
+
557
+ return assistantMessages;
558
+ }
559
+
560
+ /**
561
+ * Calculate total tokens from all messages
562
+ */
563
+ getTotalTokens() {
564
+ let totalInput = 0;
565
+ let totalOutput = 0;
566
+ let totalCacheRead = 0;
567
+ let totalCacheCreation = 0;
568
+
569
+ for (const msg of this.messages) {
570
+ let data = msg;
571
+
572
+ // Parse if string
573
+ if (typeof msg === 'string') {
574
+ try {
575
+ data = JSON.parse(msg);
576
+ } catch (e) {
577
+ continue;
578
+ }
579
+ }
580
+
581
+ // Extract usage from claude-response messages
582
+ if (data && data.type === 'claude-response' && data.data) {
583
+ const msgData = data.data;
584
+ if (msgData.message && msgData.message.usage) {
585
+ const usage = msgData.message.usage;
586
+ totalInput += usage.input_tokens || 0;
587
+ totalOutput += usage.output_tokens || 0;
588
+ totalCacheRead += usage.cache_read_input_tokens || 0;
589
+ totalCacheCreation += usage.cache_creation_input_tokens || 0;
590
+ }
591
+ }
592
+ }
593
+
594
+ return {
595
+ inputTokens: totalInput,
596
+ outputTokens: totalOutput,
597
+ cacheReadTokens: totalCacheRead,
598
+ cacheCreationTokens: totalCacheCreation,
599
+ totalTokens: totalInput + totalOutput + totalCacheRead + totalCacheCreation
600
+ };
601
+ }
602
+ }
603
+
604
+ // ===============================
605
+ // External API Endpoint
606
+ // ===============================
607
+
608
+ /**
609
+ * POST /api/agent
610
+ *
611
+ * Trigger an AI agent (Claude or Cursor) to work on a project.
612
+ * Supports automatic GitHub branch and pull request creation after successful completion.
613
+ *
614
+ * ================================================================================================
615
+ * REQUEST BODY PARAMETERS
616
+ * ================================================================================================
617
+ *
618
+ * @param {string} githubUrl - (Conditionally Required) GitHub repository URL to clone.
619
+ * Supported formats:
620
+ * - HTTPS: https://github.com/owner/repo
621
+ * - HTTPS with .git: https://github.com/owner/repo.git
622
+ * - SSH: git@github.com:owner/repo
623
+ * - SSH with .git: git@github.com:owner/repo.git
624
+ *
625
+ * @param {string} projectPath - (Conditionally Required) Path to existing project OR destination for cloning.
626
+ * Behavior depends on usage:
627
+ * - If used alone: Must point to existing project directory
628
+ * - If used with githubUrl: Target location for cloning
629
+ * - If omitted with githubUrl: Auto-generates temporary path in ~/.claude/external-projects/
630
+ *
631
+ * @param {string} message - (Required) Task description for the AI agent. Used as:
632
+ * - Instructions for the agent
633
+ * - Source for auto-generated branch names (if createBranch=true and no branchName)
634
+ * - Fallback for PR title if no commits are made
635
+ *
636
+ * @param {string} provider - (Optional) AI provider to use. Options: 'claude' | 'cursor'
637
+ * Default: 'claude'
638
+ *
639
+ * @param {boolean} stream - (Optional) Enable Server-Sent Events (SSE) streaming for real-time updates.
640
+ * Default: true
641
+ * - true: Returns text/event-stream with incremental updates
642
+ * - false: Returns complete JSON response after completion
643
+ *
644
+ * @param {string} model - (Optional) Model identifier for providers.
645
+ *
646
+ * Claude models: 'sonnet' (default), 'opus', 'haiku', 'opusplan', 'sonnet[1m]'
647
+ * Cursor models: 'gpt-5' (default), 'gpt-5.2', 'gpt-5.2-high', 'sonnet-4.5', 'opus-4.5',
648
+ * 'gemini-3-pro', 'composer-1', 'auto', 'gpt-5.1', 'gpt-5.1-high',
649
+ * 'gpt-5.1-codex', 'gpt-5.1-codex-high', 'gpt-5.1-codex-max',
650
+ * 'gpt-5.1-codex-max-high', 'opus-4.1', 'grok', and thinking variants
651
+ * Codex models: 'gpt-5.2' (default), 'gpt-5.1-codex-max', 'o3', 'o4-mini'
652
+ *
653
+ * @param {boolean} cleanup - (Optional) Auto-cleanup project directory after completion.
654
+ * Default: true
655
+ * Behavior:
656
+ * - Only applies when cloning via githubUrl (not for existing projectPath)
657
+ * - Deletes cloned repository after 5 seconds
658
+ * - Also deletes associated Claude session directory
659
+ * - Remote branch and PR remain on GitHub if created
660
+ *
661
+ * @param {string} githubToken - (Optional) GitHub Personal Access Token for authentication.
662
+ * Overrides stored token from user settings.
663
+ * Required for:
664
+ * - Private repositories
665
+ * - Branch/PR creation features
666
+ * Token must have 'repo' scope for full functionality.
667
+ *
668
+ * @param {string} branchName - (Optional) Custom name for the Git branch.
669
+ * If provided, createBranch is automatically set to true.
670
+ * Validation rules (errors returned if violated):
671
+ * - Cannot be empty or whitespace only
672
+ * - Cannot start or end with dot (.)
673
+ * - Cannot contain consecutive dots (..)
674
+ * - Cannot contain spaces
675
+ * - Cannot contain special characters: ~ ^ : ? * [ \
676
+ * - Cannot contain @{
677
+ * - Cannot start or end with forward slash (/)
678
+ * - Cannot contain consecutive slashes (//)
679
+ * - Cannot end with .lock
680
+ * - Cannot contain ASCII control characters
681
+ * Examples: 'feature/user-auth', 'bugfix/login-error', 'refactor/db-optimization'
682
+ *
683
+ * @param {boolean} createBranch - (Optional) Create a new Git branch after successful agent completion.
684
+ * Default: false (or true if branchName is provided)
685
+ * Behavior:
686
+ * - Creates branch locally and pushes to remote
687
+ * - If branch exists locally: Checks out existing branch (no error)
688
+ * - If branch exists on remote: Uses existing branch (no error)
689
+ * - Branch name: Custom (if branchName provided) or auto-generated from message
690
+ * - Requires either githubUrl OR projectPath with GitHub remote
691
+ *
692
+ * @param {boolean} createPR - (Optional) Create a GitHub Pull Request after successful completion.
693
+ * Default: false
694
+ * Behavior:
695
+ * - PR title: First commit message (or fallback to message parameter)
696
+ * - PR description: Auto-generated from all commit messages
697
+ * - Base branch: Always 'main' (currently hardcoded)
698
+ * - If PR already exists: GitHub returns error with details
699
+ * - Requires either githubUrl OR projectPath with GitHub remote
700
+ *
701
+ * ================================================================================================
702
+ * PATH HANDLING BEHAVIOR
703
+ * ================================================================================================
704
+ *
705
+ * Scenario 1: Only githubUrl provided
706
+ * Input: { githubUrl: "https://github.com/owner/repo" }
707
+ * Action: Clones to auto-generated temporary path: ~/.claude/external-projects/<hash>/
708
+ * Cleanup: Yes (if cleanup=true)
709
+ *
710
+ * Scenario 2: Only projectPath provided
711
+ * Input: { projectPath: "/home/user/my-project" }
712
+ * Action: Uses existing project at specified path
713
+ * Validation: Path must exist and be accessible
714
+ * Cleanup: No (never cleanup existing projects)
715
+ *
716
+ * Scenario 3: Both githubUrl and projectPath provided
717
+ * Input: { githubUrl: "https://github.com/owner/repo", projectPath: "/custom/path" }
718
+ * Action: Clones githubUrl to projectPath location
719
+ * Validation:
720
+ * - If projectPath exists with git repo:
721
+ * - Compares remote URL with githubUrl
722
+ * - If URLs match: Reuses existing repo
723
+ * - If URLs differ: Returns error
724
+ * Cleanup: Yes (if cleanup=true)
725
+ *
726
+ * ================================================================================================
727
+ * GITHUB BRANCH/PR CREATION REQUIREMENTS
728
+ * ================================================================================================
729
+ *
730
+ * For createBranch or createPR to work, one of the following must be true:
731
+ *
732
+ * Option A: githubUrl provided
733
+ * - Repository URL directly specified
734
+ * - Works with both cloning and existing paths
735
+ *
736
+ * Option B: projectPath with GitHub remote
737
+ * - Project must be a Git repository
738
+ * - Must have 'origin' remote configured
739
+ * - Remote URL must point to github.com
740
+ * - System auto-detects GitHub URL via: git remote get-url origin
741
+ *
742
+ * Additional Requirements:
743
+ * - Valid GitHub token (from settings or githubToken parameter)
744
+ * - Token must have 'repo' scope for private repos
745
+ * - Project must have commits (for PR creation)
746
+ *
747
+ * ================================================================================================
748
+ * VALIDATION & ERROR HANDLING
749
+ * ================================================================================================
750
+ *
751
+ * Input Validations (400 Bad Request):
752
+ * - Either githubUrl OR projectPath must be provided (not neither)
753
+ * - message must be non-empty string
754
+ * - provider must be 'claude' or 'cursor'
755
+ * - createBranch/createPR requires githubUrl OR projectPath (not neither)
756
+ * - branchName must pass Git naming rules (if provided)
757
+ *
758
+ * Runtime Validations (500 Internal Server Error or specific error in response):
759
+ * - projectPath must exist (if used alone)
760
+ * - GitHub URL format must be valid
761
+ * - Git remote URL must include github.com (for projectPath + branch/PR)
762
+ * - GitHub token must be available (for private repos and branch/PR)
763
+ * - Directory conflicts handled (existing path with different repo)
764
+ *
765
+ * Branch Name Validation Errors (returned in response, not HTTP error):
766
+ * Invalid names return: { branch: { error: "Invalid branch name: <reason>" } }
767
+ * Examples:
768
+ * - "my branch" → "Branch name cannot contain spaces"
769
+ * - ".feature" → "Branch name cannot start with a dot"
770
+ * - "feature.lock" → "Branch name cannot end with .lock"
771
+ *
772
+ * ================================================================================================
773
+ * RESPONSE FORMATS
774
+ * ================================================================================================
775
+ *
776
+ * Streaming Response (stream=true):
777
+ * Content-Type: text/event-stream
778
+ * Events:
779
+ * - { type: "status", message: "...", projectPath: "..." }
780
+ * - { type: "claude-response", data: {...} }
781
+ * - { type: "github-branch", branch: { name: "...", url: "..." } }
782
+ * - { type: "github-pr", pullRequest: { number: 42, url: "..." } }
783
+ * - { type: "github-error", error: "..." }
784
+ * - { type: "done" }
785
+ *
786
+ * Non-Streaming Response (stream=false):
787
+ * Content-Type: application/json
788
+ * {
789
+ * success: true,
790
+ * sessionId: "session-123",
791
+ * messages: [...], // Assistant messages only (filtered)
792
+ * tokens: {
793
+ * inputTokens: 150,
794
+ * outputTokens: 50,
795
+ * cacheReadTokens: 0,
796
+ * cacheCreationTokens: 0,
797
+ * totalTokens: 200
798
+ * },
799
+ * projectPath: "/path/to/project",
800
+ * branch: { // Only if createBranch=true
801
+ * name: "feature/xyz",
802
+ * url: "https://github.com/owner/repo/tree/feature/xyz"
803
+ * } | { error: "..." },
804
+ * pullRequest: { // Only if createPR=true
805
+ * number: 42,
806
+ * url: "https://github.com/owner/repo/pull/42"
807
+ * } | { error: "..." }
808
+ * }
809
+ *
810
+ * Error Response:
811
+ * HTTP Status: 400, 401, 500
812
+ * Content-Type: application/json
813
+ * { success: false, error: "Error description" }
814
+ *
815
+ * ================================================================================================
816
+ * EXAMPLES
817
+ * ================================================================================================
818
+ *
819
+ * Example 1: Clone and process with auto-cleanup
820
+ * POST /api/agent
821
+ * { "githubUrl": "https://github.com/user/repo", "message": "Fix bug" }
822
+ *
823
+ * Example 2: Use existing project with custom branch and PR
824
+ * POST /api/agent
825
+ * {
826
+ * "projectPath": "/home/user/project",
827
+ * "message": "Add feature",
828
+ * "branchName": "feature/new-feature",
829
+ * "createPR": true
830
+ * }
831
+ *
832
+ * Example 3: Clone to specific path with auto-generated branch
833
+ * POST /api/agent
834
+ * {
835
+ * "githubUrl": "https://github.com/user/repo",
836
+ * "projectPath": "/tmp/work",
837
+ * "message": "Refactor code",
838
+ * "createBranch": true,
839
+ * "cleanup": false
840
+ * }
841
+ */
842
+ router.post('/', validateExternalApiKey, async (req, res) => {
843
+ const { githubUrl, projectPath, message, provider = 'claude', model, githubToken, branchName } = req.body;
844
+
845
+ // Parse stream and cleanup as booleans (handle string "true"/"false" from curl)
846
+ const stream = req.body.stream === undefined ? true : (req.body.stream === true || req.body.stream === 'true');
847
+ const cleanup = req.body.cleanup === undefined ? true : (req.body.cleanup === true || req.body.cleanup === 'true');
848
+
849
+ // If branchName is provided, automatically enable createBranch
850
+ const createBranch = branchName ? true : (req.body.createBranch === true || req.body.createBranch === 'true');
851
+ const createPR = req.body.createPR === true || req.body.createPR === 'true';
852
+
853
+ // Validate inputs
854
+ if (!githubUrl && !projectPath) {
855
+ return res.status(400).json({ error: 'Either githubUrl or projectPath is required' });
856
+ }
857
+
858
+ if (!message || !message.trim()) {
859
+ return res.status(400).json({ error: 'message is required' });
860
+ }
861
+
862
+ if (!['claude', 'cursor', 'codex', 'gemini', 'openrouter', 'local'].includes(provider)) {
863
+ return res.status(400).json({ error: 'provider must be "claude", "cursor", "codex", "gemini", "openrouter", or "local"' });
864
+ }
865
+
866
+ // Validate GitHub branch/PR creation requirements
867
+ // Allow branch/PR creation with projectPath as long as it has a GitHub remote
868
+ if ((createBranch || createPR) && !githubUrl && !projectPath) {
869
+ return res.status(400).json({ error: 'createBranch and createPR require either githubUrl or projectPath with a GitHub remote' });
870
+ }
871
+
872
+ let finalProjectPath = null;
873
+ let writer = null;
874
+
875
+ try {
876
+ // Determine the final project path
877
+ if (githubUrl) {
878
+ // Clone repository (to projectPath if provided, otherwise generate path)
879
+ const tokenToUse = githubToken || githubTokensDb.getActiveGithubToken(req.user.id);
880
+
881
+ let targetPath;
882
+ if (projectPath) {
883
+ targetPath = projectPath;
884
+ } else {
885
+ // Generate a unique path for cloning
886
+ const repoHash = crypto.createHash('md5').update(githubUrl + Date.now()).digest('hex');
887
+ targetPath = path.join(os.homedir(), '.claude', 'external-projects', repoHash);
888
+ }
889
+
890
+ finalProjectPath = await cloneGitHubRepo(githubUrl.trim(), tokenToUse, targetPath);
891
+ } else {
892
+ // Use existing project path
893
+ finalProjectPath = path.resolve(projectPath);
894
+
895
+ // Verify the path exists
896
+ try {
897
+ await fs.access(finalProjectPath);
898
+ } catch (error) {
899
+ throw new Error(`Project path does not exist: ${finalProjectPath}`);
900
+ }
901
+ }
902
+
903
+ // Register the project (or use existing registration)
904
+ let project;
905
+ try {
906
+ project = await addProjectManually(finalProjectPath);
907
+ console.log('đŸ“Ļ Project registered:', project);
908
+ } catch (error) {
909
+ // If project already exists, that's fine - continue with the existing registration
910
+ if (error.message && error.message.includes('Project already configured')) {
911
+ console.log('đŸ“Ļ Using existing project registration for:', finalProjectPath);
912
+ project = { path: finalProjectPath };
913
+ } else {
914
+ throw error;
915
+ }
916
+ }
917
+
918
+ // Set up writer based on streaming mode
919
+ if (stream) {
920
+ // Set up SSE headers for streaming
921
+ res.setHeader('Content-Type', 'text/event-stream');
922
+ res.setHeader('Cache-Control', 'no-cache');
923
+ res.setHeader('Connection', 'keep-alive');
924
+ res.setHeader('X-Accel-Buffering', 'no'); // Disable nginx buffering
925
+
926
+ writer = new SSEStreamWriter(res);
927
+
928
+ // Send initial status
929
+ writer.send({
930
+ type: 'status',
931
+ message: githubUrl ? 'Repository cloned and session started' : 'Session started',
932
+ projectPath: finalProjectPath
933
+ });
934
+ } else {
935
+ // Non-streaming mode: collect messages
936
+ writer = new ResponseCollector();
937
+
938
+ // Collect initial status message
939
+ writer.send({
940
+ type: 'status',
941
+ message: githubUrl ? 'Repository cloned and session started' : 'Session started',
942
+ projectPath: finalProjectPath
943
+ });
944
+ }
945
+
946
+ const geminiApiKey = getGeminiApiKeyForUser(req.user?.id);
947
+ const sessionEnv = withGeminiApiKeyEnv(process.env, geminiApiKey);
948
+
949
+ // Start the appropriate session
950
+ if (provider === 'claude') {
951
+ console.log('🤖 Starting Claude SDK session');
952
+
953
+ await queryClaudeSDK(message.trim(), {
954
+ projectPath: finalProjectPath,
955
+ cwd: finalProjectPath,
956
+ sessionId: null, // New session
957
+ model: model,
958
+ env: sessionEnv,
959
+ permissionMode: 'bypassPermissions' // Bypass all permissions for API calls
960
+ }, writer);
961
+
962
+ } else if (provider === 'cursor') {
963
+ console.log('đŸ–ąī¸ Starting Cursor CLI session');
964
+
965
+ await spawnCursor(message.trim(), {
966
+ projectPath: finalProjectPath,
967
+ cwd: finalProjectPath,
968
+ sessionId: null, // New session
969
+ model: model || undefined,
970
+ env: sessionEnv,
971
+ skipPermissions: true // Bypass permissions for Cursor
972
+ }, writer);
973
+ } else if (provider === 'codex') {
974
+ console.log('🤖 Starting Codex SDK session');
975
+
976
+ await queryCodex(message.trim(), {
977
+ projectPath: finalProjectPath,
978
+ cwd: finalProjectPath,
979
+ sessionId: null,
980
+ model: model || CODEX_MODELS.DEFAULT,
981
+ env: sessionEnv,
982
+ permissionMode: 'bypassPermissions'
983
+ }, writer);
984
+ } else if (provider === 'gemini') {
985
+ console.log('🤖 Starting Gemini CLI session');
986
+
987
+ await spawnGemini(message.trim(), {
988
+ projectPath: finalProjectPath,
989
+ cwd: finalProjectPath,
990
+ sessionId: null,
991
+ env: sessionEnv,
992
+ model: model || GEMINI_MODELS.DEFAULT
993
+ }, writer);
994
+ } else if (provider === 'openrouter') {
995
+ console.log('🤖 Starting OpenRouter session');
996
+
997
+ await queryOpenRouter(message.trim(), {
998
+ projectPath: finalProjectPath,
999
+ cwd: finalProjectPath,
1000
+ sessionId: null,
1001
+ model: model || OPENROUTER_MODELS.DEFAULT,
1002
+ env: sessionEnv,
1003
+ }, writer);
1004
+ } else if (provider === 'local') {
1005
+ console.log('🤖 Starting Local GPU session');
1006
+
1007
+ await queryLocalGPU(message.trim(), {
1008
+ projectPath: finalProjectPath,
1009
+ cwd: finalProjectPath,
1010
+ sessionId: null,
1011
+ model: model || LOCAL_MODELS.DEFAULT || 'qwen3:8b',
1012
+ env: sessionEnv,
1013
+ permissionMode: 'bypassPermissions',
1014
+ }, writer);
1015
+ }
1016
+
1017
+ // Handle GitHub branch and PR creation after successful agent completion
1018
+ let branchInfo = null;
1019
+ let prInfo = null;
1020
+
1021
+ if (createBranch || createPR) {
1022
+ try {
1023
+ console.log('🔄 Starting GitHub branch/PR creation workflow...');
1024
+
1025
+ // Get GitHub token
1026
+ const tokenToUse = githubToken || githubTokensDb.getActiveGithubToken(req.user.id);
1027
+
1028
+ if (!tokenToUse) {
1029
+ throw new Error('GitHub token required for branch/PR creation. Please configure a GitHub token in settings.');
1030
+ }
1031
+
1032
+ // Initialize Octokit
1033
+ const octokit = new Octokit({ auth: tokenToUse });
1034
+
1035
+ // Get GitHub URL - either from parameter or from git remote
1036
+ let repoUrl = githubUrl;
1037
+ if (!repoUrl) {
1038
+ console.log('🔍 Getting GitHub URL from git remote...');
1039
+ try {
1040
+ repoUrl = await getGitRemoteUrl(finalProjectPath);
1041
+ if (!repoUrl.includes('github.com')) {
1042
+ throw new Error('Project does not have a GitHub remote configured');
1043
+ }
1044
+ console.log(`✅ Found GitHub remote: ${repoUrl}`);
1045
+ } catch (error) {
1046
+ throw new Error(`Failed to get GitHub remote URL: ${error.message}`);
1047
+ }
1048
+ }
1049
+
1050
+ // Parse GitHub URL to get owner and repo
1051
+ const { owner, repo } = parseGitHubUrl(repoUrl);
1052
+ console.log(`đŸ“Ļ Repository: ${owner}/${repo}`);
1053
+
1054
+ // Use provided branch name or auto-generate from message
1055
+ const finalBranchName = branchName || autogenerateBranchName(message);
1056
+ if (branchName) {
1057
+ console.log(`đŸŒŋ Using provided branch name: ${finalBranchName}`);
1058
+
1059
+ // Validate custom branch name
1060
+ const validation = validateBranchName(finalBranchName);
1061
+ if (!validation.valid) {
1062
+ throw new Error(`Invalid branch name: ${validation.error}`);
1063
+ }
1064
+ } else {
1065
+ console.log(`đŸŒŋ Auto-generated branch name: ${finalBranchName}`);
1066
+ }
1067
+
1068
+ if (createBranch) {
1069
+ // Create and checkout the new branch locally
1070
+ console.log('🔄 Creating local branch...');
1071
+ const checkoutProcess = spawn('git', ['checkout', '-b', finalBranchName], {
1072
+ cwd: finalProjectPath,
1073
+ stdio: 'pipe'
1074
+ });
1075
+
1076
+ await new Promise((resolve, reject) => {
1077
+ let stderr = '';
1078
+ checkoutProcess.stderr.on('data', (data) => { stderr += data.toString(); });
1079
+ checkoutProcess.on('close', (code) => {
1080
+ if (code === 0) {
1081
+ console.log(`✅ Created and checked out local branch '${finalBranchName}'`);
1082
+ resolve();
1083
+ } else {
1084
+ // Branch might already exist locally, try to checkout
1085
+ if (stderr.includes('already exists')) {
1086
+ console.log(`â„šī¸ Branch '${finalBranchName}' already exists locally, checking out...`);
1087
+ const checkoutExisting = spawn('git', ['checkout', finalBranchName], {
1088
+ cwd: finalProjectPath,
1089
+ stdio: 'pipe'
1090
+ });
1091
+ checkoutExisting.on('close', (checkoutCode) => {
1092
+ if (checkoutCode === 0) {
1093
+ console.log(`✅ Checked out existing branch '${finalBranchName}'`);
1094
+ resolve();
1095
+ } else {
1096
+ reject(new Error(`Failed to checkout existing branch: ${stderr}`));
1097
+ }
1098
+ });
1099
+ } else {
1100
+ reject(new Error(`Failed to create branch: ${stderr}`));
1101
+ }
1102
+ }
1103
+ });
1104
+ });
1105
+
1106
+ // Push the branch to remote
1107
+ console.log('🔄 Pushing branch to remote...');
1108
+ const pushProcess = spawn('git', ['push', '-u', 'origin', finalBranchName], {
1109
+ cwd: finalProjectPath,
1110
+ stdio: 'pipe'
1111
+ });
1112
+
1113
+ await new Promise((resolve, reject) => {
1114
+ let stderr = '';
1115
+ let stdout = '';
1116
+ pushProcess.stdout.on('data', (data) => { stdout += data.toString(); });
1117
+ pushProcess.stderr.on('data', (data) => { stderr += data.toString(); });
1118
+ pushProcess.on('close', (code) => {
1119
+ if (code === 0) {
1120
+ console.log(`✅ Pushed branch '${finalBranchName}' to remote`);
1121
+ resolve();
1122
+ } else {
1123
+ // Check if branch exists on remote but has different commits
1124
+ if (stderr.includes('already exists') || stderr.includes('up-to-date')) {
1125
+ console.log(`â„šī¸ Branch '${finalBranchName}' already exists on remote, using existing branch`);
1126
+ resolve();
1127
+ } else {
1128
+ reject(new Error(`Failed to push branch: ${stderr}`));
1129
+ }
1130
+ }
1131
+ });
1132
+ });
1133
+
1134
+ branchInfo = {
1135
+ name: finalBranchName,
1136
+ url: `https://github.com/${owner}/${repo}/tree/${finalBranchName}`
1137
+ };
1138
+ }
1139
+
1140
+ if (createPR) {
1141
+ // Get commit messages to generate PR description
1142
+ console.log('🔄 Generating PR title and description...');
1143
+ const commitMessages = await getCommitMessages(finalProjectPath, 5);
1144
+
1145
+ // Use the first commit message as the PR title, or fallback to the agent message
1146
+ const prTitle = commitMessages.length > 0 ? commitMessages[0] : message;
1147
+
1148
+ // Generate PR body from commit messages
1149
+ let prBody = '## Changes\n\n';
1150
+ if (commitMessages.length > 0) {
1151
+ prBody += commitMessages.map(msg => `- ${msg}`).join('\n');
1152
+ } else {
1153
+ prBody += `Agent task: ${message}`;
1154
+ }
1155
+ prBody += '\n\n---\n*This pull request was automatically created by Dr. Claw Agent.*';
1156
+
1157
+ console.log(`📝 PR Title: ${prTitle}`);
1158
+
1159
+ // Create the pull request
1160
+ console.log('🔄 Creating pull request...');
1161
+ prInfo = await createGitHubPR(octokit, owner, repo, finalBranchName, prTitle, prBody, 'main');
1162
+ }
1163
+
1164
+ // Send branch/PR info in response
1165
+ if (stream) {
1166
+ if (branchInfo) {
1167
+ writer.send({
1168
+ type: 'github-branch',
1169
+ branch: branchInfo
1170
+ });
1171
+ }
1172
+ if (prInfo) {
1173
+ writer.send({
1174
+ type: 'github-pr',
1175
+ pullRequest: prInfo
1176
+ });
1177
+ }
1178
+ }
1179
+
1180
+ } catch (error) {
1181
+ console.error('❌ GitHub branch/PR creation error:', error);
1182
+
1183
+ // Send error but don't fail the entire request
1184
+ if (stream) {
1185
+ writer.send({
1186
+ type: 'github-error',
1187
+ error: error.message
1188
+ });
1189
+ }
1190
+ // Store error info for non-streaming response
1191
+ if (!stream) {
1192
+ branchInfo = { error: error.message };
1193
+ prInfo = { error: error.message };
1194
+ }
1195
+ }
1196
+ }
1197
+
1198
+ // Handle response based on streaming mode
1199
+ if (stream) {
1200
+ // Streaming mode: end the SSE stream
1201
+ writer.end();
1202
+ } else {
1203
+ // Non-streaming mode: send filtered messages and token summary as JSON
1204
+ const assistantMessages = writer.getAssistantMessages();
1205
+ const tokenSummary = writer.getTotalTokens();
1206
+
1207
+ const response = {
1208
+ success: true,
1209
+ sessionId: writer.getSessionId(),
1210
+ messages: assistantMessages,
1211
+ tokens: tokenSummary,
1212
+ projectPath: finalProjectPath
1213
+ };
1214
+
1215
+ // Add branch/PR info if created
1216
+ if (branchInfo) {
1217
+ response.branch = branchInfo;
1218
+ }
1219
+ if (prInfo) {
1220
+ response.pullRequest = prInfo;
1221
+ }
1222
+
1223
+ res.json(response);
1224
+ }
1225
+
1226
+ // Clean up if requested
1227
+ if (cleanup && githubUrl) {
1228
+ // Only cleanup if we cloned a repo (not for existing project paths)
1229
+ const sessionIdForCleanup = writer.getSessionId();
1230
+ setTimeout(() => {
1231
+ cleanupProject(finalProjectPath, sessionIdForCleanup);
1232
+ }, 5000);
1233
+ }
1234
+
1235
+ } catch (error) {
1236
+ console.error('❌ External session error:', error);
1237
+
1238
+ // Clean up on error
1239
+ if (finalProjectPath && cleanup && githubUrl) {
1240
+ const sessionIdForCleanup = writer ? writer.getSessionId() : null;
1241
+ cleanupProject(finalProjectPath, sessionIdForCleanup);
1242
+ }
1243
+
1244
+ if (stream) {
1245
+ // For streaming, send error event and stop
1246
+ if (!writer) {
1247
+ // Set up SSE headers if not already done
1248
+ res.setHeader('Content-Type', 'text/event-stream');
1249
+ res.setHeader('Cache-Control', 'no-cache');
1250
+ res.setHeader('Connection', 'keep-alive');
1251
+ res.setHeader('X-Accel-Buffering', 'no');
1252
+ writer = new SSEStreamWriter(res);
1253
+ }
1254
+
1255
+ if (!res.writableEnded) {
1256
+ writer.send({
1257
+ type: 'error',
1258
+ error: error.message,
1259
+ message: `Failed: ${error.message}`
1260
+ });
1261
+ writer.end();
1262
+ }
1263
+ } else if (!res.headersSent) {
1264
+ res.status(500).json({
1265
+ success: false,
1266
+ error: error.message
1267
+ });
1268
+ }
1269
+ }
1270
+ });
1271
+
1272
+ export default router;