@pixelbyte-software/pixcode 1.54.9 → 1.54.11

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 (288) hide show
  1. package/CODE_OF_CONDUCT.md +41 -41
  2. package/CONTRIBUTING.md +156 -156
  3. package/LICENSE +21 -718
  4. package/README.de.md +169 -169
  5. package/README.ja.md +167 -167
  6. package/README.ko.md +167 -167
  7. package/README.md +435 -418
  8. package/README.ru.md +169 -169
  9. package/README.tr.md +298 -298
  10. package/README.zh-CN.md +167 -167
  11. package/SECURITY.md +46 -46
  12. package/dist/api-automation.html +110 -110
  13. package/dist/api-docs.html +548 -548
  14. package/dist/assets/{index-Bm6uAqKU.js → index-Bcqs_1vc.js} +114 -114
  15. package/dist/clear-cache.html +85 -85
  16. package/dist/convert-icons.md +52 -52
  17. package/dist/docs.html +308 -308
  18. package/dist/features.html +133 -133
  19. package/dist/generate-icons.js +48 -48
  20. package/dist/humans.txt +15 -15
  21. package/dist/icons/codex-white.svg +3 -3
  22. package/dist/icons/codex.svg +3 -3
  23. package/dist/icons/cursor-white.svg +11 -11
  24. package/dist/icons/qwen-logo.svg +14 -14
  25. package/dist/index.html +58 -58
  26. package/dist/landing.html +268 -268
  27. package/dist/llms-full.txt +119 -119
  28. package/dist/llms.txt +53 -53
  29. package/dist/manifest.json +60 -60
  30. package/dist/openapi.yaml +1696 -1696
  31. package/dist/orchestration.html +125 -125
  32. package/dist/robots.txt +4 -4
  33. package/dist/site.css +692 -692
  34. package/dist/sitemap.xml +51 -51
  35. package/dist/sw.js +132 -132
  36. package/dist-server/server/cli.js +100 -100
  37. package/dist-server/server/daemon/manager.js +33 -33
  38. package/dist-server/server/daemon-manager.js +64 -64
  39. package/dist-server/server/index.js +13 -0
  40. package/dist-server/server/index.js.map +1 -1
  41. package/dist-server/server/routes/agent.js +10 -1
  42. package/dist-server/server/routes/agent.js.map +1 -1
  43. package/dist-server/server/routes/commands.js +25 -25
  44. package/dist-server/server/routes/git.js +17 -17
  45. package/dist-server/server/routes/live-view.js +46 -46
  46. package/dist-server/server/services/public-api-manifest.js +51 -51
  47. package/dist-server/server/sessionManager.js +5 -5
  48. package/dist-server/server/sessionManager.js.map +1 -1
  49. package/package.json +224 -224
  50. package/scripts/fix-node-pty.js +67 -67
  51. package/scripts/github/create-v1.38-issues.mjs +351 -351
  52. package/scripts/github/create-vscode-workbench-issues.mjs +121 -121
  53. package/scripts/smoke/backend-resource-bounds.mjs +152 -152
  54. package/scripts/smoke/changes-panel-layout.mjs +48 -48
  55. package/scripts/smoke/chat-composer-fixed-layout.mjs +55 -55
  56. package/scripts/smoke/chat-message-timeline-order.mjs +41 -41
  57. package/scripts/smoke/chat-realtime-hydration.mjs +44 -44
  58. package/scripts/smoke/chat-session-provider-pools.mjs +35 -35
  59. package/scripts/smoke/chat-session-state.mjs +19 -19
  60. package/scripts/smoke/code-editor-theme.mjs +55 -55
  61. package/scripts/smoke/code-editor-vscode-engine.mjs +91 -91
  62. package/scripts/smoke/command-center-agent-writes.mjs +79 -79
  63. package/scripts/smoke/command-center-non-git.mjs +46 -46
  64. package/scripts/smoke/context-packet.mjs +43 -43
  65. package/scripts/smoke/control-room-ux-redesign.mjs +91 -91
  66. package/scripts/smoke/daemon-entrypoint.mjs +20 -20
  67. package/scripts/smoke/default-landing-routing.mjs +33 -33
  68. package/scripts/smoke/desktop-native-notifications.mjs +30 -30
  69. package/scripts/smoke/desktop-tray-icon.mjs +33 -33
  70. package/scripts/smoke/discord-release-workflow.mjs +24 -24
  71. package/scripts/smoke/git-install-update.mjs +255 -255
  72. package/scripts/smoke/handoff-artifact-protocol.mjs +50 -50
  73. package/scripts/smoke/live-view-diagnostics.mjs +53 -53
  74. package/scripts/smoke/live-view-environment.mjs +92 -92
  75. package/scripts/smoke/live-view-integration.mjs +450 -450
  76. package/scripts/smoke/mac-desktop-runtime.mjs +37 -37
  77. package/scripts/smoke/mobile-tunnel-guidance.mjs +29 -29
  78. package/scripts/smoke/mobile-ux.mjs +76 -76
  79. package/scripts/smoke/model-registry.mjs +36 -36
  80. package/scripts/smoke/multi-project-ui.mjs +45 -45
  81. package/scripts/smoke/multi-worker-slots.mjs +42 -42
  82. package/scripts/smoke/notification-center.mjs +87 -87
  83. package/scripts/smoke/notification-inapp-preference.mjs +23 -23
  84. package/scripts/smoke/notification-taxonomy.mjs +58 -58
  85. package/scripts/smoke/orchestration-api.mjs +172 -172
  86. package/scripts/smoke/orchestration-execution-dashboard.mjs +33 -33
  87. package/scripts/smoke/orchestration-live-run.mjs +176 -176
  88. package/scripts/smoke/orchestration-mobile-scroll.mjs +29 -29
  89. package/scripts/smoke/orchestration-model-sync.mjs +30 -30
  90. package/scripts/smoke/orchestration-permission-fallback.mjs +34 -34
  91. package/scripts/smoke/orchestration-runtime-guards.mjs +48 -48
  92. package/scripts/smoke/orchestration-user-facing-output.mjs +25 -25
  93. package/scripts/smoke/permission-policy.mjs +50 -50
  94. package/scripts/smoke/pixcode-workbench-1-48.mjs +167 -167
  95. package/scripts/smoke/provider-models-opencode-live.mjs +66 -66
  96. package/scripts/smoke/provider-rest-api.mjs +124 -124
  97. package/scripts/smoke/provider-selection-status.mjs +52 -52
  98. package/scripts/smoke/run-state-refresh.mjs +52 -52
  99. package/scripts/smoke/runtime-manager.mjs +99 -99
  100. package/scripts/smoke/shell-manual-disconnect.mjs +30 -30
  101. package/scripts/smoke/side-panel-editor-layout.mjs +34 -34
  102. package/scripts/smoke/static-root-routing.mjs +21 -21
  103. package/scripts/smoke/strict-handoff-compact.mjs +60 -60
  104. package/scripts/smoke/taskmaster-config.mjs +24 -24
  105. package/scripts/smoke/taskmaster-execution-telegram.mjs +3 -3
  106. package/scripts/smoke/taskmaster-onboarding.mjs +3 -3
  107. package/scripts/smoke/taskmaster-run-graph.mjs +3 -3
  108. package/scripts/smoke/telegram-control.mjs +331 -331
  109. package/scripts/smoke/tunnel-persistence.mjs +56 -56
  110. package/scripts/smoke/update-issue-progress.mjs +69 -69
  111. package/scripts/smoke/update-ux.mjs +55 -55
  112. package/scripts/smoke/v138-completion.mjs +132 -132
  113. package/scripts/smoke/v138-desktop-release-hardening.mjs +69 -69
  114. package/scripts/smoke/v138-diagnostics.mjs +63 -63
  115. package/scripts/smoke/v138-issue-planner.mjs +33 -33
  116. package/scripts/smoke/v143-remote-control.mjs +76 -76
  117. package/scripts/smoke/v144-production-loop.mjs +47 -47
  118. package/scripts/smoke/v145-platformization.mjs +46 -46
  119. package/scripts/smoke/v146-control-room-ui.mjs +150 -150
  120. package/scripts/smoke/version-modal-autoshow.mjs +29 -29
  121. package/scripts/smoke/vscode-workbench-layout.mjs +63 -63
  122. package/scripts/smoke/vscode-workbench-polish.mjs +461 -461
  123. package/scripts/smoke/workflow-fallback-replay.mjs +56 -56
  124. package/scripts/smoke/workflow-templates.mjs +43 -43
  125. package/scripts/smoke/workflow-trace-timeline.mjs +46 -46
  126. package/scripts/update-git-install.mjs +298 -298
  127. package/server/claude-sdk.js +927 -927
  128. package/server/cli.js +1106 -1106
  129. package/server/constants/config.js +4 -4
  130. package/server/cursor-cli.js +344 -344
  131. package/server/daemon/manager.js +563 -563
  132. package/server/daemon-manager.js +964 -964
  133. package/server/database/db.js +988 -988
  134. package/server/database/json-store.js +197 -197
  135. package/server/gemini-cli.js +550 -550
  136. package/server/gemini-response-handler.js +79 -79
  137. package/server/index.js +5671 -5659
  138. package/server/load-env.js +35 -35
  139. package/server/middleware/account-lockout.js +112 -112
  140. package/server/middleware/auth.js +277 -277
  141. package/server/middleware/rate-limiter.js +87 -87
  142. package/server/modules/orchestration/a2a/adapter-registry.ts +108 -108
  143. package/server/modules/orchestration/a2a/adapters/abstract-a2a.adapter.ts +63 -63
  144. package/server/modules/orchestration/a2a/adapters/claude-code.adapter.ts +286 -286
  145. package/server/modules/orchestration/a2a/adapters/codex.adapter.ts +244 -244
  146. package/server/modules/orchestration/a2a/adapters/cursor.adapter.ts +249 -249
  147. package/server/modules/orchestration/a2a/adapters/gemini.adapter.ts +248 -248
  148. package/server/modules/orchestration/a2a/adapters/json-event.adapter.test.ts +60 -60
  149. package/server/modules/orchestration/a2a/adapters/json-event.adapter.ts +101 -101
  150. package/server/modules/orchestration/a2a/adapters/opencode.adapter.ts +248 -248
  151. package/server/modules/orchestration/a2a/adapters/qwen.adapter.ts +248 -248
  152. package/server/modules/orchestration/a2a/agent-card.ts +55 -55
  153. package/server/modules/orchestration/a2a/auth.middleware.ts +29 -29
  154. package/server/modules/orchestration/a2a/bus.ts +46 -46
  155. package/server/modules/orchestration/a2a/routes.ts +586 -586
  156. package/server/modules/orchestration/a2a/task-dispatcher.ts +345 -345
  157. package/server/modules/orchestration/a2a/task-store.ts +178 -178
  158. package/server/modules/orchestration/a2a/types.ts +126 -126
  159. package/server/modules/orchestration/a2a/validator.ts +113 -113
  160. package/server/modules/orchestration/index.ts +99 -99
  161. package/server/modules/orchestration/preview/port-watcher.ts +112 -112
  162. package/server/modules/orchestration/preview/preview-proxy.ts +60 -60
  163. package/server/modules/orchestration/preview/types.ts +19 -19
  164. package/server/modules/orchestration/security/permission-policy.ts +401 -401
  165. package/server/modules/orchestration/tasks/orchestration-task-store.ts +41 -41
  166. package/server/modules/orchestration/tasks/orchestration-task.routes.ts +81 -81
  167. package/server/modules/orchestration/tasks/orchestration-task.service.ts +201 -201
  168. package/server/modules/orchestration/tasks/orchestration-task.types.ts +40 -40
  169. package/server/modules/orchestration/tasks/task-run-graph.ts +155 -155
  170. package/server/modules/orchestration/workflows/approval-queue.ts +106 -106
  171. package/server/modules/orchestration/workflows/built-in-workflows.ts +127 -127
  172. package/server/modules/orchestration/workflows/context-packet.ts +186 -186
  173. package/server/modules/orchestration/workflows/handoff-artifact.ts +175 -175
  174. package/server/modules/orchestration/workflows/workflow-fallback-policy.ts +161 -161
  175. package/server/modules/orchestration/workflows/workflow-replay.ts +254 -254
  176. package/server/modules/orchestration/workflows/workflow-runner.ts +2062 -2062
  177. package/server/modules/orchestration/workflows/workflow-store.ts +97 -97
  178. package/server/modules/orchestration/workflows/workflow-templates.ts +272 -272
  179. package/server/modules/orchestration/workflows/workflow-trace.ts +424 -424
  180. package/server/modules/orchestration/workflows/workflow.routes.ts +586 -586
  181. package/server/modules/orchestration/workflows/workflow.types.ts +111 -111
  182. package/server/modules/orchestration/workflows/workspace-target.ts +122 -122
  183. package/server/modules/orchestration/workspace/docker-workspace.ts +136 -136
  184. package/server/modules/orchestration/workspace/path-safety.ts +55 -55
  185. package/server/modules/orchestration/workspace/types.ts +52 -52
  186. package/server/modules/orchestration/workspace/workspace-manager.ts +102 -102
  187. package/server/modules/orchestration/workspace/worktree-workspace.ts +126 -126
  188. package/server/modules/providers/index.ts +2 -2
  189. package/server/modules/providers/list/claude/claude-auth.provider.ts +146 -146
  190. package/server/modules/providers/list/claude/claude-mcp.provider.ts +135 -135
  191. package/server/modules/providers/list/claude/claude-sessions.provider.ts +306 -306
  192. package/server/modules/providers/list/claude/claude.provider.ts +15 -15
  193. package/server/modules/providers/list/codex/codex-auth.provider.ts +117 -117
  194. package/server/modules/providers/list/codex/codex-mcp.provider.ts +135 -135
  195. package/server/modules/providers/list/codex/codex-sessions.provider.ts +319 -319
  196. package/server/modules/providers/list/codex/codex.provider.ts +15 -15
  197. package/server/modules/providers/list/cursor/cursor-auth.provider.ts +147 -147
  198. package/server/modules/providers/list/cursor/cursor-mcp.provider.ts +108 -108
  199. package/server/modules/providers/list/cursor/cursor-sessions.provider.ts +421 -421
  200. package/server/modules/providers/list/cursor/cursor.provider.ts +15 -15
  201. package/server/modules/providers/list/gemini/gemini-auth.provider.ts +173 -173
  202. package/server/modules/providers/list/gemini/gemini-mcp.provider.ts +110 -110
  203. package/server/modules/providers/list/gemini/gemini-sessions.provider.ts +227 -227
  204. package/server/modules/providers/list/gemini/gemini.provider.ts +15 -15
  205. package/server/modules/providers/list/opencode/opencode-auth.provider.ts +131 -131
  206. package/server/modules/providers/list/opencode/opencode-sessions.provider.ts +286 -286
  207. package/server/modules/providers/list/qwen/qwen-auth.provider.ts +146 -146
  208. package/server/modules/providers/list/qwen/qwen-sessions.provider.ts +265 -265
  209. package/server/modules/providers/provider.registry.ts +40 -40
  210. package/server/modules/providers/provider.routes.ts +982 -982
  211. package/server/modules/providers/services/mcp.service.ts +86 -86
  212. package/server/modules/providers/services/provider-auth.service.ts +26 -26
  213. package/server/modules/providers/services/sessions.service.ts +45 -45
  214. package/server/modules/providers/shared/base/abstract.provider.ts +20 -20
  215. package/server/modules/providers/shared/mcp/mcp.provider.ts +151 -151
  216. package/server/modules/providers/tests/mcp.test.ts +293 -293
  217. package/server/openai-codex.js +468 -468
  218. package/server/opencode-cli.js +491 -491
  219. package/server/opencode-response-handler.js +111 -111
  220. package/server/projects.js +3135 -3135
  221. package/server/qwen-code-cli.js +410 -410
  222. package/server/routes/agent.js +1462 -1451
  223. package/server/routes/auth.js +298 -298
  224. package/server/routes/codex.js +20 -20
  225. package/server/routes/commands.js +581 -581
  226. package/server/routes/cursor.js +61 -61
  227. package/server/routes/diagnostics.js +44 -44
  228. package/server/routes/gemini.js +25 -25
  229. package/server/routes/git.js +1822 -1822
  230. package/server/routes/live-view.js +434 -434
  231. package/server/routes/mcp-utils.js +13 -13
  232. package/server/routes/messages.js +97 -97
  233. package/server/routes/network.js +143 -143
  234. package/server/routes/platformization.js +231 -231
  235. package/server/routes/plugins.js +690 -690
  236. package/server/routes/production-agent-loop.js +90 -90
  237. package/server/routes/projects.js +918 -918
  238. package/server/routes/public-api.js +34 -34
  239. package/server/routes/qwen.js +27 -27
  240. package/server/routes/remote.js +56 -56
  241. package/server/routes/settings.js +321 -321
  242. package/server/routes/telegram.js +163 -163
  243. package/server/routes/user.js +125 -125
  244. package/server/routes/webhooks.js +63 -63
  245. package/server/services/control-room.js +102 -102
  246. package/server/services/diagnostics.js +165 -165
  247. package/server/services/external-access.js +403 -403
  248. package/server/services/install-jobs.js +715 -715
  249. package/server/services/live-view.js +956 -956
  250. package/server/services/managed-runtimes.js +493 -493
  251. package/server/services/model-registry.js +144 -144
  252. package/server/services/notification-orchestrator.js +365 -365
  253. package/server/services/notification-taxonomy.js +204 -204
  254. package/server/services/platformization.js +1052 -1052
  255. package/server/services/production-agent-loop.js +248 -248
  256. package/server/services/provider-cli-versions.js +149 -149
  257. package/server/services/provider-credentials.js +189 -189
  258. package/server/services/provider-models.js +396 -396
  259. package/server/services/public-api-manifest.js +181 -181
  260. package/server/services/qr-login.js +126 -126
  261. package/server/services/remote-connection.js +127 -127
  262. package/server/services/runtime-manager.js +323 -323
  263. package/server/services/startup-update.js +259 -259
  264. package/server/services/telegram/bot.js +393 -393
  265. package/server/services/telegram/control-center.js +2453 -2453
  266. package/server/services/telegram/telegram-gateway.js +314 -314
  267. package/server/services/telegram/telegram-http-client.js +201 -201
  268. package/server/services/telegram/translations.js +470 -470
  269. package/server/services/webhooks.js +216 -216
  270. package/server/sessionManager.js +225 -225
  271. package/server/setup-wizard.js +283 -283
  272. package/server/shared/interfaces.ts +54 -54
  273. package/server/shared/types.ts +172 -172
  274. package/server/shared/utils.ts +193 -193
  275. package/server/tsconfig.json +36 -36
  276. package/server/utils/colors.js +21 -21
  277. package/server/utils/commandParser.js +305 -305
  278. package/server/utils/frontmatter.js +18 -18
  279. package/server/utils/gitConfig.js +34 -34
  280. package/server/utils/plugin-loader.js +461 -461
  281. package/server/utils/plugin-process-manager.js +185 -185
  282. package/server/utils/port-access.js +227 -227
  283. package/server/utils/runtime-paths.js +37 -37
  284. package/server/utils/security-log.js +84 -84
  285. package/server/utils/url-detection.js +71 -71
  286. package/server/vite-daemon.js +79 -79
  287. package/shared/modelConstants.js +161 -161
  288. package/shared/networkHosts.js +22 -22
@@ -1,1451 +1,1462 @@
1
- import { spawn } from 'child_process';
2
- import path from 'path';
3
- import os from 'os';
4
- import { promises as fs } from 'fs';
5
- import crypto from 'crypto';
6
-
7
- import express from 'express';
8
- import { Octokit } from '@octokit/rest';
9
-
10
- import { userDb, apiKeysDb, githubTokensDb } from '../database/db.js';
11
- import { addProjectManually } from '../projects.js';
12
- import { queryClaudeSDK } from '../claude-sdk.js';
13
- import { spawnCursor } from '../cursor-cli.js';
14
- import { queryCodex } from '../openai-codex.js';
15
- import { spawnGemini } from '../gemini-cli.js';
16
- import { spawnQwen } from '../qwen-code-cli.js';
17
- import { spawnOpencode } from '../opencode-cli.js';
18
- import { IS_PLATFORM } from '../constants/config.js';
19
- import { getDefaultProviderModel } from '../services/model-registry.js';
20
-
21
- const router = express.Router();
22
- const isPixcodeApiKey = (token) => typeof token === 'string' && (token.startsWith('px_') || token.startsWith('ck_'));
23
-
24
- /**
25
- * Middleware to authenticate agent API requests.
26
- *
27
- * Supports two authentication modes:
28
- * 1. Platform mode (IS_PLATFORM=true): For managed/hosted deployments where
29
- * authentication is handled by an external proxy. Requests are trusted and
30
- * the default user context is used.
31
- *
32
- * 2. API key mode (default): For self-hosted deployments where users authenticate
33
- * via API keys created in the UI. Keys are validated against the local database.
34
- */
35
- const validateExternalApiKey = (req, res, next) => {
36
- // Platform mode: Authentication is handled externally (e.g., by a proxy layer).
37
- // Trust the request and use the default user context.
38
- if (IS_PLATFORM) {
39
- try {
40
- const user = userDb.getFirstUser();
41
- if (!user) {
42
- return res.status(500).json({ error: 'Platform mode: No user found in database' });
43
- }
44
- req.user = user;
45
- return next();
46
- } catch (error) {
47
- console.error('Platform mode error:', error);
48
- return res.status(500).json({ error: 'Platform mode: Failed to fetch user' });
49
- }
50
- }
51
-
52
- // Self-hosted mode: validate API key from any of the supported transports.
53
- // - Authorization: Bearer px_... (legacy ck_... still accepted)
54
- // auth shape as the rest of the API, per the auth-unify in this turn)
55
- // - X-API-Key: px_...
56
- // - ?apiKey=px_... (EventSource workaround)
57
- const authHeader = req.headers['authorization'];
58
- const bearer = authHeader && authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : null;
59
- const apiKey = (isPixcodeApiKey(bearer) ? bearer : null)
60
- || req.headers['x-api-key']
61
- || (typeof req.query.apiKey === 'string' ? req.query.apiKey : null);
62
-
63
- if (!apiKey) {
64
- return res.status(401).json({ error: 'API key required (Authorization: Bearer px_..., X-API-Key, or ?apiKey=)' });
65
- }
66
-
67
- const user = apiKeysDb.validateApiKey(apiKey);
68
-
69
- if (!user) {
70
- return res.status(401).json({ error: 'Invalid or inactive API key' });
71
- }
72
-
73
- req.user = user;
74
- next();
75
- };
76
-
77
- /**
78
- * Get the remote URL of a git repository
79
- * @param {string} repoPath - Path to the git repository
80
- * @returns {Promise<string>} - Remote URL of the repository
81
- */
82
- async function getGitRemoteUrl(repoPath) {
83
- return new Promise((resolve, reject) => {
84
- const gitProcess = spawn('git', ['config', '--get', 'remote.origin.url'], {
85
- cwd: repoPath,
86
- stdio: ['pipe', 'pipe', 'pipe']
87
- });
88
-
89
- let stdout = '';
90
- let stderr = '';
91
-
92
- gitProcess.stdout.on('data', (data) => {
93
- stdout += data.toString();
94
- });
95
-
96
- gitProcess.stderr.on('data', (data) => {
97
- stderr += data.toString();
98
- });
99
-
100
- gitProcess.on('close', (code) => {
101
- if (code === 0) {
102
- resolve(stdout.trim());
103
- } else {
104
- reject(new Error(`Failed to get git remote: ${stderr}`));
105
- }
106
- });
107
-
108
- gitProcess.on('error', (error) => {
109
- reject(new Error(`Failed to execute git: ${error.message}`));
110
- });
111
- });
112
- }
113
-
114
- /**
115
- * Normalize GitHub URLs for comparison
116
- * @param {string} url - GitHub URL
117
- * @returns {string} - Normalized URL
118
- */
119
- function normalizeGitHubUrl(url) {
120
- // Remove .git suffix
121
- let normalized = url.replace(/\.git$/, '');
122
- // Convert SSH to HTTPS format for comparison
123
- normalized = normalized.replace(/^git@github\.com:/, 'https://github.com/');
124
- // Remove trailing slash
125
- normalized = normalized.replace(/\/$/, '');
126
- return normalized.toLowerCase();
127
- }
128
-
129
- /**
130
- * Parse GitHub URL to extract owner and repo
131
- * @param {string} url - GitHub URL (HTTPS or SSH)
132
- * @returns {{owner: string, repo: string}} - Parsed owner and repo
133
- */
134
- function parseGitHubUrl(url) {
135
- // Handle HTTPS URLs: https://github.com/owner/repo or https://github.com/owner/repo.git
136
- // Handle SSH URLs: git@github.com:owner/repo or git@github.com:owner/repo.git
137
- const match = url.match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/);
138
- if (!match) {
139
- throw new Error('Invalid GitHub URL format');
140
- }
141
- return {
142
- owner: match[1],
143
- repo: match[2].replace(/\.git$/, '')
144
- };
145
- }
146
-
147
- /**
148
- * Auto-generate a branch name from a message
149
- * @param {string} message - The agent message
150
- * @returns {string} - Generated branch name
151
- */
152
- function autogenerateBranchName(message) {
153
- // Convert to lowercase, replace spaces/special chars with hyphens
154
- let branchName = message
155
- .toLowerCase()
156
- .replace(/[^a-z0-9\s-]/g, '') // Remove special characters
157
- .replace(/\s+/g, '-') // Replace spaces with hyphens
158
- .replace(/-+/g, '-') // Replace multiple hyphens with single
159
- .replace(/^-|-$/g, ''); // Remove leading/trailing hyphens
160
-
161
- // Ensure non-empty fallback
162
- if (!branchName) {
163
- branchName = 'task';
164
- }
165
-
166
- // Generate timestamp suffix (last 6 chars of base36 timestamp)
167
- const timestamp = Date.now().toString(36).slice(-6);
168
- const suffix = `-${timestamp}`;
169
-
170
- // Limit length to ensure total length including suffix fits within 50 characters
171
- const maxBaseLength = 50 - suffix.length;
172
- if (branchName.length > maxBaseLength) {
173
- branchName = branchName.substring(0, maxBaseLength);
174
- }
175
-
176
- // Remove any trailing hyphen after truncation and ensure no leading hyphen
177
- branchName = branchName.replace(/-$/, '').replace(/^-+/, '');
178
-
179
- // If still empty or starts with hyphen after cleanup, use fallback
180
- if (!branchName || branchName.startsWith('-')) {
181
- branchName = 'task';
182
- }
183
-
184
- // Combine base name with timestamp suffix
185
- branchName = `${branchName}${suffix}`;
186
-
187
- // Final validation: ensure it matches safe pattern
188
- if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(branchName)) {
189
- // Fallback to deterministic safe name
190
- return `branch-${timestamp}`;
191
- }
192
-
193
- return branchName;
194
- }
195
-
196
- /**
197
- * Validate a Git branch name
198
- * @param {string} branchName - Branch name to validate
199
- * @returns {{valid: boolean, error?: string}} - Validation result
200
- */
201
- function validateBranchName(branchName) {
202
- if (!branchName || branchName.trim() === '') {
203
- return { valid: false, error: 'Branch name cannot be empty' };
204
- }
205
-
206
- // Git branch name rules
207
- const invalidPatterns = [
208
- { pattern: /^\./, message: 'Branch name cannot start with a dot' },
209
- { pattern: /\.$/, message: 'Branch name cannot end with a dot' },
210
- { pattern: /\.\./, message: 'Branch name cannot contain consecutive dots (..)' },
211
- { pattern: /\s/, message: 'Branch name cannot contain spaces' },
212
- { pattern: /[~^:?*\[\\]/, message: 'Branch name cannot contain special characters: ~ ^ : ? * [ \\' },
213
- { pattern: /@{/, message: 'Branch name cannot contain @{' },
214
- { pattern: /\/$/, message: 'Branch name cannot end with a slash' },
215
- { pattern: /^\//, message: 'Branch name cannot start with a slash' },
216
- { pattern: /\/\//, message: 'Branch name cannot contain consecutive slashes' },
217
- { pattern: /\.lock$/, message: 'Branch name cannot end with .lock' }
218
- ];
219
-
220
- for (const { pattern, message } of invalidPatterns) {
221
- if (pattern.test(branchName)) {
222
- return { valid: false, error: message };
223
- }
224
- }
225
-
226
- // Check for ASCII control characters
227
- if (/[\x00-\x1F\x7F]/.test(branchName)) {
228
- return { valid: false, error: 'Branch name cannot contain control characters' };
229
- }
230
-
231
- return { valid: true };
232
- }
233
-
234
- function providerDisplayName(provider) {
235
- return ({
236
- claude: 'Claude',
237
- cursor: 'Cursor',
238
- codex: 'Codex',
239
- gemini: 'Gemini',
240
- qwen: 'Qwen',
241
- opencode: 'OpenCode',
242
- })[provider] || 'Provider';
243
- }
244
-
245
- function describeProviderFailure(rawError, provider) {
246
- const rawMessage = String(rawError || '').trim() || 'Provider returned no assistant text.';
247
- const normalized = rawMessage.toLowerCase();
248
- const name = providerDisplayName(provider);
249
-
250
- const details = {
251
- provider,
252
- providerName: name,
253
- category: 'provider_error',
254
- title: `${name} could not answer.`,
255
- action: 'Check the provider output, then retry with a shorter prompt or a different model.',
256
- rawMessage,
257
- };
258
-
259
- if (/(balance|billing|quota|credit|insufficient|payment required|402|usage limit|spend limit)/i.test(rawMessage)) {
260
- details.category = 'quota';
261
- details.title = `${name} could not answer because the account has no available balance or quota.`;
262
- details.action = 'Add credits, increase the provider usage limit, or switch to a free/available model.';
263
- } else if (/(rate limit|too many requests|429|temporarily overloaded|resource exhausted)/i.test(rawMessage)) {
264
- details.category = 'rate_limit';
265
- details.title = `${name} is rate limited right now.`;
266
- details.action = 'Wait a bit, reduce parallel runs, or switch to another provider/model.';
267
- } else if (/(unauthorized|forbidden|permission_denied|permission denied|api key|token|oauth|login|not authenticated|401|403|invalid credentials)/i.test(rawMessage)) {
268
- details.category = 'auth';
269
- details.title = `${name} is not authenticated or the selected model is not allowed.`;
270
- details.action = 'Reconnect this provider in Settings, refresh the CLI login, or choose a model enabled for the account.';
271
- } else if (/(not installed|command not found|enoent|spawn .* enoent|executable file not found|exited with code 127)/i.test(rawMessage)) {
272
- details.category = 'missing_cli';
273
- details.title = `${name} CLI is not installed or not on PATH.`;
274
- details.action = 'Install the CLI from Settings -> Agents or set the matching CLI path environment variable.';
275
- } else if (/(timeout|timed out|aborted|etimedout|deadline)/i.test(rawMessage)) {
276
- details.category = 'timeout';
277
- details.title = `${name} timed out before returning a complete answer.`;
278
- details.action = 'Retry with a shorter request, reduce orchestration parallelism, or inspect the provider session log.';
279
- } else if (normalized.includes('no assistant text') || normalized.includes('empty')) {
280
- details.category = 'no_output';
281
- details.title = `${name} finished without visible assistant text.`;
282
- details.action = 'Retry once; if it repeats, check provider stderr/session logs because the CLI may have exited before streaming text.';
283
- }
284
-
285
- details.message = `${details.title} ${details.action}`;
286
- return details;
287
- }
288
-
289
- /**
290
- * Get recent commit messages from a repository
291
- * @param {string} projectPath - Path to the git repository
292
- * @param {number} limit - Number of commits to retrieve (default: 5)
293
- * @returns {Promise<string[]>} - Array of commit messages
294
- */
295
- async function getCommitMessages(projectPath, limit = 5) {
296
- return new Promise((resolve, reject) => {
297
- const gitProcess = spawn('git', ['log', `-${limit}`, '--pretty=format:%s'], {
298
- cwd: projectPath,
299
- stdio: ['pipe', 'pipe', 'pipe']
300
- });
301
-
302
- let stdout = '';
303
- let stderr = '';
304
-
305
- gitProcess.stdout.on('data', (data) => {
306
- stdout += data.toString();
307
- });
308
-
309
- gitProcess.stderr.on('data', (data) => {
310
- stderr += data.toString();
311
- });
312
-
313
- gitProcess.on('close', (code) => {
314
- if (code === 0) {
315
- const messages = stdout.trim().split('\n').filter(msg => msg.length > 0);
316
- resolve(messages);
317
- } else {
318
- reject(new Error(`Failed to get commit messages: ${stderr}`));
319
- }
320
- });
321
-
322
- gitProcess.on('error', (error) => {
323
- reject(new Error(`Failed to execute git: ${error.message}`));
324
- });
325
- });
326
- }
327
-
328
- /**
329
- * Create a new branch on GitHub using the API
330
- * @param {Octokit} octokit - Octokit instance
331
- * @param {string} owner - Repository owner
332
- * @param {string} repo - Repository name
333
- * @param {string} branchName - Name of the new branch
334
- * @param {string} baseBranch - Base branch to branch from (default: 'main')
335
- * @returns {Promise<void>}
336
- */
337
- async function createGitHubBranch(octokit, owner, repo, branchName, baseBranch = 'main') {
338
- try {
339
- // Get the SHA of the base branch
340
- const { data: ref } = await octokit.git.getRef({
341
- owner,
342
- repo,
343
- ref: `heads/${baseBranch}`
344
- });
345
-
346
- const baseSha = ref.object.sha;
347
-
348
- // Create the new branch
349
- await octokit.git.createRef({
350
- owner,
351
- repo,
352
- ref: `refs/heads/${branchName}`,
353
- sha: baseSha
354
- });
355
-
356
- console.log(`✅ Created branch '${branchName}' on GitHub`);
357
- } catch (error) {
358
- if (error.status === 422 && error.message.includes('Reference already exists')) {
359
- console.log(`ℹ️ Branch '${branchName}' already exists on GitHub`);
360
- } else {
361
- throw error;
362
- }
363
- }
364
- }
365
-
366
- /**
367
- * Create a pull request on GitHub
368
- * @param {Octokit} octokit - Octokit instance
369
- * @param {string} owner - Repository owner
370
- * @param {string} repo - Repository name
371
- * @param {string} branchName - Head branch name
372
- * @param {string} title - PR title
373
- * @param {string} body - PR body/description
374
- * @param {string} baseBranch - Base branch (default: 'main')
375
- * @returns {Promise<{number: number, url: string}>} - PR number and URL
376
- */
377
- async function createGitHubPR(octokit, owner, repo, branchName, title, body, baseBranch = 'main') {
378
- const { data: pr } = await octokit.pulls.create({
379
- owner,
380
- repo,
381
- title,
382
- head: branchName,
383
- base: baseBranch,
384
- body
385
- });
386
-
387
- console.log(`✅ Created pull request #${pr.number}: ${pr.html_url}`);
388
-
389
- return {
390
- number: pr.number,
391
- url: pr.html_url
392
- };
393
- }
394
-
395
- /**
396
- * Clone a GitHub repository to a directory
397
- * @param {string} githubUrl - GitHub repository URL
398
- * @param {string} githubToken - Optional GitHub token for private repos
399
- * @param {string} projectPath - Path for cloning the repository
400
- * @returns {Promise<string>} - Path to the cloned repository
401
- */
402
- async function cloneGitHubRepo(githubUrl, githubToken = null, projectPath) {
403
- return new Promise(async (resolve, reject) => {
404
- try {
405
- // Validate GitHub URL
406
- if (!githubUrl || !githubUrl.includes('github.com')) {
407
- throw new Error('Invalid GitHub URL');
408
- }
409
-
410
- const cloneDir = path.resolve(projectPath);
411
-
412
- // Check if directory already exists
413
- try {
414
- await fs.access(cloneDir);
415
- // Directory exists - check if it's a git repo with the same URL
416
- try {
417
- const existingUrl = await getGitRemoteUrl(cloneDir);
418
- const normalizedExisting = normalizeGitHubUrl(existingUrl);
419
- const normalizedRequested = normalizeGitHubUrl(githubUrl);
420
-
421
- if (normalizedExisting === normalizedRequested) {
422
- console.log('✅ Repository already exists at path with correct URL');
423
- return resolve(cloneDir);
424
- } else {
425
- throw new Error(`Directory ${cloneDir} already exists with a different repository (${existingUrl}). Expected: ${githubUrl}`);
426
- }
427
- } catch (gitError) {
428
- throw new Error(`Directory ${cloneDir} already exists but is not a valid git repository or git command failed`);
429
- }
430
- } catch (accessError) {
431
- // Directory doesn't exist - proceed with clone
432
- }
433
-
434
- // Ensure parent directory exists
435
- await fs.mkdir(path.dirname(cloneDir), { recursive: true });
436
-
437
- // Prepare the git clone URL with authentication if token is provided
438
- let cloneUrl = githubUrl;
439
- if (githubToken) {
440
- // Convert HTTPS URL to authenticated URL
441
- // Example: https://github.com/user/repo -> https://token@github.com/user/repo
442
- cloneUrl = githubUrl.replace('https://github.com', `https://${githubToken}@github.com`);
443
- }
444
-
445
- console.log('🔄 Cloning repository:', githubUrl);
446
- console.log('📁 Destination:', cloneDir);
447
-
448
- // Execute git clone
449
- const gitProcess = spawn('git', ['clone', '--depth', '1', cloneUrl, cloneDir], {
450
- stdio: ['pipe', 'pipe', 'pipe']
451
- });
452
-
453
- let stdout = '';
454
- let stderr = '';
455
-
456
- gitProcess.stdout.on('data', (data) => {
457
- stdout += data.toString();
458
- });
459
-
460
- gitProcess.stderr.on('data', (data) => {
461
- stderr += data.toString();
462
- console.log('Git stderr:', data.toString());
463
- });
464
-
465
- gitProcess.on('close', (code) => {
466
- if (code === 0) {
467
- console.log('✅ Repository cloned successfully');
468
- resolve(cloneDir);
469
- } else {
470
- console.error('❌ Git clone failed:', stderr);
471
- reject(new Error(`Git clone failed: ${stderr}`));
472
- }
473
- });
474
-
475
- gitProcess.on('error', (error) => {
476
- reject(new Error(`Failed to execute git: ${error.message}`));
477
- });
478
- } catch (error) {
479
- reject(error);
480
- }
481
- });
482
- }
483
-
484
- /**
485
- * Clean up a temporary project directory and its Claude session
486
- * @param {string} projectPath - Path to the project directory
487
- * @param {string} sessionId - Session ID to clean up
488
- */
489
- async function cleanupProject(projectPath, sessionId = null) {
490
- try {
491
- // Only clean up projects in the external-projects directory
492
- if (!projectPath.includes('.claude/external-projects')) {
493
- console.warn('⚠️ Refusing to clean up non-external project:', projectPath);
494
- return;
495
- }
496
-
497
- console.log('🧹 Cleaning up project:', projectPath);
498
- await fs.rm(projectPath, { recursive: true, force: true });
499
- console.log('✅ Project cleaned up');
500
-
501
- // Also clean up the Claude session directory if sessionId provided
502
- if (sessionId) {
503
- try {
504
- const sessionPath = path.join(os.homedir(), '.claude', 'sessions', sessionId);
505
- console.log('🧹 Cleaning up session directory:', sessionPath);
506
- await fs.rm(sessionPath, { recursive: true, force: true });
507
- console.log('✅ Session directory cleaned up');
508
- } catch (error) {
509
- console.error('⚠️ Failed to clean up session directory:', error.message);
510
- }
511
- }
512
- } catch (error) {
513
- console.error('❌ Failed to clean up project:', error);
514
- }
515
- }
516
-
517
- /**
518
- * SSE Stream Writer - Adapts SDK/CLI output to Server-Sent Events
519
- */
520
- class SSEStreamWriter {
521
- constructor(res, userId = null) {
522
- this.res = res;
523
- this.sessionId = null;
524
- this.userId = userId;
525
- this.isSSEStreamWriter = true; // Marker for transport detection
526
- }
527
-
528
- send(data) {
529
- if (this.res.writableEnded) {
530
- return;
531
- }
532
-
533
- // Format as SSE - providers send raw objects, we stringify
534
- this.res.write(`data: ${JSON.stringify(data)}\n\n`);
535
- }
536
-
537
- end() {
538
- if (!this.res.writableEnded) {
539
- this.res.write('data: {"type":"done"}\n\n');
540
- this.res.end();
541
- }
542
- }
543
-
544
- setSessionId(sessionId) {
545
- this.sessionId = sessionId;
546
- this.send({ type: 'session-id', sessionId });
547
- }
548
-
549
- getSessionId() {
550
- return this.sessionId;
551
- }
552
- }
553
-
554
- /**
555
- * Non-streaming response collector
556
- */
557
- class ResponseCollector {
558
- constructor(userId = null) {
559
- this.messages = [];
560
- this.sessionId = null;
561
- this.userId = userId;
562
- }
563
-
564
- send(data) {
565
- // Store ALL messages for now - we'll filter when returning
566
- this.messages.push(data);
567
-
568
- // Extract sessionId if present
569
- if (typeof data === 'string') {
570
- try {
571
- const parsed = JSON.parse(data);
572
- if (parsed.sessionId) {
573
- this.sessionId = parsed.sessionId;
574
- }
575
- } catch (e) {
576
- // Not JSON, ignore
577
- }
578
- } else if (data && data.sessionId) {
579
- this.sessionId = data.sessionId;
580
- }
581
- }
582
-
583
- end() {
584
- // Do nothing - we'll collect all messages
585
- }
586
-
587
- setSessionId(sessionId) {
588
- this.sessionId = sessionId;
589
- }
590
-
591
- getSessionId() {
592
- return this.sessionId;
593
- }
594
-
595
- getMessages() {
596
- return this.messages;
597
- }
598
-
599
- /**
600
- * Get filtered assistant messages.
601
- *
602
- * Two message shapes are observed in the wild:
603
- * 1. Legacy Claude-only: { type:'claude-response', data:{ type:'assistant', message:{...} } }
604
- * 2. Unified normalized: { kind:'stream_delta'|'tool_use'|... , provider, content, ... }
605
- * (every provider after the v1.30+ unified-message migration emits this)
606
- *
607
- * Pre-fix this method only matched (1), so qwen / gemini / opencode / codex
608
- * runs all returned an empty array even when the provider streamed real
609
- * text. Now it builds:
610
- * - one synthetic assistant entry per chat turn from concatenated
611
- * `stream_delta` content (boundary = `stream_end` or `complete`)
612
- * - tool_use / tool_result entries pass through verbatim
613
- */
614
- getAssistantMessages() {
615
- const out = [];
616
- let textBuffer = '';
617
-
618
- const flushText = () => {
619
- if (!textBuffer) return;
620
- out.push({
621
- type: 'assistant',
622
- message: {
623
- role: 'assistant',
624
- content: [{ type: 'text', text: textBuffer }],
625
- },
626
- });
627
- textBuffer = '';
628
- };
629
-
630
- for (const raw of this.messages) {
631
- const data = typeof raw === 'string'
632
- ? (() => { try { return JSON.parse(raw); } catch { return null; } })()
633
- : raw;
634
- if (!data) continue;
635
- if (data.type === 'status') continue;
636
-
637
- // Unified shape (every modern provider).
638
- // - `stream_delta`: incremental text chunk (most providers)
639
- // - `text`: full text part for one assistant turn (Claude SDK + history reads)
640
- // - `thinking`: reasoning blocks; we coalesce as plain text so the API caller sees something
641
- if ((data.kind === 'stream_delta' || data.kind === 'text' || data.kind === 'thinking')
642
- && (typeof data.content === 'string' || Array.isArray(data.content))) {
643
- const text = typeof data.content === 'string'
644
- ? data.content
645
- : data.content.map((part) => (typeof part === 'string' ? part : (part?.text || ''))).join('');
646
- textBuffer += text;
647
- continue;
648
- }
649
- if (data.kind === 'stream_end' || data.kind === 'complete') {
650
- flushText();
651
- continue;
652
- }
653
- if (data.kind === 'tool_use') {
654
- flushText();
655
- out.push({ type: 'tool_use', id: data.toolId, name: data.toolName, input: data.toolInput });
656
- continue;
657
- }
658
- if (data.kind === 'tool_result') {
659
- out.push({ type: 'tool_result', tool_use_id: data.toolId, content: data.content, is_error: data.isError });
660
- continue;
661
- }
662
- if (data.kind === 'error' && typeof data.content === 'string') {
663
- flushText();
664
- out.push({ type: 'error', content: data.content });
665
- continue;
666
- }
667
-
668
- // Legacy Claude shape — kept so old SDK builds still report cleanly.
669
- if (data.type === 'claude-response' && data.data && data.data.type === 'assistant') {
670
- flushText();
671
- out.push(data.data);
672
- }
673
- }
674
- flushText();
675
- return out;
676
- }
677
-
678
- /**
679
- * Calculate total tokens from all messages.
680
- *
681
- * Two usage shapes observed:
682
- * 1. Legacy Claude: { type:'claude-response', data:{ message:{ usage:{ input_tokens, output_tokens, cache_*_input_tokens } } } }
683
- * 2. Unified `complete`/ { kind:'complete'|'stream_end', usage:{ input, output, cacheRead?, cacheCreation? }, cost? }
684
- * `stream_end` events
685
- */
686
- getTotalTokens() {
687
- let inputTokens = 0;
688
- let outputTokens = 0;
689
- let cacheReadTokens = 0;
690
- let cacheCreationTokens = 0;
691
-
692
- for (const raw of this.messages) {
693
- const data = typeof raw === 'string'
694
- ? (() => { try { return JSON.parse(raw); } catch { return null; } })()
695
- : raw;
696
- if (!data) continue;
697
-
698
- // Unified shape
699
- if (data.usage && typeof data.usage === 'object') {
700
- inputTokens += data.usage.input || data.usage.inputTokens || data.usage.input_tokens || 0;
701
- outputTokens += data.usage.output || data.usage.outputTokens || data.usage.output_tokens || 0;
702
- cacheReadTokens += data.usage.cacheRead || data.usage.cache_read_input_tokens || 0;
703
- cacheCreationTokens += data.usage.cacheCreation || data.usage.cache_creation_input_tokens || 0;
704
- continue;
705
- }
706
-
707
- // Legacy Claude
708
- if (data.type === 'claude-response' && data.data && data.data.message && data.data.message.usage) {
709
- const u = data.data.message.usage;
710
- inputTokens += u.input_tokens || 0;
711
- outputTokens += u.output_tokens || 0;
712
- cacheReadTokens += u.cache_read_input_tokens || 0;
713
- cacheCreationTokens += u.cache_creation_input_tokens || 0;
714
- }
715
- }
716
-
717
- return {
718
- inputTokens,
719
- outputTokens,
720
- cacheReadTokens,
721
- cacheCreationTokens,
722
- totalTokens: inputTokens + outputTokens + cacheReadTokens + cacheCreationTokens,
723
- };
724
- }
725
- }
726
-
727
- // ===============================
728
- // External API Endpoint
729
- // ===============================
730
-
731
- /**
732
- * POST /api/agent
733
- *
734
- * Trigger an AI agent (Claude or Cursor) to work on a project.
735
- * Supports automatic GitHub branch and pull request creation after successful completion.
736
- *
737
- * ================================================================================================
738
- * REQUEST BODY PARAMETERS
739
- * ================================================================================================
740
- *
741
- * @param {string} githubUrl - (Conditionally Required) GitHub repository URL to clone.
742
- * Supported formats:
743
- * - HTTPS: https://github.com/owner/repo
744
- * - HTTPS with .git: https://github.com/owner/repo.git
745
- * - SSH: git@github.com:owner/repo
746
- * - SSH with .git: git@github.com:owner/repo.git
747
- *
748
- * @param {string} projectPath - (Conditionally Required) Path to existing project OR destination for cloning.
749
- * Behavior depends on usage:
750
- * - If used alone: Must point to existing project directory
751
- * - If used with githubUrl: Target location for cloning
752
- * - If omitted with githubUrl: Auto-generates temporary path in ~/.claude/external-projects/
753
- *
754
- * @param {string} message - (Required) Task description for the AI agent. Used as:
755
- * - Instructions for the agent
756
- * - Source for auto-generated branch names (if createBranch=true and no branchName)
757
- * - Fallback for PR title if no commits are made
758
- *
759
- * @param {string} provider - (Optional) AI provider to use. Options: 'claude' | 'cursor' | 'codex' | 'gemini'
760
- * Default: 'claude'
761
- *
762
- * @param {boolean} stream - (Optional) Enable Server-Sent Events (SSE) streaming for real-time updates.
763
- * Default: true
764
- * - true: Returns text/event-stream with incremental updates
765
- * - false: Returns complete JSON response after completion
766
- *
767
- * @param {string} model - (Optional) Model identifier for providers.
768
- *
769
- * Claude models: 'sonnet' (default), 'opus', 'haiku', 'opusplan', 'sonnet[1m]'
770
- * Cursor models: 'gpt-5' (default), 'gpt-5.2', 'gpt-5.2-high', 'sonnet-4.5', 'opus-4.5',
771
- * 'gemini-3-pro', 'composer-1', 'auto', 'gpt-5.1', 'gpt-5.1-high',
772
- * 'gpt-5.1-codex', 'gpt-5.1-codex-high', 'gpt-5.1-codex-max',
773
- * 'gpt-5.1-codex-max-high', 'opus-4.1', 'grok', and thinking variants
774
- * Codex models: 'gpt-5.2' (default), 'gpt-5.1-codex-max', 'o3', 'o4-mini'
775
- *
776
- * @param {boolean} cleanup - (Optional) Auto-cleanup project directory after completion.
777
- * Default: true
778
- * Behavior:
779
- * - Only applies when cloning via githubUrl (not for existing projectPath)
780
- * - Deletes cloned repository after 5 seconds
781
- * - Also deletes associated Claude session directory
782
- * - Remote branch and PR remain on GitHub if created
783
- *
784
- * @param {string} githubToken - (Optional) GitHub Personal Access Token for authentication.
785
- * Overrides stored token from user settings.
786
- * Required for:
787
- * - Private repositories
788
- * - Branch/PR creation features
789
- * Token must have 'repo' scope for full functionality.
790
- *
791
- * @param {string} branchName - (Optional) Custom name for the Git branch.
792
- * If provided, createBranch is automatically set to true.
793
- * Validation rules (errors returned if violated):
794
- * - Cannot be empty or whitespace only
795
- * - Cannot start or end with dot (.)
796
- * - Cannot contain consecutive dots (..)
797
- * - Cannot contain spaces
798
- * - Cannot contain special characters: ~ ^ : ? * [ \
799
- * - Cannot contain @{
800
- * - Cannot start or end with forward slash (/)
801
- * - Cannot contain consecutive slashes (//)
802
- * - Cannot end with .lock
803
- * - Cannot contain ASCII control characters
804
- * Examples: 'feature/user-auth', 'bugfix/login-error', 'refactor/db-optimization'
805
- *
806
- * @param {boolean} createBranch - (Optional) Create a new Git branch after successful agent completion.
807
- * Default: false (or true if branchName is provided)
808
- * Behavior:
809
- * - Creates branch locally and pushes to remote
810
- * - If branch exists locally: Checks out existing branch (no error)
811
- * - If branch exists on remote: Uses existing branch (no error)
812
- * - Branch name: Custom (if branchName provided) or auto-generated from message
813
- * - Requires either githubUrl OR projectPath with GitHub remote
814
- *
815
- * @param {boolean} createPR - (Optional) Create a GitHub Pull Request after successful completion.
816
- * Default: false
817
- * Behavior:
818
- * - PR title: First commit message (or fallback to message parameter)
819
- * - PR description: Auto-generated from all commit messages
820
- * - Base branch: Always 'main' (currently hardcoded)
821
- * - If PR already exists: GitHub returns error with details
822
- * - Requires either githubUrl OR projectPath with GitHub remote
823
- *
824
- * ================================================================================================
825
- * PATH HANDLING BEHAVIOR
826
- * ================================================================================================
827
- *
828
- * Scenario 1: Only githubUrl provided
829
- * Input: { githubUrl: "https://github.com/owner/repo" }
830
- * Action: Clones to auto-generated temporary path: ~/.claude/external-projects/<hash>/
831
- * Cleanup: Yes (if cleanup=true)
832
- *
833
- * Scenario 2: Only projectPath provided
834
- * Input: { projectPath: "/home/user/my-project" }
835
- * Action: Uses existing project at specified path
836
- * Validation: Path must exist and be accessible
837
- * Cleanup: No (never cleanup existing projects)
838
- *
839
- * Scenario 3: Both githubUrl and projectPath provided
840
- * Input: { githubUrl: "https://github.com/owner/repo", projectPath: "/custom/path" }
841
- * Action: Clones githubUrl to projectPath location
842
- * Validation:
843
- * - If projectPath exists with git repo:
844
- * - Compares remote URL with githubUrl
845
- * - If URLs match: Reuses existing repo
846
- * - If URLs differ: Returns error
847
- * Cleanup: Yes (if cleanup=true)
848
- *
849
- * ================================================================================================
850
- * GITHUB BRANCH/PR CREATION REQUIREMENTS
851
- * ================================================================================================
852
- *
853
- * For createBranch or createPR to work, one of the following must be true:
854
- *
855
- * Option A: githubUrl provided
856
- * - Repository URL directly specified
857
- * - Works with both cloning and existing paths
858
- *
859
- * Option B: projectPath with GitHub remote
860
- * - Project must be a Git repository
861
- * - Must have 'origin' remote configured
862
- * - Remote URL must point to github.com
863
- * - System auto-detects GitHub URL via: git remote get-url origin
864
- *
865
- * Additional Requirements:
866
- * - Valid GitHub token (from settings or githubToken parameter)
867
- * - Token must have 'repo' scope for private repos
868
- * - Project must have commits (for PR creation)
869
- *
870
- * ================================================================================================
871
- * VALIDATION & ERROR HANDLING
872
- * ================================================================================================
873
- *
874
- * Input Validations (400 Bad Request):
875
- * - Either githubUrl OR projectPath must be provided (not neither)
876
- * - message must be non-empty string
877
- * - provider must be 'claude', 'cursor', 'codex', or 'gemini'
878
- * - createBranch/createPR requires githubUrl OR projectPath (not neither)
879
- * - branchName must pass Git naming rules (if provided)
880
- *
881
- * Runtime Validations (500 Internal Server Error or specific error in response):
882
- * - projectPath must exist (if used alone)
883
- * - GitHub URL format must be valid
884
- * - Git remote URL must include github.com (for projectPath + branch/PR)
885
- * - GitHub token must be available (for private repos and branch/PR)
886
- * - Directory conflicts handled (existing path with different repo)
887
- *
888
- * Branch Name Validation Errors (returned in response, not HTTP error):
889
- * Invalid names return: { branch: { error: "Invalid branch name: <reason>" } }
890
- * Examples:
891
- * - "my branch" → "Branch name cannot contain spaces"
892
- * - ".feature" "Branch name cannot start with a dot"
893
- * - "feature.lock" "Branch name cannot end with .lock"
894
- *
895
- * ================================================================================================
896
- * RESPONSE FORMATS
897
- * ================================================================================================
898
- *
899
- * Streaming Response (stream=true):
900
- * Content-Type: text/event-stream
901
- * Events:
902
- * - { type: "status", message: "...", projectPath: "..." }
903
- * - { type: "claude-response", data: {...} }
904
- * - { type: "github-branch", branch: { name: "...", url: "..." } }
905
- * - { type: "github-pr", pullRequest: { number: 42, url: "..." } }
906
- * - { type: "github-error", error: "..." }
907
- * - { type: "done" }
908
- *
909
- * Non-Streaming Response (stream=false):
910
- * Content-Type: application/json
911
- * {
912
- * success: true,
913
- * sessionId: "session-123",
914
- * messages: [...], // Assistant messages only (filtered)
915
- * tokens: {
916
- * inputTokens: 150,
917
- * outputTokens: 50,
918
- * cacheReadTokens: 0,
919
- * cacheCreationTokens: 0,
920
- * totalTokens: 200
921
- * },
922
- * projectPath: "/path/to/project",
923
- * branch: { // Only if createBranch=true
924
- * name: "feature/xyz",
925
- * url: "https://github.com/owner/repo/tree/feature/xyz"
926
- * } | { error: "..." },
927
- * pullRequest: { // Only if createPR=true
928
- * number: 42,
929
- * url: "https://github.com/owner/repo/pull/42"
930
- * } | { error: "..." }
931
- * }
932
- *
933
- * Error Response:
934
- * HTTP Status: 400, 401, 500
935
- * Content-Type: application/json
936
- * { success: false, error: "Error description" }
937
- *
938
- * ================================================================================================
939
- * EXAMPLES
940
- * ================================================================================================
941
- *
942
- * Example 1: Clone and process with auto-cleanup
943
- * POST /api/agent
944
- * { "githubUrl": "https://github.com/user/repo", "message": "Fix bug" }
945
- *
946
- * Example 2: Use existing project with custom branch and PR
947
- * POST /api/agent
948
- * {
949
- * "projectPath": "/home/user/project",
950
- * "message": "Add feature",
951
- * "branchName": "feature/new-feature",
952
- * "createPR": true
953
- * }
954
- *
955
- * Example 3: Clone to specific path with auto-generated branch
956
- * POST /api/agent
957
- * {
958
- * "githubUrl": "https://github.com/user/repo",
959
- * "projectPath": "/tmp/work",
960
- * "message": "Refactor code",
961
- * "createBranch": true,
962
- * "cleanup": false
963
- * }
964
- */
965
- router.post('/', validateExternalApiKey, async (req, res) => {
966
- const { githubUrl, projectPath, message, provider = 'claude', model, githubToken, branchName, sessionId } = req.body;
967
- const requestedPermissionMode = typeof req.body.permissionMode === 'string' ? req.body.permissionMode : null;
968
- const permissionMode = ['default', 'acceptEdits', 'bypassPermissions', 'plan', 'auto_edit', 'yolo'].includes(requestedPermissionMode)
969
- ? requestedPermissionMode
970
- : null;
971
- const suppressNotifications = req.body.suppressNotifications === true || req.body.suppressNotifications === 'true';
972
-
973
- // Parse stream and cleanup as booleans (handle string "true"/"false" from curl)
974
- const stream = req.body.stream === undefined ? true : (req.body.stream === true || req.body.stream === 'true');
975
- const cleanup = req.body.cleanup === undefined ? true : (req.body.cleanup === true || req.body.cleanup === 'true');
976
-
977
- // If branchName is provided, automatically enable createBranch
978
- const createBranch = branchName ? true : (req.body.createBranch === true || req.body.createBranch === 'true');
979
- const createPR = req.body.createPR === true || req.body.createPR === 'true';
980
-
981
- // Validate inputs
982
- if (!githubUrl && !projectPath) {
983
- return res.status(400).json({ error: 'Either githubUrl or projectPath is required' });
984
- }
985
-
986
- if (!message || !message.trim()) {
987
- return res.status(400).json({ error: 'message is required' });
988
- }
989
-
990
- if (!['claude', 'cursor', 'codex', 'gemini', 'qwen', 'opencode'].includes(provider)) {
991
- return res.status(400).json({ error: 'provider must be one of: claude, cursor, codex, gemini, qwen, opencode' });
992
- }
993
-
994
- // Validate GitHub branch/PR creation requirements
995
- // Allow branch/PR creation with projectPath as long as it has a GitHub remote
996
- if ((createBranch || createPR) && !githubUrl && !projectPath) {
997
- return res.status(400).json({ error: 'createBranch and createPR require either githubUrl or projectPath with a GitHub remote' });
998
- }
999
-
1000
- let finalProjectPath = null;
1001
- let writer = null;
1002
-
1003
- try {
1004
- // Determine the final project path
1005
- if (githubUrl) {
1006
- // Clone repository (to projectPath if provided, otherwise generate path)
1007
- const tokenToUse = githubToken || githubTokensDb.getActiveGithubToken(req.user.id);
1008
-
1009
- let targetPath;
1010
- if (projectPath) {
1011
- targetPath = projectPath;
1012
- } else {
1013
- // Generate a unique path for cloning
1014
- const repoHash = crypto.createHash('md5').update(githubUrl + Date.now()).digest('hex');
1015
- targetPath = path.join(os.homedir(), '.claude', 'external-projects', repoHash);
1016
- }
1017
-
1018
- finalProjectPath = await cloneGitHubRepo(githubUrl.trim(), tokenToUse, targetPath);
1019
- } else {
1020
- // Use existing project path
1021
- finalProjectPath = path.resolve(projectPath);
1022
-
1023
- // Verify the path exists
1024
- try {
1025
- await fs.access(finalProjectPath);
1026
- } catch (error) {
1027
- throw new Error(`Project path does not exist: ${finalProjectPath}`);
1028
- }
1029
- }
1030
-
1031
- // Register the project (or use existing registration)
1032
- let project;
1033
- try {
1034
- project = await addProjectManually(finalProjectPath);
1035
- console.log('📦 Project registered:', project);
1036
- } catch (error) {
1037
- // If project already exists, that's fine - continue with the existing registration
1038
- if (error.message && error.message.includes('Project already configured')) {
1039
- console.log('📦 Using existing project registration for:', finalProjectPath);
1040
- project = { path: finalProjectPath };
1041
- } else {
1042
- throw error;
1043
- }
1044
- }
1045
-
1046
- // Set up writer based on streaming mode
1047
- if (stream) {
1048
- // Set up SSE headers for streaming
1049
- res.setHeader('Content-Type', 'text/event-stream');
1050
- res.setHeader('Cache-Control', 'no-cache');
1051
- res.setHeader('Connection', 'keep-alive');
1052
- res.setHeader('X-Accel-Buffering', 'no'); // Disable nginx buffering
1053
-
1054
- writer = new SSEStreamWriter(res, req.user.id);
1055
-
1056
- // Send initial status
1057
- writer.send({
1058
- type: 'status',
1059
- message: githubUrl ? 'Repository cloned and session started' : 'Session started',
1060
- projectPath: finalProjectPath
1061
- });
1062
- } else {
1063
- // Non-streaming mode: collect messages
1064
- writer = new ResponseCollector(req.user.id);
1065
-
1066
- // Collect initial status message
1067
- writer.send({
1068
- type: 'status',
1069
- message: githubUrl ? 'Repository cloned and session started' : 'Session started',
1070
- projectPath: finalProjectPath
1071
- });
1072
- }
1073
-
1074
- // Start the appropriate session
1075
- if (provider === 'claude') {
1076
- console.log('🤖 Starting Claude SDK session');
1077
-
1078
- await queryClaudeSDK(message.trim(), {
1079
- projectPath: finalProjectPath,
1080
- cwd: finalProjectPath,
1081
- sessionId: sessionId || null,
1082
- model: model,
1083
- permissionMode: permissionMode || 'bypassPermissions', // Bypass all permissions for API calls unless explicitly restricted
1084
- suppressNotifications,
1085
- }, writer);
1086
-
1087
- } else if (provider === 'cursor') {
1088
- console.log('🖱️ Starting Cursor CLI session');
1089
-
1090
- await spawnCursor(message.trim(), {
1091
- projectPath: finalProjectPath,
1092
- cwd: finalProjectPath,
1093
- sessionId: sessionId || null,
1094
- model: model || undefined,
1095
- skipPermissions: permissionMode ? permissionMode === 'bypassPermissions' || permissionMode === 'acceptEdits' || permissionMode === 'yolo' : true,
1096
- suppressNotifications,
1097
- }, writer);
1098
- } else if (provider === 'codex') {
1099
- console.log('🤖 Starting Codex SDK session');
1100
-
1101
- await queryCodex(message.trim(), {
1102
- projectPath: finalProjectPath,
1103
- cwd: finalProjectPath,
1104
- sessionId: sessionId || null,
1105
- model: model || getDefaultProviderModel('codex'),
1106
- permissionMode: permissionMode || 'bypassPermissions',
1107
- suppressNotifications,
1108
- }, writer);
1109
- } else if (provider === 'gemini') {
1110
- console.log(' Starting Gemini CLI session');
1111
-
1112
- await spawnGemini(message.trim(), {
1113
- projectPath: finalProjectPath,
1114
- cwd: finalProjectPath,
1115
- sessionId: sessionId || null,
1116
- model: model,
1117
- permissionMode: permissionMode || undefined,
1118
- skipPermissions: permissionMode ? permissionMode === 'bypassPermissions' || permissionMode === 'acceptEdits' || permissionMode === 'yolo' : true,
1119
- suppressNotifications,
1120
- }, writer);
1121
- } else if (provider === 'qwen') {
1122
- console.log('🐉 Starting Qwen Code CLI session');
1123
-
1124
- await spawnQwen(message.trim(), {
1125
- projectPath: finalProjectPath,
1126
- cwd: finalProjectPath,
1127
- sessionId: sessionId || null,
1128
- model: model,
1129
- permissionMode: permissionMode || undefined,
1130
- skipPermissions: permissionMode ? permissionMode === 'bypassPermissions' || permissionMode === 'acceptEdits' || permissionMode === 'yolo' : true,
1131
- suppressNotifications,
1132
- }, writer);
1133
- } else if (provider === 'opencode') {
1134
- console.log('🅾️ Starting OpenCode CLI session');
1135
-
1136
- await spawnOpencode(message.trim(), {
1137
- projectPath: finalProjectPath,
1138
- cwd: finalProjectPath,
1139
- sessionId: sessionId || null,
1140
- model: model,
1141
- permissionMode: permissionMode || 'bypassPermissions',
1142
- toolsSettings: {
1143
- allowPatterns: [],
1144
- denyPatterns: [],
1145
- skipPermissions: permissionMode ? permissionMode === 'bypassPermissions' || permissionMode === 'acceptEdits' || permissionMode === 'yolo' : true,
1146
- },
1147
- suppressNotifications,
1148
- }, writer);
1149
- }
1150
-
1151
- // Handle GitHub branch and PR creation after successful agent completion
1152
- let branchInfo = null;
1153
- let prInfo = null;
1154
-
1155
- if (createBranch || createPR) {
1156
- try {
1157
- console.log('🔄 Starting GitHub branch/PR creation workflow...');
1158
-
1159
- // Get GitHub token
1160
- const tokenToUse = githubToken || githubTokensDb.getActiveGithubToken(req.user.id);
1161
-
1162
- if (!tokenToUse) {
1163
- throw new Error('GitHub token required for branch/PR creation. Please configure a GitHub token in settings.');
1164
- }
1165
-
1166
- // Initialize Octokit
1167
- const octokit = new Octokit({ auth: tokenToUse });
1168
-
1169
- // Get GitHub URL - either from parameter or from git remote
1170
- let repoUrl = githubUrl;
1171
- if (!repoUrl) {
1172
- console.log('🔍 Getting GitHub URL from git remote...');
1173
- try {
1174
- repoUrl = await getGitRemoteUrl(finalProjectPath);
1175
- if (!repoUrl.includes('github.com')) {
1176
- throw new Error('Project does not have a GitHub remote configured');
1177
- }
1178
- console.log(`✅ Found GitHub remote: ${repoUrl}`);
1179
- } catch (error) {
1180
- throw new Error(`Failed to get GitHub remote URL: ${error.message}`);
1181
- }
1182
- }
1183
-
1184
- // Parse GitHub URL to get owner and repo
1185
- const { owner, repo } = parseGitHubUrl(repoUrl);
1186
- console.log(`📦 Repository: ${owner}/${repo}`);
1187
-
1188
- // Use provided branch name or auto-generate from message
1189
- const finalBranchName = branchName || autogenerateBranchName(message);
1190
- if (branchName) {
1191
- console.log(`🌿 Using provided branch name: ${finalBranchName}`);
1192
-
1193
- // Validate custom branch name
1194
- const validation = validateBranchName(finalBranchName);
1195
- if (!validation.valid) {
1196
- throw new Error(`Invalid branch name: ${validation.error}`);
1197
- }
1198
- } else {
1199
- console.log(`🌿 Auto-generated branch name: ${finalBranchName}`);
1200
- }
1201
-
1202
- if (createBranch) {
1203
- // Create and checkout the new branch locally
1204
- console.log('🔄 Creating local branch...');
1205
- const checkoutProcess = spawn('git', ['checkout', '-b', finalBranchName], {
1206
- cwd: finalProjectPath,
1207
- stdio: 'pipe'
1208
- });
1209
-
1210
- await new Promise((resolve, reject) => {
1211
- let stderr = '';
1212
- checkoutProcess.stderr.on('data', (data) => { stderr += data.toString(); });
1213
- checkoutProcess.on('close', (code) => {
1214
- if (code === 0) {
1215
- console.log(`✅ Created and checked out local branch '${finalBranchName}'`);
1216
- resolve();
1217
- } else {
1218
- // Branch might already exist locally, try to checkout
1219
- if (stderr.includes('already exists')) {
1220
- console.log(`ℹ️ Branch '${finalBranchName}' already exists locally, checking out...`);
1221
- const checkoutExisting = spawn('git', ['checkout', finalBranchName], {
1222
- cwd: finalProjectPath,
1223
- stdio: 'pipe'
1224
- });
1225
- checkoutExisting.on('close', (checkoutCode) => {
1226
- if (checkoutCode === 0) {
1227
- console.log(`✅ Checked out existing branch '${finalBranchName}'`);
1228
- resolve();
1229
- } else {
1230
- reject(new Error(`Failed to checkout existing branch: ${stderr}`));
1231
- }
1232
- });
1233
- } else {
1234
- reject(new Error(`Failed to create branch: ${stderr}`));
1235
- }
1236
- }
1237
- });
1238
- });
1239
-
1240
- // Push the branch to remote
1241
- console.log('🔄 Pushing branch to remote...');
1242
- const pushProcess = spawn('git', ['push', '-u', 'origin', finalBranchName], {
1243
- cwd: finalProjectPath,
1244
- stdio: 'pipe'
1245
- });
1246
-
1247
- await new Promise((resolve, reject) => {
1248
- let stderr = '';
1249
- let stdout = '';
1250
- pushProcess.stdout.on('data', (data) => { stdout += data.toString(); });
1251
- pushProcess.stderr.on('data', (data) => { stderr += data.toString(); });
1252
- pushProcess.on('close', (code) => {
1253
- if (code === 0) {
1254
- console.log(`✅ Pushed branch '${finalBranchName}' to remote`);
1255
- resolve();
1256
- } else {
1257
- // Check if branch exists on remote but has different commits
1258
- if (stderr.includes('already exists') || stderr.includes('up-to-date')) {
1259
- console.log(`ℹ️ Branch '${finalBranchName}' already exists on remote, using existing branch`);
1260
- resolve();
1261
- } else {
1262
- reject(new Error(`Failed to push branch: ${stderr}`));
1263
- }
1264
- }
1265
- });
1266
- });
1267
-
1268
- branchInfo = {
1269
- name: finalBranchName,
1270
- url: `https://github.com/${owner}/${repo}/tree/${finalBranchName}`
1271
- };
1272
- }
1273
-
1274
- if (createPR) {
1275
- // Get commit messages to generate PR description
1276
- console.log('🔄 Generating PR title and description...');
1277
- const commitMessages = await getCommitMessages(finalProjectPath, 5);
1278
-
1279
- // Use the first commit message as the PR title, or fallback to the agent message
1280
- const prTitle = commitMessages.length > 0 ? commitMessages[0] : message;
1281
-
1282
- // Generate PR body from commit messages
1283
- let prBody = '## Changes\n\n';
1284
- if (commitMessages.length > 0) {
1285
- prBody += commitMessages.map(msg => `- ${msg}`).join('\n');
1286
- } else {
1287
- prBody += `Agent task: ${message}`;
1288
- }
1289
- prBody += '\n\n---\n*This pull request was automatically created by Pixcode Agent.*';
1290
-
1291
- console.log(`📝 PR Title: ${prTitle}`);
1292
-
1293
- // Create the pull request
1294
- console.log('🔄 Creating pull request...');
1295
- prInfo = await createGitHubPR(octokit, owner, repo, finalBranchName, prTitle, prBody, 'main');
1296
- }
1297
-
1298
- // Send branch/PR info in response
1299
- if (stream) {
1300
- if (branchInfo) {
1301
- writer.send({
1302
- type: 'github-branch',
1303
- branch: branchInfo
1304
- });
1305
- }
1306
- if (prInfo) {
1307
- writer.send({
1308
- type: 'github-pr',
1309
- pullRequest: prInfo
1310
- });
1311
- }
1312
- }
1313
-
1314
- } catch (error) {
1315
- console.error('❌ GitHub branch/PR creation error:', error);
1316
-
1317
- // Send error but don't fail the entire request
1318
- if (stream) {
1319
- writer.send({
1320
- type: 'github-error',
1321
- error: error.message
1322
- });
1323
- }
1324
- // Store error info for non-streaming response
1325
- if (!stream) {
1326
- branchInfo = { error: error.message };
1327
- prInfo = { error: error.message };
1328
- }
1329
- }
1330
- }
1331
-
1332
- // Handle response based on streaming mode
1333
- if (stream) {
1334
- // Streaming mode: end the SSE stream
1335
- writer.end();
1336
- } else {
1337
- // Non-streaming mode: send filtered messages and token summary as JSON
1338
- const assistantMessages = writer.getAssistantMessages();
1339
- const tokenSummary = writer.getTotalTokens();
1340
-
1341
- // Promote provider-side errors (`writer.send({ kind:'error', ... })`)
1342
- // to the response envelope. Without this, providers like Codex —
1343
- // whose SDK swallows throws and only emits an error message — left
1344
- // callers with `{ success:true, messages:[] }`, indistinguishable
1345
- // from a quiet success. Now: any error event => success:false and
1346
- // the human-readable text on `error`.
1347
- const errorEntry = assistantMessages.find((m) => m.type === 'error');
1348
- const hasAssistantText = assistantMessages.some(
1349
- (m) => m.type === 'assistant' && m.message?.content?.some?.((p) => p.type === 'text' && p.text)
1350
- );
1351
- const succeeded = !errorEntry && (hasAssistantText || assistantMessages.some((m) => m.type === 'tool_use' || m.type === 'tool_result'));
1352
- const failureDetails = succeeded
1353
- ? null
1354
- : describeProviderFailure(
1355
- errorEntry?.content || 'Provider returned no assistant text. Check backend log for details.',
1356
- provider,
1357
- );
1358
-
1359
- const response = {
1360
- success: succeeded,
1361
- sessionId: writer.getSessionId(),
1362
- messages: assistantMessages,
1363
- tokens: tokenSummary,
1364
- projectPath: finalProjectPath
1365
- };
1366
- if (failureDetails) {
1367
- response.error = failureDetails.message;
1368
- response.rawError = failureDetails.rawMessage;
1369
- response.errorDetails = failureDetails;
1370
- }
1371
-
1372
- // Add branch/PR info if created
1373
- if (branchInfo) {
1374
- response.branch = branchInfo;
1375
- }
1376
- if (prInfo) {
1377
- response.pullRequest = prInfo;
1378
- }
1379
-
1380
- res.status(succeeded ? 200 : 502).json(response);
1381
- }
1382
-
1383
- // Clean up if requested
1384
- if (cleanup && githubUrl) {
1385
- // Only cleanup if we cloned a repo (not for existing project paths)
1386
- const sessionIdForCleanup = writer.getSessionId();
1387
- setTimeout(() => {
1388
- cleanupProject(finalProjectPath, sessionIdForCleanup);
1389
- }, 5000);
1390
- }
1391
-
1392
- } catch (error) {
1393
- console.error('❌ External session error:', error);
1394
-
1395
- // Clean up on error
1396
- if (finalProjectPath && cleanup && githubUrl) {
1397
- const sessionIdForCleanup = writer ? writer.getSessionId() : null;
1398
- cleanupProject(finalProjectPath, sessionIdForCleanup);
1399
- }
1400
-
1401
- if (stream) {
1402
- // For streaming, send error event and stop
1403
- if (!writer) {
1404
- // Set up SSE headers if not already done
1405
- res.setHeader('Content-Type', 'text/event-stream');
1406
- res.setHeader('Cache-Control', 'no-cache');
1407
- res.setHeader('Connection', 'keep-alive');
1408
- res.setHeader('X-Accel-Buffering', 'no');
1409
- writer = new SSEStreamWriter(res, req.user.id);
1410
- }
1411
-
1412
- if (!res.writableEnded) {
1413
- writer.send({
1414
- type: 'error',
1415
- error: 'Failed to process agent request.',
1416
- message: 'Failed to process agent request.'
1417
- });
1418
- writer.end();
1419
- }
1420
- } else if (!res.headersSent) {
1421
- // Surface any provider-side stderr/error events the writer collected
1422
- // BEFORE the throw — without this, callers only see the bland
1423
- // "Gemini CLI exited with code 403" wrapper and lose the actual
1424
- // "PERMISSION_DENIED, model not enabled for this account" detail
1425
- // that the CLI printed to stderr.
1426
- let collectedError = null;
1427
- let collectedMessages = [];
1428
- if (writer && typeof writer.getAssistantMessages === 'function') {
1429
- try {
1430
- collectedMessages = writer.getAssistantMessages();
1431
- const errorText = collectedMessages
1432
- .filter((m) => m.type === 'error' && typeof m.content === 'string' && m.content.trim())
1433
- .map((m) => m.content.trim())
1434
- .join('\n');
1435
- if (errorText) collectedError = errorText;
1436
- } catch { /* ignore — fall back to error.message */ }
1437
- }
1438
- const failureDetails = describeProviderFailure(collectedError || 'Provider returned no assistant text.', provider);
1439
- res.status(502).json({
1440
- success: false,
1441
- sessionId: writer && typeof writer.getSessionId === 'function' ? writer.getSessionId() : null,
1442
- error: failureDetails.message,
1443
- rawError: failureDetails.rawMessage,
1444
- errorDetails: failureDetails,
1445
- messages: collectedMessages,
1446
- });
1447
- }
1448
- }
1449
- });
1450
-
1451
- export default router;
1
+ import { spawn } from 'child_process';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { promises as fs } from 'fs';
5
+ import crypto from 'crypto';
6
+
7
+ import express from 'express';
8
+ import { Octokit } from '@octokit/rest';
9
+
10
+ import { userDb, apiKeysDb, githubTokensDb } from '../database/db.js';
11
+ import { addProjectManually } from '../projects.js';
12
+ import { queryClaudeSDK } from '../claude-sdk.js';
13
+ import { spawnCursor } from '../cursor-cli.js';
14
+ import { queryCodex } from '../openai-codex.js';
15
+ import { spawnGemini } from '../gemini-cli.js';
16
+ import { spawnQwen } from '../qwen-code-cli.js';
17
+ import { spawnOpencode } from '../opencode-cli.js';
18
+ import { IS_PLATFORM } from '../constants/config.js';
19
+ import { getDefaultProviderModel } from '../services/model-registry.js';
20
+
21
+ const router = express.Router();
22
+ const isPixcodeApiKey = (token) => typeof token === 'string' && (token.startsWith('px_') || token.startsWith('ck_'));
23
+ const EXTERNAL_PROJECTS_BASE = path.join(os.homedir(), '.claude', 'external-projects');
24
+
25
+ function isPathWithinExternalProjects(resolvedPath) {
26
+ const normalized = path.resolve(resolvedPath);
27
+ return normalized.startsWith(EXTERNAL_PROJECTS_BASE + path.sep) || normalized === EXTERNAL_PROJECTS_BASE;
28
+ }
29
+
30
+ /**
31
+ * Middleware to authenticate agent API requests.
32
+ *
33
+ * Supports two authentication modes:
34
+ * 1. Platform mode (IS_PLATFORM=true): For managed/hosted deployments where
35
+ * authentication is handled by an external proxy. Requests are trusted and
36
+ * the default user context is used.
37
+ *
38
+ * 2. API key mode (default): For self-hosted deployments where users authenticate
39
+ * via API keys created in the UI. Keys are validated against the local database.
40
+ */
41
+ const validateExternalApiKey = (req, res, next) => {
42
+ // Platform mode: Authentication is handled externally (e.g., by a proxy layer).
43
+ // Trust the request and use the default user context.
44
+ if (IS_PLATFORM) {
45
+ try {
46
+ const user = userDb.getFirstUser();
47
+ if (!user) {
48
+ return res.status(500).json({ error: 'Platform mode: No user found in database' });
49
+ }
50
+ req.user = user;
51
+ return next();
52
+ } catch (error) {
53
+ console.error('Platform mode error:', error);
54
+ return res.status(500).json({ error: 'Platform mode: Failed to fetch user' });
55
+ }
56
+ }
57
+
58
+ // Self-hosted mode: validate API key from any of the supported transports.
59
+ // - Authorization: Bearer px_... (legacy ck_... still accepted)
60
+ // auth shape as the rest of the API, per the auth-unify in this turn)
61
+ // - X-API-Key: px_...
62
+ // - ?apiKey=px_... (EventSource workaround)
63
+ const authHeader = req.headers['authorization'];
64
+ const bearer = authHeader && authHeader.startsWith('Bearer ') ? authHeader.slice(7).trim() : null;
65
+ const apiKey = (isPixcodeApiKey(bearer) ? bearer : null)
66
+ || req.headers['x-api-key']
67
+ || (typeof req.query.apiKey === 'string' ? req.query.apiKey : null);
68
+
69
+ if (!apiKey) {
70
+ return res.status(401).json({ error: 'API key required (Authorization: Bearer px_..., X-API-Key, or ?apiKey=)' });
71
+ }
72
+
73
+ const user = apiKeysDb.validateApiKey(apiKey);
74
+
75
+ if (!user) {
76
+ return res.status(401).json({ error: 'Invalid or inactive API key' });
77
+ }
78
+
79
+ req.user = user;
80
+ next();
81
+ };
82
+
83
+ /**
84
+ * Get the remote URL of a git repository
85
+ * @param {string} repoPath - Path to the git repository
86
+ * @returns {Promise<string>} - Remote URL of the repository
87
+ */
88
+ async function getGitRemoteUrl(repoPath) {
89
+ return new Promise((resolve, reject) => {
90
+ const gitProcess = spawn('git', ['config', '--get', 'remote.origin.url'], {
91
+ cwd: repoPath,
92
+ stdio: ['pipe', 'pipe', 'pipe']
93
+ });
94
+
95
+ let stdout = '';
96
+ let stderr = '';
97
+
98
+ gitProcess.stdout.on('data', (data) => {
99
+ stdout += data.toString();
100
+ });
101
+
102
+ gitProcess.stderr.on('data', (data) => {
103
+ stderr += data.toString();
104
+ });
105
+
106
+ gitProcess.on('close', (code) => {
107
+ if (code === 0) {
108
+ resolve(stdout.trim());
109
+ } else {
110
+ reject(new Error(`Failed to get git remote: ${stderr}`));
111
+ }
112
+ });
113
+
114
+ gitProcess.on('error', (error) => {
115
+ reject(new Error(`Failed to execute git: ${error.message}`));
116
+ });
117
+ });
118
+ }
119
+
120
+ /**
121
+ * Normalize GitHub URLs for comparison
122
+ * @param {string} url - GitHub URL
123
+ * @returns {string} - Normalized URL
124
+ */
125
+ function normalizeGitHubUrl(url) {
126
+ // Remove .git suffix
127
+ let normalized = url.replace(/\.git$/, '');
128
+ // Convert SSH to HTTPS format for comparison
129
+ normalized = normalized.replace(/^git@github\.com:/, 'https://github.com/');
130
+ // Remove trailing slash
131
+ normalized = normalized.replace(/\/$/, '');
132
+ return normalized.toLowerCase();
133
+ }
134
+
135
+ /**
136
+ * Parse GitHub URL to extract owner and repo
137
+ * @param {string} url - GitHub URL (HTTPS or SSH)
138
+ * @returns {{owner: string, repo: string}} - Parsed owner and repo
139
+ */
140
+ function parseGitHubUrl(url) {
141
+ // Handle HTTPS URLs: https://github.com/owner/repo or https://github.com/owner/repo.git
142
+ // Handle SSH URLs: git@github.com:owner/repo or git@github.com:owner/repo.git
143
+ const match = url.match(/github\.com[:/]([^/]+)\/([^/]+?)(?:\.git)?$/);
144
+ if (!match) {
145
+ throw new Error('Invalid GitHub URL format');
146
+ }
147
+ return {
148
+ owner: match[1],
149
+ repo: match[2].replace(/\.git$/, '')
150
+ };
151
+ }
152
+
153
+ /**
154
+ * Auto-generate a branch name from a message
155
+ * @param {string} message - The agent message
156
+ * @returns {string} - Generated branch name
157
+ */
158
+ function autogenerateBranchName(message) {
159
+ // Convert to lowercase, replace spaces/special chars with hyphens
160
+ let branchName = message
161
+ .toLowerCase()
162
+ .replace(/[^a-z0-9\s-]/g, '') // Remove special characters
163
+ .replace(/\s+/g, '-') // Replace spaces with hyphens
164
+ .replace(/-+/g, '-') // Replace multiple hyphens with single
165
+ .replace(/^-|-$/g, ''); // Remove leading/trailing hyphens
166
+
167
+ // Ensure non-empty fallback
168
+ if (!branchName) {
169
+ branchName = 'task';
170
+ }
171
+
172
+ // Generate timestamp suffix (last 6 chars of base36 timestamp)
173
+ const timestamp = Date.now().toString(36).slice(-6);
174
+ const suffix = `-${timestamp}`;
175
+
176
+ // Limit length to ensure total length including suffix fits within 50 characters
177
+ const maxBaseLength = 50 - suffix.length;
178
+ if (branchName.length > maxBaseLength) {
179
+ branchName = branchName.substring(0, maxBaseLength);
180
+ }
181
+
182
+ // Remove any trailing hyphen after truncation and ensure no leading hyphen
183
+ branchName = branchName.replace(/-$/, '').replace(/^-+/, '');
184
+
185
+ // If still empty or starts with hyphen after cleanup, use fallback
186
+ if (!branchName || branchName.startsWith('-')) {
187
+ branchName = 'task';
188
+ }
189
+
190
+ // Combine base name with timestamp suffix
191
+ branchName = `${branchName}${suffix}`;
192
+
193
+ // Final validation: ensure it matches safe pattern
194
+ if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(branchName)) {
195
+ // Fallback to deterministic safe name
196
+ return `branch-${timestamp}`;
197
+ }
198
+
199
+ return branchName;
200
+ }
201
+
202
+ /**
203
+ * Validate a Git branch name
204
+ * @param {string} branchName - Branch name to validate
205
+ * @returns {{valid: boolean, error?: string}} - Validation result
206
+ */
207
+ function validateBranchName(branchName) {
208
+ if (!branchName || branchName.trim() === '') {
209
+ return { valid: false, error: 'Branch name cannot be empty' };
210
+ }
211
+
212
+ // Git branch name rules
213
+ const invalidPatterns = [
214
+ { pattern: /^\./, message: 'Branch name cannot start with a dot' },
215
+ { pattern: /\.$/, message: 'Branch name cannot end with a dot' },
216
+ { pattern: /\.\./, message: 'Branch name cannot contain consecutive dots (..)' },
217
+ { pattern: /\s/, message: 'Branch name cannot contain spaces' },
218
+ { pattern: /[~^:?*\[\\]/, message: 'Branch name cannot contain special characters: ~ ^ : ? * [ \\' },
219
+ { pattern: /@{/, message: 'Branch name cannot contain @{' },
220
+ { pattern: /\/$/, message: 'Branch name cannot end with a slash' },
221
+ { pattern: /^\//, message: 'Branch name cannot start with a slash' },
222
+ { pattern: /\/\//, message: 'Branch name cannot contain consecutive slashes' },
223
+ { pattern: /\.lock$/, message: 'Branch name cannot end with .lock' }
224
+ ];
225
+
226
+ for (const { pattern, message } of invalidPatterns) {
227
+ if (pattern.test(branchName)) {
228
+ return { valid: false, error: message };
229
+ }
230
+ }
231
+
232
+ // Check for ASCII control characters
233
+ if (/[\x00-\x1F\x7F]/.test(branchName)) {
234
+ return { valid: false, error: 'Branch name cannot contain control characters' };
235
+ }
236
+
237
+ return { valid: true };
238
+ }
239
+
240
+ function providerDisplayName(provider) {
241
+ return ({
242
+ claude: 'Claude',
243
+ cursor: 'Cursor',
244
+ codex: 'Codex',
245
+ gemini: 'Gemini',
246
+ qwen: 'Qwen',
247
+ opencode: 'OpenCode',
248
+ })[provider] || 'Provider';
249
+ }
250
+
251
+ function describeProviderFailure(rawError, provider) {
252
+ const rawMessage = String(rawError || '').trim() || 'Provider returned no assistant text.';
253
+ const normalized = rawMessage.toLowerCase();
254
+ const name = providerDisplayName(provider);
255
+
256
+ const details = {
257
+ provider,
258
+ providerName: name,
259
+ category: 'provider_error',
260
+ title: `${name} could not answer.`,
261
+ action: 'Check the provider output, then retry with a shorter prompt or a different model.',
262
+ rawMessage,
263
+ };
264
+
265
+ if (/(balance|billing|quota|credit|insufficient|payment required|402|usage limit|spend limit)/i.test(rawMessage)) {
266
+ details.category = 'quota';
267
+ details.title = `${name} could not answer because the account has no available balance or quota.`;
268
+ details.action = 'Add credits, increase the provider usage limit, or switch to a free/available model.';
269
+ } else if (/(rate limit|too many requests|429|temporarily overloaded|resource exhausted)/i.test(rawMessage)) {
270
+ details.category = 'rate_limit';
271
+ details.title = `${name} is rate limited right now.`;
272
+ details.action = 'Wait a bit, reduce parallel runs, or switch to another provider/model.';
273
+ } else if (/(unauthorized|forbidden|permission_denied|permission denied|api key|token|oauth|login|not authenticated|401|403|invalid credentials)/i.test(rawMessage)) {
274
+ details.category = 'auth';
275
+ details.title = `${name} is not authenticated or the selected model is not allowed.`;
276
+ details.action = 'Reconnect this provider in Settings, refresh the CLI login, or choose a model enabled for the account.';
277
+ } else if (/(not installed|command not found|enoent|spawn .* enoent|executable file not found|exited with code 127)/i.test(rawMessage)) {
278
+ details.category = 'missing_cli';
279
+ details.title = `${name} CLI is not installed or not on PATH.`;
280
+ details.action = 'Install the CLI from Settings -> Agents or set the matching CLI path environment variable.';
281
+ } else if (/(timeout|timed out|aborted|etimedout|deadline)/i.test(rawMessage)) {
282
+ details.category = 'timeout';
283
+ details.title = `${name} timed out before returning a complete answer.`;
284
+ details.action = 'Retry with a shorter request, reduce orchestration parallelism, or inspect the provider session log.';
285
+ } else if (normalized.includes('no assistant text') || normalized.includes('empty')) {
286
+ details.category = 'no_output';
287
+ details.title = `${name} finished without visible assistant text.`;
288
+ details.action = 'Retry once; if it repeats, check provider stderr/session logs because the CLI may have exited before streaming text.';
289
+ }
290
+
291
+ details.message = `${details.title} ${details.action}`;
292
+ return details;
293
+ }
294
+
295
+ /**
296
+ * Get recent commit messages from a repository
297
+ * @param {string} projectPath - Path to the git repository
298
+ * @param {number} limit - Number of commits to retrieve (default: 5)
299
+ * @returns {Promise<string[]>} - Array of commit messages
300
+ */
301
+ async function getCommitMessages(projectPath, limit = 5) {
302
+ return new Promise((resolve, reject) => {
303
+ const gitProcess = spawn('git', ['log', `-${limit}`, '--pretty=format:%s'], {
304
+ cwd: projectPath,
305
+ stdio: ['pipe', 'pipe', 'pipe']
306
+ });
307
+
308
+ let stdout = '';
309
+ let stderr = '';
310
+
311
+ gitProcess.stdout.on('data', (data) => {
312
+ stdout += data.toString();
313
+ });
314
+
315
+ gitProcess.stderr.on('data', (data) => {
316
+ stderr += data.toString();
317
+ });
318
+
319
+ gitProcess.on('close', (code) => {
320
+ if (code === 0) {
321
+ const messages = stdout.trim().split('\n').filter(msg => msg.length > 0);
322
+ resolve(messages);
323
+ } else {
324
+ reject(new Error(`Failed to get commit messages: ${stderr}`));
325
+ }
326
+ });
327
+
328
+ gitProcess.on('error', (error) => {
329
+ reject(new Error(`Failed to execute git: ${error.message}`));
330
+ });
331
+ });
332
+ }
333
+
334
+ /**
335
+ * Create a new branch on GitHub using the API
336
+ * @param {Octokit} octokit - Octokit instance
337
+ * @param {string} owner - Repository owner
338
+ * @param {string} repo - Repository name
339
+ * @param {string} branchName - Name of the new branch
340
+ * @param {string} baseBranch - Base branch to branch from (default: 'main')
341
+ * @returns {Promise<void>}
342
+ */
343
+ async function createGitHubBranch(octokit, owner, repo, branchName, baseBranch = 'main') {
344
+ try {
345
+ // Get the SHA of the base branch
346
+ const { data: ref } = await octokit.git.getRef({
347
+ owner,
348
+ repo,
349
+ ref: `heads/${baseBranch}`
350
+ });
351
+
352
+ const baseSha = ref.object.sha;
353
+
354
+ // Create the new branch
355
+ await octokit.git.createRef({
356
+ owner,
357
+ repo,
358
+ ref: `refs/heads/${branchName}`,
359
+ sha: baseSha
360
+ });
361
+
362
+ console.log(`✅ Created branch '${branchName}' on GitHub`);
363
+ } catch (error) {
364
+ if (error.status === 422 && error.message.includes('Reference already exists')) {
365
+ console.log(`ℹ️ Branch '${branchName}' already exists on GitHub`);
366
+ } else {
367
+ throw error;
368
+ }
369
+ }
370
+ }
371
+
372
+ /**
373
+ * Create a pull request on GitHub
374
+ * @param {Octokit} octokit - Octokit instance
375
+ * @param {string} owner - Repository owner
376
+ * @param {string} repo - Repository name
377
+ * @param {string} branchName - Head branch name
378
+ * @param {string} title - PR title
379
+ * @param {string} body - PR body/description
380
+ * @param {string} baseBranch - Base branch (default: 'main')
381
+ * @returns {Promise<{number: number, url: string}>} - PR number and URL
382
+ */
383
+ async function createGitHubPR(octokit, owner, repo, branchName, title, body, baseBranch = 'main') {
384
+ const { data: pr } = await octokit.pulls.create({
385
+ owner,
386
+ repo,
387
+ title,
388
+ head: branchName,
389
+ base: baseBranch,
390
+ body
391
+ });
392
+
393
+ console.log(`✅ Created pull request #${pr.number}: ${pr.html_url}`);
394
+
395
+ return {
396
+ number: pr.number,
397
+ url: pr.html_url
398
+ };
399
+ }
400
+
401
+ /**
402
+ * Clone a GitHub repository to a directory
403
+ * @param {string} githubUrl - GitHub repository URL
404
+ * @param {string} githubToken - Optional GitHub token for private repos
405
+ * @param {string} projectPath - Path for cloning the repository
406
+ * @returns {Promise<string>} - Path to the cloned repository
407
+ */
408
+ async function cloneGitHubRepo(githubUrl, githubToken = null, projectPath) {
409
+ return new Promise(async (resolve, reject) => {
410
+ try {
411
+ // Validate GitHub URL
412
+ if (!githubUrl || !githubUrl.includes('github.com')) {
413
+ throw new Error('Invalid GitHub URL');
414
+ }
415
+
416
+ const cloneDir = path.resolve(projectPath);
417
+
418
+ if (!isPathWithinExternalProjects(cloneDir)) {
419
+ throw new Error('Clone directory must be within ~/.claude/external-projects');
420
+ }
421
+
422
+ // Check if directory already exists
423
+ try {
424
+ await fs.access(cloneDir);
425
+ // Directory exists - check if it's a git repo with the same URL
426
+ try {
427
+ const existingUrl = await getGitRemoteUrl(cloneDir);
428
+ const normalizedExisting = normalizeGitHubUrl(existingUrl);
429
+ const normalizedRequested = normalizeGitHubUrl(githubUrl);
430
+
431
+ if (normalizedExisting === normalizedRequested) {
432
+ console.log('✅ Repository already exists at path with correct URL');
433
+ return resolve(cloneDir);
434
+ } else {
435
+ throw new Error(`Directory ${cloneDir} already exists with a different repository (${existingUrl}). Expected: ${githubUrl}`);
436
+ }
437
+ } catch (gitError) {
438
+ throw new Error(`Directory ${cloneDir} already exists but is not a valid git repository or git command failed`);
439
+ }
440
+ } catch (accessError) {
441
+ // Directory doesn't exist - proceed with clone
442
+ }
443
+
444
+ // Ensure parent directory exists
445
+ await fs.mkdir(path.dirname(cloneDir), { recursive: true });
446
+
447
+ // Prepare the git clone URL with authentication if token is provided
448
+ let cloneUrl = githubUrl;
449
+ if (githubToken) {
450
+ // Convert HTTPS URL to authenticated URL
451
+ // Example: https://github.com/user/repo -> https://token@github.com/user/repo
452
+ cloneUrl = githubUrl.replace('https://github.com', `https://${githubToken}@github.com`);
453
+ }
454
+
455
+ console.log('🔄 Cloning repository:', githubUrl);
456
+ console.log('📁 Destination:', cloneDir);
457
+
458
+ // Execute git clone
459
+ const gitProcess = spawn('git', ['clone', '--depth', '1', cloneUrl, cloneDir], {
460
+ stdio: ['pipe', 'pipe', 'pipe']
461
+ });
462
+
463
+ let stdout = '';
464
+ let stderr = '';
465
+
466
+ gitProcess.stdout.on('data', (data) => {
467
+ stdout += data.toString();
468
+ });
469
+
470
+ gitProcess.stderr.on('data', (data) => {
471
+ stderr += data.toString();
472
+ console.log('Git stderr:', data.toString());
473
+ });
474
+
475
+ gitProcess.on('close', (code) => {
476
+ if (code === 0) {
477
+ console.log('✅ Repository cloned successfully');
478
+ resolve(cloneDir);
479
+ } else {
480
+ console.error('❌ Git clone failed:', stderr);
481
+ reject(new Error(`Git clone failed: ${stderr}`));
482
+ }
483
+ });
484
+
485
+ gitProcess.on('error', (error) => {
486
+ reject(new Error(`Failed to execute git: ${error.message}`));
487
+ });
488
+ } catch (error) {
489
+ reject(error);
490
+ }
491
+ });
492
+ }
493
+
494
+ /**
495
+ * Clean up a temporary project directory and its Claude session
496
+ * @param {string} projectPath - Path to the project directory
497
+ * @param {string} sessionId - Session ID to clean up
498
+ */
499
+ async function cleanupProject(projectPath, sessionId = null) {
500
+ try {
501
+ // Only clean up projects in the external-projects directory
502
+ const resolvedPath = path.resolve(projectPath);
503
+ if (!isPathWithinExternalProjects(resolvedPath)) {
504
+ console.warn('⚠️ Refusing to clean up non-external project:', projectPath);
505
+ return;
506
+ }
507
+
508
+ console.log('🧹 Cleaning up project:', projectPath);
509
+ await fs.rm(projectPath, { recursive: true, force: true });
510
+ console.log('✅ Project cleaned up');
511
+
512
+ // Also clean up the Claude session directory if sessionId provided
513
+ if (sessionId) {
514
+ try {
515
+ const sessionPath = path.join(os.homedir(), '.claude', 'sessions', sessionId);
516
+ console.log('🧹 Cleaning up session directory:', sessionPath);
517
+ await fs.rm(sessionPath, { recursive: true, force: true });
518
+ console.log('✅ Session directory cleaned up');
519
+ } catch (error) {
520
+ console.error('⚠️ Failed to clean up session directory:', error.message);
521
+ }
522
+ }
523
+ } catch (error) {
524
+ console.error('❌ Failed to clean up project:', error);
525
+ }
526
+ }
527
+
528
+ /**
529
+ * SSE Stream Writer - Adapts SDK/CLI output to Server-Sent Events
530
+ */
531
+ class SSEStreamWriter {
532
+ constructor(res, userId = null) {
533
+ this.res = res;
534
+ this.sessionId = null;
535
+ this.userId = userId;
536
+ this.isSSEStreamWriter = true; // Marker for transport detection
537
+ }
538
+
539
+ send(data) {
540
+ if (this.res.writableEnded) {
541
+ return;
542
+ }
543
+
544
+ // Format as SSE - providers send raw objects, we stringify
545
+ this.res.write(`data: ${JSON.stringify(data)}\n\n`);
546
+ }
547
+
548
+ end() {
549
+ if (!this.res.writableEnded) {
550
+ this.res.write('data: {"type":"done"}\n\n');
551
+ this.res.end();
552
+ }
553
+ }
554
+
555
+ setSessionId(sessionId) {
556
+ this.sessionId = sessionId;
557
+ this.send({ type: 'session-id', sessionId });
558
+ }
559
+
560
+ getSessionId() {
561
+ return this.sessionId;
562
+ }
563
+ }
564
+
565
+ /**
566
+ * Non-streaming response collector
567
+ */
568
+ class ResponseCollector {
569
+ constructor(userId = null) {
570
+ this.messages = [];
571
+ this.sessionId = null;
572
+ this.userId = userId;
573
+ }
574
+
575
+ send(data) {
576
+ // Store ALL messages for now - we'll filter when returning
577
+ this.messages.push(data);
578
+
579
+ // Extract sessionId if present
580
+ if (typeof data === 'string') {
581
+ try {
582
+ const parsed = JSON.parse(data);
583
+ if (parsed.sessionId) {
584
+ this.sessionId = parsed.sessionId;
585
+ }
586
+ } catch (e) {
587
+ // Not JSON, ignore
588
+ }
589
+ } else if (data && data.sessionId) {
590
+ this.sessionId = data.sessionId;
591
+ }
592
+ }
593
+
594
+ end() {
595
+ // Do nothing - we'll collect all messages
596
+ }
597
+
598
+ setSessionId(sessionId) {
599
+ this.sessionId = sessionId;
600
+ }
601
+
602
+ getSessionId() {
603
+ return this.sessionId;
604
+ }
605
+
606
+ getMessages() {
607
+ return this.messages;
608
+ }
609
+
610
+ /**
611
+ * Get filtered assistant messages.
612
+ *
613
+ * Two message shapes are observed in the wild:
614
+ * 1. Legacy Claude-only: { type:'claude-response', data:{ type:'assistant', message:{...} } }
615
+ * 2. Unified normalized: { kind:'stream_delta'|'tool_use'|... , provider, content, ... }
616
+ * (every provider after the v1.30+ unified-message migration emits this)
617
+ *
618
+ * Pre-fix this method only matched (1), so qwen / gemini / opencode / codex
619
+ * runs all returned an empty array even when the provider streamed real
620
+ * text. Now it builds:
621
+ * - one synthetic assistant entry per chat turn from concatenated
622
+ * `stream_delta` content (boundary = `stream_end` or `complete`)
623
+ * - tool_use / tool_result entries pass through verbatim
624
+ */
625
+ getAssistantMessages() {
626
+ const out = [];
627
+ let textBuffer = '';
628
+
629
+ const flushText = () => {
630
+ if (!textBuffer) return;
631
+ out.push({
632
+ type: 'assistant',
633
+ message: {
634
+ role: 'assistant',
635
+ content: [{ type: 'text', text: textBuffer }],
636
+ },
637
+ });
638
+ textBuffer = '';
639
+ };
640
+
641
+ for (const raw of this.messages) {
642
+ const data = typeof raw === 'string'
643
+ ? (() => { try { return JSON.parse(raw); } catch { return null; } })()
644
+ : raw;
645
+ if (!data) continue;
646
+ if (data.type === 'status') continue;
647
+
648
+ // Unified shape (every modern provider).
649
+ // - `stream_delta`: incremental text chunk (most providers)
650
+ // - `text`: full text part for one assistant turn (Claude SDK + history reads)
651
+ // - `thinking`: reasoning blocks; we coalesce as plain text so the API caller sees something
652
+ if ((data.kind === 'stream_delta' || data.kind === 'text' || data.kind === 'thinking')
653
+ && (typeof data.content === 'string' || Array.isArray(data.content))) {
654
+ const text = typeof data.content === 'string'
655
+ ? data.content
656
+ : data.content.map((part) => (typeof part === 'string' ? part : (part?.text || ''))).join('');
657
+ textBuffer += text;
658
+ continue;
659
+ }
660
+ if (data.kind === 'stream_end' || data.kind === 'complete') {
661
+ flushText();
662
+ continue;
663
+ }
664
+ if (data.kind === 'tool_use') {
665
+ flushText();
666
+ out.push({ type: 'tool_use', id: data.toolId, name: data.toolName, input: data.toolInput });
667
+ continue;
668
+ }
669
+ if (data.kind === 'tool_result') {
670
+ out.push({ type: 'tool_result', tool_use_id: data.toolId, content: data.content, is_error: data.isError });
671
+ continue;
672
+ }
673
+ if (data.kind === 'error' && typeof data.content === 'string') {
674
+ flushText();
675
+ out.push({ type: 'error', content: data.content });
676
+ continue;
677
+ }
678
+
679
+ // Legacy Claude shape kept so old SDK builds still report cleanly.
680
+ if (data.type === 'claude-response' && data.data && data.data.type === 'assistant') {
681
+ flushText();
682
+ out.push(data.data);
683
+ }
684
+ }
685
+ flushText();
686
+ return out;
687
+ }
688
+
689
+ /**
690
+ * Calculate total tokens from all messages.
691
+ *
692
+ * Two usage shapes observed:
693
+ * 1. Legacy Claude: { type:'claude-response', data:{ message:{ usage:{ input_tokens, output_tokens, cache_*_input_tokens } } } }
694
+ * 2. Unified `complete`/ { kind:'complete'|'stream_end', usage:{ input, output, cacheRead?, cacheCreation? }, cost? }
695
+ * `stream_end` events
696
+ */
697
+ getTotalTokens() {
698
+ let inputTokens = 0;
699
+ let outputTokens = 0;
700
+ let cacheReadTokens = 0;
701
+ let cacheCreationTokens = 0;
702
+
703
+ for (const raw of this.messages) {
704
+ const data = typeof raw === 'string'
705
+ ? (() => { try { return JSON.parse(raw); } catch { return null; } })()
706
+ : raw;
707
+ if (!data) continue;
708
+
709
+ // Unified shape
710
+ if (data.usage && typeof data.usage === 'object') {
711
+ inputTokens += data.usage.input || data.usage.inputTokens || data.usage.input_tokens || 0;
712
+ outputTokens += data.usage.output || data.usage.outputTokens || data.usage.output_tokens || 0;
713
+ cacheReadTokens += data.usage.cacheRead || data.usage.cache_read_input_tokens || 0;
714
+ cacheCreationTokens += data.usage.cacheCreation || data.usage.cache_creation_input_tokens || 0;
715
+ continue;
716
+ }
717
+
718
+ // Legacy Claude
719
+ if (data.type === 'claude-response' && data.data && data.data.message && data.data.message.usage) {
720
+ const u = data.data.message.usage;
721
+ inputTokens += u.input_tokens || 0;
722
+ outputTokens += u.output_tokens || 0;
723
+ cacheReadTokens += u.cache_read_input_tokens || 0;
724
+ cacheCreationTokens += u.cache_creation_input_tokens || 0;
725
+ }
726
+ }
727
+
728
+ return {
729
+ inputTokens,
730
+ outputTokens,
731
+ cacheReadTokens,
732
+ cacheCreationTokens,
733
+ totalTokens: inputTokens + outputTokens + cacheReadTokens + cacheCreationTokens,
734
+ };
735
+ }
736
+ }
737
+
738
+ // ===============================
739
+ // External API Endpoint
740
+ // ===============================
741
+
742
+ /**
743
+ * POST /api/agent
744
+ *
745
+ * Trigger an AI agent (Claude or Cursor) to work on a project.
746
+ * Supports automatic GitHub branch and pull request creation after successful completion.
747
+ *
748
+ * ================================================================================================
749
+ * REQUEST BODY PARAMETERS
750
+ * ================================================================================================
751
+ *
752
+ * @param {string} githubUrl - (Conditionally Required) GitHub repository URL to clone.
753
+ * Supported formats:
754
+ * - HTTPS: https://github.com/owner/repo
755
+ * - HTTPS with .git: https://github.com/owner/repo.git
756
+ * - SSH: git@github.com:owner/repo
757
+ * - SSH with .git: git@github.com:owner/repo.git
758
+ *
759
+ * @param {string} projectPath - (Conditionally Required) Path to existing project OR destination for cloning.
760
+ * Behavior depends on usage:
761
+ * - If used alone: Must point to existing project directory
762
+ * - If used with githubUrl: Target location for cloning
763
+ * - If omitted with githubUrl: Auto-generates temporary path in ~/.claude/external-projects/
764
+ *
765
+ * @param {string} message - (Required) Task description for the AI agent. Used as:
766
+ * - Instructions for the agent
767
+ * - Source for auto-generated branch names (if createBranch=true and no branchName)
768
+ * - Fallback for PR title if no commits are made
769
+ *
770
+ * @param {string} provider - (Optional) AI provider to use. Options: 'claude' | 'cursor' | 'codex' | 'gemini'
771
+ * Default: 'claude'
772
+ *
773
+ * @param {boolean} stream - (Optional) Enable Server-Sent Events (SSE) streaming for real-time updates.
774
+ * Default: true
775
+ * - true: Returns text/event-stream with incremental updates
776
+ * - false: Returns complete JSON response after completion
777
+ *
778
+ * @param {string} model - (Optional) Model identifier for providers.
779
+ *
780
+ * Claude models: 'sonnet' (default), 'opus', 'haiku', 'opusplan', 'sonnet[1m]'
781
+ * Cursor models: 'gpt-5' (default), 'gpt-5.2', 'gpt-5.2-high', 'sonnet-4.5', 'opus-4.5',
782
+ * 'gemini-3-pro', 'composer-1', 'auto', 'gpt-5.1', 'gpt-5.1-high',
783
+ * 'gpt-5.1-codex', 'gpt-5.1-codex-high', 'gpt-5.1-codex-max',
784
+ * 'gpt-5.1-codex-max-high', 'opus-4.1', 'grok', and thinking variants
785
+ * Codex models: 'gpt-5.2' (default), 'gpt-5.1-codex-max', 'o3', 'o4-mini'
786
+ *
787
+ * @param {boolean} cleanup - (Optional) Auto-cleanup project directory after completion.
788
+ * Default: true
789
+ * Behavior:
790
+ * - Only applies when cloning via githubUrl (not for existing projectPath)
791
+ * - Deletes cloned repository after 5 seconds
792
+ * - Also deletes associated Claude session directory
793
+ * - Remote branch and PR remain on GitHub if created
794
+ *
795
+ * @param {string} githubToken - (Optional) GitHub Personal Access Token for authentication.
796
+ * Overrides stored token from user settings.
797
+ * Required for:
798
+ * - Private repositories
799
+ * - Branch/PR creation features
800
+ * Token must have 'repo' scope for full functionality.
801
+ *
802
+ * @param {string} branchName - (Optional) Custom name for the Git branch.
803
+ * If provided, createBranch is automatically set to true.
804
+ * Validation rules (errors returned if violated):
805
+ * - Cannot be empty or whitespace only
806
+ * - Cannot start or end with dot (.)
807
+ * - Cannot contain consecutive dots (..)
808
+ * - Cannot contain spaces
809
+ * - Cannot contain special characters: ~ ^ : ? * [ \
810
+ * - Cannot contain @{
811
+ * - Cannot start or end with forward slash (/)
812
+ * - Cannot contain consecutive slashes (//)
813
+ * - Cannot end with .lock
814
+ * - Cannot contain ASCII control characters
815
+ * Examples: 'feature/user-auth', 'bugfix/login-error', 'refactor/db-optimization'
816
+ *
817
+ * @param {boolean} createBranch - (Optional) Create a new Git branch after successful agent completion.
818
+ * Default: false (or true if branchName is provided)
819
+ * Behavior:
820
+ * - Creates branch locally and pushes to remote
821
+ * - If branch exists locally: Checks out existing branch (no error)
822
+ * - If branch exists on remote: Uses existing branch (no error)
823
+ * - Branch name: Custom (if branchName provided) or auto-generated from message
824
+ * - Requires either githubUrl OR projectPath with GitHub remote
825
+ *
826
+ * @param {boolean} createPR - (Optional) Create a GitHub Pull Request after successful completion.
827
+ * Default: false
828
+ * Behavior:
829
+ * - PR title: First commit message (or fallback to message parameter)
830
+ * - PR description: Auto-generated from all commit messages
831
+ * - Base branch: Always 'main' (currently hardcoded)
832
+ * - If PR already exists: GitHub returns error with details
833
+ * - Requires either githubUrl OR projectPath with GitHub remote
834
+ *
835
+ * ================================================================================================
836
+ * PATH HANDLING BEHAVIOR
837
+ * ================================================================================================
838
+ *
839
+ * Scenario 1: Only githubUrl provided
840
+ * Input: { githubUrl: "https://github.com/owner/repo" }
841
+ * Action: Clones to auto-generated temporary path: ~/.claude/external-projects/<hash>/
842
+ * Cleanup: Yes (if cleanup=true)
843
+ *
844
+ * Scenario 2: Only projectPath provided
845
+ * Input: { projectPath: "/home/user/my-project" }
846
+ * Action: Uses existing project at specified path
847
+ * Validation: Path must exist and be accessible
848
+ * Cleanup: No (never cleanup existing projects)
849
+ *
850
+ * Scenario 3: Both githubUrl and projectPath provided
851
+ * Input: { githubUrl: "https://github.com/owner/repo", projectPath: "/custom/path" }
852
+ * Action: Clones githubUrl to projectPath location
853
+ * Validation:
854
+ * - If projectPath exists with git repo:
855
+ * - Compares remote URL with githubUrl
856
+ * - If URLs match: Reuses existing repo
857
+ * - If URLs differ: Returns error
858
+ * Cleanup: Yes (if cleanup=true)
859
+ *
860
+ * ================================================================================================
861
+ * GITHUB BRANCH/PR CREATION REQUIREMENTS
862
+ * ================================================================================================
863
+ *
864
+ * For createBranch or createPR to work, one of the following must be true:
865
+ *
866
+ * Option A: githubUrl provided
867
+ * - Repository URL directly specified
868
+ * - Works with both cloning and existing paths
869
+ *
870
+ * Option B: projectPath with GitHub remote
871
+ * - Project must be a Git repository
872
+ * - Must have 'origin' remote configured
873
+ * - Remote URL must point to github.com
874
+ * - System auto-detects GitHub URL via: git remote get-url origin
875
+ *
876
+ * Additional Requirements:
877
+ * - Valid GitHub token (from settings or githubToken parameter)
878
+ * - Token must have 'repo' scope for private repos
879
+ * - Project must have commits (for PR creation)
880
+ *
881
+ * ================================================================================================
882
+ * VALIDATION & ERROR HANDLING
883
+ * ================================================================================================
884
+ *
885
+ * Input Validations (400 Bad Request):
886
+ * - Either githubUrl OR projectPath must be provided (not neither)
887
+ * - message must be non-empty string
888
+ * - provider must be 'claude', 'cursor', 'codex', or 'gemini'
889
+ * - createBranch/createPR requires githubUrl OR projectPath (not neither)
890
+ * - branchName must pass Git naming rules (if provided)
891
+ *
892
+ * Runtime Validations (500 Internal Server Error or specific error in response):
893
+ * - projectPath must exist (if used alone)
894
+ * - GitHub URL format must be valid
895
+ * - Git remote URL must include github.com (for projectPath + branch/PR)
896
+ * - GitHub token must be available (for private repos and branch/PR)
897
+ * - Directory conflicts handled (existing path with different repo)
898
+ *
899
+ * Branch Name Validation Errors (returned in response, not HTTP error):
900
+ * Invalid names return: { branch: { error: "Invalid branch name: <reason>" } }
901
+ * Examples:
902
+ * - "my branch" "Branch name cannot contain spaces"
903
+ * - ".feature" "Branch name cannot start with a dot"
904
+ * - "feature.lock" "Branch name cannot end with .lock"
905
+ *
906
+ * ================================================================================================
907
+ * RESPONSE FORMATS
908
+ * ================================================================================================
909
+ *
910
+ * Streaming Response (stream=true):
911
+ * Content-Type: text/event-stream
912
+ * Events:
913
+ * - { type: "status", message: "...", projectPath: "..." }
914
+ * - { type: "claude-response", data: {...} }
915
+ * - { type: "github-branch", branch: { name: "...", url: "..." } }
916
+ * - { type: "github-pr", pullRequest: { number: 42, url: "..." } }
917
+ * - { type: "github-error", error: "..." }
918
+ * - { type: "done" }
919
+ *
920
+ * Non-Streaming Response (stream=false):
921
+ * Content-Type: application/json
922
+ * {
923
+ * success: true,
924
+ * sessionId: "session-123",
925
+ * messages: [...], // Assistant messages only (filtered)
926
+ * tokens: {
927
+ * inputTokens: 150,
928
+ * outputTokens: 50,
929
+ * cacheReadTokens: 0,
930
+ * cacheCreationTokens: 0,
931
+ * totalTokens: 200
932
+ * },
933
+ * projectPath: "/path/to/project",
934
+ * branch: { // Only if createBranch=true
935
+ * name: "feature/xyz",
936
+ * url: "https://github.com/owner/repo/tree/feature/xyz"
937
+ * } | { error: "..." },
938
+ * pullRequest: { // Only if createPR=true
939
+ * number: 42,
940
+ * url: "https://github.com/owner/repo/pull/42"
941
+ * } | { error: "..." }
942
+ * }
943
+ *
944
+ * Error Response:
945
+ * HTTP Status: 400, 401, 500
946
+ * Content-Type: application/json
947
+ * { success: false, error: "Error description" }
948
+ *
949
+ * ================================================================================================
950
+ * EXAMPLES
951
+ * ================================================================================================
952
+ *
953
+ * Example 1: Clone and process with auto-cleanup
954
+ * POST /api/agent
955
+ * { "githubUrl": "https://github.com/user/repo", "message": "Fix bug" }
956
+ *
957
+ * Example 2: Use existing project with custom branch and PR
958
+ * POST /api/agent
959
+ * {
960
+ * "projectPath": "/home/user/project",
961
+ * "message": "Add feature",
962
+ * "branchName": "feature/new-feature",
963
+ * "createPR": true
964
+ * }
965
+ *
966
+ * Example 3: Clone to specific path with auto-generated branch
967
+ * POST /api/agent
968
+ * {
969
+ * "githubUrl": "https://github.com/user/repo",
970
+ * "projectPath": "/tmp/work",
971
+ * "message": "Refactor code",
972
+ * "createBranch": true,
973
+ * "cleanup": false
974
+ * }
975
+ */
976
+ router.post('/', validateExternalApiKey, async (req, res) => {
977
+ const { githubUrl, projectPath, message, provider = 'claude', model, githubToken, branchName, sessionId } = req.body;
978
+ const requestedPermissionMode = typeof req.body.permissionMode === 'string' ? req.body.permissionMode : null;
979
+ const permissionMode = ['default', 'acceptEdits', 'bypassPermissions', 'plan', 'auto_edit', 'yolo'].includes(requestedPermissionMode)
980
+ ? requestedPermissionMode
981
+ : null;
982
+ const suppressNotifications = req.body.suppressNotifications === true || req.body.suppressNotifications === 'true';
983
+
984
+ // Parse stream and cleanup as booleans (handle string "true"/"false" from curl)
985
+ const stream = req.body.stream === undefined ? true : (req.body.stream === true || req.body.stream === 'true');
986
+ const cleanup = req.body.cleanup === undefined ? true : (req.body.cleanup === true || req.body.cleanup === 'true');
987
+
988
+ // If branchName is provided, automatically enable createBranch
989
+ const createBranch = branchName ? true : (req.body.createBranch === true || req.body.createBranch === 'true');
990
+ const createPR = req.body.createPR === true || req.body.createPR === 'true';
991
+
992
+ // Validate inputs
993
+ if (!githubUrl && !projectPath) {
994
+ return res.status(400).json({ error: 'Either githubUrl or projectPath is required' });
995
+ }
996
+
997
+ if (!message || !message.trim()) {
998
+ return res.status(400).json({ error: 'message is required' });
999
+ }
1000
+
1001
+ if (!['claude', 'cursor', 'codex', 'gemini', 'qwen', 'opencode'].includes(provider)) {
1002
+ return res.status(400).json({ error: 'provider must be one of: claude, cursor, codex, gemini, qwen, opencode' });
1003
+ }
1004
+
1005
+ // Validate GitHub branch/PR creation requirements
1006
+ // Allow branch/PR creation with projectPath as long as it has a GitHub remote
1007
+ if ((createBranch || createPR) && !githubUrl && !projectPath) {
1008
+ return res.status(400).json({ error: 'createBranch and createPR require either githubUrl or projectPath with a GitHub remote' });
1009
+ }
1010
+
1011
+ let finalProjectPath = null;
1012
+ let writer = null;
1013
+
1014
+ try {
1015
+ // Determine the final project path
1016
+ if (githubUrl) {
1017
+ // Clone repository (to projectPath if provided, otherwise generate path)
1018
+ const tokenToUse = githubToken || githubTokensDb.getActiveGithubToken(req.user.id);
1019
+
1020
+ let targetPath;
1021
+ if (projectPath) {
1022
+ targetPath = projectPath;
1023
+ } else {
1024
+ // Generate a unique path for cloning
1025
+ const repoHash = crypto.createHash('md5').update(githubUrl + Date.now()).digest('hex');
1026
+ targetPath = path.join(os.homedir(), '.claude', 'external-projects', repoHash);
1027
+ }
1028
+
1029
+ finalProjectPath = await cloneGitHubRepo(githubUrl.trim(), tokenToUse, targetPath);
1030
+ } else {
1031
+ // Use existing project path
1032
+ finalProjectPath = path.resolve(projectPath);
1033
+
1034
+ // Verify the path exists
1035
+ try {
1036
+ await fs.access(finalProjectPath);
1037
+ } catch (error) {
1038
+ throw new Error(`Project path does not exist: ${finalProjectPath}`);
1039
+ }
1040
+ }
1041
+
1042
+ // Register the project (or use existing registration)
1043
+ let project;
1044
+ try {
1045
+ project = await addProjectManually(finalProjectPath);
1046
+ console.log('📦 Project registered:', project);
1047
+ } catch (error) {
1048
+ // If project already exists, that's fine - continue with the existing registration
1049
+ if (error.message && error.message.includes('Project already configured')) {
1050
+ console.log('📦 Using existing project registration for:', finalProjectPath);
1051
+ project = { path: finalProjectPath };
1052
+ } else {
1053
+ throw error;
1054
+ }
1055
+ }
1056
+
1057
+ // Set up writer based on streaming mode
1058
+ if (stream) {
1059
+ // Set up SSE headers for streaming
1060
+ res.setHeader('Content-Type', 'text/event-stream');
1061
+ res.setHeader('Cache-Control', 'no-cache');
1062
+ res.setHeader('Connection', 'keep-alive');
1063
+ res.setHeader('X-Accel-Buffering', 'no'); // Disable nginx buffering
1064
+
1065
+ writer = new SSEStreamWriter(res, req.user.id);
1066
+
1067
+ // Send initial status
1068
+ writer.send({
1069
+ type: 'status',
1070
+ message: githubUrl ? 'Repository cloned and session started' : 'Session started',
1071
+ projectPath: finalProjectPath
1072
+ });
1073
+ } else {
1074
+ // Non-streaming mode: collect messages
1075
+ writer = new ResponseCollector(req.user.id);
1076
+
1077
+ // Collect initial status message
1078
+ writer.send({
1079
+ type: 'status',
1080
+ message: githubUrl ? 'Repository cloned and session started' : 'Session started',
1081
+ projectPath: finalProjectPath
1082
+ });
1083
+ }
1084
+
1085
+ // Start the appropriate session
1086
+ if (provider === 'claude') {
1087
+ console.log('🤖 Starting Claude SDK session');
1088
+
1089
+ await queryClaudeSDK(message.trim(), {
1090
+ projectPath: finalProjectPath,
1091
+ cwd: finalProjectPath,
1092
+ sessionId: sessionId || null,
1093
+ model: model,
1094
+ permissionMode: permissionMode || 'bypassPermissions', // Bypass all permissions for API calls unless explicitly restricted
1095
+ suppressNotifications,
1096
+ }, writer);
1097
+
1098
+ } else if (provider === 'cursor') {
1099
+ console.log('🖱️ Starting Cursor CLI session');
1100
+
1101
+ await spawnCursor(message.trim(), {
1102
+ projectPath: finalProjectPath,
1103
+ cwd: finalProjectPath,
1104
+ sessionId: sessionId || null,
1105
+ model: model || undefined,
1106
+ skipPermissions: permissionMode ? permissionMode === 'bypassPermissions' || permissionMode === 'acceptEdits' || permissionMode === 'yolo' : true,
1107
+ suppressNotifications,
1108
+ }, writer);
1109
+ } else if (provider === 'codex') {
1110
+ console.log('🤖 Starting Codex SDK session');
1111
+
1112
+ await queryCodex(message.trim(), {
1113
+ projectPath: finalProjectPath,
1114
+ cwd: finalProjectPath,
1115
+ sessionId: sessionId || null,
1116
+ model: model || getDefaultProviderModel('codex'),
1117
+ permissionMode: permissionMode || 'bypassPermissions',
1118
+ suppressNotifications,
1119
+ }, writer);
1120
+ } else if (provider === 'gemini') {
1121
+ console.log('✨ Starting Gemini CLI session');
1122
+
1123
+ await spawnGemini(message.trim(), {
1124
+ projectPath: finalProjectPath,
1125
+ cwd: finalProjectPath,
1126
+ sessionId: sessionId || null,
1127
+ model: model,
1128
+ permissionMode: permissionMode || undefined,
1129
+ skipPermissions: permissionMode ? permissionMode === 'bypassPermissions' || permissionMode === 'acceptEdits' || permissionMode === 'yolo' : true,
1130
+ suppressNotifications,
1131
+ }, writer);
1132
+ } else if (provider === 'qwen') {
1133
+ console.log('🐉 Starting Qwen Code CLI session');
1134
+
1135
+ await spawnQwen(message.trim(), {
1136
+ projectPath: finalProjectPath,
1137
+ cwd: finalProjectPath,
1138
+ sessionId: sessionId || null,
1139
+ model: model,
1140
+ permissionMode: permissionMode || undefined,
1141
+ skipPermissions: permissionMode ? permissionMode === 'bypassPermissions' || permissionMode === 'acceptEdits' || permissionMode === 'yolo' : true,
1142
+ suppressNotifications,
1143
+ }, writer);
1144
+ } else if (provider === 'opencode') {
1145
+ console.log('🅾️ Starting OpenCode CLI session');
1146
+
1147
+ await spawnOpencode(message.trim(), {
1148
+ projectPath: finalProjectPath,
1149
+ cwd: finalProjectPath,
1150
+ sessionId: sessionId || null,
1151
+ model: model,
1152
+ permissionMode: permissionMode || 'bypassPermissions',
1153
+ toolsSettings: {
1154
+ allowPatterns: [],
1155
+ denyPatterns: [],
1156
+ skipPermissions: permissionMode ? permissionMode === 'bypassPermissions' || permissionMode === 'acceptEdits' || permissionMode === 'yolo' : true,
1157
+ },
1158
+ suppressNotifications,
1159
+ }, writer);
1160
+ }
1161
+
1162
+ // Handle GitHub branch and PR creation after successful agent completion
1163
+ let branchInfo = null;
1164
+ let prInfo = null;
1165
+
1166
+ if (createBranch || createPR) {
1167
+ try {
1168
+ console.log('🔄 Starting GitHub branch/PR creation workflow...');
1169
+
1170
+ // Get GitHub token
1171
+ const tokenToUse = githubToken || githubTokensDb.getActiveGithubToken(req.user.id);
1172
+
1173
+ if (!tokenToUse) {
1174
+ throw new Error('GitHub token required for branch/PR creation. Please configure a GitHub token in settings.');
1175
+ }
1176
+
1177
+ // Initialize Octokit
1178
+ const octokit = new Octokit({ auth: tokenToUse });
1179
+
1180
+ // Get GitHub URL - either from parameter or from git remote
1181
+ let repoUrl = githubUrl;
1182
+ if (!repoUrl) {
1183
+ console.log('🔍 Getting GitHub URL from git remote...');
1184
+ try {
1185
+ repoUrl = await getGitRemoteUrl(finalProjectPath);
1186
+ if (!repoUrl.includes('github.com')) {
1187
+ throw new Error('Project does not have a GitHub remote configured');
1188
+ }
1189
+ console.log(`✅ Found GitHub remote: ${repoUrl}`);
1190
+ } catch (error) {
1191
+ throw new Error(`Failed to get GitHub remote URL: ${error.message}`);
1192
+ }
1193
+ }
1194
+
1195
+ // Parse GitHub URL to get owner and repo
1196
+ const { owner, repo } = parseGitHubUrl(repoUrl);
1197
+ console.log(`📦 Repository: ${owner}/${repo}`);
1198
+
1199
+ // Use provided branch name or auto-generate from message
1200
+ const finalBranchName = branchName || autogenerateBranchName(message);
1201
+ if (branchName) {
1202
+ console.log(`🌿 Using provided branch name: ${finalBranchName}`);
1203
+
1204
+ // Validate custom branch name
1205
+ const validation = validateBranchName(finalBranchName);
1206
+ if (!validation.valid) {
1207
+ throw new Error(`Invalid branch name: ${validation.error}`);
1208
+ }
1209
+ } else {
1210
+ console.log(`🌿 Auto-generated branch name: ${finalBranchName}`);
1211
+ }
1212
+
1213
+ if (createBranch) {
1214
+ // Create and checkout the new branch locally
1215
+ console.log('🔄 Creating local branch...');
1216
+ const checkoutProcess = spawn('git', ['checkout', '-b', finalBranchName], {
1217
+ cwd: finalProjectPath,
1218
+ stdio: 'pipe'
1219
+ });
1220
+
1221
+ await new Promise((resolve, reject) => {
1222
+ let stderr = '';
1223
+ checkoutProcess.stderr.on('data', (data) => { stderr += data.toString(); });
1224
+ checkoutProcess.on('close', (code) => {
1225
+ if (code === 0) {
1226
+ console.log(`✅ Created and checked out local branch '${finalBranchName}'`);
1227
+ resolve();
1228
+ } else {
1229
+ // Branch might already exist locally, try to checkout
1230
+ if (stderr.includes('already exists')) {
1231
+ console.log(`ℹ️ Branch '${finalBranchName}' already exists locally, checking out...`);
1232
+ const checkoutExisting = spawn('git', ['checkout', finalBranchName], {
1233
+ cwd: finalProjectPath,
1234
+ stdio: 'pipe'
1235
+ });
1236
+ checkoutExisting.on('close', (checkoutCode) => {
1237
+ if (checkoutCode === 0) {
1238
+ console.log(`✅ Checked out existing branch '${finalBranchName}'`);
1239
+ resolve();
1240
+ } else {
1241
+ reject(new Error(`Failed to checkout existing branch: ${stderr}`));
1242
+ }
1243
+ });
1244
+ } else {
1245
+ reject(new Error(`Failed to create branch: ${stderr}`));
1246
+ }
1247
+ }
1248
+ });
1249
+ });
1250
+
1251
+ // Push the branch to remote
1252
+ console.log('🔄 Pushing branch to remote...');
1253
+ const pushProcess = spawn('git', ['push', '-u', 'origin', finalBranchName], {
1254
+ cwd: finalProjectPath,
1255
+ stdio: 'pipe'
1256
+ });
1257
+
1258
+ await new Promise((resolve, reject) => {
1259
+ let stderr = '';
1260
+ let stdout = '';
1261
+ pushProcess.stdout.on('data', (data) => { stdout += data.toString(); });
1262
+ pushProcess.stderr.on('data', (data) => { stderr += data.toString(); });
1263
+ pushProcess.on('close', (code) => {
1264
+ if (code === 0) {
1265
+ console.log(`✅ Pushed branch '${finalBranchName}' to remote`);
1266
+ resolve();
1267
+ } else {
1268
+ // Check if branch exists on remote but has different commits
1269
+ if (stderr.includes('already exists') || stderr.includes('up-to-date')) {
1270
+ console.log(`ℹ️ Branch '${finalBranchName}' already exists on remote, using existing branch`);
1271
+ resolve();
1272
+ } else {
1273
+ reject(new Error(`Failed to push branch: ${stderr}`));
1274
+ }
1275
+ }
1276
+ });
1277
+ });
1278
+
1279
+ branchInfo = {
1280
+ name: finalBranchName,
1281
+ url: `https://github.com/${owner}/${repo}/tree/${finalBranchName}`
1282
+ };
1283
+ }
1284
+
1285
+ if (createPR) {
1286
+ // Get commit messages to generate PR description
1287
+ console.log('🔄 Generating PR title and description...');
1288
+ const commitMessages = await getCommitMessages(finalProjectPath, 5);
1289
+
1290
+ // Use the first commit message as the PR title, or fallback to the agent message
1291
+ const prTitle = commitMessages.length > 0 ? commitMessages[0] : message;
1292
+
1293
+ // Generate PR body from commit messages
1294
+ let prBody = '## Changes\n\n';
1295
+ if (commitMessages.length > 0) {
1296
+ prBody += commitMessages.map(msg => `- ${msg}`).join('\n');
1297
+ } else {
1298
+ prBody += `Agent task: ${message}`;
1299
+ }
1300
+ prBody += '\n\n---\n*This pull request was automatically created by Pixcode Agent.*';
1301
+
1302
+ console.log(`📝 PR Title: ${prTitle}`);
1303
+
1304
+ // Create the pull request
1305
+ console.log('🔄 Creating pull request...');
1306
+ prInfo = await createGitHubPR(octokit, owner, repo, finalBranchName, prTitle, prBody, 'main');
1307
+ }
1308
+
1309
+ // Send branch/PR info in response
1310
+ if (stream) {
1311
+ if (branchInfo) {
1312
+ writer.send({
1313
+ type: 'github-branch',
1314
+ branch: branchInfo
1315
+ });
1316
+ }
1317
+ if (prInfo) {
1318
+ writer.send({
1319
+ type: 'github-pr',
1320
+ pullRequest: prInfo
1321
+ });
1322
+ }
1323
+ }
1324
+
1325
+ } catch (error) {
1326
+ console.error('❌ GitHub branch/PR creation error:', error);
1327
+
1328
+ // Send error but don't fail the entire request
1329
+ if (stream) {
1330
+ writer.send({
1331
+ type: 'github-error',
1332
+ error: error.message
1333
+ });
1334
+ }
1335
+ // Store error info for non-streaming response
1336
+ if (!stream) {
1337
+ branchInfo = { error: error.message };
1338
+ prInfo = { error: error.message };
1339
+ }
1340
+ }
1341
+ }
1342
+
1343
+ // Handle response based on streaming mode
1344
+ if (stream) {
1345
+ // Streaming mode: end the SSE stream
1346
+ writer.end();
1347
+ } else {
1348
+ // Non-streaming mode: send filtered messages and token summary as JSON
1349
+ const assistantMessages = writer.getAssistantMessages();
1350
+ const tokenSummary = writer.getTotalTokens();
1351
+
1352
+ // Promote provider-side errors (`writer.send({ kind:'error', ... })`)
1353
+ // to the response envelope. Without this, providers like Codex —
1354
+ // whose SDK swallows throws and only emits an error message — left
1355
+ // callers with `{ success:true, messages:[] }`, indistinguishable
1356
+ // from a quiet success. Now: any error event => success:false and
1357
+ // the human-readable text on `error`.
1358
+ const errorEntry = assistantMessages.find((m) => m.type === 'error');
1359
+ const hasAssistantText = assistantMessages.some(
1360
+ (m) => m.type === 'assistant' && m.message?.content?.some?.((p) => p.type === 'text' && p.text)
1361
+ );
1362
+ const succeeded = !errorEntry && (hasAssistantText || assistantMessages.some((m) => m.type === 'tool_use' || m.type === 'tool_result'));
1363
+ const failureDetails = succeeded
1364
+ ? null
1365
+ : describeProviderFailure(
1366
+ errorEntry?.content || 'Provider returned no assistant text. Check backend log for details.',
1367
+ provider,
1368
+ );
1369
+
1370
+ const response = {
1371
+ success: succeeded,
1372
+ sessionId: writer.getSessionId(),
1373
+ messages: assistantMessages,
1374
+ tokens: tokenSummary,
1375
+ projectPath: finalProjectPath
1376
+ };
1377
+ if (failureDetails) {
1378
+ response.error = failureDetails.message;
1379
+ response.rawError = failureDetails.rawMessage;
1380
+ response.errorDetails = failureDetails;
1381
+ }
1382
+
1383
+ // Add branch/PR info if created
1384
+ if (branchInfo) {
1385
+ response.branch = branchInfo;
1386
+ }
1387
+ if (prInfo) {
1388
+ response.pullRequest = prInfo;
1389
+ }
1390
+
1391
+ res.status(succeeded ? 200 : 502).json(response);
1392
+ }
1393
+
1394
+ // Clean up if requested
1395
+ if (cleanup && githubUrl) {
1396
+ // Only cleanup if we cloned a repo (not for existing project paths)
1397
+ const sessionIdForCleanup = writer.getSessionId();
1398
+ setTimeout(() => {
1399
+ cleanupProject(finalProjectPath, sessionIdForCleanup);
1400
+ }, 5000);
1401
+ }
1402
+
1403
+ } catch (error) {
1404
+ console.error('❌ External session error:', error);
1405
+
1406
+ // Clean up on error
1407
+ if (finalProjectPath && cleanup && githubUrl) {
1408
+ const sessionIdForCleanup = writer ? writer.getSessionId() : null;
1409
+ cleanupProject(finalProjectPath, sessionIdForCleanup);
1410
+ }
1411
+
1412
+ if (stream) {
1413
+ // For streaming, send error event and stop
1414
+ if (!writer) {
1415
+ // Set up SSE headers if not already done
1416
+ res.setHeader('Content-Type', 'text/event-stream');
1417
+ res.setHeader('Cache-Control', 'no-cache');
1418
+ res.setHeader('Connection', 'keep-alive');
1419
+ res.setHeader('X-Accel-Buffering', 'no');
1420
+ writer = new SSEStreamWriter(res, req.user.id);
1421
+ }
1422
+
1423
+ if (!res.writableEnded) {
1424
+ writer.send({
1425
+ type: 'error',
1426
+ error: 'Failed to process agent request.',
1427
+ message: 'Failed to process agent request.'
1428
+ });
1429
+ writer.end();
1430
+ }
1431
+ } else if (!res.headersSent) {
1432
+ // Surface any provider-side stderr/error events the writer collected
1433
+ // BEFORE the throw — without this, callers only see the bland
1434
+ // "Gemini CLI exited with code 403" wrapper and lose the actual
1435
+ // "PERMISSION_DENIED, model not enabled for this account" detail
1436
+ // that the CLI printed to stderr.
1437
+ let collectedError = null;
1438
+ let collectedMessages = [];
1439
+ if (writer && typeof writer.getAssistantMessages === 'function') {
1440
+ try {
1441
+ collectedMessages = writer.getAssistantMessages();
1442
+ const errorText = collectedMessages
1443
+ .filter((m) => m.type === 'error' && typeof m.content === 'string' && m.content.trim())
1444
+ .map((m) => m.content.trim())
1445
+ .join('\n');
1446
+ if (errorText) collectedError = errorText;
1447
+ } catch { /* ignore — fall back to error.message */ }
1448
+ }
1449
+ const failureDetails = describeProviderFailure(collectedError || 'Provider returned no assistant text.', provider);
1450
+ res.status(502).json({
1451
+ success: false,
1452
+ sessionId: writer && typeof writer.getSessionId === 'function' ? writer.getSessionId() : null,
1453
+ error: failureDetails.message,
1454
+ rawError: failureDetails.rawMessage,
1455
+ errorDetails: failureDetails,
1456
+ messages: collectedMessages,
1457
+ });
1458
+ }
1459
+ }
1460
+ });
1461
+
1462
+ export default router;