claude-wec 1.0.0

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