@axhub/genie 0.1.1

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 (140) hide show
  1. package/LICENSE +675 -0
  2. package/README.md +2 -0
  3. package/dist/api-docs.html +922 -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-C75hHmvH.js +1249 -0
  64. package/dist/assets/index-CtRxrKDm.css +32 -0
  65. package/dist/assets/vendor-codemirror-B88_OPWf.js +39 -0
  66. package/dist/assets/vendor-react-C3RJLQGO.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 +108 -0
  110. package/server/claude-sdk.js +724 -0
  111. package/server/cli.js +439 -0
  112. package/server/constants/config.js +5 -0
  113. package/server/cursor-cli.js +276 -0
  114. package/server/database/auth.db +0 -0
  115. package/server/database/db.js +361 -0
  116. package/server/database/init.sql +52 -0
  117. package/server/index.js +1944 -0
  118. package/server/load-env.js +24 -0
  119. package/server/middleware/auth.js +117 -0
  120. package/server/openai-codex.js +447 -0
  121. package/server/projects.js +1679 -0
  122. package/server/routes/agent.js +1327 -0
  123. package/server/routes/auth.js +135 -0
  124. package/server/routes/cli-auth.js +263 -0
  125. package/server/routes/codex.js +344 -0
  126. package/server/routes/commands.js +521 -0
  127. package/server/routes/cursor.js +795 -0
  128. package/server/routes/git.js +1128 -0
  129. package/server/routes/mcp-utils.js +48 -0
  130. package/server/routes/mcp.js +552 -0
  131. package/server/routes/projects.js +550 -0
  132. package/server/routes/settings.js +178 -0
  133. package/server/routes/taskmaster.js +1963 -0
  134. package/server/routes/user.js +106 -0
  135. package/server/utils/codexTokenUsage.js +87 -0
  136. package/server/utils/commandParser.js +303 -0
  137. package/server/utils/gitConfig.js +24 -0
  138. package/server/utils/mcp-detector.js +198 -0
  139. package/server/utils/taskmaster-websocket.js +129 -0
  140. package/shared/modelConstants.js +65 -0
@@ -0,0 +1,550 @@
1
+ import express from 'express';
2
+ import { promises as fs } from 'fs';
3
+ import path from 'path';
4
+ import { spawn } from 'child_process';
5
+ import os from 'os';
6
+ import { addProjectManually } from '../projects.js';
7
+
8
+ const router = express.Router();
9
+
10
+ function sanitizeGitError(message, token) {
11
+ if (!message || !token) return message;
12
+ return message.replace(new RegExp(token.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'), '***');
13
+ }
14
+
15
+ // Configure allowed workspace root (defaults to user's home directory)
16
+ export const WORKSPACES_ROOT = process.env.WORKSPACES_ROOT || os.homedir();
17
+
18
+ // System-critical paths that should never be used as workspace directories
19
+ export const FORBIDDEN_PATHS = [
20
+ // Unix
21
+ '/',
22
+ '/etc',
23
+ '/bin',
24
+ '/sbin',
25
+ '/usr',
26
+ '/dev',
27
+ '/proc',
28
+ '/sys',
29
+ '/var',
30
+ '/boot',
31
+ '/root',
32
+ '/lib',
33
+ '/lib64',
34
+ '/opt',
35
+ '/tmp',
36
+ '/run',
37
+ // Windows
38
+ 'C:\\Windows',
39
+ 'C:\\Program Files',
40
+ 'C:\\Program Files (x86)',
41
+ 'C:\\ProgramData',
42
+ 'C:\\System Volume Information',
43
+ 'C:\\$Recycle.Bin'
44
+ ];
45
+
46
+ /**
47
+ * Validates that a path is safe for workspace operations
48
+ * @param {string} requestedPath - The path to validate
49
+ * @returns {Promise<{valid: boolean, resolvedPath?: string, error?: string}>}
50
+ */
51
+ export async function validateWorkspacePath(requestedPath) {
52
+ try {
53
+ // Resolve to absolute path
54
+ let absolutePath = path.resolve(requestedPath);
55
+
56
+ // Check if path is a forbidden system directory
57
+ const normalizedPath = path.normalize(absolutePath);
58
+ if (FORBIDDEN_PATHS.includes(normalizedPath) || normalizedPath === '/') {
59
+ return {
60
+ valid: false,
61
+ error: 'Cannot use system-critical directories as workspace locations'
62
+ };
63
+ }
64
+
65
+ // Additional check for paths starting with forbidden directories
66
+ for (const forbidden of FORBIDDEN_PATHS) {
67
+ if (normalizedPath === forbidden ||
68
+ normalizedPath.startsWith(forbidden + path.sep)) {
69
+ // Exception: /var/tmp and similar user-accessible paths might be allowed
70
+ // but /var itself and most /var subdirectories should be blocked
71
+ if (forbidden === '/var' &&
72
+ (normalizedPath.startsWith('/var/tmp') ||
73
+ normalizedPath.startsWith('/var/folders'))) {
74
+ continue; // Allow these specific cases
75
+ }
76
+
77
+ return {
78
+ valid: false,
79
+ error: `Cannot create workspace in system directory: ${forbidden}`
80
+ };
81
+ }
82
+ }
83
+
84
+ // Try to resolve the real path (following symlinks)
85
+ let realPath;
86
+ try {
87
+ // Check if path exists to resolve real path
88
+ await fs.access(absolutePath);
89
+ realPath = await fs.realpath(absolutePath);
90
+ } catch (error) {
91
+ if (error.code === 'ENOENT') {
92
+ // Path doesn't exist yet - check parent directory
93
+ let parentPath = path.dirname(absolutePath);
94
+ try {
95
+ const parentRealPath = await fs.realpath(parentPath);
96
+
97
+ // Reconstruct the full path with real parent
98
+ realPath = path.join(parentRealPath, path.basename(absolutePath));
99
+ } catch (parentError) {
100
+ if (parentError.code === 'ENOENT') {
101
+ // Parent doesn't exist either - use the absolute path as-is
102
+ // We'll validate it's within allowed root
103
+ realPath = absolutePath;
104
+ } else {
105
+ throw parentError;
106
+ }
107
+ }
108
+ } else {
109
+ throw error;
110
+ }
111
+ }
112
+
113
+ // Resolve the workspace root to its real path
114
+ const resolvedWorkspaceRoot = await fs.realpath(WORKSPACES_ROOT);
115
+
116
+ // Ensure the resolved path is contained within the allowed workspace root
117
+ if (!realPath.startsWith(resolvedWorkspaceRoot + path.sep) &&
118
+ realPath !== resolvedWorkspaceRoot) {
119
+ return {
120
+ valid: false,
121
+ error: `Workspace path must be within the allowed workspace root: ${WORKSPACES_ROOT}`
122
+ };
123
+ }
124
+
125
+ // Additional symlink check for existing paths
126
+ try {
127
+ await fs.access(absolutePath);
128
+ const stats = await fs.lstat(absolutePath);
129
+
130
+ if (stats.isSymbolicLink()) {
131
+ // Verify symlink target is also within allowed root
132
+ const linkTarget = await fs.readlink(absolutePath);
133
+ const resolvedTarget = path.resolve(path.dirname(absolutePath), linkTarget);
134
+ const realTarget = await fs.realpath(resolvedTarget);
135
+
136
+ if (!realTarget.startsWith(resolvedWorkspaceRoot + path.sep) &&
137
+ realTarget !== resolvedWorkspaceRoot) {
138
+ return {
139
+ valid: false,
140
+ error: 'Symlink target is outside the allowed workspace root'
141
+ };
142
+ }
143
+ }
144
+ } catch (error) {
145
+ if (error.code !== 'ENOENT') {
146
+ throw error;
147
+ }
148
+ // Path doesn't exist - that's fine for new workspace creation
149
+ }
150
+
151
+ return {
152
+ valid: true,
153
+ resolvedPath: realPath
154
+ };
155
+
156
+ } catch (error) {
157
+ return {
158
+ valid: false,
159
+ error: `Path validation failed: ${error.message}`
160
+ };
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Create a new workspace
166
+ * POST /api/projects/create-workspace
167
+ *
168
+ * Body:
169
+ * - workspaceType: 'existing' | 'new'
170
+ * - path: string (workspace path)
171
+ * - githubUrl?: string (optional, for new workspaces)
172
+ * - githubTokenId?: number (optional, ID of stored token)
173
+ * - newGithubToken?: string (optional, one-time token)
174
+ */
175
+ router.post('/create-workspace', async (req, res) => {
176
+ try {
177
+ const { workspaceType, path: workspacePath, githubUrl, githubTokenId, newGithubToken } = req.body;
178
+
179
+ // Validate required fields
180
+ if (!workspaceType || !workspacePath) {
181
+ return res.status(400).json({ error: 'workspaceType and path are required' });
182
+ }
183
+
184
+ if (!['existing', 'new'].includes(workspaceType)) {
185
+ return res.status(400).json({ error: 'workspaceType must be "existing" or "new"' });
186
+ }
187
+
188
+ // Validate path safety before any operations
189
+ const validation = await validateWorkspacePath(workspacePath);
190
+ if (!validation.valid) {
191
+ return res.status(400).json({
192
+ error: 'Invalid workspace path',
193
+ details: validation.error
194
+ });
195
+ }
196
+
197
+ const absolutePath = validation.resolvedPath;
198
+
199
+ // Handle existing workspace
200
+ if (workspaceType === 'existing') {
201
+ // Check if the path exists
202
+ try {
203
+ await fs.access(absolutePath);
204
+ const stats = await fs.stat(absolutePath);
205
+
206
+ if (!stats.isDirectory()) {
207
+ return res.status(400).json({ error: 'Path exists but is not a directory' });
208
+ }
209
+ } catch (error) {
210
+ if (error.code === 'ENOENT') {
211
+ return res.status(404).json({ error: 'Workspace path does not exist' });
212
+ }
213
+ throw error;
214
+ }
215
+
216
+ // Add the existing workspace to the project list
217
+ const project = await addProjectManually(absolutePath);
218
+
219
+ return res.json({
220
+ success: true,
221
+ project,
222
+ message: 'Existing workspace added successfully'
223
+ });
224
+ }
225
+
226
+ // Handle new workspace creation
227
+ if (workspaceType === 'new') {
228
+ // Create the directory if it doesn't exist
229
+ await fs.mkdir(absolutePath, { recursive: true });
230
+
231
+ // If GitHub URL is provided, clone the repository
232
+ if (githubUrl) {
233
+ let githubToken = null;
234
+
235
+ // Get GitHub token if needed
236
+ if (githubTokenId) {
237
+ // Fetch token from database
238
+ const token = await getGithubTokenById(githubTokenId, req.user.id);
239
+ if (!token) {
240
+ // Clean up created directory
241
+ await fs.rm(absolutePath, { recursive: true, force: true });
242
+ return res.status(404).json({ error: 'GitHub token not found' });
243
+ }
244
+ githubToken = token.github_token;
245
+ } else if (newGithubToken) {
246
+ githubToken = newGithubToken;
247
+ }
248
+
249
+ // Extract repo name from URL for the clone destination
250
+ const normalizedUrl = githubUrl.replace(/\/+$/, '').replace(/\.git$/, '');
251
+ const repoName = normalizedUrl.split('/').pop() || 'repository';
252
+ const clonePath = path.join(absolutePath, repoName);
253
+
254
+ // Check if clone destination already exists to prevent data loss
255
+ try {
256
+ await fs.access(clonePath);
257
+ return res.status(409).json({
258
+ error: 'Directory already exists',
259
+ details: `The destination path "${clonePath}" already exists. Please choose a different location or remove the existing directory.`
260
+ });
261
+ } catch (err) {
262
+ // Directory doesn't exist, which is what we want
263
+ }
264
+
265
+ // Clone the repository into a subfolder
266
+ try {
267
+ await cloneGitHubRepository(githubUrl, clonePath, githubToken);
268
+ } catch (error) {
269
+ // Only clean up if clone created partial data (check if dir exists and is empty or partial)
270
+ try {
271
+ const stats = await fs.stat(clonePath);
272
+ if (stats.isDirectory()) {
273
+ await fs.rm(clonePath, { recursive: true, force: true });
274
+ }
275
+ } catch (cleanupError) {
276
+ // Directory doesn't exist or cleanup failed - ignore
277
+ }
278
+ throw new Error(`Failed to clone repository: ${error.message}`);
279
+ }
280
+
281
+ // Add the cloned repo path to the project list
282
+ const project = await addProjectManually(clonePath);
283
+
284
+ return res.json({
285
+ success: true,
286
+ project,
287
+ message: 'New workspace created and repository cloned successfully'
288
+ });
289
+ }
290
+
291
+ // Add the new workspace to the project list (no clone)
292
+ const project = await addProjectManually(absolutePath);
293
+
294
+ return res.json({
295
+ success: true,
296
+ project,
297
+ message: 'New workspace created successfully'
298
+ });
299
+ }
300
+
301
+ } catch (error) {
302
+ console.error('Error creating workspace:', error);
303
+ res.status(500).json({
304
+ error: error.message || 'Failed to create workspace',
305
+ details: process.env.NODE_ENV === 'development' ? error.stack : undefined
306
+ });
307
+ }
308
+ });
309
+
310
+ /**
311
+ * Helper function to get GitHub token from database
312
+ */
313
+ async function getGithubTokenById(tokenId, userId) {
314
+ const { getDatabase } = await import('../database/db.js');
315
+ const db = await getDatabase();
316
+
317
+ const credential = await db.get(
318
+ 'SELECT * FROM user_credentials WHERE id = ? AND user_id = ? AND credential_type = ? AND is_active = 1',
319
+ [tokenId, userId, 'github_token']
320
+ );
321
+
322
+ // Return in the expected format (github_token field for compatibility)
323
+ if (credential) {
324
+ return {
325
+ ...credential,
326
+ github_token: credential.credential_value
327
+ };
328
+ }
329
+
330
+ return null;
331
+ }
332
+
333
+ /**
334
+ * Clone repository with progress streaming (SSE)
335
+ * GET /api/projects/clone-progress
336
+ */
337
+ router.get('/clone-progress', async (req, res) => {
338
+ const { path: workspacePath, githubUrl, githubTokenId, newGithubToken } = req.query;
339
+
340
+ res.setHeader('Content-Type', 'text/event-stream');
341
+ res.setHeader('Cache-Control', 'no-cache');
342
+ res.setHeader('Connection', 'keep-alive');
343
+ res.flushHeaders();
344
+
345
+ const sendEvent = (type, data) => {
346
+ res.write(`data: ${JSON.stringify({ type, ...data })}\n\n`);
347
+ };
348
+
349
+ try {
350
+ if (!workspacePath || !githubUrl) {
351
+ sendEvent('error', { message: 'workspacePath and githubUrl are required' });
352
+ res.end();
353
+ return;
354
+ }
355
+
356
+ const validation = await validateWorkspacePath(workspacePath);
357
+ if (!validation.valid) {
358
+ sendEvent('error', { message: validation.error });
359
+ res.end();
360
+ return;
361
+ }
362
+
363
+ const absolutePath = validation.resolvedPath;
364
+
365
+ await fs.mkdir(absolutePath, { recursive: true });
366
+
367
+ let githubToken = null;
368
+ if (githubTokenId) {
369
+ const token = await getGithubTokenById(parseInt(githubTokenId), req.user.id);
370
+ if (!token) {
371
+ await fs.rm(absolutePath, { recursive: true, force: true });
372
+ sendEvent('error', { message: 'GitHub token not found' });
373
+ res.end();
374
+ return;
375
+ }
376
+ githubToken = token.github_token;
377
+ } else if (newGithubToken) {
378
+ githubToken = newGithubToken;
379
+ }
380
+
381
+ const normalizedUrl = githubUrl.replace(/\/+$/, '').replace(/\.git$/, '');
382
+ const repoName = normalizedUrl.split('/').pop() || 'repository';
383
+ const clonePath = path.join(absolutePath, repoName);
384
+
385
+ // Check if clone destination already exists to prevent data loss
386
+ try {
387
+ await fs.access(clonePath);
388
+ sendEvent('error', { message: `Directory "${repoName}" already exists. Please choose a different location or remove the existing directory.` });
389
+ res.end();
390
+ return;
391
+ } catch (err) {
392
+ // Directory doesn't exist, which is what we want
393
+ }
394
+
395
+ let cloneUrl = githubUrl;
396
+ if (githubToken) {
397
+ try {
398
+ const url = new URL(githubUrl);
399
+ url.username = githubToken;
400
+ url.password = '';
401
+ cloneUrl = url.toString();
402
+ } catch (error) {
403
+ // SSH URL or invalid - use as-is
404
+ }
405
+ }
406
+
407
+ sendEvent('progress', { message: `Cloning into '${repoName}'...` });
408
+
409
+ const gitProcess = spawn('git', ['clone', '--progress', cloneUrl, clonePath], {
410
+ stdio: ['ignore', 'pipe', 'pipe'],
411
+ env: {
412
+ ...process.env,
413
+ GIT_TERMINAL_PROMPT: '0'
414
+ }
415
+ });
416
+
417
+ let lastError = '';
418
+
419
+ gitProcess.stdout.on('data', (data) => {
420
+ const message = data.toString().trim();
421
+ if (message) {
422
+ sendEvent('progress', { message });
423
+ }
424
+ });
425
+
426
+ gitProcess.stderr.on('data', (data) => {
427
+ const message = data.toString().trim();
428
+ lastError = message;
429
+ if (message) {
430
+ sendEvent('progress', { message });
431
+ }
432
+ });
433
+
434
+ gitProcess.on('close', async (code) => {
435
+ if (code === 0) {
436
+ try {
437
+ const project = await addProjectManually(clonePath);
438
+ sendEvent('complete', { project, message: 'Repository cloned successfully' });
439
+ } catch (error) {
440
+ sendEvent('error', { message: `Clone succeeded but failed to add project: ${error.message}` });
441
+ }
442
+ } else {
443
+ const sanitizedError = sanitizeGitError(lastError, githubToken);
444
+ let errorMessage = 'Git clone failed';
445
+ if (lastError.includes('Authentication failed') || lastError.includes('could not read Username')) {
446
+ errorMessage = 'Authentication failed. Please check your credentials.';
447
+ } else if (lastError.includes('Repository not found')) {
448
+ errorMessage = 'Repository not found. Please check the URL and ensure you have access.';
449
+ } else if (lastError.includes('already exists')) {
450
+ errorMessage = 'Directory already exists';
451
+ } else if (sanitizedError) {
452
+ errorMessage = sanitizedError;
453
+ }
454
+ try {
455
+ await fs.rm(clonePath, { recursive: true, force: true });
456
+ } catch (cleanupError) {
457
+ console.error('Failed to clean up after clone failure:', sanitizeGitError(cleanupError.message, githubToken));
458
+ }
459
+ sendEvent('error', { message: errorMessage });
460
+ }
461
+ res.end();
462
+ });
463
+
464
+ gitProcess.on('error', (error) => {
465
+ if (error.code === 'ENOENT') {
466
+ sendEvent('error', { message: 'Git is not installed or not in PATH' });
467
+ } else {
468
+ sendEvent('error', { message: error.message });
469
+ }
470
+ res.end();
471
+ });
472
+
473
+ req.on('close', () => {
474
+ gitProcess.kill();
475
+ });
476
+
477
+ } catch (error) {
478
+ sendEvent('error', { message: error.message });
479
+ res.end();
480
+ }
481
+ });
482
+
483
+ /**
484
+ * Helper function to clone a GitHub repository
485
+ */
486
+ function cloneGitHubRepository(githubUrl, destinationPath, githubToken = null) {
487
+ return new Promise((resolve, reject) => {
488
+ let cloneUrl = githubUrl;
489
+
490
+ if (githubToken) {
491
+ try {
492
+ const url = new URL(githubUrl);
493
+ url.username = githubToken;
494
+ url.password = '';
495
+ cloneUrl = url.toString();
496
+ } catch (error) {
497
+ // SSH URL - use as-is
498
+ }
499
+ }
500
+
501
+ const gitProcess = spawn('git', ['clone', '--progress', cloneUrl, destinationPath], {
502
+ stdio: ['ignore', 'pipe', 'pipe'],
503
+ env: {
504
+ ...process.env,
505
+ GIT_TERMINAL_PROMPT: '0'
506
+ }
507
+ });
508
+
509
+ let stdout = '';
510
+ let stderr = '';
511
+
512
+ gitProcess.stdout.on('data', (data) => {
513
+ stdout += data.toString();
514
+ });
515
+
516
+ gitProcess.stderr.on('data', (data) => {
517
+ stderr += data.toString();
518
+ });
519
+
520
+ gitProcess.on('close', (code) => {
521
+ if (code === 0) {
522
+ resolve({ stdout, stderr });
523
+ } else {
524
+ let errorMessage = 'Git clone failed';
525
+
526
+ if (stderr.includes('Authentication failed') || stderr.includes('could not read Username')) {
527
+ errorMessage = 'Authentication failed. Please check your GitHub token.';
528
+ } else if (stderr.includes('Repository not found')) {
529
+ errorMessage = 'Repository not found. Please check the URL and ensure you have access.';
530
+ } else if (stderr.includes('already exists')) {
531
+ errorMessage = 'Directory already exists';
532
+ } else if (stderr) {
533
+ errorMessage = stderr;
534
+ }
535
+
536
+ reject(new Error(errorMessage));
537
+ }
538
+ });
539
+
540
+ gitProcess.on('error', (error) => {
541
+ if (error.code === 'ENOENT') {
542
+ reject(new Error('Git is not installed or not in PATH'));
543
+ } else {
544
+ reject(error);
545
+ }
546
+ });
547
+ });
548
+ }
549
+
550
+ export default router;