@cloudcli-ai/cloudcli 1.29.2 → 1.29.3

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