@cloudcli-ai/cloudcli 1.29.2 → 1.29.4

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