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