@cloudcli-ai/cloudcli 1.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (163) hide show
  1. package/LICENSE +718 -0
  2. package/README.de.md +239 -0
  3. package/README.ja.md +231 -0
  4. package/README.ko.md +230 -0
  5. package/README.md +242 -0
  6. package/README.ru.md +239 -0
  7. package/README.zh-CN.md +230 -0
  8. package/dist/api-docs.html +879 -0
  9. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  10. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  11. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  12. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  13. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  14. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  15. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  16. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  17. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  18. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  19. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  20. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  21. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  22. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  23. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  24. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  25. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  26. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  27. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  28. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  29. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  30. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  31. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  32. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  33. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  34. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  35. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  36. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  37. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  38. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  39. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  40. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  41. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  42. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  43. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  44. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  45. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  46. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  47. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  48. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  49. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  50. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  51. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  52. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  53. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  54. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  55. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  56. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  57. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  58. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  59. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  60. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  61. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  62. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  63. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  64. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  65. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  66. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  67. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  68. package/dist/assets/index-B1XAhG_4.css +32 -0
  69. package/dist/assets/index-BWQPmiP5.js +1275 -0
  70. package/dist/assets/vendor-codemirror-C8f1vU1x.js +41 -0
  71. package/dist/assets/vendor-react-CdSTmIF1.js +59 -0
  72. package/dist/assets/vendor-xterm-CJZjLICi.js +66 -0
  73. package/dist/clear-cache.html +85 -0
  74. package/dist/convert-icons.md +53 -0
  75. package/dist/favicon.png +0 -0
  76. package/dist/favicon.svg +9 -0
  77. package/dist/generate-icons.js +49 -0
  78. package/dist/icons/claude-ai-icon.svg +1 -0
  79. package/dist/icons/codex-white.svg +3 -0
  80. package/dist/icons/codex.svg +3 -0
  81. package/dist/icons/cursor-white.svg +12 -0
  82. package/dist/icons/cursor.svg +1 -0
  83. package/dist/icons/gemini-ai-icon.svg +1 -0
  84. package/dist/icons/icon-128x128.png +0 -0
  85. package/dist/icons/icon-128x128.svg +12 -0
  86. package/dist/icons/icon-144x144.png +0 -0
  87. package/dist/icons/icon-144x144.svg +12 -0
  88. package/dist/icons/icon-152x152.png +0 -0
  89. package/dist/icons/icon-152x152.svg +12 -0
  90. package/dist/icons/icon-192x192.png +0 -0
  91. package/dist/icons/icon-192x192.svg +12 -0
  92. package/dist/icons/icon-384x384.png +0 -0
  93. package/dist/icons/icon-384x384.svg +12 -0
  94. package/dist/icons/icon-512x512.png +0 -0
  95. package/dist/icons/icon-512x512.svg +12 -0
  96. package/dist/icons/icon-72x72.png +0 -0
  97. package/dist/icons/icon-72x72.svg +12 -0
  98. package/dist/icons/icon-96x96.png +0 -0
  99. package/dist/icons/icon-96x96.svg +12 -0
  100. package/dist/icons/icon-template.svg +12 -0
  101. package/dist/index.html +52 -0
  102. package/dist/logo-128.png +0 -0
  103. package/dist/logo-256.png +0 -0
  104. package/dist/logo-32.png +0 -0
  105. package/dist/logo-512.png +0 -0
  106. package/dist/logo-64.png +0 -0
  107. package/dist/logo.svg +17 -0
  108. package/dist/manifest.json +61 -0
  109. package/dist/screenshots/cli-selection.png +0 -0
  110. package/dist/screenshots/desktop-main.png +0 -0
  111. package/dist/screenshots/mobile-chat.png +0 -0
  112. package/dist/screenshots/tools-modal.png +0 -0
  113. package/dist/sw.js +124 -0
  114. package/package.json +153 -0
  115. package/scripts/fix-node-pty.js +67 -0
  116. package/server/claude-sdk.js +817 -0
  117. package/server/cli.js +330 -0
  118. package/server/constants/config.js +5 -0
  119. package/server/cursor-cli.js +335 -0
  120. package/server/database/db.js +630 -0
  121. package/server/database/init.sql +99 -0
  122. package/server/gemini-cli.js +453 -0
  123. package/server/gemini-response-handler.js +79 -0
  124. package/server/index.js +2577 -0
  125. package/server/load-env.js +29 -0
  126. package/server/middleware/auth.js +132 -0
  127. package/server/openai-codex.js +418 -0
  128. package/server/projects.js +2561 -0
  129. package/server/providers/claude/adapter.js +278 -0
  130. package/server/providers/codex/adapter.js +248 -0
  131. package/server/providers/cursor/adapter.js +353 -0
  132. package/server/providers/gemini/adapter.js +186 -0
  133. package/server/providers/registry.js +44 -0
  134. package/server/providers/types.js +119 -0
  135. package/server/providers/utils.js +29 -0
  136. package/server/routes/agent.js +1245 -0
  137. package/server/routes/auth.js +135 -0
  138. package/server/routes/cli-auth.js +434 -0
  139. package/server/routes/codex.js +329 -0
  140. package/server/routes/commands.js +601 -0
  141. package/server/routes/cursor.js +798 -0
  142. package/server/routes/gemini.js +24 -0
  143. package/server/routes/git.js +1488 -0
  144. package/server/routes/mcp-utils.js +48 -0
  145. package/server/routes/mcp.js +552 -0
  146. package/server/routes/messages.js +61 -0
  147. package/server/routes/plugins.js +307 -0
  148. package/server/routes/projects.js +548 -0
  149. package/server/routes/settings.js +276 -0
  150. package/server/routes/taskmaster.js +1963 -0
  151. package/server/routes/user.js +123 -0
  152. package/server/services/notification-orchestrator.js +227 -0
  153. package/server/services/vapid-keys.js +35 -0
  154. package/server/sessionManager.js +226 -0
  155. package/server/utils/commandParser.js +303 -0
  156. package/server/utils/frontmatter.js +18 -0
  157. package/server/utils/gitConfig.js +34 -0
  158. package/server/utils/mcp-detector.js +198 -0
  159. package/server/utils/plugin-loader.js +457 -0
  160. package/server/utils/plugin-process-manager.js +184 -0
  161. package/server/utils/taskmaster-websocket.js +129 -0
  162. package/shared/modelConstants.js +92 -0
  163. package/shared/networkHosts.js +22 -0
@@ -0,0 +1,2577 @@
1
+ #!/usr/bin/env node
2
+ // Load environment variables before other imports execute
3
+ import './load-env.js';
4
+ import fs from 'fs';
5
+ import path from 'path';
6
+ import { fileURLToPath } from 'url';
7
+ import { dirname } from 'path';
8
+
9
+ const __filename = fileURLToPath(import.meta.url);
10
+ const __dirname = dirname(__filename);
11
+
12
+ const installMode = fs.existsSync(path.join(__dirname, '..', '.git')) ? 'git' : 'npm';
13
+
14
+ // ANSI color codes for terminal output
15
+ const colors = {
16
+ reset: '\x1b[0m',
17
+ bright: '\x1b[1m',
18
+ cyan: '\x1b[36m',
19
+ green: '\x1b[32m',
20
+ yellow: '\x1b[33m',
21
+ blue: '\x1b[34m',
22
+ dim: '\x1b[2m',
23
+ };
24
+
25
+ const c = {
26
+ info: (text) => `${colors.cyan}${text}${colors.reset}`,
27
+ ok: (text) => `${colors.green}${text}${colors.reset}`,
28
+ warn: (text) => `${colors.yellow}${text}${colors.reset}`,
29
+ tip: (text) => `${colors.blue}${text}${colors.reset}`,
30
+ bright: (text) => `${colors.bright}${text}${colors.reset}`,
31
+ dim: (text) => `${colors.dim}${text}${colors.reset}`,
32
+ };
33
+
34
+ console.log('SERVER_PORT from env:', process.env.SERVER_PORT);
35
+
36
+ import express from 'express';
37
+ import { WebSocketServer, WebSocket } from 'ws';
38
+ import os from 'os';
39
+ import http from 'http';
40
+ import cors from 'cors';
41
+ import { promises as fsPromises } from 'fs';
42
+ import { spawn } from 'child_process';
43
+ import pty from 'node-pty';
44
+ import fetch from 'node-fetch';
45
+ import mime from 'mime-types';
46
+
47
+ import { getProjects, getSessions, renameProject, deleteSession, deleteProject, addProjectManually, extractProjectDirectory, clearProjectDirectoryCache, searchConversations } from './projects.js';
48
+ import { queryClaudeSDK, abortClaudeSDKSession, isClaudeSDKSessionActive, getActiveClaudeSDKSessions, resolveToolApproval, getPendingApprovalsForSession, reconnectSessionWriter } from './claude-sdk.js';
49
+ import { spawnCursor, abortCursorSession, isCursorSessionActive, getActiveCursorSessions } from './cursor-cli.js';
50
+ import { queryCodex, abortCodexSession, isCodexSessionActive, getActiveCodexSessions } from './openai-codex.js';
51
+ import { spawnGemini, abortGeminiSession, isGeminiSessionActive, getActiveGeminiSessions } from './gemini-cli.js';
52
+ import sessionManager from './sessionManager.js';
53
+ import gitRoutes from './routes/git.js';
54
+ import authRoutes from './routes/auth.js';
55
+ import mcpRoutes from './routes/mcp.js';
56
+ import cursorRoutes from './routes/cursor.js';
57
+ import taskmasterRoutes from './routes/taskmaster.js';
58
+ import mcpUtilsRoutes from './routes/mcp-utils.js';
59
+ import commandsRoutes from './routes/commands.js';
60
+ import settingsRoutes from './routes/settings.js';
61
+ import agentRoutes from './routes/agent.js';
62
+ import projectsRoutes, { WORKSPACES_ROOT, validateWorkspacePath } from './routes/projects.js';
63
+ import cliAuthRoutes from './routes/cli-auth.js';
64
+ import userRoutes from './routes/user.js';
65
+ import codexRoutes from './routes/codex.js';
66
+ import geminiRoutes from './routes/gemini.js';
67
+ import pluginsRoutes from './routes/plugins.js';
68
+ import messagesRoutes from './routes/messages.js';
69
+ import { createNormalizedMessage } from './providers/types.js';
70
+ import { startEnabledPluginServers, stopAllPlugins, getPluginPort } from './utils/plugin-process-manager.js';
71
+ import { initializeDatabase, sessionNamesDb, applyCustomSessionNames } from './database/db.js';
72
+ import { configureWebPush } from './services/vapid-keys.js';
73
+ import { validateApiKey, authenticateToken, authenticateWebSocket } from './middleware/auth.js';
74
+ import { IS_PLATFORM } from './constants/config.js';
75
+ import { getConnectableHost } from '../shared/networkHosts.js';
76
+
77
+ const VALID_PROVIDERS = ['claude', 'codex', 'cursor', 'gemini'];
78
+
79
+ // File system watchers for provider project/session folders
80
+ const PROVIDER_WATCH_PATHS = [
81
+ { provider: 'claude', rootPath: path.join(os.homedir(), '.claude', 'projects') },
82
+ { provider: 'cursor', rootPath: path.join(os.homedir(), '.cursor', 'chats') },
83
+ { provider: 'codex', rootPath: path.join(os.homedir(), '.codex', 'sessions') },
84
+ { provider: 'gemini', rootPath: path.join(os.homedir(), '.gemini', 'projects') },
85
+ { provider: 'gemini_sessions', rootPath: path.join(os.homedir(), '.gemini', 'sessions') }
86
+ ];
87
+ const WATCHER_IGNORED_PATTERNS = [
88
+ '**/node_modules/**',
89
+ '**/.git/**',
90
+ '**/dist/**',
91
+ '**/build/**',
92
+ '**/*.tmp',
93
+ '**/*.swp',
94
+ '**/.DS_Store'
95
+ ];
96
+ const WATCHER_DEBOUNCE_MS = 300;
97
+ let projectsWatchers = [];
98
+ let projectsWatcherDebounceTimer = null;
99
+ const connectedClients = new Set();
100
+ let isGetProjectsRunning = false; // Flag to prevent reentrant calls
101
+
102
+ // Broadcast progress to all connected WebSocket clients
103
+ function broadcastProgress(progress) {
104
+ const message = JSON.stringify({
105
+ type: 'loading_progress',
106
+ ...progress
107
+ });
108
+ connectedClients.forEach(client => {
109
+ if (client.readyState === WebSocket.OPEN) {
110
+ client.send(message);
111
+ }
112
+ });
113
+ }
114
+
115
+ // Setup file system watchers for Claude, Cursor, and Codex project/session folders
116
+ async function setupProjectsWatcher() {
117
+ const chokidar = (await import('chokidar')).default;
118
+
119
+ if (projectsWatcherDebounceTimer) {
120
+ clearTimeout(projectsWatcherDebounceTimer);
121
+ projectsWatcherDebounceTimer = null;
122
+ }
123
+
124
+ await Promise.all(
125
+ projectsWatchers.map(async (watcher) => {
126
+ try {
127
+ await watcher.close();
128
+ } catch (error) {
129
+ console.error('[WARN] Failed to close watcher:', error);
130
+ }
131
+ })
132
+ );
133
+ projectsWatchers = [];
134
+
135
+ const debouncedUpdate = (eventType, filePath, provider, rootPath) => {
136
+ if (projectsWatcherDebounceTimer) {
137
+ clearTimeout(projectsWatcherDebounceTimer);
138
+ }
139
+
140
+ projectsWatcherDebounceTimer = setTimeout(async () => {
141
+ // Prevent reentrant calls
142
+ if (isGetProjectsRunning) {
143
+ return;
144
+ }
145
+
146
+ try {
147
+ isGetProjectsRunning = true;
148
+
149
+ // Clear project directory cache when files change
150
+ clearProjectDirectoryCache();
151
+
152
+ // Get updated projects list
153
+ const updatedProjects = await getProjects(broadcastProgress);
154
+
155
+ // Notify all connected clients about the project changes
156
+ const updateMessage = JSON.stringify({
157
+ type: 'projects_updated',
158
+ projects: updatedProjects,
159
+ timestamp: new Date().toISOString(),
160
+ changeType: eventType,
161
+ changedFile: path.relative(rootPath, filePath),
162
+ watchProvider: provider
163
+ });
164
+
165
+ connectedClients.forEach(client => {
166
+ if (client.readyState === WebSocket.OPEN) {
167
+ client.send(updateMessage);
168
+ }
169
+ });
170
+
171
+ } catch (error) {
172
+ console.error('[ERROR] Error handling project changes:', error);
173
+ } finally {
174
+ isGetProjectsRunning = false;
175
+ }
176
+ }, WATCHER_DEBOUNCE_MS);
177
+ };
178
+
179
+ for (const { provider, rootPath } of PROVIDER_WATCH_PATHS) {
180
+ try {
181
+ // chokidar v4 emits ENOENT via the "error" event for missing roots and will not auto-recover.
182
+ // Ensure provider folders exist before creating the watcher so watching stays active.
183
+ await fsPromises.mkdir(rootPath, { recursive: true });
184
+
185
+ // Initialize chokidar watcher with optimized settings
186
+ const watcher = chokidar.watch(rootPath, {
187
+ ignored: WATCHER_IGNORED_PATTERNS,
188
+ persistent: true,
189
+ ignoreInitial: true, // Don't fire events for existing files on startup
190
+ followSymlinks: false,
191
+ depth: 10, // Reasonable depth limit
192
+ awaitWriteFinish: {
193
+ stabilityThreshold: 100, // Wait 100ms for file to stabilize
194
+ pollInterval: 50
195
+ }
196
+ });
197
+
198
+ // Set up event listeners
199
+ watcher
200
+ .on('add', (filePath) => debouncedUpdate('add', filePath, provider, rootPath))
201
+ .on('change', (filePath) => debouncedUpdate('change', filePath, provider, rootPath))
202
+ .on('unlink', (filePath) => debouncedUpdate('unlink', filePath, provider, rootPath))
203
+ .on('addDir', (dirPath) => debouncedUpdate('addDir', dirPath, provider, rootPath))
204
+ .on('unlinkDir', (dirPath) => debouncedUpdate('unlinkDir', dirPath, provider, rootPath))
205
+ .on('error', (error) => {
206
+ console.error(`[ERROR] ${provider} watcher error:`, error);
207
+ })
208
+ .on('ready', () => {
209
+ });
210
+
211
+ projectsWatchers.push(watcher);
212
+ } catch (error) {
213
+ console.error(`[ERROR] Failed to setup ${provider} watcher for ${rootPath}:`, error);
214
+ }
215
+ }
216
+
217
+ if (projectsWatchers.length === 0) {
218
+ console.error('[ERROR] Failed to setup any provider watchers');
219
+ }
220
+ }
221
+
222
+
223
+ const app = express();
224
+ const server = http.createServer(app);
225
+
226
+ const ptySessionsMap = new Map();
227
+ const PTY_SESSION_TIMEOUT = 30 * 60 * 1000;
228
+ const SHELL_URL_PARSE_BUFFER_LIMIT = 32768;
229
+ const ANSI_ESCAPE_SEQUENCE_REGEX = /\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~]|\][^\x07]*(?:\x07|\x1B\\))/g;
230
+ const TRAILING_URL_PUNCTUATION_REGEX = /[)\]}>.,;:!?]+$/;
231
+
232
+ function stripAnsiSequences(value = '') {
233
+ return value.replace(ANSI_ESCAPE_SEQUENCE_REGEX, '');
234
+ }
235
+
236
+ function normalizeDetectedUrl(url) {
237
+ if (!url || typeof url !== 'string') return null;
238
+
239
+ const cleaned = url.trim().replace(TRAILING_URL_PUNCTUATION_REGEX, '');
240
+ if (!cleaned) return null;
241
+
242
+ try {
243
+ const parsed = new URL(cleaned);
244
+ if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
245
+ return null;
246
+ }
247
+ return parsed.toString();
248
+ } catch {
249
+ return null;
250
+ }
251
+ }
252
+
253
+ function extractUrlsFromText(value = '') {
254
+ const directMatches = value.match(/https?:\/\/[^\s<>"'`\\\x1b\x07]+/gi) || [];
255
+
256
+ // Handle wrapped terminal URLs split across lines by terminal width.
257
+ const wrappedMatches = [];
258
+ const continuationRegex = /^[A-Za-z0-9\-._~:/?#\[\]@!$&'()*+,;=%]+$/;
259
+ const lines = value.split(/\r?\n/);
260
+ for (let i = 0; i < lines.length; i++) {
261
+ const line = lines[i].trim();
262
+ const startMatch = line.match(/https?:\/\/[^\s<>"'`\\\x1b\x07]+/i);
263
+ if (!startMatch) continue;
264
+
265
+ let combined = startMatch[0];
266
+ let j = i + 1;
267
+ while (j < lines.length) {
268
+ const continuation = lines[j].trim();
269
+ if (!continuation) break;
270
+ if (!continuationRegex.test(continuation)) break;
271
+ combined += continuation;
272
+ j++;
273
+ }
274
+
275
+ wrappedMatches.push(combined.replace(/\r?\n\s*/g, ''));
276
+ }
277
+
278
+ return Array.from(new Set([...directMatches, ...wrappedMatches]));
279
+ }
280
+
281
+ function shouldAutoOpenUrlFromOutput(value = '') {
282
+ const normalized = value.toLowerCase();
283
+ return (
284
+ normalized.includes('browser didn\'t open') ||
285
+ normalized.includes('open this url') ||
286
+ normalized.includes('continue in your browser') ||
287
+ normalized.includes('press enter to open') ||
288
+ normalized.includes('open_url:')
289
+ );
290
+ }
291
+
292
+ // Single WebSocket server that handles both paths
293
+ const wss = new WebSocketServer({
294
+ server,
295
+ verifyClient: (info) => {
296
+ console.log('WebSocket connection attempt to:', info.req.url);
297
+
298
+ // Platform mode: always allow connection
299
+ if (IS_PLATFORM) {
300
+ const user = authenticateWebSocket(null); // Will return first user
301
+ if (!user) {
302
+ console.log('[WARN] Platform mode: No user found in database');
303
+ return false;
304
+ }
305
+ info.req.user = user;
306
+ console.log('[OK] Platform mode WebSocket authenticated for user:', user.username);
307
+ return true;
308
+ }
309
+
310
+ // Normal mode: verify token
311
+ // Extract token from query parameters or headers
312
+ const url = new URL(info.req.url, 'http://localhost');
313
+ const token = url.searchParams.get('token') ||
314
+ info.req.headers.authorization?.split(' ')[1];
315
+
316
+ // Verify token
317
+ const user = authenticateWebSocket(token);
318
+ if (!user) {
319
+ console.log('[WARN] WebSocket authentication failed');
320
+ return false;
321
+ }
322
+
323
+ // Store user info in the request for later use
324
+ info.req.user = user;
325
+ console.log('[OK] WebSocket authenticated for user:', user.username);
326
+ return true;
327
+ }
328
+ });
329
+
330
+ // Make WebSocket server available to routes
331
+ app.locals.wss = wss;
332
+
333
+ app.use(cors({ exposedHeaders: ['X-Refreshed-Token'] }));
334
+ app.use(express.json({
335
+ limit: '50mb',
336
+ type: (req) => {
337
+ // Skip multipart/form-data requests (for file uploads like images)
338
+ const contentType = req.headers['content-type'] || '';
339
+ if (contentType.includes('multipart/form-data')) {
340
+ return false;
341
+ }
342
+ return contentType.includes('json');
343
+ }
344
+ }));
345
+ app.use(express.urlencoded({ limit: '50mb', extended: true }));
346
+
347
+ // Public health check endpoint (no authentication required)
348
+ app.get('/health', (req, res) => {
349
+ res.json({
350
+ status: 'ok',
351
+ timestamp: new Date().toISOString(),
352
+ installMode
353
+ });
354
+ });
355
+
356
+ // Optional API key validation (if configured)
357
+ app.use('/api', validateApiKey);
358
+
359
+ // Authentication routes (public)
360
+ app.use('/api/auth', authRoutes);
361
+
362
+ // Projects API Routes (protected)
363
+ app.use('/api/projects', authenticateToken, projectsRoutes);
364
+
365
+ // Git API Routes (protected)
366
+ app.use('/api/git', authenticateToken, gitRoutes);
367
+
368
+ // MCP API Routes (protected)
369
+ app.use('/api/mcp', authenticateToken, mcpRoutes);
370
+
371
+ // Cursor API Routes (protected)
372
+ app.use('/api/cursor', authenticateToken, cursorRoutes);
373
+
374
+ // TaskMaster API Routes (protected)
375
+ app.use('/api/taskmaster', authenticateToken, taskmasterRoutes);
376
+
377
+ // MCP utilities
378
+ app.use('/api/mcp-utils', authenticateToken, mcpUtilsRoutes);
379
+
380
+ // Commands API Routes (protected)
381
+ app.use('/api/commands', authenticateToken, commandsRoutes);
382
+
383
+ // Settings API Routes (protected)
384
+ app.use('/api/settings', authenticateToken, settingsRoutes);
385
+
386
+ // CLI Authentication API Routes (protected)
387
+ app.use('/api/cli', authenticateToken, cliAuthRoutes);
388
+
389
+ // User API Routes (protected)
390
+ app.use('/api/user', authenticateToken, userRoutes);
391
+
392
+ // Codex API Routes (protected)
393
+ app.use('/api/codex', authenticateToken, codexRoutes);
394
+
395
+ // Gemini API Routes (protected)
396
+ app.use('/api/gemini', authenticateToken, geminiRoutes);
397
+
398
+ // Plugins API Routes (protected)
399
+ app.use('/api/plugins', authenticateToken, pluginsRoutes);
400
+
401
+ // Unified session messages route (protected)
402
+ app.use('/api/sessions', authenticateToken, messagesRoutes);
403
+
404
+ // Agent API Routes (uses API key authentication)
405
+ app.use('/api/agent', agentRoutes);
406
+
407
+ // Serve public files (like api-docs.html)
408
+ app.use(express.static(path.join(__dirname, '../public')));
409
+
410
+ // Static files served after API routes
411
+ // Add cache control: HTML files should not be cached, but assets can be cached
412
+ app.use(express.static(path.join(__dirname, '../dist'), {
413
+ setHeaders: (res, filePath) => {
414
+ if (filePath.endsWith('.html')) {
415
+ // Prevent HTML caching to avoid service worker issues after builds
416
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
417
+ res.setHeader('Pragma', 'no-cache');
418
+ res.setHeader('Expires', '0');
419
+ } else if (filePath.match(/\.(js|css|woff2?|ttf|eot|svg|png|jpg|jpeg|gif|ico)$/)) {
420
+ // Cache static assets for 1 year (they have hashed names)
421
+ res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
422
+ }
423
+ }
424
+ }));
425
+
426
+ // API Routes (protected)
427
+ // /api/config endpoint removed - no longer needed
428
+ // Frontend now uses window.location for WebSocket URLs
429
+
430
+ // System update endpoint
431
+ app.post('/api/system/update', authenticateToken, async (req, res) => {
432
+ try {
433
+ // Get the project root directory (parent of server directory)
434
+ const projectRoot = path.join(__dirname, '..');
435
+
436
+ console.log('Starting system update from directory:', projectRoot);
437
+
438
+ // Run the update command based on install mode
439
+ const updateCommand = installMode === 'git'
440
+ ? 'git checkout main && git pull && npm install'
441
+ : 'npm install -g @cloudcli-ai/cloudcli@latest';
442
+
443
+ const child = spawn('sh', ['-c', updateCommand], {
444
+ cwd: installMode === 'git' ? projectRoot : os.homedir(),
445
+ env: process.env
446
+ });
447
+
448
+ let output = '';
449
+ let errorOutput = '';
450
+
451
+ child.stdout.on('data', (data) => {
452
+ const text = data.toString();
453
+ output += text;
454
+ console.log('Update output:', text);
455
+ });
456
+
457
+ child.stderr.on('data', (data) => {
458
+ const text = data.toString();
459
+ errorOutput += text;
460
+ console.error('Update error:', text);
461
+ });
462
+
463
+ child.on('close', (code) => {
464
+ if (code === 0) {
465
+ res.json({
466
+ success: true,
467
+ output: output || 'Update completed successfully',
468
+ message: 'Update completed. Please restart the server to apply changes.'
469
+ });
470
+ } else {
471
+ res.status(500).json({
472
+ success: false,
473
+ error: 'Update command failed',
474
+ output: output,
475
+ errorOutput: errorOutput
476
+ });
477
+ }
478
+ });
479
+
480
+ child.on('error', (error) => {
481
+ console.error('Update process error:', error);
482
+ res.status(500).json({
483
+ success: false,
484
+ error: error.message
485
+ });
486
+ });
487
+
488
+ } catch (error) {
489
+ console.error('System update error:', error);
490
+ res.status(500).json({
491
+ success: false,
492
+ error: error.message
493
+ });
494
+ }
495
+ });
496
+
497
+ app.get('/api/projects', authenticateToken, async (req, res) => {
498
+ try {
499
+ const projects = await getProjects(broadcastProgress);
500
+ res.json(projects);
501
+ } catch (error) {
502
+ res.status(500).json({ error: error.message });
503
+ }
504
+ });
505
+
506
+ app.get('/api/projects/:projectName/sessions', authenticateToken, async (req, res) => {
507
+ try {
508
+ const { limit = 5, offset = 0 } = req.query;
509
+ const result = await getSessions(req.params.projectName, parseInt(limit), parseInt(offset));
510
+ applyCustomSessionNames(result.sessions, 'claude');
511
+ res.json(result);
512
+ } catch (error) {
513
+ res.status(500).json({ error: error.message });
514
+ }
515
+ });
516
+
517
+ // Rename project endpoint
518
+ app.put('/api/projects/:projectName/rename', authenticateToken, async (req, res) => {
519
+ try {
520
+ const { displayName } = req.body;
521
+ await renameProject(req.params.projectName, displayName);
522
+ res.json({ success: true });
523
+ } catch (error) {
524
+ res.status(500).json({ error: error.message });
525
+ }
526
+ });
527
+
528
+ // Delete session endpoint
529
+ app.delete('/api/projects/:projectName/sessions/:sessionId', authenticateToken, async (req, res) => {
530
+ try {
531
+ const { projectName, sessionId } = req.params;
532
+ console.log(`[API] Deleting session: ${sessionId} from project: ${projectName}`);
533
+ await deleteSession(projectName, sessionId);
534
+ sessionNamesDb.deleteName(sessionId, 'claude');
535
+ console.log(`[API] Session ${sessionId} deleted successfully`);
536
+ res.json({ success: true });
537
+ } catch (error) {
538
+ console.error(`[API] Error deleting session ${req.params.sessionId}:`, error);
539
+ res.status(500).json({ error: error.message });
540
+ }
541
+ });
542
+
543
+ // Rename session endpoint
544
+ app.put('/api/sessions/:sessionId/rename', authenticateToken, async (req, res) => {
545
+ try {
546
+ const { sessionId } = req.params;
547
+ const safeSessionId = String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '');
548
+ if (!safeSessionId || safeSessionId !== String(sessionId)) {
549
+ return res.status(400).json({ error: 'Invalid sessionId' });
550
+ }
551
+ const { summary, provider } = req.body;
552
+ if (!summary || typeof summary !== 'string' || summary.trim() === '') {
553
+ return res.status(400).json({ error: 'Summary is required' });
554
+ }
555
+ if (summary.trim().length > 500) {
556
+ return res.status(400).json({ error: 'Summary must not exceed 500 characters' });
557
+ }
558
+ if (!provider || !VALID_PROVIDERS.includes(provider)) {
559
+ return res.status(400).json({ error: `Provider must be one of: ${VALID_PROVIDERS.join(', ')}` });
560
+ }
561
+ sessionNamesDb.setName(safeSessionId, provider, summary.trim());
562
+ res.json({ success: true });
563
+ } catch (error) {
564
+ console.error(`[API] Error renaming session ${req.params.sessionId}:`, error);
565
+ res.status(500).json({ error: error.message });
566
+ }
567
+ });
568
+
569
+ // Delete project endpoint (force=true to delete with sessions)
570
+ app.delete('/api/projects/:projectName', authenticateToken, async (req, res) => {
571
+ try {
572
+ const { projectName } = req.params;
573
+ const force = req.query.force === 'true';
574
+ await deleteProject(projectName, force);
575
+ res.json({ success: true });
576
+ } catch (error) {
577
+ res.status(500).json({ error: error.message });
578
+ }
579
+ });
580
+
581
+ // Create project endpoint
582
+ app.post('/api/projects/create', authenticateToken, async (req, res) => {
583
+ try {
584
+ const { path: projectPath } = req.body;
585
+
586
+ if (!projectPath || !projectPath.trim()) {
587
+ return res.status(400).json({ error: 'Project path is required' });
588
+ }
589
+
590
+ const project = await addProjectManually(projectPath.trim());
591
+ res.json({ success: true, project });
592
+ } catch (error) {
593
+ console.error('Error creating project:', error);
594
+ res.status(500).json({ error: error.message });
595
+ }
596
+ });
597
+
598
+ // Search conversations content (SSE streaming)
599
+ app.get('/api/search/conversations', authenticateToken, async (req, res) => {
600
+ const query = typeof req.query.q === 'string' ? req.query.q.trim() : '';
601
+ const parsedLimit = Number.parseInt(String(req.query.limit), 10);
602
+ const limit = Number.isNaN(parsedLimit) ? 50 : Math.max(1, Math.min(parsedLimit, 100));
603
+
604
+ if (query.length < 2) {
605
+ return res.status(400).json({ error: 'Query must be at least 2 characters' });
606
+ }
607
+
608
+ res.writeHead(200, {
609
+ 'Content-Type': 'text/event-stream',
610
+ 'Cache-Control': 'no-cache',
611
+ 'Connection': 'keep-alive',
612
+ 'X-Accel-Buffering': 'no',
613
+ });
614
+
615
+ let closed = false;
616
+ const abortController = new AbortController();
617
+ req.on('close', () => { closed = true; abortController.abort(); });
618
+
619
+ try {
620
+ await searchConversations(query, limit, ({ projectResult, totalMatches, scannedProjects, totalProjects }) => {
621
+ if (closed) return;
622
+ if (projectResult) {
623
+ res.write(`event: result\ndata: ${JSON.stringify({ projectResult, totalMatches, scannedProjects, totalProjects })}\n\n`);
624
+ } else {
625
+ res.write(`event: progress\ndata: ${JSON.stringify({ totalMatches, scannedProjects, totalProjects })}\n\n`);
626
+ }
627
+ }, abortController.signal);
628
+ if (!closed) {
629
+ res.write(`event: done\ndata: {}\n\n`);
630
+ }
631
+ } catch (error) {
632
+ console.error('Error searching conversations:', error);
633
+ if (!closed) {
634
+ res.write(`event: error\ndata: ${JSON.stringify({ error: 'Search failed' })}\n\n`);
635
+ }
636
+ } finally {
637
+ if (!closed) {
638
+ res.end();
639
+ }
640
+ }
641
+ });
642
+
643
+ const expandWorkspacePath = (inputPath) => {
644
+ if (!inputPath) return inputPath;
645
+ if (inputPath === '~') {
646
+ return WORKSPACES_ROOT;
647
+ }
648
+ if (inputPath.startsWith('~/') || inputPath.startsWith('~\\')) {
649
+ return path.join(WORKSPACES_ROOT, inputPath.slice(2));
650
+ }
651
+ return inputPath;
652
+ };
653
+
654
+ // Browse filesystem endpoint for project suggestions - uses existing getFileTree
655
+ app.get('/api/browse-filesystem', authenticateToken, async (req, res) => {
656
+ try {
657
+ const { path: dirPath } = req.query;
658
+
659
+ console.log('[API] Browse filesystem request for path:', dirPath);
660
+ console.log('[API] WORKSPACES_ROOT is:', WORKSPACES_ROOT);
661
+ // Default to home directory if no path provided
662
+ const defaultRoot = WORKSPACES_ROOT;
663
+ let targetPath = dirPath ? expandWorkspacePath(dirPath) : defaultRoot;
664
+
665
+ // Resolve and normalize the path
666
+ targetPath = path.resolve(targetPath);
667
+
668
+ // Security check - ensure path is within allowed workspace root
669
+ const validation = await validateWorkspacePath(targetPath);
670
+ if (!validation.valid) {
671
+ return res.status(403).json({ error: validation.error });
672
+ }
673
+ const resolvedPath = validation.resolvedPath || targetPath;
674
+
675
+ // Security check - ensure path is accessible
676
+ try {
677
+ await fs.promises.access(resolvedPath);
678
+ const stats = await fs.promises.stat(resolvedPath);
679
+
680
+ if (!stats.isDirectory()) {
681
+ return res.status(400).json({ error: 'Path is not a directory' });
682
+ }
683
+ } catch (err) {
684
+ return res.status(404).json({ error: 'Directory not accessible' });
685
+ }
686
+
687
+ // Use existing getFileTree function with shallow depth (only direct children)
688
+ const fileTree = await getFileTree(resolvedPath, 1, 0, false); // maxDepth=1, showHidden=false
689
+
690
+ // Filter only directories and format for suggestions
691
+ const directories = fileTree
692
+ .filter(item => item.type === 'directory')
693
+ .map(item => ({
694
+ path: item.path,
695
+ name: item.name,
696
+ type: 'directory'
697
+ }))
698
+ .sort((a, b) => {
699
+ const aHidden = a.name.startsWith('.');
700
+ const bHidden = b.name.startsWith('.');
701
+ if (aHidden && !bHidden) return 1;
702
+ if (!aHidden && bHidden) return -1;
703
+ return a.name.localeCompare(b.name);
704
+ });
705
+
706
+ // Add common directories if browsing home directory
707
+ const suggestions = [];
708
+ let resolvedWorkspaceRoot = defaultRoot;
709
+ try {
710
+ resolvedWorkspaceRoot = await fsPromises.realpath(defaultRoot);
711
+ } catch (error) {
712
+ // Use default root as-is if realpath fails
713
+ }
714
+ if (resolvedPath === resolvedWorkspaceRoot) {
715
+ const commonDirs = ['Desktop', 'Documents', 'Projects', 'Development', 'Dev', 'Code', 'workspace'];
716
+ const existingCommon = directories.filter(dir => commonDirs.includes(dir.name));
717
+ const otherDirs = directories.filter(dir => !commonDirs.includes(dir.name));
718
+
719
+ suggestions.push(...existingCommon, ...otherDirs);
720
+ } else {
721
+ suggestions.push(...directories);
722
+ }
723
+
724
+ res.json({
725
+ path: resolvedPath,
726
+ suggestions: suggestions
727
+ });
728
+
729
+ } catch (error) {
730
+ console.error('Error browsing filesystem:', error);
731
+ res.status(500).json({ error: 'Failed to browse filesystem' });
732
+ }
733
+ });
734
+
735
+ app.post('/api/create-folder', authenticateToken, async (req, res) => {
736
+ try {
737
+ const { path: folderPath } = req.body;
738
+ if (!folderPath) {
739
+ return res.status(400).json({ error: 'Path is required' });
740
+ }
741
+ const expandedPath = expandWorkspacePath(folderPath);
742
+ const resolvedInput = path.resolve(expandedPath);
743
+ const validation = await validateWorkspacePath(resolvedInput);
744
+ if (!validation.valid) {
745
+ return res.status(403).json({ error: validation.error });
746
+ }
747
+ const targetPath = validation.resolvedPath || resolvedInput;
748
+ const parentDir = path.dirname(targetPath);
749
+ try {
750
+ await fs.promises.access(parentDir);
751
+ } catch (err) {
752
+ return res.status(404).json({ error: 'Parent directory does not exist' });
753
+ }
754
+ try {
755
+ await fs.promises.access(targetPath);
756
+ return res.status(409).json({ error: 'Folder already exists' });
757
+ } catch (err) {
758
+ // Folder doesn't exist, which is what we want
759
+ }
760
+ try {
761
+ await fs.promises.mkdir(targetPath, { recursive: false });
762
+ res.json({ success: true, path: targetPath });
763
+ } catch (mkdirError) {
764
+ if (mkdirError.code === 'EEXIST') {
765
+ return res.status(409).json({ error: 'Folder already exists' });
766
+ }
767
+ throw mkdirError;
768
+ }
769
+ } catch (error) {
770
+ console.error('Error creating folder:', error);
771
+ res.status(500).json({ error: 'Failed to create folder' });
772
+ }
773
+ });
774
+
775
+ // Read file content endpoint
776
+ app.get('/api/projects/:projectName/file', authenticateToken, async (req, res) => {
777
+ try {
778
+ const { projectName } = req.params;
779
+ const { filePath } = req.query;
780
+
781
+
782
+ // Security: ensure the requested path is inside the project root
783
+ if (!filePath) {
784
+ return res.status(400).json({ error: 'Invalid file path' });
785
+ }
786
+
787
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
788
+ if (!projectRoot) {
789
+ return res.status(404).json({ error: 'Project not found' });
790
+ }
791
+
792
+ // Handle both absolute and relative paths
793
+ const resolved = path.isAbsolute(filePath)
794
+ ? path.resolve(filePath)
795
+ : path.resolve(projectRoot, filePath);
796
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
797
+ if (!resolved.startsWith(normalizedRoot)) {
798
+ return res.status(403).json({ error: 'Path must be under project root' });
799
+ }
800
+
801
+ const content = await fsPromises.readFile(resolved, 'utf8');
802
+ res.json({ content, path: resolved });
803
+ } catch (error) {
804
+ console.error('Error reading file:', error);
805
+ if (error.code === 'ENOENT') {
806
+ res.status(404).json({ error: 'File not found' });
807
+ } else if (error.code === 'EACCES') {
808
+ res.status(403).json({ error: 'Permission denied' });
809
+ } else {
810
+ res.status(500).json({ error: error.message });
811
+ }
812
+ }
813
+ });
814
+
815
+ // Serve binary file content endpoint (for images, etc.)
816
+ app.get('/api/projects/:projectName/files/content', authenticateToken, async (req, res) => {
817
+ try {
818
+ const { projectName } = req.params;
819
+ const { path: filePath } = req.query;
820
+
821
+
822
+ // Security: ensure the requested path is inside the project root
823
+ if (!filePath) {
824
+ return res.status(400).json({ error: 'Invalid file path' });
825
+ }
826
+
827
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
828
+ if (!projectRoot) {
829
+ return res.status(404).json({ error: 'Project not found' });
830
+ }
831
+
832
+ const resolved = path.resolve(filePath);
833
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
834
+ if (!resolved.startsWith(normalizedRoot)) {
835
+ return res.status(403).json({ error: 'Path must be under project root' });
836
+ }
837
+
838
+ // Check if file exists
839
+ try {
840
+ await fsPromises.access(resolved);
841
+ } catch (error) {
842
+ return res.status(404).json({ error: 'File not found' });
843
+ }
844
+
845
+ // Get file extension and set appropriate content type
846
+ const mimeType = mime.lookup(resolved) || 'application/octet-stream';
847
+ res.setHeader('Content-Type', mimeType);
848
+
849
+ // Stream the file
850
+ const fileStream = fs.createReadStream(resolved);
851
+ fileStream.pipe(res);
852
+
853
+ fileStream.on('error', (error) => {
854
+ console.error('Error streaming file:', error);
855
+ if (!res.headersSent) {
856
+ res.status(500).json({ error: 'Error reading file' });
857
+ }
858
+ });
859
+
860
+ } catch (error) {
861
+ console.error('Error serving binary file:', error);
862
+ if (!res.headersSent) {
863
+ res.status(500).json({ error: error.message });
864
+ }
865
+ }
866
+ });
867
+
868
+ // Save file content endpoint
869
+ app.put('/api/projects/:projectName/file', authenticateToken, async (req, res) => {
870
+ try {
871
+ const { projectName } = req.params;
872
+ const { filePath, content } = req.body;
873
+
874
+
875
+ // Security: ensure the requested path is inside the project root
876
+ if (!filePath) {
877
+ return res.status(400).json({ error: 'Invalid file path' });
878
+ }
879
+
880
+ if (content === undefined) {
881
+ return res.status(400).json({ error: 'Content is required' });
882
+ }
883
+
884
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
885
+ if (!projectRoot) {
886
+ return res.status(404).json({ error: 'Project not found' });
887
+ }
888
+
889
+ // Handle both absolute and relative paths
890
+ const resolved = path.isAbsolute(filePath)
891
+ ? path.resolve(filePath)
892
+ : path.resolve(projectRoot, filePath);
893
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
894
+ if (!resolved.startsWith(normalizedRoot)) {
895
+ return res.status(403).json({ error: 'Path must be under project root' });
896
+ }
897
+
898
+ // Write the new content
899
+ await fsPromises.writeFile(resolved, content, 'utf8');
900
+
901
+ res.json({
902
+ success: true,
903
+ path: resolved,
904
+ message: 'File saved successfully'
905
+ });
906
+ } catch (error) {
907
+ console.error('Error saving file:', error);
908
+ if (error.code === 'ENOENT') {
909
+ res.status(404).json({ error: 'File or directory not found' });
910
+ } else if (error.code === 'EACCES') {
911
+ res.status(403).json({ error: 'Permission denied' });
912
+ } else {
913
+ res.status(500).json({ error: error.message });
914
+ }
915
+ }
916
+ });
917
+
918
+ app.get('/api/projects/:projectName/files', authenticateToken, async (req, res) => {
919
+ try {
920
+
921
+ // Using fsPromises from import
922
+
923
+ // Use extractProjectDirectory to get the actual project path
924
+ let actualPath;
925
+ try {
926
+ actualPath = await extractProjectDirectory(req.params.projectName);
927
+ } catch (error) {
928
+ console.error('Error extracting project directory:', error);
929
+ // Fallback to simple dash replacement
930
+ actualPath = req.params.projectName.replace(/-/g, '/');
931
+ }
932
+
933
+ // Check if path exists
934
+ try {
935
+ await fsPromises.access(actualPath);
936
+ } catch (e) {
937
+ return res.status(404).json({ error: `Project path not found: ${actualPath}` });
938
+ }
939
+
940
+ const files = await getFileTree(actualPath, 10, 0, true);
941
+ res.json(files);
942
+ } catch (error) {
943
+ console.error('[ERROR] File tree error:', error.message);
944
+ res.status(500).json({ error: error.message });
945
+ }
946
+ });
947
+
948
+ // ============================================================================
949
+ // FILE OPERATIONS API ENDPOINTS
950
+ // ============================================================================
951
+
952
+ /**
953
+ * Validate that a path is within the project root
954
+ * @param {string} projectRoot - The project root path
955
+ * @param {string} targetPath - The path to validate
956
+ * @returns {{ valid: boolean, resolved?: string, error?: string }}
957
+ */
958
+ function validatePathInProject(projectRoot, targetPath) {
959
+ const resolved = path.isAbsolute(targetPath)
960
+ ? path.resolve(targetPath)
961
+ : path.resolve(projectRoot, targetPath);
962
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
963
+ if (!resolved.startsWith(normalizedRoot)) {
964
+ return { valid: false, error: 'Path must be under project root' };
965
+ }
966
+ return { valid: true, resolved };
967
+ }
968
+
969
+ /**
970
+ * Validate filename - check for invalid characters
971
+ * @param {string} name - The filename to validate
972
+ * @returns {{ valid: boolean, error?: string }}
973
+ */
974
+ function validateFilename(name) {
975
+ if (!name || !name.trim()) {
976
+ return { valid: false, error: 'Filename cannot be empty' };
977
+ }
978
+ // Check for invalid characters (Windows + Unix)
979
+ const invalidChars = /[<>:"/\\|?*\x00-\x1f]/;
980
+ if (invalidChars.test(name)) {
981
+ return { valid: false, error: 'Filename contains invalid characters' };
982
+ }
983
+ // Check for reserved names (Windows)
984
+ const reserved = /^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$/i;
985
+ if (reserved.test(name)) {
986
+ return { valid: false, error: 'Filename is a reserved name' };
987
+ }
988
+ // Check for dots only
989
+ if (/^\.+$/.test(name)) {
990
+ return { valid: false, error: 'Filename cannot be only dots' };
991
+ }
992
+ return { valid: true };
993
+ }
994
+
995
+ // POST /api/projects/:projectName/files/create - Create new file or directory
996
+ app.post('/api/projects/:projectName/files/create', authenticateToken, async (req, res) => {
997
+ try {
998
+ const { projectName } = req.params;
999
+ const { path: parentPath, type, name } = req.body;
1000
+
1001
+ // Validate input
1002
+ if (!name || !type) {
1003
+ return res.status(400).json({ error: 'Name and type are required' });
1004
+ }
1005
+
1006
+ if (!['file', 'directory'].includes(type)) {
1007
+ return res.status(400).json({ error: 'Type must be "file" or "directory"' });
1008
+ }
1009
+
1010
+ const nameValidation = validateFilename(name);
1011
+ if (!nameValidation.valid) {
1012
+ return res.status(400).json({ error: nameValidation.error });
1013
+ }
1014
+
1015
+ // Get project root
1016
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
1017
+ if (!projectRoot) {
1018
+ return res.status(404).json({ error: 'Project not found' });
1019
+ }
1020
+
1021
+ // Build and validate target path
1022
+ const targetDir = parentPath || '';
1023
+ const targetPath = targetDir ? path.join(targetDir, name) : name;
1024
+ const validation = validatePathInProject(projectRoot, targetPath);
1025
+ if (!validation.valid) {
1026
+ return res.status(403).json({ error: validation.error });
1027
+ }
1028
+
1029
+ const resolvedPath = validation.resolved;
1030
+
1031
+ // Check if already exists
1032
+ try {
1033
+ await fsPromises.access(resolvedPath);
1034
+ return res.status(409).json({ error: `${type === 'file' ? 'File' : 'Directory'} already exists` });
1035
+ } catch {
1036
+ // Doesn't exist, which is what we want
1037
+ }
1038
+
1039
+ // Create file or directory
1040
+ if (type === 'directory') {
1041
+ await fsPromises.mkdir(resolvedPath, { recursive: false });
1042
+ } else {
1043
+ // Ensure parent directory exists
1044
+ const parentDir = path.dirname(resolvedPath);
1045
+ try {
1046
+ await fsPromises.access(parentDir);
1047
+ } catch {
1048
+ await fsPromises.mkdir(parentDir, { recursive: true });
1049
+ }
1050
+ await fsPromises.writeFile(resolvedPath, '', 'utf8');
1051
+ }
1052
+
1053
+ res.json({
1054
+ success: true,
1055
+ path: resolvedPath,
1056
+ name,
1057
+ type,
1058
+ message: `${type === 'file' ? 'File' : 'Directory'} created successfully`
1059
+ });
1060
+ } catch (error) {
1061
+ console.error('Error creating file/directory:', error);
1062
+ if (error.code === 'EACCES') {
1063
+ res.status(403).json({ error: 'Permission denied' });
1064
+ } else if (error.code === 'ENOENT') {
1065
+ res.status(404).json({ error: 'Parent directory not found' });
1066
+ } else {
1067
+ res.status(500).json({ error: error.message });
1068
+ }
1069
+ }
1070
+ });
1071
+
1072
+ // PUT /api/projects/:projectName/files/rename - Rename file or directory
1073
+ app.put('/api/projects/:projectName/files/rename', authenticateToken, async (req, res) => {
1074
+ try {
1075
+ const { projectName } = req.params;
1076
+ const { oldPath, newName } = req.body;
1077
+
1078
+ // Validate input
1079
+ if (!oldPath || !newName) {
1080
+ return res.status(400).json({ error: 'oldPath and newName are required' });
1081
+ }
1082
+
1083
+ const nameValidation = validateFilename(newName);
1084
+ if (!nameValidation.valid) {
1085
+ return res.status(400).json({ error: nameValidation.error });
1086
+ }
1087
+
1088
+ // Get project root
1089
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
1090
+ if (!projectRoot) {
1091
+ return res.status(404).json({ error: 'Project not found' });
1092
+ }
1093
+
1094
+ // Validate old path
1095
+ const oldValidation = validatePathInProject(projectRoot, oldPath);
1096
+ if (!oldValidation.valid) {
1097
+ return res.status(403).json({ error: oldValidation.error });
1098
+ }
1099
+
1100
+ const resolvedOldPath = oldValidation.resolved;
1101
+
1102
+ // Check if old path exists
1103
+ try {
1104
+ await fsPromises.access(resolvedOldPath);
1105
+ } catch {
1106
+ return res.status(404).json({ error: 'File or directory not found' });
1107
+ }
1108
+
1109
+ // Build and validate new path
1110
+ const parentDir = path.dirname(resolvedOldPath);
1111
+ const resolvedNewPath = path.join(parentDir, newName);
1112
+ const newValidation = validatePathInProject(projectRoot, resolvedNewPath);
1113
+ if (!newValidation.valid) {
1114
+ return res.status(403).json({ error: newValidation.error });
1115
+ }
1116
+
1117
+ // Check if new path already exists
1118
+ try {
1119
+ await fsPromises.access(resolvedNewPath);
1120
+ return res.status(409).json({ error: 'A file or directory with this name already exists' });
1121
+ } catch {
1122
+ // Doesn't exist, which is what we want
1123
+ }
1124
+
1125
+ // Rename
1126
+ await fsPromises.rename(resolvedOldPath, resolvedNewPath);
1127
+
1128
+ res.json({
1129
+ success: true,
1130
+ oldPath: resolvedOldPath,
1131
+ newPath: resolvedNewPath,
1132
+ newName,
1133
+ message: 'Renamed successfully'
1134
+ });
1135
+ } catch (error) {
1136
+ console.error('Error renaming file/directory:', error);
1137
+ if (error.code === 'EACCES') {
1138
+ res.status(403).json({ error: 'Permission denied' });
1139
+ } else if (error.code === 'ENOENT') {
1140
+ res.status(404).json({ error: 'File or directory not found' });
1141
+ } else if (error.code === 'EXDEV') {
1142
+ res.status(400).json({ error: 'Cannot move across different filesystems' });
1143
+ } else {
1144
+ res.status(500).json({ error: error.message });
1145
+ }
1146
+ }
1147
+ });
1148
+
1149
+ // DELETE /api/projects/:projectName/files - Delete file or directory
1150
+ app.delete('/api/projects/:projectName/files', authenticateToken, async (req, res) => {
1151
+ try {
1152
+ const { projectName } = req.params;
1153
+ const { path: targetPath, type } = req.body;
1154
+
1155
+ // Validate input
1156
+ if (!targetPath) {
1157
+ return res.status(400).json({ error: 'Path is required' });
1158
+ }
1159
+
1160
+ // Get project root
1161
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
1162
+ if (!projectRoot) {
1163
+ return res.status(404).json({ error: 'Project not found' });
1164
+ }
1165
+
1166
+ // Validate path
1167
+ const validation = validatePathInProject(projectRoot, targetPath);
1168
+ if (!validation.valid) {
1169
+ return res.status(403).json({ error: validation.error });
1170
+ }
1171
+
1172
+ const resolvedPath = validation.resolved;
1173
+
1174
+ // Check if path exists and get stats
1175
+ let stats;
1176
+ try {
1177
+ stats = await fsPromises.stat(resolvedPath);
1178
+ } catch {
1179
+ return res.status(404).json({ error: 'File or directory not found' });
1180
+ }
1181
+
1182
+ // Prevent deleting the project root itself
1183
+ if (resolvedPath === path.resolve(projectRoot)) {
1184
+ return res.status(403).json({ error: 'Cannot delete project root directory' });
1185
+ }
1186
+
1187
+ // Delete based on type
1188
+ if (stats.isDirectory()) {
1189
+ await fsPromises.rm(resolvedPath, { recursive: true, force: true });
1190
+ } else {
1191
+ await fsPromises.unlink(resolvedPath);
1192
+ }
1193
+
1194
+ res.json({
1195
+ success: true,
1196
+ path: resolvedPath,
1197
+ type: stats.isDirectory() ? 'directory' : 'file',
1198
+ message: 'Deleted successfully'
1199
+ });
1200
+ } catch (error) {
1201
+ console.error('Error deleting file/directory:', error);
1202
+ if (error.code === 'EACCES') {
1203
+ res.status(403).json({ error: 'Permission denied' });
1204
+ } else if (error.code === 'ENOENT') {
1205
+ res.status(404).json({ error: 'File or directory not found' });
1206
+ } else if (error.code === 'ENOTEMPTY') {
1207
+ res.status(400).json({ error: 'Directory is not empty' });
1208
+ } else {
1209
+ res.status(500).json({ error: error.message });
1210
+ }
1211
+ }
1212
+ });
1213
+
1214
+ // POST /api/projects/:projectName/files/upload - Upload files
1215
+ // Dynamic import of multer for file uploads
1216
+ const uploadFilesHandler = async (req, res) => {
1217
+ // Dynamic import of multer
1218
+ const multer = (await import('multer')).default;
1219
+
1220
+ const uploadMiddleware = multer({
1221
+ storage: multer.diskStorage({
1222
+ destination: (req, file, cb) => {
1223
+ cb(null, os.tmpdir());
1224
+ },
1225
+ filename: (req, file, cb) => {
1226
+ // Use a unique temp name, but preserve original name in file.originalname
1227
+ // Note: file.originalname may contain path separators for folder uploads
1228
+ const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
1229
+ // For temp file, just use a safe unique name without the path
1230
+ cb(null, `upload-${uniqueSuffix}`);
1231
+ }
1232
+ }),
1233
+ limits: {
1234
+ fileSize: 50 * 1024 * 1024, // 50MB limit
1235
+ files: 20 // Max 20 files at once
1236
+ }
1237
+ });
1238
+
1239
+ // Use multer middleware
1240
+ uploadMiddleware.array('files', 20)(req, res, async (err) => {
1241
+ if (err) {
1242
+ console.error('Multer error:', err);
1243
+ if (err.code === 'LIMIT_FILE_SIZE') {
1244
+ return res.status(400).json({ error: 'File too large. Maximum size is 50MB.' });
1245
+ }
1246
+ if (err.code === 'LIMIT_FILE_COUNT') {
1247
+ return res.status(400).json({ error: 'Too many files. Maximum is 20 files.' });
1248
+ }
1249
+ return res.status(500).json({ error: err.message });
1250
+ }
1251
+
1252
+ try {
1253
+ const { projectName } = req.params;
1254
+ const { targetPath, relativePaths } = req.body;
1255
+
1256
+ // Parse relative paths if provided (for folder uploads)
1257
+ let filePaths = [];
1258
+ if (relativePaths) {
1259
+ try {
1260
+ filePaths = JSON.parse(relativePaths);
1261
+ } catch (e) {
1262
+ console.log('[DEBUG] Failed to parse relativePaths:', relativePaths);
1263
+ }
1264
+ }
1265
+
1266
+ console.log('[DEBUG] File upload request:', {
1267
+ projectName,
1268
+ targetPath: JSON.stringify(targetPath),
1269
+ targetPathType: typeof targetPath,
1270
+ filesCount: req.files?.length,
1271
+ relativePaths: filePaths
1272
+ });
1273
+
1274
+ if (!req.files || req.files.length === 0) {
1275
+ return res.status(400).json({ error: 'No files provided' });
1276
+ }
1277
+
1278
+ // Get project root
1279
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
1280
+ if (!projectRoot) {
1281
+ return res.status(404).json({ error: 'Project not found' });
1282
+ }
1283
+
1284
+ console.log('[DEBUG] Project root:', projectRoot);
1285
+
1286
+ // Validate and resolve target path
1287
+ // If targetPath is empty or '.', use project root directly
1288
+ const targetDir = targetPath || '';
1289
+ let resolvedTargetDir;
1290
+
1291
+ console.log('[DEBUG] Target dir:', JSON.stringify(targetDir));
1292
+
1293
+ if (!targetDir || targetDir === '.' || targetDir === './') {
1294
+ // Empty path means upload to project root
1295
+ resolvedTargetDir = path.resolve(projectRoot);
1296
+ console.log('[DEBUG] Using project root as target:', resolvedTargetDir);
1297
+ } else {
1298
+ const validation = validatePathInProject(projectRoot, targetDir);
1299
+ if (!validation.valid) {
1300
+ console.log('[DEBUG] Path validation failed:', validation.error);
1301
+ return res.status(403).json({ error: validation.error });
1302
+ }
1303
+ resolvedTargetDir = validation.resolved;
1304
+ console.log('[DEBUG] Resolved target dir:', resolvedTargetDir);
1305
+ }
1306
+
1307
+ // Ensure target directory exists
1308
+ try {
1309
+ await fsPromises.access(resolvedTargetDir);
1310
+ } catch {
1311
+ await fsPromises.mkdir(resolvedTargetDir, { recursive: true });
1312
+ }
1313
+
1314
+ // Move uploaded files from temp to target directory
1315
+ const uploadedFiles = [];
1316
+ console.log('[DEBUG] Processing files:', req.files.map(f => ({ originalname: f.originalname, path: f.path })));
1317
+ for (let i = 0; i < req.files.length; i++) {
1318
+ const file = req.files[i];
1319
+ // Use relative path if provided (for folder uploads), otherwise use originalname
1320
+ const fileName = (filePaths && filePaths[i]) ? filePaths[i] : file.originalname;
1321
+ console.log('[DEBUG] Processing file:', fileName, '(originalname:', file.originalname + ')');
1322
+ const destPath = path.join(resolvedTargetDir, fileName);
1323
+
1324
+ // Validate destination path
1325
+ const destValidation = validatePathInProject(projectRoot, destPath);
1326
+ if (!destValidation.valid) {
1327
+ console.log('[DEBUG] Destination validation failed for:', destPath);
1328
+ // Clean up temp file
1329
+ await fsPromises.unlink(file.path).catch(() => {});
1330
+ continue;
1331
+ }
1332
+
1333
+ // Ensure parent directory exists (for nested files from folder upload)
1334
+ const parentDir = path.dirname(destPath);
1335
+ try {
1336
+ await fsPromises.access(parentDir);
1337
+ } catch {
1338
+ await fsPromises.mkdir(parentDir, { recursive: true });
1339
+ }
1340
+
1341
+ // Move file (copy + unlink to handle cross-device scenarios)
1342
+ await fsPromises.copyFile(file.path, destPath);
1343
+ await fsPromises.unlink(file.path);
1344
+
1345
+ uploadedFiles.push({
1346
+ name: fileName,
1347
+ path: destPath,
1348
+ size: file.size,
1349
+ mimeType: file.mimetype
1350
+ });
1351
+ }
1352
+
1353
+ res.json({
1354
+ success: true,
1355
+ files: uploadedFiles,
1356
+ targetPath: resolvedTargetDir,
1357
+ message: `Uploaded ${uploadedFiles.length} file(s) successfully`
1358
+ });
1359
+ } catch (error) {
1360
+ console.error('Error uploading files:', error);
1361
+ // Clean up any remaining temp files
1362
+ if (req.files) {
1363
+ for (const file of req.files) {
1364
+ await fsPromises.unlink(file.path).catch(() => {});
1365
+ }
1366
+ }
1367
+ if (error.code === 'EACCES') {
1368
+ res.status(403).json({ error: 'Permission denied' });
1369
+ } else {
1370
+ res.status(500).json({ error: error.message });
1371
+ }
1372
+ }
1373
+ });
1374
+ };
1375
+
1376
+ app.post('/api/projects/:projectName/files/upload', authenticateToken, uploadFilesHandler);
1377
+
1378
+ /**
1379
+ * Proxy an authenticated client WebSocket to a plugin's internal WS server.
1380
+ * Auth is enforced by verifyClient before this function is reached.
1381
+ */
1382
+ function handlePluginWsProxy(clientWs, pathname) {
1383
+ const pluginName = pathname.replace('/plugin-ws/', '');
1384
+ if (!pluginName || /[^a-zA-Z0-9_-]/.test(pluginName)) {
1385
+ clientWs.close(4400, 'Invalid plugin name');
1386
+ return;
1387
+ }
1388
+
1389
+ const port = getPluginPort(pluginName);
1390
+ if (!port) {
1391
+ clientWs.close(4404, 'Plugin not running');
1392
+ return;
1393
+ }
1394
+
1395
+ const upstream = new WebSocket(`ws://127.0.0.1:${port}/ws`);
1396
+
1397
+ upstream.on('open', () => {
1398
+ console.log(`[Plugins] WS proxy connected to "${pluginName}" on port ${port}`);
1399
+ });
1400
+
1401
+ // Relay messages bidirectionally
1402
+ upstream.on('message', (data) => {
1403
+ if (clientWs.readyState === WebSocket.OPEN) clientWs.send(data);
1404
+ });
1405
+ clientWs.on('message', (data) => {
1406
+ if (upstream.readyState === WebSocket.OPEN) upstream.send(data);
1407
+ });
1408
+
1409
+ // Propagate close in both directions
1410
+ upstream.on('close', () => { if (clientWs.readyState === WebSocket.OPEN) clientWs.close(); });
1411
+ clientWs.on('close', () => { if (upstream.readyState === WebSocket.OPEN) upstream.close(); });
1412
+
1413
+ upstream.on('error', (err) => {
1414
+ console.error(`[Plugins] WS proxy error for "${pluginName}":`, err.message);
1415
+ if (clientWs.readyState === WebSocket.OPEN) clientWs.close(4502, 'Upstream error');
1416
+ });
1417
+ clientWs.on('error', () => {
1418
+ if (upstream.readyState === WebSocket.OPEN) upstream.close();
1419
+ });
1420
+ }
1421
+
1422
+ // WebSocket connection handler that routes based on URL path
1423
+ wss.on('connection', (ws, request) => {
1424
+ const url = request.url;
1425
+ console.log('[INFO] Client connected to:', url);
1426
+
1427
+ // Parse URL to get pathname without query parameters
1428
+ const urlObj = new URL(url, 'http://localhost');
1429
+ const pathname = urlObj.pathname;
1430
+
1431
+ if (pathname === '/shell') {
1432
+ handleShellConnection(ws);
1433
+ } else if (pathname === '/ws') {
1434
+ handleChatConnection(ws, request);
1435
+ } else if (pathname.startsWith('/plugin-ws/')) {
1436
+ handlePluginWsProxy(ws, pathname);
1437
+ } else {
1438
+ console.log('[WARN] Unknown WebSocket path:', pathname);
1439
+ ws.close();
1440
+ }
1441
+ });
1442
+
1443
+ /**
1444
+ * WebSocket Writer - Wrapper for WebSocket to match SSEStreamWriter interface
1445
+ *
1446
+ * Provider files use `createNormalizedMessage()` from `providers/types.js` and
1447
+ * adapter `normalizeMessage()` to produce unified NormalizedMessage events.
1448
+ * The writer simply serialises and sends.
1449
+ */
1450
+ class WebSocketWriter {
1451
+ constructor(ws, userId = null) {
1452
+ this.ws = ws;
1453
+ this.sessionId = null;
1454
+ this.userId = userId;
1455
+ this.isWebSocketWriter = true; // Marker for transport detection
1456
+ }
1457
+
1458
+ send(data) {
1459
+ if (this.ws.readyState === 1) { // WebSocket.OPEN
1460
+ this.ws.send(JSON.stringify(data));
1461
+ }
1462
+ }
1463
+
1464
+ updateWebSocket(newRawWs) {
1465
+ this.ws = newRawWs;
1466
+ }
1467
+
1468
+ setSessionId(sessionId) {
1469
+ this.sessionId = sessionId;
1470
+ }
1471
+
1472
+ getSessionId() {
1473
+ return this.sessionId;
1474
+ }
1475
+ }
1476
+
1477
+ // Handle chat WebSocket connections
1478
+ function handleChatConnection(ws, request) {
1479
+ console.log('[INFO] Chat WebSocket connected');
1480
+
1481
+ // Add to connected clients for project updates
1482
+ connectedClients.add(ws);
1483
+
1484
+ // Wrap WebSocket with writer for consistent interface with SSEStreamWriter
1485
+ const writer = new WebSocketWriter(ws, request?.user?.id ?? request?.user?.userId ?? null);
1486
+
1487
+ ws.on('message', async (message) => {
1488
+ try {
1489
+ const data = JSON.parse(message);
1490
+
1491
+ if (data.type === 'claude-command') {
1492
+ console.log('[DEBUG] User message:', data.command || '[Continue/Resume]');
1493
+ console.log('📁 Project:', data.options?.projectPath || 'Unknown');
1494
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
1495
+
1496
+ // Use Claude Agents SDK
1497
+ await queryClaudeSDK(data.command, data.options, writer);
1498
+ } else if (data.type === 'cursor-command') {
1499
+ console.log('[DEBUG] Cursor message:', data.command || '[Continue/Resume]');
1500
+ console.log('📁 Project:', data.options?.cwd || 'Unknown');
1501
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
1502
+ console.log('🤖 Model:', data.options?.model || 'default');
1503
+ await spawnCursor(data.command, data.options, writer);
1504
+ } else if (data.type === 'codex-command') {
1505
+ console.log('[DEBUG] Codex message:', data.command || '[Continue/Resume]');
1506
+ console.log('📁 Project:', data.options?.projectPath || data.options?.cwd || 'Unknown');
1507
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
1508
+ console.log('🤖 Model:', data.options?.model || 'default');
1509
+ await queryCodex(data.command, data.options, writer);
1510
+ } else if (data.type === 'gemini-command') {
1511
+ console.log('[DEBUG] Gemini message:', data.command || '[Continue/Resume]');
1512
+ console.log('📁 Project:', data.options?.projectPath || data.options?.cwd || 'Unknown');
1513
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
1514
+ console.log('🤖 Model:', data.options?.model || 'default');
1515
+ await spawnGemini(data.command, data.options, writer);
1516
+ } else if (data.type === 'cursor-resume') {
1517
+ // Backward compatibility: treat as cursor-command with resume and no prompt
1518
+ console.log('[DEBUG] Cursor resume session (compat):', data.sessionId);
1519
+ await spawnCursor('', {
1520
+ sessionId: data.sessionId,
1521
+ resume: true,
1522
+ cwd: data.options?.cwd
1523
+ }, writer);
1524
+ } else if (data.type === 'abort-session') {
1525
+ console.log('[DEBUG] Abort session request:', data.sessionId);
1526
+ const provider = data.provider || 'claude';
1527
+ let success;
1528
+
1529
+ if (provider === 'cursor') {
1530
+ success = abortCursorSession(data.sessionId);
1531
+ } else if (provider === 'codex') {
1532
+ success = abortCodexSession(data.sessionId);
1533
+ } else if (provider === 'gemini') {
1534
+ success = abortGeminiSession(data.sessionId);
1535
+ } else {
1536
+ // Use Claude Agents SDK
1537
+ success = await abortClaudeSDKSession(data.sessionId);
1538
+ }
1539
+
1540
+ writer.send(createNormalizedMessage({ kind: 'complete', exitCode: success ? 0 : 1, aborted: true, success, sessionId: data.sessionId, provider }));
1541
+ } else if (data.type === 'claude-permission-response') {
1542
+ // Relay UI approval decisions back into the SDK control flow.
1543
+ // This does not persist permissions; it only resolves the in-flight request,
1544
+ // introduced so the SDK can resume once the user clicks Allow/Deny.
1545
+ if (data.requestId) {
1546
+ resolveToolApproval(data.requestId, {
1547
+ allow: Boolean(data.allow),
1548
+ updatedInput: data.updatedInput,
1549
+ message: data.message,
1550
+ rememberEntry: data.rememberEntry
1551
+ });
1552
+ }
1553
+ } else if (data.type === 'cursor-abort') {
1554
+ console.log('[DEBUG] Abort Cursor session:', data.sessionId);
1555
+ const success = abortCursorSession(data.sessionId);
1556
+ writer.send(createNormalizedMessage({ kind: 'complete', exitCode: success ? 0 : 1, aborted: true, success, sessionId: data.sessionId, provider: 'cursor' }));
1557
+ } else if (data.type === 'check-session-status') {
1558
+ // Check if a specific session is currently processing
1559
+ const provider = data.provider || 'claude';
1560
+ const sessionId = data.sessionId;
1561
+ let isActive;
1562
+
1563
+ if (provider === 'cursor') {
1564
+ isActive = isCursorSessionActive(sessionId);
1565
+ } else if (provider === 'codex') {
1566
+ isActive = isCodexSessionActive(sessionId);
1567
+ } else if (provider === 'gemini') {
1568
+ isActive = isGeminiSessionActive(sessionId);
1569
+ } else {
1570
+ // Use Claude Agents SDK
1571
+ isActive = isClaudeSDKSessionActive(sessionId);
1572
+ if (isActive) {
1573
+ // Reconnect the session's writer to the new WebSocket so
1574
+ // subsequent SDK output flows to the refreshed client.
1575
+ reconnectSessionWriter(sessionId, ws);
1576
+ }
1577
+ }
1578
+
1579
+ writer.send({
1580
+ type: 'session-status',
1581
+ sessionId,
1582
+ provider,
1583
+ isProcessing: isActive
1584
+ });
1585
+ } else if (data.type === 'get-pending-permissions') {
1586
+ // Return pending permission requests for a session
1587
+ const sessionId = data.sessionId;
1588
+ if (sessionId && isClaudeSDKSessionActive(sessionId)) {
1589
+ const pending = getPendingApprovalsForSession(sessionId);
1590
+ writer.send({
1591
+ type: 'pending-permissions-response',
1592
+ sessionId,
1593
+ data: pending
1594
+ });
1595
+ }
1596
+ } else if (data.type === 'get-active-sessions') {
1597
+ // Get all currently active sessions
1598
+ const activeSessions = {
1599
+ claude: getActiveClaudeSDKSessions(),
1600
+ cursor: getActiveCursorSessions(),
1601
+ codex: getActiveCodexSessions(),
1602
+ gemini: getActiveGeminiSessions()
1603
+ };
1604
+ writer.send({
1605
+ type: 'active-sessions',
1606
+ sessions: activeSessions
1607
+ });
1608
+ }
1609
+ } catch (error) {
1610
+ console.error('[ERROR] Chat WebSocket error:', error.message);
1611
+ writer.send({
1612
+ type: 'error',
1613
+ error: error.message
1614
+ });
1615
+ }
1616
+ });
1617
+
1618
+ ws.on('close', () => {
1619
+ console.log('🔌 Chat client disconnected');
1620
+ // Remove from connected clients
1621
+ connectedClients.delete(ws);
1622
+ });
1623
+ }
1624
+
1625
+ // Handle shell WebSocket connections
1626
+ function handleShellConnection(ws) {
1627
+ console.log('🐚 Shell client connected');
1628
+ let shellProcess = null;
1629
+ let ptySessionKey = null;
1630
+ let urlDetectionBuffer = '';
1631
+ const announcedAuthUrls = new Set();
1632
+
1633
+ ws.on('message', async (message) => {
1634
+ try {
1635
+ const data = JSON.parse(message);
1636
+ console.log('📨 Shell message received:', data.type);
1637
+
1638
+ if (data.type === 'init') {
1639
+ const projectPath = data.projectPath || process.cwd();
1640
+ const sessionId = data.sessionId;
1641
+ const hasSession = data.hasSession;
1642
+ const provider = data.provider || 'claude';
1643
+ const initialCommand = data.initialCommand;
1644
+ const isPlainShell = data.isPlainShell || (!!initialCommand && !hasSession) || provider === 'plain-shell';
1645
+ urlDetectionBuffer = '';
1646
+ announcedAuthUrls.clear();
1647
+
1648
+ // Login commands (Claude/Cursor auth) should never reuse cached sessions
1649
+ const isLoginCommand = initialCommand && (
1650
+ initialCommand.includes('setup-token') ||
1651
+ initialCommand.includes('cursor-agent login') ||
1652
+ initialCommand.includes('auth login')
1653
+ );
1654
+
1655
+ // Include command hash in session key so different commands get separate sessions
1656
+ const commandSuffix = isPlainShell && initialCommand
1657
+ ? `_cmd_${Buffer.from(initialCommand).toString('base64').slice(0, 16)}`
1658
+ : '';
1659
+ ptySessionKey = `${projectPath}_${sessionId || 'default'}${commandSuffix}`;
1660
+
1661
+ // Kill any existing login session before starting fresh
1662
+ if (isLoginCommand) {
1663
+ const oldSession = ptySessionsMap.get(ptySessionKey);
1664
+ if (oldSession) {
1665
+ console.log('🧹 Cleaning up existing login session:', ptySessionKey);
1666
+ if (oldSession.timeoutId) clearTimeout(oldSession.timeoutId);
1667
+ if (oldSession.pty && oldSession.pty.kill) oldSession.pty.kill();
1668
+ ptySessionsMap.delete(ptySessionKey);
1669
+ }
1670
+ }
1671
+
1672
+ const existingSession = isLoginCommand ? null : ptySessionsMap.get(ptySessionKey);
1673
+ if (existingSession) {
1674
+ console.log('♻️ Reconnecting to existing PTY session:', ptySessionKey);
1675
+ shellProcess = existingSession.pty;
1676
+
1677
+ clearTimeout(existingSession.timeoutId);
1678
+
1679
+ ws.send(JSON.stringify({
1680
+ type: 'output',
1681
+ data: `\x1b[36m[Reconnected to existing session]\x1b[0m\r\n`
1682
+ }));
1683
+
1684
+ if (existingSession.buffer && existingSession.buffer.length > 0) {
1685
+ console.log(`📜 Sending ${existingSession.buffer.length} buffered messages`);
1686
+ existingSession.buffer.forEach(bufferedData => {
1687
+ ws.send(JSON.stringify({
1688
+ type: 'output',
1689
+ data: bufferedData
1690
+ }));
1691
+ });
1692
+ }
1693
+
1694
+ existingSession.ws = ws;
1695
+
1696
+ return;
1697
+ }
1698
+
1699
+ console.log('[INFO] Starting shell in:', projectPath);
1700
+ console.log('📋 Session info:', hasSession ? `Resume session ${sessionId}` : (isPlainShell ? 'Plain shell mode' : 'New session'));
1701
+ console.log('🤖 Provider:', isPlainShell ? 'plain-shell' : provider);
1702
+ if (initialCommand) {
1703
+ console.log('⚡ Initial command:', initialCommand);
1704
+ }
1705
+
1706
+ // First send a welcome message
1707
+ let welcomeMsg;
1708
+ if (isPlainShell) {
1709
+ welcomeMsg = `\x1b[36mStarting terminal in: ${projectPath}\x1b[0m\r\n`;
1710
+ } else {
1711
+ const providerName = provider === 'cursor' ? 'Cursor' : (provider === 'codex' ? 'Codex' : (provider === 'gemini' ? 'Gemini' : 'Claude'));
1712
+ welcomeMsg = hasSession ?
1713
+ `\x1b[36mResuming ${providerName} session ${sessionId} in: ${projectPath}\x1b[0m\r\n` :
1714
+ `\x1b[36mStarting new ${providerName} session in: ${projectPath}\x1b[0m\r\n`;
1715
+ }
1716
+
1717
+ ws.send(JSON.stringify({
1718
+ type: 'output',
1719
+ data: welcomeMsg
1720
+ }));
1721
+
1722
+ try {
1723
+ // Validate projectPath — resolve to absolute and verify it exists
1724
+ const resolvedProjectPath = path.resolve(projectPath);
1725
+ try {
1726
+ const stats = fs.statSync(resolvedProjectPath);
1727
+ if (!stats.isDirectory()) {
1728
+ throw new Error('Not a directory');
1729
+ }
1730
+ } catch (pathErr) {
1731
+ ws.send(JSON.stringify({ type: 'error', message: 'Invalid project path' }));
1732
+ return;
1733
+ }
1734
+
1735
+ // Validate sessionId — only allow safe characters
1736
+ const safeSessionIdPattern = /^[a-zA-Z0-9_.\-:]+$/;
1737
+ if (sessionId && !safeSessionIdPattern.test(sessionId)) {
1738
+ ws.send(JSON.stringify({ type: 'error', message: 'Invalid session ID' }));
1739
+ return;
1740
+ }
1741
+
1742
+ // Build shell command — use cwd for project path (never interpolate into shell string)
1743
+ let shellCommand;
1744
+ if (isPlainShell) {
1745
+ // Plain shell mode - run the initial command in the project directory
1746
+ shellCommand = initialCommand;
1747
+ } else if (provider === 'cursor') {
1748
+ if (hasSession && sessionId) {
1749
+ shellCommand = `cursor-agent --resume="${sessionId}"`;
1750
+ } else {
1751
+ shellCommand = 'cursor-agent';
1752
+ }
1753
+ } else if (provider === 'codex') {
1754
+ // Use codex command; attempt to resume and fall back to a new session when the resume fails.
1755
+ if (hasSession && sessionId) {
1756
+ if (os.platform() === 'win32') {
1757
+ // PowerShell syntax for fallback
1758
+ shellCommand = `codex resume "${sessionId}"; if ($LASTEXITCODE -ne 0) { codex }`;
1759
+ } else {
1760
+ shellCommand = `codex resume "${sessionId}" || codex`;
1761
+ }
1762
+ } else {
1763
+ shellCommand = 'codex';
1764
+ }
1765
+ } else if (provider === 'gemini') {
1766
+ const command = initialCommand || 'gemini';
1767
+ let resumeId = sessionId;
1768
+ if (hasSession && sessionId) {
1769
+ try {
1770
+ // Gemini CLI enforces its own native session IDs, unlike other agents that accept arbitrary string names.
1771
+ // The UI only knows about its internal generated `sessionId` (e.g. gemini_1234).
1772
+ // We must fetch the mapping from the backend session manager to pass the native `cliSessionId` to the shell.
1773
+ const sess = sessionManager.getSession(sessionId);
1774
+ if (sess && sess.cliSessionId) {
1775
+ resumeId = sess.cliSessionId;
1776
+ // Validate the looked-up CLI session ID too
1777
+ if (!safeSessionIdPattern.test(resumeId)) {
1778
+ resumeId = null;
1779
+ }
1780
+ }
1781
+ } catch (err) {
1782
+ console.error('Failed to get Gemini CLI session ID:', err);
1783
+ }
1784
+ }
1785
+
1786
+ if (hasSession && resumeId) {
1787
+ shellCommand = `${command} --resume "${resumeId}"`;
1788
+ } else {
1789
+ shellCommand = command;
1790
+ }
1791
+ } else {
1792
+ // Claude (default provider)
1793
+ const command = initialCommand || 'claude';
1794
+ if (hasSession && sessionId) {
1795
+ if (os.platform() === 'win32') {
1796
+ shellCommand = `claude --resume "${sessionId}"; if ($LASTEXITCODE -ne 0) { claude }`;
1797
+ } else {
1798
+ shellCommand = `claude --resume "${sessionId}" || claude`;
1799
+ }
1800
+ } else {
1801
+ shellCommand = command;
1802
+ }
1803
+ }
1804
+
1805
+ console.log('🔧 Executing shell command:', shellCommand);
1806
+
1807
+ // Use appropriate shell based on platform
1808
+ const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';
1809
+ const shellArgs = os.platform() === 'win32' ? ['-Command', shellCommand] : ['-c', shellCommand];
1810
+
1811
+ // Use terminal dimensions from client if provided, otherwise use defaults
1812
+ const termCols = data.cols || 80;
1813
+ const termRows = data.rows || 24;
1814
+ console.log('📐 Using terminal dimensions:', termCols, 'x', termRows);
1815
+
1816
+ shellProcess = pty.spawn(shell, shellArgs, {
1817
+ name: 'xterm-256color',
1818
+ cols: termCols,
1819
+ rows: termRows,
1820
+ cwd: resolvedProjectPath,
1821
+ env: {
1822
+ ...process.env,
1823
+ TERM: 'xterm-256color',
1824
+ COLORTERM: 'truecolor',
1825
+ FORCE_COLOR: '3'
1826
+ }
1827
+ });
1828
+
1829
+ console.log('🟢 Shell process started with PTY, PID:', shellProcess.pid);
1830
+
1831
+ ptySessionsMap.set(ptySessionKey, {
1832
+ pty: shellProcess,
1833
+ ws: ws,
1834
+ buffer: [],
1835
+ timeoutId: null,
1836
+ projectPath,
1837
+ sessionId
1838
+ });
1839
+
1840
+ // Handle data output
1841
+ shellProcess.onData((data) => {
1842
+ const session = ptySessionsMap.get(ptySessionKey);
1843
+ if (!session) return;
1844
+
1845
+ if (session.buffer.length < 5000) {
1846
+ session.buffer.push(data);
1847
+ } else {
1848
+ session.buffer.shift();
1849
+ session.buffer.push(data);
1850
+ }
1851
+
1852
+ if (session.ws && session.ws.readyState === WebSocket.OPEN) {
1853
+ let outputData = data;
1854
+
1855
+ const cleanChunk = stripAnsiSequences(data);
1856
+ urlDetectionBuffer = `${urlDetectionBuffer}${cleanChunk}`.slice(-SHELL_URL_PARSE_BUFFER_LIMIT);
1857
+
1858
+ outputData = outputData.replace(
1859
+ /OPEN_URL:\s*(https?:\/\/[^\s\x1b\x07]+)/g,
1860
+ '[INFO] Opening in browser: $1'
1861
+ );
1862
+
1863
+ const emitAuthUrl = (detectedUrl, autoOpen = false) => {
1864
+ const normalizedUrl = normalizeDetectedUrl(detectedUrl);
1865
+ if (!normalizedUrl) return;
1866
+
1867
+ const isNewUrl = !announcedAuthUrls.has(normalizedUrl);
1868
+ if (isNewUrl) {
1869
+ announcedAuthUrls.add(normalizedUrl);
1870
+ session.ws.send(JSON.stringify({
1871
+ type: 'auth_url',
1872
+ url: normalizedUrl,
1873
+ autoOpen
1874
+ }));
1875
+ }
1876
+
1877
+ };
1878
+
1879
+ const normalizedDetectedUrls = extractUrlsFromText(urlDetectionBuffer)
1880
+ .map((url) => normalizeDetectedUrl(url))
1881
+ .filter(Boolean);
1882
+
1883
+ // Prefer the most complete URL if shorter prefix variants are also present.
1884
+ const dedupedDetectedUrls = Array.from(new Set(normalizedDetectedUrls)).filter((url, _, urls) =>
1885
+ !urls.some((otherUrl) => otherUrl !== url && otherUrl.startsWith(url))
1886
+ );
1887
+
1888
+ dedupedDetectedUrls.forEach((url) => emitAuthUrl(url, false));
1889
+
1890
+ if (shouldAutoOpenUrlFromOutput(cleanChunk) && dedupedDetectedUrls.length > 0) {
1891
+ const bestUrl = dedupedDetectedUrls.reduce((longest, current) =>
1892
+ current.length > longest.length ? current : longest
1893
+ );
1894
+ emitAuthUrl(bestUrl, true);
1895
+ }
1896
+
1897
+ // Send regular output
1898
+ session.ws.send(JSON.stringify({
1899
+ type: 'output',
1900
+ data: outputData
1901
+ }));
1902
+ }
1903
+ });
1904
+
1905
+ // Handle process exit
1906
+ shellProcess.onExit((exitCode) => {
1907
+ console.log('🔚 Shell process exited with code:', exitCode.exitCode, 'signal:', exitCode.signal);
1908
+ const session = ptySessionsMap.get(ptySessionKey);
1909
+ if (session && session.ws && session.ws.readyState === WebSocket.OPEN) {
1910
+ session.ws.send(JSON.stringify({
1911
+ type: 'output',
1912
+ data: `\r\n\x1b[33mProcess exited with code ${exitCode.exitCode}${exitCode.signal ? ` (${exitCode.signal})` : ''}\x1b[0m\r\n`
1913
+ }));
1914
+ }
1915
+ if (session && session.timeoutId) {
1916
+ clearTimeout(session.timeoutId);
1917
+ }
1918
+ ptySessionsMap.delete(ptySessionKey);
1919
+ shellProcess = null;
1920
+ });
1921
+
1922
+ } catch (spawnError) {
1923
+ console.error('[ERROR] Error spawning process:', spawnError);
1924
+ ws.send(JSON.stringify({
1925
+ type: 'output',
1926
+ data: `\r\n\x1b[31mError: ${spawnError.message}\x1b[0m\r\n`
1927
+ }));
1928
+ }
1929
+
1930
+ } else if (data.type === 'input') {
1931
+ // Send input to shell process
1932
+ if (shellProcess && shellProcess.write) {
1933
+ try {
1934
+ shellProcess.write(data.data);
1935
+ } catch (error) {
1936
+ console.error('Error writing to shell:', error);
1937
+ }
1938
+ } else {
1939
+ console.warn('No active shell process to send input to');
1940
+ }
1941
+ } else if (data.type === 'resize') {
1942
+ // Handle terminal resize
1943
+ if (shellProcess && shellProcess.resize) {
1944
+ console.log('Terminal resize requested:', data.cols, 'x', data.rows);
1945
+ shellProcess.resize(data.cols, data.rows);
1946
+ }
1947
+ }
1948
+ } catch (error) {
1949
+ console.error('[ERROR] Shell WebSocket error:', error.message);
1950
+ if (ws.readyState === WebSocket.OPEN) {
1951
+ ws.send(JSON.stringify({
1952
+ type: 'output',
1953
+ data: `\r\n\x1b[31mError: ${error.message}\x1b[0m\r\n`
1954
+ }));
1955
+ }
1956
+ }
1957
+ });
1958
+
1959
+ ws.on('close', () => {
1960
+ console.log('🔌 Shell client disconnected');
1961
+
1962
+ if (ptySessionKey) {
1963
+ const session = ptySessionsMap.get(ptySessionKey);
1964
+ if (session) {
1965
+ console.log('⏳ PTY session kept alive, will timeout in 30 minutes:', ptySessionKey);
1966
+ session.ws = null;
1967
+
1968
+ session.timeoutId = setTimeout(() => {
1969
+ console.log('⏰ PTY session timeout, killing process:', ptySessionKey);
1970
+ if (session.pty && session.pty.kill) {
1971
+ session.pty.kill();
1972
+ }
1973
+ ptySessionsMap.delete(ptySessionKey);
1974
+ }, PTY_SESSION_TIMEOUT);
1975
+ }
1976
+ }
1977
+ });
1978
+
1979
+ ws.on('error', (error) => {
1980
+ console.error('[ERROR] Shell WebSocket error:', error);
1981
+ });
1982
+ }
1983
+ // Audio transcription endpoint
1984
+ app.post('/api/transcribe', authenticateToken, async (req, res) => {
1985
+ try {
1986
+ const multer = (await import('multer')).default;
1987
+ const upload = multer({ storage: multer.memoryStorage() });
1988
+
1989
+ // Handle multipart form data
1990
+ upload.single('audio')(req, res, async (err) => {
1991
+ if (err) {
1992
+ return res.status(400).json({ error: 'Failed to process audio file' });
1993
+ }
1994
+
1995
+ if (!req.file) {
1996
+ return res.status(400).json({ error: 'No audio file provided' });
1997
+ }
1998
+
1999
+ const apiKey = process.env.OPENAI_API_KEY;
2000
+ if (!apiKey) {
2001
+ return res.status(500).json({ error: 'OpenAI API key not configured. Please set OPENAI_API_KEY in server environment.' });
2002
+ }
2003
+
2004
+ try {
2005
+ // Create form data for OpenAI
2006
+ const FormData = (await import('form-data')).default;
2007
+ const formData = new FormData();
2008
+ formData.append('file', req.file.buffer, {
2009
+ filename: req.file.originalname,
2010
+ contentType: req.file.mimetype
2011
+ });
2012
+ formData.append('model', 'whisper-1');
2013
+ formData.append('response_format', 'json');
2014
+ formData.append('language', 'en');
2015
+
2016
+ // Make request to OpenAI
2017
+ const response = await fetch('https://api.openai.com/v1/audio/transcriptions', {
2018
+ method: 'POST',
2019
+ headers: {
2020
+ 'Authorization': `Bearer ${apiKey}`,
2021
+ ...formData.getHeaders()
2022
+ },
2023
+ body: formData
2024
+ });
2025
+
2026
+ if (!response.ok) {
2027
+ const errorData = await response.json().catch(() => ({}));
2028
+ throw new Error(errorData.error?.message || `Whisper API error: ${response.status}`);
2029
+ }
2030
+
2031
+ const data = await response.json();
2032
+ let transcribedText = data.text || '';
2033
+
2034
+ // Check if enhancement mode is enabled
2035
+ const mode = req.body.mode || 'default';
2036
+
2037
+ // If no transcribed text, return empty
2038
+ if (!transcribedText) {
2039
+ return res.json({ text: '' });
2040
+ }
2041
+
2042
+ // If default mode, return transcribed text without enhancement
2043
+ if (mode === 'default') {
2044
+ return res.json({ text: transcribedText });
2045
+ }
2046
+
2047
+ // Handle different enhancement modes
2048
+ try {
2049
+ const OpenAI = (await import('openai')).default;
2050
+ const openai = new OpenAI({ apiKey });
2051
+
2052
+ let prompt, systemMessage, temperature = 0.7, maxTokens = 800;
2053
+
2054
+ switch (mode) {
2055
+ case 'prompt':
2056
+ systemMessage = 'You are an expert prompt engineer who creates clear, detailed, and effective prompts.';
2057
+ prompt = `You are an expert prompt engineer. Transform the following rough instruction into a clear, detailed, and context-aware AI prompt.
2058
+
2059
+ Your enhanced prompt should:
2060
+ 1. Be specific and unambiguous
2061
+ 2. Include relevant context and constraints
2062
+ 3. Specify the desired output format
2063
+ 4. Use clear, actionable language
2064
+ 5. Include examples where helpful
2065
+ 6. Consider edge cases and potential ambiguities
2066
+
2067
+ Transform this rough instruction into a well-crafted prompt:
2068
+ "${transcribedText}"
2069
+
2070
+ Enhanced prompt:`;
2071
+ break;
2072
+
2073
+ case 'vibe':
2074
+ case 'instructions':
2075
+ case 'architect':
2076
+ systemMessage = 'You are a helpful assistant that formats ideas into clear, actionable instructions for AI agents.';
2077
+ temperature = 0.5; // Lower temperature for more controlled output
2078
+ prompt = `Transform the following idea into clear, well-structured instructions that an AI agent can easily understand and execute.
2079
+
2080
+ IMPORTANT RULES:
2081
+ - Format as clear, step-by-step instructions
2082
+ - Add reasonable implementation details based on common patterns
2083
+ - Only include details directly related to what was asked
2084
+ - Do NOT add features or functionality not mentioned
2085
+ - Keep the original intent and scope intact
2086
+ - Use clear, actionable language an agent can follow
2087
+
2088
+ Transform this idea into agent-friendly instructions:
2089
+ "${transcribedText}"
2090
+
2091
+ Agent instructions:`;
2092
+ break;
2093
+
2094
+ default:
2095
+ // No enhancement needed
2096
+ break;
2097
+ }
2098
+
2099
+ // Only make GPT call if we have a prompt
2100
+ if (prompt) {
2101
+ const completion = await openai.chat.completions.create({
2102
+ model: 'gpt-4o-mini',
2103
+ messages: [
2104
+ { role: 'system', content: systemMessage },
2105
+ { role: 'user', content: prompt }
2106
+ ],
2107
+ temperature: temperature,
2108
+ max_tokens: maxTokens
2109
+ });
2110
+
2111
+ transcribedText = completion.choices[0].message.content || transcribedText;
2112
+ }
2113
+
2114
+ } catch (gptError) {
2115
+ console.error('GPT processing error:', gptError);
2116
+ // Fall back to original transcription if GPT fails
2117
+ }
2118
+
2119
+ res.json({ text: transcribedText });
2120
+
2121
+ } catch (error) {
2122
+ console.error('Transcription error:', error);
2123
+ res.status(500).json({ error: error.message });
2124
+ }
2125
+ });
2126
+ } catch (error) {
2127
+ console.error('Endpoint error:', error);
2128
+ res.status(500).json({ error: 'Internal server error' });
2129
+ }
2130
+ });
2131
+
2132
+ // Image upload endpoint
2133
+ app.post('/api/projects/:projectName/upload-images', authenticateToken, async (req, res) => {
2134
+ try {
2135
+ const multer = (await import('multer')).default;
2136
+ const path = (await import('path')).default;
2137
+ const fs = (await import('fs')).promises;
2138
+ const os = (await import('os')).default;
2139
+
2140
+ // Configure multer for image uploads
2141
+ const storage = multer.diskStorage({
2142
+ destination: async (req, file, cb) => {
2143
+ const uploadDir = path.join(os.tmpdir(), 'claude-ui-uploads', String(req.user.id));
2144
+ await fs.mkdir(uploadDir, { recursive: true });
2145
+ cb(null, uploadDir);
2146
+ },
2147
+ filename: (req, file, cb) => {
2148
+ const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
2149
+ const sanitizedName = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '_');
2150
+ cb(null, uniqueSuffix + '-' + sanitizedName);
2151
+ }
2152
+ });
2153
+
2154
+ const fileFilter = (req, file, cb) => {
2155
+ const allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
2156
+ if (allowedMimes.includes(file.mimetype)) {
2157
+ cb(null, true);
2158
+ } else {
2159
+ cb(new Error('Invalid file type. Only JPEG, PNG, GIF, WebP, and SVG are allowed.'));
2160
+ }
2161
+ };
2162
+
2163
+ const upload = multer({
2164
+ storage,
2165
+ fileFilter,
2166
+ limits: {
2167
+ fileSize: 5 * 1024 * 1024, // 5MB
2168
+ files: 5
2169
+ }
2170
+ });
2171
+
2172
+ // Handle multipart form data
2173
+ upload.array('images', 5)(req, res, async (err) => {
2174
+ if (err) {
2175
+ return res.status(400).json({ error: err.message });
2176
+ }
2177
+
2178
+ if (!req.files || req.files.length === 0) {
2179
+ return res.status(400).json({ error: 'No image files provided' });
2180
+ }
2181
+
2182
+ try {
2183
+ // Process uploaded images
2184
+ const processedImages = await Promise.all(
2185
+ req.files.map(async (file) => {
2186
+ // Read file and convert to base64
2187
+ const buffer = await fs.readFile(file.path);
2188
+ const base64 = buffer.toString('base64');
2189
+ const mimeType = file.mimetype;
2190
+
2191
+ // Clean up temp file immediately
2192
+ await fs.unlink(file.path);
2193
+
2194
+ return {
2195
+ name: file.originalname,
2196
+ data: `data:${mimeType};base64,${base64}`,
2197
+ size: file.size,
2198
+ mimeType: mimeType
2199
+ };
2200
+ })
2201
+ );
2202
+
2203
+ res.json({ images: processedImages });
2204
+ } catch (error) {
2205
+ console.error('Error processing images:', error);
2206
+ // Clean up any remaining files
2207
+ await Promise.all(req.files.map(f => fs.unlink(f.path).catch(() => { })));
2208
+ res.status(500).json({ error: 'Failed to process images' });
2209
+ }
2210
+ });
2211
+ } catch (error) {
2212
+ console.error('Error in image upload endpoint:', error);
2213
+ res.status(500).json({ error: 'Internal server error' });
2214
+ }
2215
+ });
2216
+
2217
+ // Get token usage for a specific session
2218
+ app.get('/api/projects/:projectName/sessions/:sessionId/token-usage', authenticateToken, async (req, res) => {
2219
+ try {
2220
+ const { projectName, sessionId } = req.params;
2221
+ const { provider = 'claude' } = req.query;
2222
+ const homeDir = os.homedir();
2223
+
2224
+ // Allow only safe characters in sessionId
2225
+ const safeSessionId = String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '');
2226
+ if (!safeSessionId || safeSessionId !== String(sessionId)) {
2227
+ return res.status(400).json({ error: 'Invalid sessionId' });
2228
+ }
2229
+
2230
+ // Handle Cursor sessions - they use SQLite and don't have token usage info
2231
+ if (provider === 'cursor') {
2232
+ return res.json({
2233
+ used: 0,
2234
+ total: 0,
2235
+ breakdown: { input: 0, cacheCreation: 0, cacheRead: 0 },
2236
+ unsupported: true,
2237
+ message: 'Token usage tracking not available for Cursor sessions'
2238
+ });
2239
+ }
2240
+
2241
+ // Handle Gemini sessions - they are raw logs in our current setup
2242
+ if (provider === 'gemini') {
2243
+ return res.json({
2244
+ used: 0,
2245
+ total: 0,
2246
+ breakdown: { input: 0, cacheCreation: 0, cacheRead: 0 },
2247
+ unsupported: true,
2248
+ message: 'Token usage tracking not available for Gemini sessions'
2249
+ });
2250
+ }
2251
+
2252
+ // Handle Codex sessions
2253
+ if (provider === 'codex') {
2254
+ const codexSessionsDir = path.join(homeDir, '.codex', 'sessions');
2255
+
2256
+ // Find the session file by searching for the session ID
2257
+ const findSessionFile = async (dir) => {
2258
+ try {
2259
+ const entries = await fsPromises.readdir(dir, { withFileTypes: true });
2260
+ for (const entry of entries) {
2261
+ const fullPath = path.join(dir, entry.name);
2262
+ if (entry.isDirectory()) {
2263
+ const found = await findSessionFile(fullPath);
2264
+ if (found) return found;
2265
+ } else if (entry.name.includes(safeSessionId) && entry.name.endsWith('.jsonl')) {
2266
+ return fullPath;
2267
+ }
2268
+ }
2269
+ } catch (error) {
2270
+ // Skip directories we can't read
2271
+ }
2272
+ return null;
2273
+ };
2274
+
2275
+ const sessionFilePath = await findSessionFile(codexSessionsDir);
2276
+
2277
+ if (!sessionFilePath) {
2278
+ return res.status(404).json({ error: 'Codex session file not found', sessionId: safeSessionId });
2279
+ }
2280
+
2281
+ // Read and parse the Codex JSONL file
2282
+ let fileContent;
2283
+ try {
2284
+ fileContent = await fsPromises.readFile(sessionFilePath, 'utf8');
2285
+ } catch (error) {
2286
+ if (error.code === 'ENOENT') {
2287
+ return res.status(404).json({ error: 'Session file not found', path: sessionFilePath });
2288
+ }
2289
+ throw error;
2290
+ }
2291
+ const lines = fileContent.trim().split('\n');
2292
+ let totalTokens = 0;
2293
+ let contextWindow = 200000; // Default for Codex/OpenAI
2294
+
2295
+ // Find the latest token_count event with info (scan from end)
2296
+ for (let i = lines.length - 1; i >= 0; i--) {
2297
+ try {
2298
+ const entry = JSON.parse(lines[i]);
2299
+
2300
+ // Codex stores token info in event_msg with type: "token_count"
2301
+ if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload?.info) {
2302
+ const tokenInfo = entry.payload.info;
2303
+ if (tokenInfo.total_token_usage) {
2304
+ totalTokens = tokenInfo.total_token_usage.total_tokens || 0;
2305
+ }
2306
+ if (tokenInfo.model_context_window) {
2307
+ contextWindow = tokenInfo.model_context_window;
2308
+ }
2309
+ break; // Stop after finding the latest token count
2310
+ }
2311
+ } catch (parseError) {
2312
+ // Skip lines that can't be parsed
2313
+ continue;
2314
+ }
2315
+ }
2316
+
2317
+ return res.json({
2318
+ used: totalTokens,
2319
+ total: contextWindow
2320
+ });
2321
+ }
2322
+
2323
+ // Handle Claude sessions (default)
2324
+ // Extract actual project path
2325
+ let projectPath;
2326
+ try {
2327
+ projectPath = await extractProjectDirectory(projectName);
2328
+ } catch (error) {
2329
+ console.error('Error extracting project directory:', error);
2330
+ return res.status(500).json({ error: 'Failed to determine project path' });
2331
+ }
2332
+
2333
+ // Construct the JSONL file path
2334
+ // Claude stores session files in ~/.claude/projects/[encoded-project-path]/[session-id].jsonl
2335
+ // The encoding replaces any non-alphanumeric character (except -) with -
2336
+ const encodedPath = projectPath.replace(/[^a-zA-Z0-9-]/g, '-');
2337
+ const projectDir = path.join(homeDir, '.claude', 'projects', encodedPath);
2338
+
2339
+ const jsonlPath = path.join(projectDir, `${safeSessionId}.jsonl`);
2340
+
2341
+ // Constrain to projectDir
2342
+ const rel = path.relative(path.resolve(projectDir), path.resolve(jsonlPath));
2343
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
2344
+ return res.status(400).json({ error: 'Invalid path' });
2345
+ }
2346
+
2347
+ // Read and parse the JSONL file
2348
+ let fileContent;
2349
+ try {
2350
+ fileContent = await fsPromises.readFile(jsonlPath, 'utf8');
2351
+ } catch (error) {
2352
+ if (error.code === 'ENOENT') {
2353
+ return res.status(404).json({ error: 'Session file not found', path: jsonlPath });
2354
+ }
2355
+ throw error; // Re-throw other errors to be caught by outer try-catch
2356
+ }
2357
+ const lines = fileContent.trim().split('\n');
2358
+
2359
+ const parsedContextWindow = parseInt(process.env.CONTEXT_WINDOW, 10);
2360
+ const contextWindow = Number.isFinite(parsedContextWindow) ? parsedContextWindow : 160000;
2361
+ let inputTokens = 0;
2362
+ let cacheCreationTokens = 0;
2363
+ let cacheReadTokens = 0;
2364
+
2365
+ // Find the latest assistant message with usage data (scan from end)
2366
+ for (let i = lines.length - 1; i >= 0; i--) {
2367
+ try {
2368
+ const entry = JSON.parse(lines[i]);
2369
+
2370
+ // Only count assistant messages which have usage data
2371
+ if (entry.type === 'assistant' && entry.message?.usage) {
2372
+ const usage = entry.message.usage;
2373
+
2374
+ // Use token counts from latest assistant message only
2375
+ inputTokens = usage.input_tokens || 0;
2376
+ cacheCreationTokens = usage.cache_creation_input_tokens || 0;
2377
+ cacheReadTokens = usage.cache_read_input_tokens || 0;
2378
+
2379
+ break; // Stop after finding the latest assistant message
2380
+ }
2381
+ } catch (parseError) {
2382
+ // Skip lines that can't be parsed
2383
+ continue;
2384
+ }
2385
+ }
2386
+
2387
+ // Calculate total context usage (excluding output_tokens, as per ccusage)
2388
+ const totalUsed = inputTokens + cacheCreationTokens + cacheReadTokens;
2389
+
2390
+ res.json({
2391
+ used: totalUsed,
2392
+ total: contextWindow,
2393
+ breakdown: {
2394
+ input: inputTokens,
2395
+ cacheCreation: cacheCreationTokens,
2396
+ cacheRead: cacheReadTokens
2397
+ }
2398
+ });
2399
+ } catch (error) {
2400
+ console.error('Error reading session token usage:', error);
2401
+ res.status(500).json({ error: 'Failed to read session token usage' });
2402
+ }
2403
+ });
2404
+
2405
+ // Serve React app for all other routes (excluding static files)
2406
+ app.get('*', (req, res) => {
2407
+ // Skip requests for static assets (files with extensions)
2408
+ if (path.extname(req.path)) {
2409
+ return res.status(404).send('Not found');
2410
+ }
2411
+
2412
+ // Only serve index.html for HTML routes, not for static assets
2413
+ // Static assets should already be handled by express.static middleware above
2414
+ const indexPath = path.join(__dirname, '../dist/index.html');
2415
+
2416
+ // Check if dist/index.html exists (production build available)
2417
+ if (fs.existsSync(indexPath)) {
2418
+ // Set no-cache headers for HTML to prevent service worker issues
2419
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
2420
+ res.setHeader('Pragma', 'no-cache');
2421
+ res.setHeader('Expires', '0');
2422
+ res.sendFile(indexPath);
2423
+ } else {
2424
+ // In development, redirect to Vite dev server only if dist doesn't exist
2425
+ const redirectHost = getConnectableHost(req.hostname);
2426
+ res.redirect(`${req.protocol}://${redirectHost}:${VITE_PORT}`);
2427
+ }
2428
+ });
2429
+
2430
+ // Helper function to convert permissions to rwx format
2431
+ function permToRwx(perm) {
2432
+ const r = perm & 4 ? 'r' : '-';
2433
+ const w = perm & 2 ? 'w' : '-';
2434
+ const x = perm & 1 ? 'x' : '-';
2435
+ return r + w + x;
2436
+ }
2437
+
2438
+ async function getFileTree(dirPath, maxDepth = 3, currentDepth = 0, showHidden = true) {
2439
+ // Using fsPromises from import
2440
+ const items = [];
2441
+
2442
+ try {
2443
+ const entries = await fsPromises.readdir(dirPath, { withFileTypes: true });
2444
+
2445
+ for (const entry of entries) {
2446
+ // Debug: log all entries including hidden files
2447
+
2448
+
2449
+ // Skip heavy build directories and VCS directories
2450
+ if (entry.name === 'node_modules' ||
2451
+ entry.name === 'dist' ||
2452
+ entry.name === 'build' ||
2453
+ entry.name === '.git' ||
2454
+ entry.name === '.svn' ||
2455
+ entry.name === '.hg') continue;
2456
+
2457
+ const itemPath = path.join(dirPath, entry.name);
2458
+ const item = {
2459
+ name: entry.name,
2460
+ path: itemPath,
2461
+ type: entry.isDirectory() ? 'directory' : 'file'
2462
+ };
2463
+
2464
+ // Get file stats for additional metadata
2465
+ try {
2466
+ const stats = await fsPromises.stat(itemPath);
2467
+ item.size = stats.size;
2468
+ item.modified = stats.mtime.toISOString();
2469
+
2470
+ // Convert permissions to rwx format
2471
+ const mode = stats.mode;
2472
+ const ownerPerm = (mode >> 6) & 7;
2473
+ const groupPerm = (mode >> 3) & 7;
2474
+ const otherPerm = mode & 7;
2475
+ item.permissions = ((mode >> 6) & 7).toString() + ((mode >> 3) & 7).toString() + (mode & 7).toString();
2476
+ item.permissionsRwx = permToRwx(ownerPerm) + permToRwx(groupPerm) + permToRwx(otherPerm);
2477
+ } catch (statError) {
2478
+ // If stat fails, provide default values
2479
+ item.size = 0;
2480
+ item.modified = null;
2481
+ item.permissions = '000';
2482
+ item.permissionsRwx = '---------';
2483
+ }
2484
+
2485
+ if (entry.isDirectory() && currentDepth < maxDepth) {
2486
+ // Recursively get subdirectories but limit depth
2487
+ try {
2488
+ // Check if we can access the directory before trying to read it
2489
+ await fsPromises.access(item.path, fs.constants.R_OK);
2490
+ item.children = await getFileTree(item.path, maxDepth, currentDepth + 1, showHidden);
2491
+ } catch (e) {
2492
+ // Silently skip directories we can't access (permission denied, etc.)
2493
+ item.children = [];
2494
+ }
2495
+ }
2496
+
2497
+ items.push(item);
2498
+ }
2499
+ } catch (error) {
2500
+ // Only log non-permission errors to avoid spam
2501
+ if (error.code !== 'EACCES' && error.code !== 'EPERM') {
2502
+ console.error('Error reading directory:', error);
2503
+ }
2504
+ }
2505
+
2506
+ return items.sort((a, b) => {
2507
+ if (a.type !== b.type) {
2508
+ return a.type === 'directory' ? -1 : 1;
2509
+ }
2510
+ return a.name.localeCompare(b.name);
2511
+ });
2512
+ }
2513
+
2514
+ const SERVER_PORT = process.env.SERVER_PORT || 3001;
2515
+ const HOST = process.env.HOST || '0.0.0.0';
2516
+ const DISPLAY_HOST = getConnectableHost(HOST);
2517
+ const VITE_PORT = process.env.VITE_PORT || 5173;
2518
+
2519
+ // Initialize database and start server
2520
+ async function startServer() {
2521
+ try {
2522
+ // Initialize authentication database
2523
+ await initializeDatabase();
2524
+
2525
+ // Configure Web Push (VAPID keys)
2526
+ configureWebPush();
2527
+
2528
+ // Check if running in production mode (dist folder exists)
2529
+ const distIndexPath = path.join(__dirname, '../dist/index.html');
2530
+ const isProduction = fs.existsSync(distIndexPath);
2531
+
2532
+ // Log Claude implementation mode
2533
+ console.log(`${c.info('[INFO]')} Using Claude Agents SDK for Claude integration`);
2534
+ console.log('');
2535
+
2536
+ if (isProduction) {
2537
+ console.log(`${c.info('[INFO]')} To run in production mode, go to http://${DISPLAY_HOST}:${SERVER_PORT}`);
2538
+ }
2539
+
2540
+ console.log(`${c.info('[INFO]')} To run in development mode with hot-module replacement, go to http://${DISPLAY_HOST}:${VITE_PORT}`);
2541
+
2542
+ server.listen(SERVER_PORT, HOST, async () => {
2543
+ const appInstallPath = path.join(__dirname, '..');
2544
+
2545
+ console.log('');
2546
+ console.log(c.dim('═'.repeat(63)));
2547
+ console.log(` ${c.bright('Claude Code UI Server - Ready')}`);
2548
+ console.log(c.dim('═'.repeat(63)));
2549
+ console.log('');
2550
+ console.log(`${c.info('[INFO]')} Server URL: ${c.bright('http://' + DISPLAY_HOST + ':' + SERVER_PORT)}`);
2551
+ console.log(`${c.info('[INFO]')} Installed at: ${c.dim(appInstallPath)}`);
2552
+ console.log(`${c.tip('[TIP]')} Run "cloudcli status" for full configuration details`);
2553
+ console.log('');
2554
+
2555
+ // Start watching the projects folder for changes
2556
+ await setupProjectsWatcher();
2557
+
2558
+ // Start server-side plugin processes for enabled plugins
2559
+ startEnabledPluginServers().catch(err => {
2560
+ console.error('[Plugins] Error during startup:', err.message);
2561
+ });
2562
+ });
2563
+
2564
+ // Clean up plugin processes on shutdown
2565
+ const shutdownPlugins = async () => {
2566
+ await stopAllPlugins();
2567
+ process.exit(0);
2568
+ };
2569
+ process.on('SIGTERM', () => void shutdownPlugins());
2570
+ process.on('SIGINT', () => void shutdownPlugins());
2571
+ } catch (error) {
2572
+ console.error('[ERROR] Failed to start server:', error);
2573
+ process.exit(1);
2574
+ }
2575
+ }
2576
+
2577
+ startServer();