notioncode 0.1.1 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/README.md +10 -4
  2. package/agent-runtime-server/package-lock.json +4377 -0
  3. package/agent-runtime-server/package.json +36 -0
  4. package/agent-runtime-server/scripts/fix-node-pty.js +67 -0
  5. package/agent-runtime-server/server/agent-session-service.js +816 -0
  6. package/agent-runtime-server/server/claude-sdk.js +836 -0
  7. package/agent-runtime-server/server/cli.js +330 -0
  8. package/agent-runtime-server/server/constants/config.js +5 -0
  9. package/agent-runtime-server/server/cursor-cli.js +335 -0
  10. package/agent-runtime-server/server/database/db.js +653 -0
  11. package/agent-runtime-server/server/database/init.sql +99 -0
  12. package/agent-runtime-server/server/gemini-cli.js +460 -0
  13. package/agent-runtime-server/server/gemini-response-handler.js +79 -0
  14. package/agent-runtime-server/server/index.js +2569 -0
  15. package/agent-runtime-server/server/load-env.js +32 -0
  16. package/agent-runtime-server/server/middleware/auth.js +132 -0
  17. package/agent-runtime-server/server/openai-codex.js +512 -0
  18. package/agent-runtime-server/server/projects.js +2594 -0
  19. package/agent-runtime-server/server/providers/claude/adapter.js +278 -0
  20. package/agent-runtime-server/server/providers/codex/adapter.js +248 -0
  21. package/agent-runtime-server/server/providers/cursor/adapter.js +353 -0
  22. package/agent-runtime-server/server/providers/gemini/adapter.js +186 -0
  23. package/agent-runtime-server/server/providers/registry.js +44 -0
  24. package/agent-runtime-server/server/providers/types.js +119 -0
  25. package/agent-runtime-server/server/providers/utils.js +29 -0
  26. package/agent-runtime-server/server/routes/agent-sessions.js +238 -0
  27. package/agent-runtime-server/server/routes/agent.js +1244 -0
  28. package/agent-runtime-server/server/routes/auth.js +144 -0
  29. package/agent-runtime-server/server/routes/cli-auth.js +478 -0
  30. package/agent-runtime-server/server/routes/codex.js +329 -0
  31. package/agent-runtime-server/server/routes/commands.js +596 -0
  32. package/agent-runtime-server/server/routes/cursor.js +798 -0
  33. package/agent-runtime-server/server/routes/gemini.js +24 -0
  34. package/agent-runtime-server/server/routes/git.js +1508 -0
  35. package/agent-runtime-server/server/routes/mcp-utils.js +48 -0
  36. package/agent-runtime-server/server/routes/mcp.js +552 -0
  37. package/agent-runtime-server/server/routes/messages.js +61 -0
  38. package/agent-runtime-server/server/routes/plugins.js +307 -0
  39. package/agent-runtime-server/server/routes/projects.js +548 -0
  40. package/agent-runtime-server/server/routes/settings.js +276 -0
  41. package/agent-runtime-server/server/routes/taskmaster.js +1963 -0
  42. package/agent-runtime-server/server/routes/user.js +123 -0
  43. package/agent-runtime-server/server/services/notification-orchestrator.js +227 -0
  44. package/agent-runtime-server/server/services/vapid-keys.js +35 -0
  45. package/agent-runtime-server/server/sessionManager.js +226 -0
  46. package/agent-runtime-server/server/utils/commandParser.js +303 -0
  47. package/agent-runtime-server/server/utils/frontmatter.js +18 -0
  48. package/agent-runtime-server/server/utils/gitConfig.js +34 -0
  49. package/agent-runtime-server/server/utils/mcp-detector.js +198 -0
  50. package/agent-runtime-server/server/utils/plugin-loader.js +457 -0
  51. package/agent-runtime-server/server/utils/plugin-process-manager.js +184 -0
  52. package/agent-runtime-server/server/utils/taskmaster-websocket.js +129 -0
  53. package/agent-runtime-server/shared/modelConstants.js +12 -0
  54. package/agent-runtime-server/shared/modelConstants.test.js +34 -0
  55. package/agent-runtime-server/shared/networkHosts.js +22 -0
  56. package/agent-runtime-server/test_sdk.mjs +16 -0
  57. package/bin/bridges/darwin-x64/nocode-bridge +0 -0
  58. package/bin/{nocode-local.js → notioncode.js} +0 -0
  59. package/dist/assets/icon-CQtd7WEB.png +0 -0
  60. package/dist/assets/index-D_1ZrHDe.js +1 -0
  61. package/dist/assets/index-DhCWie1Z.css +1 -0
  62. package/dist/assets/index-DkGqIiwF.js +689 -0
  63. package/dist/index.html +46 -0
  64. package/dist/onboarding/step1_create.png +0 -0
  65. package/dist/onboarding/step2_capabilities.png +0 -0
  66. package/dist/onboarding/step2b_content_access.png +0 -0
  67. package/dist/onboarding/step2c_page_access.png +0 -0
  68. package/dist/onboarding/step3_token.png +0 -0
  69. package/dist/onboarding/step4_webhook.png +0 -0
  70. package/dist/onboarding/step6a_verify.png +0 -0
  71. package/dist/onboarding/step6b_copy_verify_token.png +0 -0
  72. package/dist/tinyfish-fish-only.png +0 -0
  73. package/lib/install.js +33 -2
  74. package/lib/start.js +157 -25
  75. package/package.json +7 -4
  76. package/src/shared/modelRegistry.d.ts +24 -0
  77. package/src/shared/modelRegistry.js +163 -0
@@ -0,0 +1,1244 @@
1
+ import express from 'express';
2
+ import { spawn } from 'child_process';
3
+ import path from 'path';
4
+ import os from 'os';
5
+ import { promises as fs } from 'fs';
6
+ import crypto from 'crypto';
7
+ import { userDb, apiKeysDb, githubTokensDb } from '../database/db.js';
8
+ import { addProjectManually } from '../projects.js';
9
+ import { queryClaudeSDK } from '../claude-sdk.js';
10
+ import { spawnCursor } from '../cursor-cli.js';
11
+ import { queryCodex } from '../openai-codex.js';
12
+ import { spawnGemini } from '../gemini-cli.js';
13
+ import { Octokit } from '@octokit/rest';
14
+ import { getDefaultModel } from '../../shared/modelConstants.js';
15
+ import { IS_PLATFORM } from '../constants/config.js';
16
+
17
+ const router = express.Router();
18
+
19
+ /**
20
+ * Middleware to authenticate agent API requests.
21
+ *
22
+ * Supports two authentication modes:
23
+ * 1. Platform mode (IS_PLATFORM=true): For managed/hosted deployments where
24
+ * authentication is handled by an external proxy. Requests are trusted and
25
+ * the default user context is used.
26
+ *
27
+ * 2. API key mode (default): For self-hosted deployments where users authenticate
28
+ * via API keys created in the UI. Keys are validated against the local database.
29
+ */
30
+ const validateExternalApiKey = (req, res, next) => {
31
+ // Platform mode: Authentication is handled externally (e.g., by a proxy layer).
32
+ // Trust the request and use the default user context.
33
+ if (IS_PLATFORM) {
34
+ try {
35
+ const user = userDb.ensurePlatformUser();
36
+ if (!user) {
37
+ return res.status(500).json({ error: 'Platform mode: No user found in database' });
38
+ }
39
+ req.user = user;
40
+ return next();
41
+ } catch (error) {
42
+ console.error('Platform mode error:', error);
43
+ return res.status(500).json({ error: 'Platform mode: Failed to fetch user' });
44
+ }
45
+ }
46
+
47
+ // Self-hosted mode: Validate API key from header or query parameter
48
+ const apiKey = req.headers['x-api-key'] || req.query.apiKey;
49
+
50
+ if (!apiKey) {
51
+ return res.status(401).json({ error: 'API key required' });
52
+ }
53
+
54
+ const user = apiKeysDb.validateApiKey(apiKey);
55
+
56
+ if (!user) {
57
+ return res.status(401).json({ error: 'Invalid or inactive API key' });
58
+ }
59
+
60
+ req.user = user;
61
+ next();
62
+ };
63
+
64
+ /**
65
+ * Get the remote URL of a git repository
66
+ * @param {string} repoPath - Path to the git repository
67
+ * @returns {Promise<string>} - Remote URL of the repository
68
+ */
69
+ async function getGitRemoteUrl(repoPath) {
70
+ return new Promise((resolve, reject) => {
71
+ const gitProcess = spawn('git', ['config', '--get', 'remote.origin.url'], {
72
+ cwd: repoPath,
73
+ stdio: ['pipe', 'pipe', 'pipe']
74
+ });
75
+
76
+ let stdout = '';
77
+ let stderr = '';
78
+
79
+ gitProcess.stdout.on('data', (data) => {
80
+ stdout += data.toString();
81
+ });
82
+
83
+ gitProcess.stderr.on('data', (data) => {
84
+ stderr += data.toString();
85
+ });
86
+
87
+ gitProcess.on('close', (code) => {
88
+ if (code === 0) {
89
+ resolve(stdout.trim());
90
+ } else {
91
+ reject(new Error(`Failed to get git remote: ${stderr}`));
92
+ }
93
+ });
94
+
95
+ gitProcess.on('error', (error) => {
96
+ reject(new Error(`Failed to execute git: ${error.message}`));
97
+ });
98
+ });
99
+ }
100
+
101
+ /**
102
+ * Normalize GitHub URLs for comparison
103
+ * @param {string} url - GitHub URL
104
+ * @returns {string} - Normalized URL
105
+ */
106
+ function normalizeGitHubUrl(url) {
107
+ // Remove .git suffix
108
+ let normalized = url.replace(/\.git$/, '');
109
+ // Convert SSH to HTTPS format for comparison
110
+ normalized = normalized.replace(/^git@github\.com:/, 'https://github.com/');
111
+ // Remove trailing slash
112
+ normalized = normalized.replace(/\/$/, '');
113
+ return normalized.toLowerCase();
114
+ }
115
+
116
+ /**
117
+ * Parse GitHub URL to extract owner and repo
118
+ * @param {string} url - GitHub URL (HTTPS or SSH)
119
+ * @returns {{owner: string, repo: string}} - Parsed owner and repo
120
+ */
121
+ function parseGitHubUrl(url) {
122
+ // Handle HTTPS URLs: https://github.com/owner/repo or https://github.com/owner/repo.git
123
+ // Handle SSH URLs: git@github.com:owner/repo or git@github.com:owner/repo.git
124
+ const match = url.match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/);
125
+ if (!match) {
126
+ throw new Error('Invalid GitHub URL format');
127
+ }
128
+ return {
129
+ owner: match[1],
130
+ repo: match[2].replace(/\.git$/, '')
131
+ };
132
+ }
133
+
134
+ /**
135
+ * Auto-generate a branch name from a message
136
+ * @param {string} message - The agent message
137
+ * @returns {string} - Generated branch name
138
+ */
139
+ function autogenerateBranchName(message) {
140
+ // Convert to lowercase, replace spaces/special chars with hyphens
141
+ let branchName = message
142
+ .toLowerCase()
143
+ .replace(/[^a-z0-9\s-]/g, '') // Remove special characters
144
+ .replace(/\s+/g, '-') // Replace spaces with hyphens
145
+ .replace(/-+/g, '-') // Replace multiple hyphens with single
146
+ .replace(/^-|-$/g, ''); // Remove leading/trailing hyphens
147
+
148
+ // Ensure non-empty fallback
149
+ if (!branchName) {
150
+ branchName = 'task';
151
+ }
152
+
153
+ // Generate timestamp suffix (last 6 chars of base36 timestamp)
154
+ const timestamp = Date.now().toString(36).slice(-6);
155
+ const suffix = `-${timestamp}`;
156
+
157
+ // Limit length to ensure total length including suffix fits within 50 characters
158
+ const maxBaseLength = 50 - suffix.length;
159
+ if (branchName.length > maxBaseLength) {
160
+ branchName = branchName.substring(0, maxBaseLength);
161
+ }
162
+
163
+ // Remove any trailing hyphen after truncation and ensure no leading hyphen
164
+ branchName = branchName.replace(/-$/, '').replace(/^-+/, '');
165
+
166
+ // If still empty or starts with hyphen after cleanup, use fallback
167
+ if (!branchName || branchName.startsWith('-')) {
168
+ branchName = 'task';
169
+ }
170
+
171
+ // Combine base name with timestamp suffix
172
+ branchName = `${branchName}${suffix}`;
173
+
174
+ // Final validation: ensure it matches safe pattern
175
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(branchName)) {
176
+ // Fallback to deterministic safe name
177
+ return `branch-${timestamp}`;
178
+ }
179
+
180
+ return branchName;
181
+ }
182
+
183
+ /**
184
+ * Validate a Git branch name
185
+ * @param {string} branchName - Branch name to validate
186
+ * @returns {{valid: boolean, error?: string}} - Validation result
187
+ */
188
+ function validateBranchName(branchName) {
189
+ if (!branchName || branchName.trim() === '') {
190
+ return { valid: false, error: 'Branch name cannot be empty' };
191
+ }
192
+
193
+ // Git branch name rules
194
+ const invalidPatterns = [
195
+ { pattern: /^\./, message: 'Branch name cannot start with a dot' },
196
+ { pattern: /\.$/, message: 'Branch name cannot end with a dot' },
197
+ { pattern: /\.\./, message: 'Branch name cannot contain consecutive dots (..)' },
198
+ { pattern: /\s/, message: 'Branch name cannot contain spaces' },
199
+ { pattern: /[~^:?*\[\\]/, message: 'Branch name cannot contain special characters: ~ ^ : ? * [ \\' },
200
+ { pattern: /@{/, message: 'Branch name cannot contain @{' },
201
+ { pattern: /\/$/, message: 'Branch name cannot end with a slash' },
202
+ { pattern: /^\//, message: 'Branch name cannot start with a slash' },
203
+ { pattern: /\/\//, message: 'Branch name cannot contain consecutive slashes' },
204
+ { pattern: /\.lock$/, message: 'Branch name cannot end with .lock' }
205
+ ];
206
+
207
+ for (const { pattern, message } of invalidPatterns) {
208
+ if (pattern.test(branchName)) {
209
+ return { valid: false, error: message };
210
+ }
211
+ }
212
+
213
+ // Check for ASCII control characters
214
+ if (/[\x00-\x1F\x7F]/.test(branchName)) {
215
+ return { valid: false, error: 'Branch name cannot contain control characters' };
216
+ }
217
+
218
+ return { valid: true };
219
+ }
220
+
221
+ /**
222
+ * Get recent commit messages from a repository
223
+ * @param {string} projectPath - Path to the git repository
224
+ * @param {number} limit - Number of commits to retrieve (default: 5)
225
+ * @returns {Promise<string[]>} - Array of commit messages
226
+ */
227
+ async function getCommitMessages(projectPath, limit = 5) {
228
+ return new Promise((resolve, reject) => {
229
+ const gitProcess = spawn('git', ['log', `-${limit}`, '--pretty=format:%s'], {
230
+ cwd: projectPath,
231
+ stdio: ['pipe', 'pipe', 'pipe']
232
+ });
233
+
234
+ let stdout = '';
235
+ let stderr = '';
236
+
237
+ gitProcess.stdout.on('data', (data) => {
238
+ stdout += data.toString();
239
+ });
240
+
241
+ gitProcess.stderr.on('data', (data) => {
242
+ stderr += data.toString();
243
+ });
244
+
245
+ gitProcess.on('close', (code) => {
246
+ if (code === 0) {
247
+ const messages = stdout.trim().split('\n').filter(msg => msg.length > 0);
248
+ resolve(messages);
249
+ } else {
250
+ reject(new Error(`Failed to get commit messages: ${stderr}`));
251
+ }
252
+ });
253
+
254
+ gitProcess.on('error', (error) => {
255
+ reject(new Error(`Failed to execute git: ${error.message}`));
256
+ });
257
+ });
258
+ }
259
+
260
+ /**
261
+ * Create a new branch on GitHub using the API
262
+ * @param {Octokit} octokit - Octokit instance
263
+ * @param {string} owner - Repository owner
264
+ * @param {string} repo - Repository name
265
+ * @param {string} branchName - Name of the new branch
266
+ * @param {string} baseBranch - Base branch to branch from (default: 'main')
267
+ * @returns {Promise<void>}
268
+ */
269
+ async function createGitHubBranch(octokit, owner, repo, branchName, baseBranch = 'main') {
270
+ try {
271
+ // Get the SHA of the base branch
272
+ const { data: ref } = await octokit.git.getRef({
273
+ owner,
274
+ repo,
275
+ ref: `heads/${baseBranch}`
276
+ });
277
+
278
+ const baseSha = ref.object.sha;
279
+
280
+ // Create the new branch
281
+ await octokit.git.createRef({
282
+ owner,
283
+ repo,
284
+ ref: `refs/heads/${branchName}`,
285
+ sha: baseSha
286
+ });
287
+
288
+ console.log(`✅ Created branch '${branchName}' on GitHub`);
289
+ } catch (error) {
290
+ if (error.status === 422 && error.message.includes('Reference already exists')) {
291
+ console.log(`ℹ️ Branch '${branchName}' already exists on GitHub`);
292
+ } else {
293
+ throw error;
294
+ }
295
+ }
296
+ }
297
+
298
+ /**
299
+ * Create a pull request on GitHub
300
+ * @param {Octokit} octokit - Octokit instance
301
+ * @param {string} owner - Repository owner
302
+ * @param {string} repo - Repository name
303
+ * @param {string} branchName - Head branch name
304
+ * @param {string} title - PR title
305
+ * @param {string} body - PR body/description
306
+ * @param {string} baseBranch - Base branch (default: 'main')
307
+ * @returns {Promise<{number: number, url: string}>} - PR number and URL
308
+ */
309
+ async function createGitHubPR(octokit, owner, repo, branchName, title, body, baseBranch = 'main') {
310
+ const { data: pr } = await octokit.pulls.create({
311
+ owner,
312
+ repo,
313
+ title,
314
+ head: branchName,
315
+ base: baseBranch,
316
+ body
317
+ });
318
+
319
+ console.log(`✅ Created pull request #${pr.number}: ${pr.html_url}`);
320
+
321
+ return {
322
+ number: pr.number,
323
+ url: pr.html_url
324
+ };
325
+ }
326
+
327
+ /**
328
+ * Clone a GitHub repository to a directory
329
+ * @param {string} githubUrl - GitHub repository URL
330
+ * @param {string} githubToken - Optional GitHub token for private repos
331
+ * @param {string} projectPath - Path for cloning the repository
332
+ * @returns {Promise<string>} - Path to the cloned repository
333
+ */
334
+ async function cloneGitHubRepo(githubUrl, githubToken = null, projectPath) {
335
+ return new Promise(async (resolve, reject) => {
336
+ try {
337
+ // Validate GitHub URL
338
+ if (!githubUrl || !githubUrl.includes('github.com')) {
339
+ throw new Error('Invalid GitHub URL');
340
+ }
341
+
342
+ const cloneDir = path.resolve(projectPath);
343
+
344
+ // Check if directory already exists
345
+ try {
346
+ await fs.access(cloneDir);
347
+ // Directory exists - check if it's a git repo with the same URL
348
+ try {
349
+ const existingUrl = await getGitRemoteUrl(cloneDir);
350
+ const normalizedExisting = normalizeGitHubUrl(existingUrl);
351
+ const normalizedRequested = normalizeGitHubUrl(githubUrl);
352
+
353
+ if (normalizedExisting === normalizedRequested) {
354
+ console.log('✅ Repository already exists at path with correct URL');
355
+ return resolve(cloneDir);
356
+ } else {
357
+ throw new Error(`Directory ${cloneDir} already exists with a different repository (${existingUrl}). Expected: ${githubUrl}`);
358
+ }
359
+ } catch (gitError) {
360
+ throw new Error(`Directory ${cloneDir} already exists but is not a valid git repository or git command failed`);
361
+ }
362
+ } catch (accessError) {
363
+ // Directory doesn't exist - proceed with clone
364
+ }
365
+
366
+ // Ensure parent directory exists
367
+ await fs.mkdir(path.dirname(cloneDir), { recursive: true });
368
+
369
+ // Prepare the git clone URL with authentication if token is provided
370
+ let cloneUrl = githubUrl;
371
+ if (githubToken) {
372
+ // Convert HTTPS URL to authenticated URL
373
+ // Example: https://github.com/user/repo -> https://token@github.com/user/repo
374
+ cloneUrl = githubUrl.replace('https://github.com', `https://${githubToken}@github.com`);
375
+ }
376
+
377
+ console.log('🔄 Cloning repository:', githubUrl);
378
+ console.log('📁 Destination:', cloneDir);
379
+
380
+ // Execute git clone
381
+ const gitProcess = spawn('git', ['clone', '--depth', '1', cloneUrl, cloneDir], {
382
+ stdio: ['pipe', 'pipe', 'pipe']
383
+ });
384
+
385
+ let stdout = '';
386
+ let stderr = '';
387
+
388
+ gitProcess.stdout.on('data', (data) => {
389
+ stdout += data.toString();
390
+ });
391
+
392
+ gitProcess.stderr.on('data', (data) => {
393
+ stderr += data.toString();
394
+ console.log('Git stderr:', data.toString());
395
+ });
396
+
397
+ gitProcess.on('close', (code) => {
398
+ if (code === 0) {
399
+ console.log('✅ Repository cloned successfully');
400
+ resolve(cloneDir);
401
+ } else {
402
+ console.error('❌ Git clone failed:', stderr);
403
+ reject(new Error(`Git clone failed: ${stderr}`));
404
+ }
405
+ });
406
+
407
+ gitProcess.on('error', (error) => {
408
+ reject(new Error(`Failed to execute git: ${error.message}`));
409
+ });
410
+ } catch (error) {
411
+ reject(error);
412
+ }
413
+ });
414
+ }
415
+
416
+ /**
417
+ * Clean up a temporary project directory and its Claude session
418
+ * @param {string} projectPath - Path to the project directory
419
+ * @param {string} sessionId - Session ID to clean up
420
+ */
421
+ async function cleanupProject(projectPath, sessionId = null) {
422
+ try {
423
+ // Only clean up projects in the external-projects directory
424
+ if (!projectPath.includes('.claude/external-projects')) {
425
+ console.warn('⚠️ Refusing to clean up non-external project:', projectPath);
426
+ return;
427
+ }
428
+
429
+ console.log('🧹 Cleaning up project:', projectPath);
430
+ await fs.rm(projectPath, { recursive: true, force: true });
431
+ console.log('✅ Project cleaned up');
432
+
433
+ // Also clean up the Claude session directory if sessionId provided
434
+ if (sessionId) {
435
+ try {
436
+ const sessionPath = path.join(os.homedir(), '.claude', 'sessions', sessionId);
437
+ console.log('🧹 Cleaning up session directory:', sessionPath);
438
+ await fs.rm(sessionPath, { recursive: true, force: true });
439
+ console.log('✅ Session directory cleaned up');
440
+ } catch (error) {
441
+ console.error('⚠️ Failed to clean up session directory:', error.message);
442
+ }
443
+ }
444
+ } catch (error) {
445
+ console.error('❌ Failed to clean up project:', error);
446
+ }
447
+ }
448
+
449
+ /**
450
+ * SSE Stream Writer - Adapts SDK/CLI output to Server-Sent Events
451
+ */
452
+ class SSEStreamWriter {
453
+ constructor(res, userId = null) {
454
+ this.res = res;
455
+ this.sessionId = null;
456
+ this.userId = userId;
457
+ this.isSSEStreamWriter = true; // Marker for transport detection
458
+ }
459
+
460
+ send(data) {
461
+ if (this.res.writableEnded) {
462
+ return;
463
+ }
464
+
465
+ // Format as SSE - providers send raw objects, we stringify
466
+ this.res.write(`data: ${JSON.stringify(data)}\n\n`);
467
+ }
468
+
469
+ end() {
470
+ if (!this.res.writableEnded) {
471
+ this.res.write('data: {"type":"done"}\n\n');
472
+ this.res.end();
473
+ }
474
+ }
475
+
476
+ setSessionId(sessionId) {
477
+ this.sessionId = sessionId;
478
+ }
479
+
480
+ getSessionId() {
481
+ return this.sessionId;
482
+ }
483
+ }
484
+
485
+ /**
486
+ * Non-streaming response collector
487
+ */
488
+ class ResponseCollector {
489
+ constructor(userId = null) {
490
+ this.messages = [];
491
+ this.sessionId = null;
492
+ this.userId = userId;
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' | 'codex' | 'gemini'
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', 'cursor', 'codex', or 'gemini'
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', 'gemini'].includes(provider)) {
862
+ return res.status(400).json({ error: 'provider must be "claude", "cursor", "codex", or "gemini"' });
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
+ console.log('📦 Project registered:', project);
907
+ } catch (error) {
908
+ // If project already exists, that's fine - continue with the existing registration
909
+ if (error.message && error.message.includes('Project already configured')) {
910
+ console.log('📦 Using existing project registration for:', finalProjectPath);
911
+ project = { path: finalProjectPath };
912
+ } else {
913
+ throw error;
914
+ }
915
+ }
916
+
917
+ // Set up writer based on streaming mode
918
+ if (stream) {
919
+ // Set up SSE headers for streaming
920
+ res.setHeader('Content-Type', 'text/event-stream');
921
+ res.setHeader('Cache-Control', 'no-cache');
922
+ res.setHeader('Connection', 'keep-alive');
923
+ res.setHeader('X-Accel-Buffering', 'no'); // Disable nginx buffering
924
+
925
+ writer = new SSEStreamWriter(res, req.user.id);
926
+
927
+ // Send initial status
928
+ writer.send({
929
+ type: 'status',
930
+ message: githubUrl ? 'Repository cloned and session started' : 'Session started',
931
+ projectPath: finalProjectPath
932
+ });
933
+ } else {
934
+ // Non-streaming mode: collect messages
935
+ writer = new ResponseCollector(req.user.id);
936
+
937
+ // Collect initial status message
938
+ writer.send({
939
+ type: 'status',
940
+ message: githubUrl ? 'Repository cloned and session started' : 'Session started',
941
+ projectPath: finalProjectPath
942
+ });
943
+ }
944
+
945
+ // Start the appropriate session
946
+ if (provider === 'claude') {
947
+ console.log('🤖 Starting Claude SDK session');
948
+
949
+ await queryClaudeSDK(message.trim(), {
950
+ projectPath: finalProjectPath,
951
+ cwd: finalProjectPath,
952
+ sessionId: null, // New session
953
+ model: model || getDefaultModel('claude'),
954
+ permissionMode: 'bypassPermissions' // Bypass all permissions for API calls
955
+ }, writer);
956
+
957
+ } else if (provider === 'cursor') {
958
+ console.log('🖱️ Starting Cursor CLI session');
959
+
960
+ await spawnCursor(message.trim(), {
961
+ projectPath: finalProjectPath,
962
+ cwd: finalProjectPath,
963
+ sessionId: null, // New session
964
+ model: model || getDefaultModel('cursor'),
965
+ skipPermissions: true // Bypass permissions for Cursor
966
+ }, writer);
967
+ } else if (provider === 'codex') {
968
+ console.log('🤖 Starting Codex SDK session');
969
+
970
+ await queryCodex(message.trim(), {
971
+ projectPath: finalProjectPath,
972
+ cwd: finalProjectPath,
973
+ sessionId: null,
974
+ model: model || getDefaultModel('codex'),
975
+ permissionMode: 'bypassPermissions'
976
+ }, writer);
977
+ } else if (provider === 'gemini') {
978
+ console.log('✨ Starting Gemini CLI session');
979
+
980
+ await spawnGemini(message.trim(), {
981
+ projectPath: finalProjectPath,
982
+ cwd: finalProjectPath,
983
+ sessionId: null,
984
+ model: model || getDefaultModel('gemini'),
985
+ skipPermissions: true // CLI mode bypasses permissions
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
+ console.log('🔄 Starting GitHub branch/PR creation workflow...');
996
+
997
+ // Get GitHub token
998
+ const tokenToUse = githubToken || githubTokensDb.getActiveGithubToken(req.user.id);
999
+
1000
+ if (!tokenToUse) {
1001
+ throw new Error('GitHub token required for branch/PR creation. Please configure a GitHub token in settings.');
1002
+ }
1003
+
1004
+ // Initialize Octokit
1005
+ const octokit = new Octokit({ auth: tokenToUse });
1006
+
1007
+ // Get GitHub URL - either from parameter or from git remote
1008
+ let repoUrl = githubUrl;
1009
+ if (!repoUrl) {
1010
+ console.log('🔍 Getting GitHub URL from git remote...');
1011
+ try {
1012
+ repoUrl = await getGitRemoteUrl(finalProjectPath);
1013
+ if (!repoUrl.includes('github.com')) {
1014
+ throw new Error('Project does not have a GitHub remote configured');
1015
+ }
1016
+ console.log(`✅ Found GitHub remote: ${repoUrl}`);
1017
+ } catch (error) {
1018
+ throw new Error(`Failed to get GitHub remote URL: ${error.message}`);
1019
+ }
1020
+ }
1021
+
1022
+ // Parse GitHub URL to get owner and repo
1023
+ const { owner, repo } = parseGitHubUrl(repoUrl);
1024
+ console.log(`📦 Repository: ${owner}/${repo}`);
1025
+
1026
+ // Use provided branch name or auto-generate from message
1027
+ const finalBranchName = branchName || autogenerateBranchName(message);
1028
+ if (branchName) {
1029
+ console.log(`🌿 Using provided branch name: ${finalBranchName}`);
1030
+
1031
+ // Validate custom branch name
1032
+ const validation = validateBranchName(finalBranchName);
1033
+ if (!validation.valid) {
1034
+ throw new Error(`Invalid branch name: ${validation.error}`);
1035
+ }
1036
+ } else {
1037
+ console.log(`🌿 Auto-generated branch name: ${finalBranchName}`);
1038
+ }
1039
+
1040
+ if (createBranch) {
1041
+ // Create and checkout the new branch locally
1042
+ console.log('🔄 Creating local branch...');
1043
+ const checkoutProcess = spawn('git', ['checkout', '-b', finalBranchName], {
1044
+ cwd: finalProjectPath,
1045
+ stdio: 'pipe'
1046
+ });
1047
+
1048
+ await new Promise((resolve, reject) => {
1049
+ let stderr = '';
1050
+ checkoutProcess.stderr.on('data', (data) => { stderr += data.toString(); });
1051
+ checkoutProcess.on('close', (code) => {
1052
+ if (code === 0) {
1053
+ console.log(`✅ Created and checked out local branch '${finalBranchName}'`);
1054
+ resolve();
1055
+ } else {
1056
+ // Branch might already exist locally, try to checkout
1057
+ if (stderr.includes('already exists')) {
1058
+ console.log(`ℹ️ Branch '${finalBranchName}' already exists locally, checking out...`);
1059
+ const checkoutExisting = spawn('git', ['checkout', finalBranchName], {
1060
+ cwd: finalProjectPath,
1061
+ stdio: 'pipe'
1062
+ });
1063
+ checkoutExisting.on('close', (checkoutCode) => {
1064
+ if (checkoutCode === 0) {
1065
+ console.log(`✅ Checked out existing branch '${finalBranchName}'`);
1066
+ resolve();
1067
+ } else {
1068
+ reject(new Error(`Failed to checkout existing branch: ${stderr}`));
1069
+ }
1070
+ });
1071
+ } else {
1072
+ reject(new Error(`Failed to create branch: ${stderr}`));
1073
+ }
1074
+ }
1075
+ });
1076
+ });
1077
+
1078
+ // Push the branch to remote
1079
+ console.log('🔄 Pushing branch to remote...');
1080
+ const pushProcess = spawn('git', ['push', '-u', 'origin', finalBranchName], {
1081
+ cwd: finalProjectPath,
1082
+ stdio: 'pipe'
1083
+ });
1084
+
1085
+ await new Promise((resolve, reject) => {
1086
+ let stderr = '';
1087
+ let stdout = '';
1088
+ pushProcess.stdout.on('data', (data) => { stdout += data.toString(); });
1089
+ pushProcess.stderr.on('data', (data) => { stderr += data.toString(); });
1090
+ pushProcess.on('close', (code) => {
1091
+ if (code === 0) {
1092
+ console.log(`✅ Pushed branch '${finalBranchName}' to remote`);
1093
+ resolve();
1094
+ } else {
1095
+ // Check if branch exists on remote but has different commits
1096
+ if (stderr.includes('already exists') || stderr.includes('up-to-date')) {
1097
+ console.log(`ℹ️ Branch '${finalBranchName}' already exists on remote, using existing branch`);
1098
+ resolve();
1099
+ } else {
1100
+ reject(new Error(`Failed to push branch: ${stderr}`));
1101
+ }
1102
+ }
1103
+ });
1104
+ });
1105
+
1106
+ branchInfo = {
1107
+ name: finalBranchName,
1108
+ url: `https://github.com/${owner}/${repo}/tree/${finalBranchName}`
1109
+ };
1110
+ }
1111
+
1112
+ if (createPR) {
1113
+ // Get commit messages to generate PR description
1114
+ console.log('🔄 Generating PR title and description...');
1115
+ const commitMessages = await getCommitMessages(finalProjectPath, 5);
1116
+
1117
+ // Use the first commit message as the PR title, or fallback to the agent message
1118
+ const prTitle = commitMessages.length > 0 ? commitMessages[0] : message;
1119
+
1120
+ // Generate PR body from commit messages
1121
+ let prBody = '## Changes\n\n';
1122
+ if (commitMessages.length > 0) {
1123
+ prBody += commitMessages.map(msg => `- ${msg}`).join('\n');
1124
+ } else {
1125
+ prBody += `Agent task: ${message}`;
1126
+ }
1127
+ prBody += '\n\n---\n*This pull request was automatically created by Claude Code UI Agent.*';
1128
+
1129
+ console.log(`📝 PR Title: ${prTitle}`);
1130
+
1131
+ // Create the pull request
1132
+ console.log('🔄 Creating pull request...');
1133
+ prInfo = await createGitHubPR(octokit, owner, repo, finalBranchName, prTitle, prBody, 'main');
1134
+ }
1135
+
1136
+ // Send branch/PR info in response
1137
+ if (stream) {
1138
+ if (branchInfo) {
1139
+ writer.send({
1140
+ type: 'github-branch',
1141
+ branch: branchInfo
1142
+ });
1143
+ }
1144
+ if (prInfo) {
1145
+ writer.send({
1146
+ type: 'github-pr',
1147
+ pullRequest: prInfo
1148
+ });
1149
+ }
1150
+ }
1151
+
1152
+ } catch (error) {
1153
+ console.error('❌ GitHub branch/PR creation error:', error);
1154
+
1155
+ // Send error but don't fail the entire request
1156
+ if (stream) {
1157
+ writer.send({
1158
+ type: 'github-error',
1159
+ error: error.message
1160
+ });
1161
+ }
1162
+ // Store error info for non-streaming response
1163
+ if (!stream) {
1164
+ branchInfo = { error: error.message };
1165
+ prInfo = { error: error.message };
1166
+ }
1167
+ }
1168
+ }
1169
+
1170
+ // Handle response based on streaming mode
1171
+ if (stream) {
1172
+ // Streaming mode: end the SSE stream
1173
+ writer.end();
1174
+ } else {
1175
+ // Non-streaming mode: send filtered messages and token summary as JSON
1176
+ const assistantMessages = writer.getAssistantMessages();
1177
+ const tokenSummary = writer.getTotalTokens();
1178
+
1179
+ const response = {
1180
+ success: true,
1181
+ sessionId: writer.getSessionId(),
1182
+ messages: assistantMessages,
1183
+ tokens: tokenSummary,
1184
+ projectPath: finalProjectPath
1185
+ };
1186
+
1187
+ // Add branch/PR info if created
1188
+ if (branchInfo) {
1189
+ response.branch = branchInfo;
1190
+ }
1191
+ if (prInfo) {
1192
+ response.pullRequest = prInfo;
1193
+ }
1194
+
1195
+ res.json(response);
1196
+ }
1197
+
1198
+ // Clean up if requested
1199
+ if (cleanup && githubUrl) {
1200
+ // Only cleanup if we cloned a repo (not for existing project paths)
1201
+ const sessionIdForCleanup = writer.getSessionId();
1202
+ setTimeout(() => {
1203
+ cleanupProject(finalProjectPath, sessionIdForCleanup);
1204
+ }, 5000);
1205
+ }
1206
+
1207
+ } catch (error) {
1208
+ console.error('❌ External session error:', error);
1209
+
1210
+ // Clean up on error
1211
+ if (finalProjectPath && cleanup && githubUrl) {
1212
+ const sessionIdForCleanup = writer ? writer.getSessionId() : null;
1213
+ cleanupProject(finalProjectPath, sessionIdForCleanup);
1214
+ }
1215
+
1216
+ if (stream) {
1217
+ // For streaming, send error event and stop
1218
+ if (!writer) {
1219
+ // Set up SSE headers if not already done
1220
+ res.setHeader('Content-Type', 'text/event-stream');
1221
+ res.setHeader('Cache-Control', 'no-cache');
1222
+ res.setHeader('Connection', 'keep-alive');
1223
+ res.setHeader('X-Accel-Buffering', 'no');
1224
+ writer = new SSEStreamWriter(res, req.user.id);
1225
+ }
1226
+
1227
+ if (!res.writableEnded) {
1228
+ writer.send({
1229
+ type: 'error',
1230
+ error: error.message,
1231
+ message: `Failed: ${error.message}`
1232
+ });
1233
+ writer.end();
1234
+ }
1235
+ } else if (!res.headersSent) {
1236
+ res.status(500).json({
1237
+ success: false,
1238
+ error: error.message
1239
+ });
1240
+ }
1241
+ }
1242
+ });
1243
+
1244
+ export default router;