claude-wec 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +675 -0
  2. package/README.md +371 -0
  3. package/dist/api-docs.html +879 -0
  4. package/dist/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  5. package/dist/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  6. package/dist/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  7. package/dist/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  8. package/dist/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  9. package/dist/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  10. package/dist/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  11. package/dist/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  12. package/dist/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  13. package/dist/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  14. package/dist/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  15. package/dist/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  16. package/dist/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  17. package/dist/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  18. package/dist/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  19. package/dist/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  20. package/dist/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  21. package/dist/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  22. package/dist/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  23. package/dist/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  24. package/dist/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  25. package/dist/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  26. package/dist/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  27. package/dist/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  28. package/dist/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  29. package/dist/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  30. package/dist/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  31. package/dist/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  32. package/dist/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  33. package/dist/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  34. package/dist/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  35. package/dist/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  36. package/dist/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  37. package/dist/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  38. package/dist/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  39. package/dist/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  40. package/dist/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  41. package/dist/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  42. package/dist/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  43. package/dist/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  44. package/dist/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  45. package/dist/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  46. package/dist/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  47. package/dist/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  48. package/dist/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  49. package/dist/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  50. package/dist/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  51. package/dist/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  52. package/dist/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  53. package/dist/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  54. package/dist/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  55. package/dist/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  56. package/dist/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  57. package/dist/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  58. package/dist/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  59. package/dist/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  60. package/dist/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  61. package/dist/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  62. package/dist/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  63. package/dist/assets/index-cIxJ4RXb.js +1226 -0
  64. package/dist/assets/index-oyEz69sP.css +32 -0
  65. package/dist/assets/vendor-codemirror-CJLzwpLB.js +39 -0
  66. package/dist/assets/vendor-react-DcyRfQm3.js +59 -0
  67. package/dist/assets/vendor-xterm-DfaPXD3y.js +66 -0
  68. package/dist/clear-cache.html +85 -0
  69. package/dist/convert-icons.md +53 -0
  70. package/dist/favicon.png +0 -0
  71. package/dist/favicon.svg +9 -0
  72. package/dist/generate-icons.js +49 -0
  73. package/dist/icons/claude-ai-icon.svg +1 -0
  74. package/dist/icons/codex-white.svg +3 -0
  75. package/dist/icons/codex.svg +3 -0
  76. package/dist/icons/cursor-white.svg +12 -0
  77. package/dist/icons/cursor.svg +1 -0
  78. package/dist/icons/generate-icons.md +19 -0
  79. package/dist/icons/icon-128x128.png +0 -0
  80. package/dist/icons/icon-128x128.svg +12 -0
  81. package/dist/icons/icon-144x144.png +0 -0
  82. package/dist/icons/icon-144x144.svg +12 -0
  83. package/dist/icons/icon-152x152.png +0 -0
  84. package/dist/icons/icon-152x152.svg +12 -0
  85. package/dist/icons/icon-192x192.png +0 -0
  86. package/dist/icons/icon-192x192.svg +12 -0
  87. package/dist/icons/icon-384x384.png +0 -0
  88. package/dist/icons/icon-384x384.svg +12 -0
  89. package/dist/icons/icon-512x512.png +0 -0
  90. package/dist/icons/icon-512x512.svg +12 -0
  91. package/dist/icons/icon-72x72.png +0 -0
  92. package/dist/icons/icon-72x72.svg +12 -0
  93. package/dist/icons/icon-96x96.png +0 -0
  94. package/dist/icons/icon-96x96.svg +12 -0
  95. package/dist/icons/icon-template.svg +12 -0
  96. package/dist/index.html +52 -0
  97. package/dist/logo-128.png +0 -0
  98. package/dist/logo-256.png +0 -0
  99. package/dist/logo-32.png +0 -0
  100. package/dist/logo-512.png +0 -0
  101. package/dist/logo-64.png +0 -0
  102. package/dist/logo.svg +17 -0
  103. package/dist/manifest.json +61 -0
  104. package/dist/screenshots/cli-selection.png +0 -0
  105. package/dist/screenshots/desktop-main.png +0 -0
  106. package/dist/screenshots/mobile-chat.png +0 -0
  107. package/dist/screenshots/tools-modal.png +0 -0
  108. package/dist/sw.js +49 -0
  109. package/package.json +109 -0
  110. package/server/claude-sdk.js +721 -0
  111. package/server/cli.js +327 -0
  112. package/server/cursor-cli.js +267 -0
  113. package/server/database/auth.db +0 -0
  114. package/server/database/db.js +361 -0
  115. package/server/database/init.sql +52 -0
  116. package/server/index.js +1747 -0
  117. package/server/middleware/auth.js +111 -0
  118. package/server/openai-codex.js +389 -0
  119. package/server/projects.js +1604 -0
  120. package/server/routes/agent.js +1230 -0
  121. package/server/routes/auth.js +135 -0
  122. package/server/routes/cli-auth.js +263 -0
  123. package/server/routes/codex.js +345 -0
  124. package/server/routes/commands.js +521 -0
  125. package/server/routes/cursor.js +795 -0
  126. package/server/routes/git.js +1128 -0
  127. package/server/routes/mcp-utils.js +48 -0
  128. package/server/routes/mcp.js +552 -0
  129. package/server/routes/projects.js +378 -0
  130. package/server/routes/settings.js +178 -0
  131. package/server/routes/taskmaster.js +1963 -0
  132. package/server/routes/user.js +106 -0
  133. package/server/utils/commandParser.js +303 -0
  134. package/server/utils/gitConfig.js +24 -0
  135. package/server/utils/mcp-detector.js +198 -0
  136. package/server/utils/taskmaster-websocket.js +129 -0
  137. package/shared/modelConstants.js +65 -0
@@ -0,0 +1,1747 @@
1
+ #!/usr/bin/env node
2
+ // Load environment variables from .env file
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { fileURLToPath } from 'url';
6
+ import { dirname } from 'path';
7
+
8
+ const __filename = fileURLToPath(import.meta.url);
9
+ const __dirname = dirname(__filename);
10
+
11
+ // ANSI color codes for terminal output
12
+ const colors = {
13
+ reset: '\x1b[0m',
14
+ bright: '\x1b[1m',
15
+ cyan: '\x1b[36m',
16
+ green: '\x1b[32m',
17
+ yellow: '\x1b[33m',
18
+ blue: '\x1b[34m',
19
+ dim: '\x1b[2m',
20
+ };
21
+
22
+ const c = {
23
+ info: (text) => `${colors.cyan}${text}${colors.reset}`,
24
+ ok: (text) => `${colors.green}${text}${colors.reset}`,
25
+ warn: (text) => `${colors.yellow}${text}${colors.reset}`,
26
+ tip: (text) => `${colors.blue}${text}${colors.reset}`,
27
+ bright: (text) => `${colors.bright}${text}${colors.reset}`,
28
+ dim: (text) => `${colors.dim}${text}${colors.reset}`,
29
+ };
30
+
31
+ try {
32
+ const envPath = path.join(__dirname, '../.env');
33
+ const envFile = fs.readFileSync(envPath, 'utf8');
34
+ envFile.split('\n').forEach(line => {
35
+ const trimmedLine = line.trim();
36
+ if (trimmedLine && !trimmedLine.startsWith('#')) {
37
+ const [key, ...valueParts] = trimmedLine.split('=');
38
+ if (key && valueParts.length > 0 && !process.env[key]) {
39
+ process.env[key] = valueParts.join('=').trim();
40
+ }
41
+ }
42
+ });
43
+ } catch (e) {
44
+ console.log('No .env file found or error reading it:', e.message);
45
+ }
46
+
47
+ console.log('PORT from env:', process.env.PORT);
48
+
49
+ import express from 'express';
50
+ import { WebSocketServer, WebSocket } from 'ws';
51
+ import os from 'os';
52
+ import http from 'http';
53
+ import cors from 'cors';
54
+ import { promises as fsPromises } from 'fs';
55
+ import { spawn } from 'child_process';
56
+ import pty from 'node-pty';
57
+ import fetch from 'node-fetch';
58
+ import mime from 'mime-types';
59
+
60
+ import { getProjects, getSessions, getSessionMessages, renameProject, deleteSession, deleteProject, addProjectManually, extractProjectDirectory, clearProjectDirectoryCache } from './projects.js';
61
+ import { queryClaudeSDK, abortClaudeSDKSession, isClaudeSDKSessionActive, getActiveClaudeSDKSessions, resolveToolApproval } from './claude-sdk.js';
62
+ import { spawnCursor, abortCursorSession, isCursorSessionActive, getActiveCursorSessions } from './cursor-cli.js';
63
+ import { queryCodex, abortCodexSession, isCodexSessionActive, getActiveCodexSessions } from './openai-codex.js';
64
+ import gitRoutes from './routes/git.js';
65
+ import authRoutes from './routes/auth.js';
66
+ import mcpRoutes from './routes/mcp.js';
67
+ import cursorRoutes from './routes/cursor.js';
68
+ import taskmasterRoutes from './routes/taskmaster.js';
69
+ import mcpUtilsRoutes from './routes/mcp-utils.js';
70
+ import commandsRoutes from './routes/commands.js';
71
+ import settingsRoutes from './routes/settings.js';
72
+ import agentRoutes from './routes/agent.js';
73
+ import projectsRoutes from './routes/projects.js';
74
+ import cliAuthRoutes from './routes/cli-auth.js';
75
+ import userRoutes from './routes/user.js';
76
+ import codexRoutes from './routes/codex.js';
77
+ import { initializeDatabase } from './database/db.js';
78
+ import { validateApiKey, authenticateToken, authenticateWebSocket } from './middleware/auth.js';
79
+
80
+ // File system watcher for projects folder
81
+ let projectsWatcher = null;
82
+ const connectedClients = new Set();
83
+
84
+ // Setup file system watcher for Claude projects folder using chokidar
85
+ async function setupProjectsWatcher() {
86
+ const chokidar = (await import('chokidar')).default;
87
+ const claudeProjectsPath = path.join(os.homedir(), '.claude', 'projects');
88
+
89
+ if (projectsWatcher) {
90
+ projectsWatcher.close();
91
+ }
92
+
93
+ try {
94
+ // Initialize chokidar watcher with optimized settings
95
+ projectsWatcher = chokidar.watch(claudeProjectsPath, {
96
+ ignored: [
97
+ '**/node_modules/**',
98
+ '**/.git/**',
99
+ '**/dist/**',
100
+ '**/build/**',
101
+ '**/*.tmp',
102
+ '**/*.swp',
103
+ '**/.DS_Store'
104
+ ],
105
+ persistent: true,
106
+ ignoreInitial: true, // Don't fire events for existing files on startup
107
+ followSymlinks: false,
108
+ depth: 10, // Reasonable depth limit
109
+ awaitWriteFinish: {
110
+ stabilityThreshold: 100, // Wait 100ms for file to stabilize
111
+ pollInterval: 50
112
+ }
113
+ });
114
+
115
+ // Debounce function to prevent excessive notifications
116
+ let debounceTimer;
117
+ const debouncedUpdate = async (eventType, filePath) => {
118
+ clearTimeout(debounceTimer);
119
+ debounceTimer = setTimeout(async () => {
120
+ try {
121
+
122
+ // Clear project directory cache when files change
123
+ clearProjectDirectoryCache();
124
+
125
+ // Get updated projects list
126
+ const updatedProjects = await getProjects();
127
+
128
+ // Notify all connected clients about the project changes
129
+ const updateMessage = JSON.stringify({
130
+ type: 'projects_updated',
131
+ projects: updatedProjects,
132
+ timestamp: new Date().toISOString(),
133
+ changeType: eventType,
134
+ changedFile: path.relative(claudeProjectsPath, filePath)
135
+ });
136
+
137
+ connectedClients.forEach(client => {
138
+ if (client.readyState === WebSocket.OPEN) {
139
+ client.send(updateMessage);
140
+ }
141
+ });
142
+
143
+ } catch (error) {
144
+ console.error('[ERROR] Error handling project changes:', error);
145
+ }
146
+ }, 300); // 300ms debounce (slightly faster than before)
147
+ };
148
+
149
+ // Set up event listeners
150
+ projectsWatcher
151
+ .on('add', (filePath) => debouncedUpdate('add', filePath))
152
+ .on('change', (filePath) => debouncedUpdate('change', filePath))
153
+ .on('unlink', (filePath) => debouncedUpdate('unlink', filePath))
154
+ .on('addDir', (dirPath) => debouncedUpdate('addDir', dirPath))
155
+ .on('unlinkDir', (dirPath) => debouncedUpdate('unlinkDir', dirPath))
156
+ .on('error', (error) => {
157
+ console.error('[ERROR] Chokidar watcher error:', error);
158
+ })
159
+ .on('ready', () => {
160
+ });
161
+
162
+ } catch (error) {
163
+ console.error('[ERROR] Failed to setup projects watcher:', error);
164
+ }
165
+ }
166
+
167
+
168
+ const app = express();
169
+ const server = http.createServer(app);
170
+
171
+ const ptySessionsMap = new Map();
172
+ const PTY_SESSION_TIMEOUT = 30 * 60 * 1000;
173
+
174
+ // Single WebSocket server that handles both paths
175
+ const wss = new WebSocketServer({
176
+ server,
177
+ verifyClient: (info) => {
178
+ console.log('WebSocket connection attempt to:', info.req.url);
179
+
180
+ // Platform mode: always allow connection
181
+ if (process.env.VITE_IS_PLATFORM === 'true') {
182
+ const user = authenticateWebSocket(null); // Will return first user
183
+ if (!user) {
184
+ console.log('[WARN] Platform mode: No user found in database');
185
+ return false;
186
+ }
187
+ info.req.user = user;
188
+ console.log('[OK] Platform mode WebSocket authenticated for user:', user.username);
189
+ return true;
190
+ }
191
+
192
+ // Normal mode: verify token
193
+ // Extract token from query parameters or headers
194
+ const url = new URL(info.req.url, 'http://localhost');
195
+ const token = url.searchParams.get('token') ||
196
+ info.req.headers.authorization?.split(' ')[1];
197
+
198
+ // Verify token
199
+ const user = authenticateWebSocket(token);
200
+ if (!user) {
201
+ console.log('[WARN] WebSocket authentication failed');
202
+ return false;
203
+ }
204
+
205
+ // Store user info in the request for later use
206
+ info.req.user = user;
207
+ console.log('[OK] WebSocket authenticated for user:', user.username);
208
+ return true;
209
+ }
210
+ });
211
+
212
+ // Make WebSocket server available to routes
213
+ app.locals.wss = wss;
214
+
215
+ app.use(cors());
216
+ app.use(express.json({
217
+ limit: '50mb',
218
+ type: (req) => {
219
+ // Skip multipart/form-data requests (for file uploads like images)
220
+ const contentType = req.headers['content-type'] || '';
221
+ if (contentType.includes('multipart/form-data')) {
222
+ return false;
223
+ }
224
+ return contentType.includes('json');
225
+ }
226
+ }));
227
+ app.use(express.urlencoded({ limit: '50mb', extended: true }));
228
+
229
+ // Public health check endpoint (no authentication required)
230
+ app.get('/health', (req, res) => {
231
+ res.json({
232
+ status: 'ok',
233
+ timestamp: new Date().toISOString()
234
+ });
235
+ });
236
+
237
+ // Optional API key validation (if configured)
238
+ app.use('/api', validateApiKey);
239
+
240
+ // Authentication routes (public)
241
+ app.use('/api/auth', authRoutes);
242
+
243
+ // Projects API Routes (protected)
244
+ app.use('/api/projects', authenticateToken, projectsRoutes);
245
+
246
+ // Git API Routes (protected)
247
+ app.use('/api/git', authenticateToken, gitRoutes);
248
+
249
+ // MCP API Routes (protected)
250
+ app.use('/api/mcp', authenticateToken, mcpRoutes);
251
+
252
+ // Cursor API Routes (protected)
253
+ app.use('/api/cursor', authenticateToken, cursorRoutes);
254
+
255
+ // TaskMaster API Routes (protected)
256
+ app.use('/api/taskmaster', authenticateToken, taskmasterRoutes);
257
+
258
+ // MCP utilities
259
+ app.use('/api/mcp-utils', authenticateToken, mcpUtilsRoutes);
260
+
261
+ // Commands API Routes (protected)
262
+ app.use('/api/commands', authenticateToken, commandsRoutes);
263
+
264
+ // Settings API Routes (protected)
265
+ app.use('/api/settings', authenticateToken, settingsRoutes);
266
+
267
+ // CLI Authentication API Routes (protected)
268
+ app.use('/api/cli', authenticateToken, cliAuthRoutes);
269
+
270
+ // User API Routes (protected)
271
+ app.use('/api/user', authenticateToken, userRoutes);
272
+
273
+ // Codex API Routes (protected)
274
+ app.use('/api/codex', authenticateToken, codexRoutes);
275
+
276
+ // Agent API Routes (uses API key authentication)
277
+ app.use('/api/agent', agentRoutes);
278
+
279
+ // Serve public files (like api-docs.html)
280
+ app.use(express.static(path.join(__dirname, '../public')));
281
+
282
+ // Static files served after API routes
283
+ // Add cache control: HTML files should not be cached, but assets can be cached
284
+ app.use(express.static(path.join(__dirname, '../dist'), {
285
+ setHeaders: (res, filePath) => {
286
+ if (filePath.endsWith('.html')) {
287
+ // Prevent HTML caching to avoid service worker issues after builds
288
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
289
+ res.setHeader('Pragma', 'no-cache');
290
+ res.setHeader('Expires', '0');
291
+ } else if (filePath.match(/\.(js|css|woff2?|ttf|eot|svg|png|jpg|jpeg|gif|ico)$/)) {
292
+ // Cache static assets for 1 year (they have hashed names)
293
+ res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
294
+ }
295
+ }
296
+ }));
297
+
298
+ // API Routes (protected)
299
+ // /api/config endpoint removed - no longer needed
300
+ // Frontend now uses window.location for WebSocket URLs
301
+
302
+ // System update endpoint
303
+ app.post('/api/system/update', authenticateToken, async (req, res) => {
304
+ try {
305
+ // Get the project root directory (parent of server directory)
306
+ const projectRoot = path.join(__dirname, '..');
307
+
308
+ console.log('Starting system update from directory:', projectRoot);
309
+
310
+ // Run the update command
311
+ const updateCommand = 'git checkout main && git pull && npm install';
312
+
313
+ const child = spawn('sh', ['-c', updateCommand], {
314
+ cwd: projectRoot,
315
+ env: process.env
316
+ });
317
+
318
+ let output = '';
319
+ let errorOutput = '';
320
+
321
+ child.stdout.on('data', (data) => {
322
+ const text = data.toString();
323
+ output += text;
324
+ console.log('Update output:', text);
325
+ });
326
+
327
+ child.stderr.on('data', (data) => {
328
+ const text = data.toString();
329
+ errorOutput += text;
330
+ console.error('Update error:', text);
331
+ });
332
+
333
+ child.on('close', (code) => {
334
+ if (code === 0) {
335
+ res.json({
336
+ success: true,
337
+ output: output || 'Update completed successfully',
338
+ message: 'Update completed. Please restart the server to apply changes.'
339
+ });
340
+ } else {
341
+ res.status(500).json({
342
+ success: false,
343
+ error: 'Update command failed',
344
+ output: output,
345
+ errorOutput: errorOutput
346
+ });
347
+ }
348
+ });
349
+
350
+ child.on('error', (error) => {
351
+ console.error('Update process error:', error);
352
+ res.status(500).json({
353
+ success: false,
354
+ error: error.message
355
+ });
356
+ });
357
+
358
+ } catch (error) {
359
+ console.error('System update error:', error);
360
+ res.status(500).json({
361
+ success: false,
362
+ error: error.message
363
+ });
364
+ }
365
+ });
366
+
367
+ app.get('/api/projects', authenticateToken, async (req, res) => {
368
+ try {
369
+ const projects = await getProjects();
370
+ res.json(projects);
371
+ } catch (error) {
372
+ res.status(500).json({ error: error.message });
373
+ }
374
+ });
375
+
376
+ app.get('/api/projects/:projectName/sessions', authenticateToken, async (req, res) => {
377
+ try {
378
+ const { limit = 5, offset = 0 } = req.query;
379
+ const result = await getSessions(req.params.projectName, parseInt(limit), parseInt(offset));
380
+ res.json(result);
381
+ } catch (error) {
382
+ res.status(500).json({ error: error.message });
383
+ }
384
+ });
385
+
386
+ // Get messages for a specific session
387
+ app.get('/api/projects/:projectName/sessions/:sessionId/messages', authenticateToken, async (req, res) => {
388
+ try {
389
+ const { projectName, sessionId } = req.params;
390
+ const { limit, offset } = req.query;
391
+
392
+ // Parse limit and offset if provided
393
+ const parsedLimit = limit ? parseInt(limit, 10) : null;
394
+ const parsedOffset = offset ? parseInt(offset, 10) : 0;
395
+
396
+ const result = await getSessionMessages(projectName, sessionId, parsedLimit, parsedOffset);
397
+
398
+ // Handle both old and new response formats
399
+ if (Array.isArray(result)) {
400
+ // Backward compatibility: no pagination parameters were provided
401
+ res.json({ messages: result });
402
+ } else {
403
+ // New format with pagination info
404
+ res.json(result);
405
+ }
406
+ } catch (error) {
407
+ res.status(500).json({ error: error.message });
408
+ }
409
+ });
410
+
411
+ // Rename project endpoint
412
+ app.put('/api/projects/:projectName/rename', authenticateToken, async (req, res) => {
413
+ try {
414
+ const { displayName } = req.body;
415
+ await renameProject(req.params.projectName, displayName);
416
+ res.json({ success: true });
417
+ } catch (error) {
418
+ res.status(500).json({ error: error.message });
419
+ }
420
+ });
421
+
422
+ // Delete session endpoint
423
+ app.delete('/api/projects/:projectName/sessions/:sessionId', authenticateToken, async (req, res) => {
424
+ try {
425
+ const { projectName, sessionId } = req.params;
426
+ console.log(`[API] Deleting session: ${sessionId} from project: ${projectName}`);
427
+ await deleteSession(projectName, sessionId);
428
+ console.log(`[API] Session ${sessionId} deleted successfully`);
429
+ res.json({ success: true });
430
+ } catch (error) {
431
+ console.error(`[API] Error deleting session ${req.params.sessionId}:`, error);
432
+ res.status(500).json({ error: error.message });
433
+ }
434
+ });
435
+
436
+ // Delete project endpoint (only if empty)
437
+ app.delete('/api/projects/:projectName', authenticateToken, async (req, res) => {
438
+ try {
439
+ const { projectName } = req.params;
440
+ await deleteProject(projectName);
441
+ res.json({ success: true });
442
+ } catch (error) {
443
+ res.status(500).json({ error: error.message });
444
+ }
445
+ });
446
+
447
+ // Create project endpoint
448
+ app.post('/api/projects/create', authenticateToken, async (req, res) => {
449
+ try {
450
+ const { path: projectPath } = req.body;
451
+
452
+ if (!projectPath || !projectPath.trim()) {
453
+ return res.status(400).json({ error: 'Project path is required' });
454
+ }
455
+
456
+ const project = await addProjectManually(projectPath.trim());
457
+ res.json({ success: true, project });
458
+ } catch (error) {
459
+ console.error('Error creating project:', error);
460
+ res.status(500).json({ error: error.message });
461
+ }
462
+ });
463
+
464
+ // Browse filesystem endpoint for project suggestions - uses existing getFileTree
465
+ app.get('/api/browse-filesystem', authenticateToken, async (req, res) => {
466
+ try {
467
+ const { path: dirPath } = req.query;
468
+
469
+ // Default to home directory if no path provided
470
+ const homeDir = os.homedir();
471
+ let targetPath = dirPath ? dirPath.replace('~', homeDir) : homeDir;
472
+
473
+ // Resolve and normalize the path
474
+ targetPath = path.resolve(targetPath);
475
+
476
+ // Security check - ensure path is accessible
477
+ try {
478
+ await fs.promises.access(targetPath);
479
+ const stats = await fs.promises.stat(targetPath);
480
+
481
+ if (!stats.isDirectory()) {
482
+ return res.status(400).json({ error: 'Path is not a directory' });
483
+ }
484
+ } catch (err) {
485
+ return res.status(404).json({ error: 'Directory not accessible' });
486
+ }
487
+
488
+ // Use existing getFileTree function with shallow depth (only direct children)
489
+ const fileTree = await getFileTree(targetPath, 1, 0, false); // maxDepth=1, showHidden=false
490
+
491
+ // Filter only directories and format for suggestions
492
+ const directories = fileTree
493
+ .filter(item => item.type === 'directory')
494
+ .map(item => ({
495
+ path: item.path,
496
+ name: item.name,
497
+ type: 'directory'
498
+ }))
499
+ .slice(0, 20); // Limit results
500
+
501
+ // Add common directories if browsing home directory
502
+ const suggestions = [];
503
+ if (targetPath === homeDir) {
504
+ const commonDirs = ['Desktop', 'Documents', 'Projects', 'Development', 'Dev', 'Code', 'workspace'];
505
+ const existingCommon = directories.filter(dir => commonDirs.includes(dir.name));
506
+ const otherDirs = directories.filter(dir => !commonDirs.includes(dir.name));
507
+
508
+ suggestions.push(...existingCommon, ...otherDirs);
509
+ } else {
510
+ suggestions.push(...directories);
511
+ }
512
+
513
+ res.json({
514
+ path: targetPath,
515
+ suggestions: suggestions
516
+ });
517
+
518
+ } catch (error) {
519
+ console.error('Error browsing filesystem:', error);
520
+ res.status(500).json({ error: 'Failed to browse filesystem' });
521
+ }
522
+ });
523
+
524
+ // Read file content endpoint
525
+ app.get('/api/projects/:projectName/file', authenticateToken, async (req, res) => {
526
+ try {
527
+ const { projectName } = req.params;
528
+ const { filePath } = req.query;
529
+
530
+ console.log('[DEBUG] File read request:', projectName, filePath);
531
+
532
+ // Security: ensure the requested path is inside the project root
533
+ if (!filePath) {
534
+ return res.status(400).json({ error: 'Invalid file path' });
535
+ }
536
+
537
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
538
+ if (!projectRoot) {
539
+ return res.status(404).json({ error: 'Project not found' });
540
+ }
541
+
542
+ // Handle both absolute and relative paths
543
+ const resolved = path.isAbsolute(filePath)
544
+ ? path.resolve(filePath)
545
+ : path.resolve(projectRoot, filePath);
546
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
547
+ if (!resolved.startsWith(normalizedRoot)) {
548
+ return res.status(403).json({ error: 'Path must be under project root' });
549
+ }
550
+
551
+ const content = await fsPromises.readFile(resolved, 'utf8');
552
+ res.json({ content, path: resolved });
553
+ } catch (error) {
554
+ console.error('Error reading file:', error);
555
+ if (error.code === 'ENOENT') {
556
+ res.status(404).json({ error: 'File not found' });
557
+ } else if (error.code === 'EACCES') {
558
+ res.status(403).json({ error: 'Permission denied' });
559
+ } else {
560
+ res.status(500).json({ error: error.message });
561
+ }
562
+ }
563
+ });
564
+
565
+ // Serve binary file content endpoint (for images, etc.)
566
+ app.get('/api/projects/:projectName/files/content', authenticateToken, async (req, res) => {
567
+ try {
568
+ const { projectName } = req.params;
569
+ const { path: filePath } = req.query;
570
+
571
+ console.log('[DEBUG] Binary file serve request:', projectName, filePath);
572
+
573
+ // Security: ensure the requested path is inside the project root
574
+ if (!filePath) {
575
+ return res.status(400).json({ error: 'Invalid file path' });
576
+ }
577
+
578
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
579
+ if (!projectRoot) {
580
+ return res.status(404).json({ error: 'Project not found' });
581
+ }
582
+
583
+ const resolved = path.resolve(filePath);
584
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
585
+ if (!resolved.startsWith(normalizedRoot)) {
586
+ return res.status(403).json({ error: 'Path must be under project root' });
587
+ }
588
+
589
+ // Check if file exists
590
+ try {
591
+ await fsPromises.access(resolved);
592
+ } catch (error) {
593
+ return res.status(404).json({ error: 'File not found' });
594
+ }
595
+
596
+ // Get file extension and set appropriate content type
597
+ const mimeType = mime.lookup(resolved) || 'application/octet-stream';
598
+ res.setHeader('Content-Type', mimeType);
599
+
600
+ // Stream the file
601
+ const fileStream = fs.createReadStream(resolved);
602
+ fileStream.pipe(res);
603
+
604
+ fileStream.on('error', (error) => {
605
+ console.error('Error streaming file:', error);
606
+ if (!res.headersSent) {
607
+ res.status(500).json({ error: 'Error reading file' });
608
+ }
609
+ });
610
+
611
+ } catch (error) {
612
+ console.error('Error serving binary file:', error);
613
+ if (!res.headersSent) {
614
+ res.status(500).json({ error: error.message });
615
+ }
616
+ }
617
+ });
618
+
619
+ // Save file content endpoint
620
+ app.put('/api/projects/:projectName/file', authenticateToken, async (req, res) => {
621
+ try {
622
+ const { projectName } = req.params;
623
+ const { filePath, content } = req.body;
624
+
625
+ console.log('[DEBUG] File save request:', projectName, filePath);
626
+
627
+ // Security: ensure the requested path is inside the project root
628
+ if (!filePath) {
629
+ return res.status(400).json({ error: 'Invalid file path' });
630
+ }
631
+
632
+ if (content === undefined) {
633
+ return res.status(400).json({ error: 'Content is required' });
634
+ }
635
+
636
+ const projectRoot = await extractProjectDirectory(projectName).catch(() => null);
637
+ if (!projectRoot) {
638
+ return res.status(404).json({ error: 'Project not found' });
639
+ }
640
+
641
+ // Handle both absolute and relative paths
642
+ const resolved = path.isAbsolute(filePath)
643
+ ? path.resolve(filePath)
644
+ : path.resolve(projectRoot, filePath);
645
+ const normalizedRoot = path.resolve(projectRoot) + path.sep;
646
+ if (!resolved.startsWith(normalizedRoot)) {
647
+ return res.status(403).json({ error: 'Path must be under project root' });
648
+ }
649
+
650
+ // Write the new content
651
+ await fsPromises.writeFile(resolved, content, 'utf8');
652
+
653
+ res.json({
654
+ success: true,
655
+ path: resolved,
656
+ message: 'File saved successfully'
657
+ });
658
+ } catch (error) {
659
+ console.error('Error saving file:', error);
660
+ if (error.code === 'ENOENT') {
661
+ res.status(404).json({ error: 'File or directory not found' });
662
+ } else if (error.code === 'EACCES') {
663
+ res.status(403).json({ error: 'Permission denied' });
664
+ } else {
665
+ res.status(500).json({ error: error.message });
666
+ }
667
+ }
668
+ });
669
+
670
+ app.get('/api/projects/:projectName/files', authenticateToken, async (req, res) => {
671
+ try {
672
+
673
+ // Using fsPromises from import
674
+
675
+ // Use extractProjectDirectory to get the actual project path
676
+ let actualPath;
677
+ try {
678
+ actualPath = await extractProjectDirectory(req.params.projectName);
679
+ } catch (error) {
680
+ console.error('Error extracting project directory:', error);
681
+ // Fallback to simple dash replacement
682
+ actualPath = req.params.projectName.replace(/-/g, '/');
683
+ }
684
+
685
+ // Check if path exists
686
+ try {
687
+ await fsPromises.access(actualPath);
688
+ } catch (e) {
689
+ return res.status(404).json({ error: `Project path not found: ${actualPath}` });
690
+ }
691
+
692
+ const files = await getFileTree(actualPath, 10, 0, true);
693
+ const hiddenFiles = files.filter(f => f.name.startsWith('.'));
694
+ res.json(files);
695
+ } catch (error) {
696
+ console.error('[ERROR] File tree error:', error.message);
697
+ res.status(500).json({ error: error.message });
698
+ }
699
+ });
700
+
701
+ // WebSocket connection handler that routes based on URL path
702
+ wss.on('connection', (ws, request) => {
703
+ const url = request.url;
704
+ console.log('[INFO] Client connected to:', url);
705
+
706
+ // Parse URL to get pathname without query parameters
707
+ const urlObj = new URL(url, 'http://localhost');
708
+ const pathname = urlObj.pathname;
709
+
710
+ if (pathname === '/shell') {
711
+ handleShellConnection(ws);
712
+ } else if (pathname === '/ws') {
713
+ handleChatConnection(ws);
714
+ } else {
715
+ console.log('[WARN] Unknown WebSocket path:', pathname);
716
+ ws.close();
717
+ }
718
+ });
719
+
720
+ /**
721
+ * WebSocket Writer - Wrapper for WebSocket to match SSEStreamWriter interface
722
+ */
723
+ class WebSocketWriter {
724
+ constructor(ws) {
725
+ this.ws = ws;
726
+ this.sessionId = null;
727
+ this.isWebSocketWriter = true; // Marker for transport detection
728
+ }
729
+
730
+ send(data) {
731
+ if (this.ws.readyState === 1) { // WebSocket.OPEN
732
+ // Providers send raw objects, we stringify for WebSocket
733
+ this.ws.send(JSON.stringify(data));
734
+ }
735
+ }
736
+
737
+ setSessionId(sessionId) {
738
+ this.sessionId = sessionId;
739
+ }
740
+
741
+ getSessionId() {
742
+ return this.sessionId;
743
+ }
744
+ }
745
+
746
+ // Handle chat WebSocket connections
747
+ function handleChatConnection(ws) {
748
+ console.log('[INFO] Chat WebSocket connected');
749
+
750
+ // Add to connected clients for project updates
751
+ connectedClients.add(ws);
752
+
753
+ // Wrap WebSocket with writer for consistent interface with SSEStreamWriter
754
+ const writer = new WebSocketWriter(ws);
755
+
756
+ ws.on('message', async (message) => {
757
+ try {
758
+ const data = JSON.parse(message);
759
+
760
+ if (data.type === 'claude-command') {
761
+ console.log('[DEBUG] User message:', data.command || '[Continue/Resume]');
762
+ console.log('📁 Project:', data.options?.projectPath || 'Unknown');
763
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
764
+
765
+ // Use Claude Agents SDK
766
+ await queryClaudeSDK(data.command, data.options, writer);
767
+ } else if (data.type === 'cursor-command') {
768
+ console.log('[DEBUG] Cursor message:', data.command || '[Continue/Resume]');
769
+ console.log('📁 Project:', data.options?.cwd || 'Unknown');
770
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
771
+ console.log('🤖 Model:', data.options?.model || 'default');
772
+ await spawnCursor(data.command, data.options, writer);
773
+ } else if (data.type === 'codex-command') {
774
+ console.log('[DEBUG] Codex message:', data.command || '[Continue/Resume]');
775
+ console.log('📁 Project:', data.options?.projectPath || data.options?.cwd || 'Unknown');
776
+ console.log('🔄 Session:', data.options?.sessionId ? 'Resume' : 'New');
777
+ console.log('🤖 Model:', data.options?.model || 'default');
778
+ await queryCodex(data.command, data.options, writer);
779
+ } else if (data.type === 'cursor-resume') {
780
+ // Backward compatibility: treat as cursor-command with resume and no prompt
781
+ console.log('[DEBUG] Cursor resume session (compat):', data.sessionId);
782
+ await spawnCursor('', {
783
+ sessionId: data.sessionId,
784
+ resume: true,
785
+ cwd: data.options?.cwd
786
+ }, writer);
787
+ } else if (data.type === 'abort-session') {
788
+ console.log('[DEBUG] Abort session request:', data.sessionId);
789
+ const provider = data.provider || 'claude';
790
+ let success;
791
+
792
+ if (provider === 'cursor') {
793
+ success = abortCursorSession(data.sessionId);
794
+ } else if (provider === 'codex') {
795
+ success = abortCodexSession(data.sessionId);
796
+ } else {
797
+ // Use Claude Agents SDK
798
+ success = await abortClaudeSDKSession(data.sessionId);
799
+ }
800
+
801
+ writer.send({
802
+ type: 'session-aborted',
803
+ sessionId: data.sessionId,
804
+ provider,
805
+ success
806
+ });
807
+ } else if (data.type === 'claude-permission-response') {
808
+ // Relay UI approval decisions back into the SDK control flow.
809
+ // This does not persist permissions; it only resolves the in-flight request,
810
+ // introduced so the SDK can resume once the user clicks Allow/Deny.
811
+ if (data.requestId) {
812
+ resolveToolApproval(data.requestId, {
813
+ allow: Boolean(data.allow),
814
+ updatedInput: data.updatedInput,
815
+ message: data.message,
816
+ rememberEntry: data.rememberEntry
817
+ });
818
+ }
819
+ } else if (data.type === 'cursor-abort') {
820
+ console.log('[DEBUG] Abort Cursor session:', data.sessionId);
821
+ const success = abortCursorSession(data.sessionId);
822
+ writer.send({
823
+ type: 'session-aborted',
824
+ sessionId: data.sessionId,
825
+ provider: 'cursor',
826
+ success
827
+ });
828
+ } else if (data.type === 'check-session-status') {
829
+ // Check if a specific session is currently processing
830
+ const provider = data.provider || 'claude';
831
+ const sessionId = data.sessionId;
832
+ let isActive;
833
+
834
+ if (provider === 'cursor') {
835
+ isActive = isCursorSessionActive(sessionId);
836
+ } else if (provider === 'codex') {
837
+ isActive = isCodexSessionActive(sessionId);
838
+ } else {
839
+ // Use Claude Agents SDK
840
+ isActive = isClaudeSDKSessionActive(sessionId);
841
+ }
842
+
843
+ writer.send({
844
+ type: 'session-status',
845
+ sessionId,
846
+ provider,
847
+ isProcessing: isActive
848
+ });
849
+ } else if (data.type === 'get-active-sessions') {
850
+ // Get all currently active sessions
851
+ const activeSessions = {
852
+ claude: getActiveClaudeSDKSessions(),
853
+ cursor: getActiveCursorSessions(),
854
+ codex: getActiveCodexSessions()
855
+ };
856
+ writer.send({
857
+ type: 'active-sessions',
858
+ sessions: activeSessions
859
+ });
860
+ }
861
+ } catch (error) {
862
+ console.error('[ERROR] Chat WebSocket error:', error.message);
863
+ writer.send({
864
+ type: 'error',
865
+ error: error.message
866
+ });
867
+ }
868
+ });
869
+
870
+ ws.on('close', () => {
871
+ console.log('🔌 Chat client disconnected');
872
+ // Remove from connected clients
873
+ connectedClients.delete(ws);
874
+ });
875
+ }
876
+
877
+ // Handle shell WebSocket connections
878
+ function handleShellConnection(ws) {
879
+ console.log('🐚 Shell client connected');
880
+ let shellProcess = null;
881
+ let ptySessionKey = null;
882
+ let outputBuffer = [];
883
+
884
+ ws.on('message', async (message) => {
885
+ try {
886
+ const data = JSON.parse(message);
887
+ console.log('📨 Shell message received:', data.type);
888
+
889
+ if (data.type === 'init') {
890
+ const projectPath = data.projectPath || process.cwd();
891
+ const sessionId = data.sessionId;
892
+ const hasSession = data.hasSession;
893
+ const provider = data.provider || 'claude';
894
+ const initialCommand = data.initialCommand;
895
+ const isPlainShell = data.isPlainShell || (!!initialCommand && !hasSession) || provider === 'plain-shell';
896
+
897
+ // Login commands (Claude/Cursor auth) should never reuse cached sessions
898
+ const isLoginCommand = initialCommand && (
899
+ initialCommand.includes('setup-token') ||
900
+ initialCommand.includes('cursor-agent login') ||
901
+ initialCommand.includes('auth login')
902
+ );
903
+
904
+ // Include command hash in session key so different commands get separate sessions
905
+ const commandSuffix = isPlainShell && initialCommand
906
+ ? `_cmd_${Buffer.from(initialCommand).toString('base64').slice(0, 16)}`
907
+ : '';
908
+ ptySessionKey = `${projectPath}_${sessionId || 'default'}${commandSuffix}`;
909
+
910
+ // Kill any existing login session before starting fresh
911
+ if (isLoginCommand) {
912
+ const oldSession = ptySessionsMap.get(ptySessionKey);
913
+ if (oldSession) {
914
+ console.log('🧹 Cleaning up existing login session:', ptySessionKey);
915
+ if (oldSession.timeoutId) clearTimeout(oldSession.timeoutId);
916
+ if (oldSession.pty && oldSession.pty.kill) oldSession.pty.kill();
917
+ ptySessionsMap.delete(ptySessionKey);
918
+ }
919
+ }
920
+
921
+ const existingSession = isLoginCommand ? null : ptySessionsMap.get(ptySessionKey);
922
+ if (existingSession) {
923
+ console.log('♻️ Reconnecting to existing PTY session:', ptySessionKey);
924
+ shellProcess = existingSession.pty;
925
+
926
+ clearTimeout(existingSession.timeoutId);
927
+
928
+ ws.send(JSON.stringify({
929
+ type: 'output',
930
+ data: `\x1b[36m[Reconnected to existing session]\x1b[0m\r\n`
931
+ }));
932
+
933
+ if (existingSession.buffer && existingSession.buffer.length > 0) {
934
+ console.log(`📜 Sending ${existingSession.buffer.length} buffered messages`);
935
+ existingSession.buffer.forEach(bufferedData => {
936
+ ws.send(JSON.stringify({
937
+ type: 'output',
938
+ data: bufferedData
939
+ }));
940
+ });
941
+ }
942
+
943
+ existingSession.ws = ws;
944
+
945
+ return;
946
+ }
947
+
948
+ console.log('[INFO] Starting shell in:', projectPath);
949
+ console.log('📋 Session info:', hasSession ? `Resume session ${sessionId}` : (isPlainShell ? 'Plain shell mode' : 'New session'));
950
+ console.log('🤖 Provider:', isPlainShell ? 'plain-shell' : provider);
951
+ if (initialCommand) {
952
+ console.log('⚡ Initial command:', initialCommand);
953
+ }
954
+
955
+ // First send a welcome message
956
+ let welcomeMsg;
957
+ if (isPlainShell) {
958
+ welcomeMsg = `\x1b[36mStarting terminal in: ${projectPath}\x1b[0m\r\n`;
959
+ } else {
960
+ const providerName = provider === 'cursor' ? 'Cursor' : 'Claude';
961
+ welcomeMsg = hasSession ?
962
+ `\x1b[36mResuming ${providerName} session ${sessionId} in: ${projectPath}\x1b[0m\r\n` :
963
+ `\x1b[36mStarting new ${providerName} session in: ${projectPath}\x1b[0m\r\n`;
964
+ }
965
+
966
+ ws.send(JSON.stringify({
967
+ type: 'output',
968
+ data: welcomeMsg
969
+ }));
970
+
971
+ try {
972
+ // Prepare the shell command adapted to the platform and provider
973
+ let shellCommand;
974
+ if (isPlainShell) {
975
+ // Plain shell mode - just run the initial command in the project directory
976
+ if (os.platform() === 'win32') {
977
+ shellCommand = `Set-Location -Path "${projectPath}"; ${initialCommand}`;
978
+ } else {
979
+ shellCommand = `cd "${projectPath}" && ${initialCommand}`;
980
+ }
981
+ } else if (provider === 'cursor') {
982
+ // Use cursor-agent command
983
+ if (os.platform() === 'win32') {
984
+ if (hasSession && sessionId) {
985
+ shellCommand = `Set-Location -Path "${projectPath}"; cursor-agent --resume="${sessionId}"`;
986
+ } else {
987
+ shellCommand = `Set-Location -Path "${projectPath}"; cursor-agent`;
988
+ }
989
+ } else {
990
+ if (hasSession && sessionId) {
991
+ shellCommand = `cd "${projectPath}" && cursor-agent --resume="${sessionId}"`;
992
+ } else {
993
+ shellCommand = `cd "${projectPath}" && cursor-agent`;
994
+ }
995
+ }
996
+ } else {
997
+ // Use claude command (default) or initialCommand if provided
998
+ const command = initialCommand || 'claude';
999
+ if (os.platform() === 'win32') {
1000
+ if (hasSession && sessionId) {
1001
+ // Try to resume session, but with fallback to new session if it fails
1002
+ shellCommand = `Set-Location -Path "${projectPath}"; claude --resume ${sessionId}; if ($LASTEXITCODE -ne 0) { claude }`;
1003
+ } else {
1004
+ shellCommand = `Set-Location -Path "${projectPath}"; ${command}`;
1005
+ }
1006
+ } else {
1007
+ if (hasSession && sessionId) {
1008
+ shellCommand = `cd "${projectPath}" && claude --resume ${sessionId} || claude`;
1009
+ } else {
1010
+ shellCommand = `cd "${projectPath}" && ${command}`;
1011
+ }
1012
+ }
1013
+ }
1014
+
1015
+ console.log('🔧 Executing shell command:', shellCommand);
1016
+
1017
+ // Use appropriate shell based on platform
1018
+ const shell = os.platform() === 'win32' ? 'powershell.exe' : 'bash';
1019
+ const shellArgs = os.platform() === 'win32' ? ['-Command', shellCommand] : ['-c', shellCommand];
1020
+
1021
+ // Use terminal dimensions from client if provided, otherwise use defaults
1022
+ const termCols = data.cols || 80;
1023
+ const termRows = data.rows || 24;
1024
+ console.log('📐 Using terminal dimensions:', termCols, 'x', termRows);
1025
+
1026
+ shellProcess = pty.spawn(shell, shellArgs, {
1027
+ name: 'xterm-256color',
1028
+ cols: termCols,
1029
+ rows: termRows,
1030
+ cwd: os.homedir(),
1031
+ env: {
1032
+ ...process.env,
1033
+ TERM: 'xterm-256color',
1034
+ COLORTERM: 'truecolor',
1035
+ FORCE_COLOR: '3',
1036
+ // Override browser opening commands to echo URL for detection
1037
+ BROWSER: os.platform() === 'win32' ? 'echo "OPEN_URL:"' : 'echo "OPEN_URL:"'
1038
+ }
1039
+ });
1040
+
1041
+ console.log('🟢 Shell process started with PTY, PID:', shellProcess.pid);
1042
+
1043
+ ptySessionsMap.set(ptySessionKey, {
1044
+ pty: shellProcess,
1045
+ ws: ws,
1046
+ buffer: [],
1047
+ timeoutId: null,
1048
+ projectPath,
1049
+ sessionId
1050
+ });
1051
+
1052
+ // Handle data output
1053
+ shellProcess.onData((data) => {
1054
+ const session = ptySessionsMap.get(ptySessionKey);
1055
+ if (!session) return;
1056
+
1057
+ if (session.buffer.length < 5000) {
1058
+ session.buffer.push(data);
1059
+ } else {
1060
+ session.buffer.shift();
1061
+ session.buffer.push(data);
1062
+ }
1063
+
1064
+ if (session.ws && session.ws.readyState === WebSocket.OPEN) {
1065
+ let outputData = data;
1066
+
1067
+ // Check for various URL opening patterns
1068
+ const patterns = [
1069
+ // Direct browser opening commands
1070
+ /(?:xdg-open|open|start)\s+(https?:\/\/[^\s\x1b\x07]+)/g,
1071
+ // BROWSER environment variable override
1072
+ /OPEN_URL:\s*(https?:\/\/[^\s\x1b\x07]+)/g,
1073
+ // Git and other tools opening URLs
1074
+ /Opening\s+(https?:\/\/[^\s\x1b\x07]+)/gi,
1075
+ // General URL patterns that might be opened
1076
+ /Visit:\s*(https?:\/\/[^\s\x1b\x07]+)/gi,
1077
+ /View at:\s*(https?:\/\/[^\s\x1b\x07]+)/gi,
1078
+ /Browse to:\s*(https?:\/\/[^\s\x1b\x07]+)/gi
1079
+ ];
1080
+
1081
+ patterns.forEach(pattern => {
1082
+ let match;
1083
+ while ((match = pattern.exec(data)) !== null) {
1084
+ const url = match[1];
1085
+ console.log('[DEBUG] Detected URL for opening:', url);
1086
+
1087
+ // Send URL opening message to client
1088
+ session.ws.send(JSON.stringify({
1089
+ type: 'url_open',
1090
+ url: url
1091
+ }));
1092
+
1093
+ // Replace the OPEN_URL pattern with a user-friendly message
1094
+ if (pattern.source.includes('OPEN_URL')) {
1095
+ outputData = outputData.replace(match[0], `[INFO] Opening in browser: ${url}`);
1096
+ }
1097
+ }
1098
+ });
1099
+
1100
+ // Send regular output
1101
+ session.ws.send(JSON.stringify({
1102
+ type: 'output',
1103
+ data: outputData
1104
+ }));
1105
+ }
1106
+ });
1107
+
1108
+ // Handle process exit
1109
+ shellProcess.onExit((exitCode) => {
1110
+ console.log('🔚 Shell process exited with code:', exitCode.exitCode, 'signal:', exitCode.signal);
1111
+ const session = ptySessionsMap.get(ptySessionKey);
1112
+ if (session && session.ws && session.ws.readyState === WebSocket.OPEN) {
1113
+ session.ws.send(JSON.stringify({
1114
+ type: 'output',
1115
+ data: `\r\n\x1b[33mProcess exited with code ${exitCode.exitCode}${exitCode.signal ? ` (${exitCode.signal})` : ''}\x1b[0m\r\n`
1116
+ }));
1117
+ }
1118
+ if (session && session.timeoutId) {
1119
+ clearTimeout(session.timeoutId);
1120
+ }
1121
+ ptySessionsMap.delete(ptySessionKey);
1122
+ shellProcess = null;
1123
+ });
1124
+
1125
+ } catch (spawnError) {
1126
+ console.error('[ERROR] Error spawning process:', spawnError);
1127
+ ws.send(JSON.stringify({
1128
+ type: 'output',
1129
+ data: `\r\n\x1b[31mError: ${spawnError.message}\x1b[0m\r\n`
1130
+ }));
1131
+ }
1132
+
1133
+ } else if (data.type === 'input') {
1134
+ // Send input to shell process
1135
+ if (shellProcess && shellProcess.write) {
1136
+ try {
1137
+ shellProcess.write(data.data);
1138
+ } catch (error) {
1139
+ console.error('Error writing to shell:', error);
1140
+ }
1141
+ } else {
1142
+ console.warn('No active shell process to send input to');
1143
+ }
1144
+ } else if (data.type === 'resize') {
1145
+ // Handle terminal resize
1146
+ if (shellProcess && shellProcess.resize) {
1147
+ console.log('Terminal resize requested:', data.cols, 'x', data.rows);
1148
+ shellProcess.resize(data.cols, data.rows);
1149
+ }
1150
+ }
1151
+ } catch (error) {
1152
+ console.error('[ERROR] Shell WebSocket error:', error.message);
1153
+ if (ws.readyState === WebSocket.OPEN) {
1154
+ ws.send(JSON.stringify({
1155
+ type: 'output',
1156
+ data: `\r\n\x1b[31mError: ${error.message}\x1b[0m\r\n`
1157
+ }));
1158
+ }
1159
+ }
1160
+ });
1161
+
1162
+ ws.on('close', () => {
1163
+ console.log('🔌 Shell client disconnected');
1164
+
1165
+ if (ptySessionKey) {
1166
+ const session = ptySessionsMap.get(ptySessionKey);
1167
+ if (session) {
1168
+ console.log('⏳ PTY session kept alive, will timeout in 30 minutes:', ptySessionKey);
1169
+ session.ws = null;
1170
+
1171
+ session.timeoutId = setTimeout(() => {
1172
+ console.log('⏰ PTY session timeout, killing process:', ptySessionKey);
1173
+ if (session.pty && session.pty.kill) {
1174
+ session.pty.kill();
1175
+ }
1176
+ ptySessionsMap.delete(ptySessionKey);
1177
+ }, PTY_SESSION_TIMEOUT);
1178
+ }
1179
+ }
1180
+ });
1181
+
1182
+ ws.on('error', (error) => {
1183
+ console.error('[ERROR] Shell WebSocket error:', error);
1184
+ });
1185
+ }
1186
+ // Audio transcription endpoint
1187
+ app.post('/api/transcribe', authenticateToken, async (req, res) => {
1188
+ try {
1189
+ const multer = (await import('multer')).default;
1190
+ const upload = multer({ storage: multer.memoryStorage() });
1191
+
1192
+ // Handle multipart form data
1193
+ upload.single('audio')(req, res, async (err) => {
1194
+ if (err) {
1195
+ return res.status(400).json({ error: 'Failed to process audio file' });
1196
+ }
1197
+
1198
+ if (!req.file) {
1199
+ return res.status(400).json({ error: 'No audio file provided' });
1200
+ }
1201
+
1202
+ const apiKey = process.env.OPENAI_API_KEY;
1203
+ if (!apiKey) {
1204
+ return res.status(500).json({ error: 'OpenAI API key not configured. Please set OPENAI_API_KEY in server environment.' });
1205
+ }
1206
+
1207
+ try {
1208
+ // Create form data for OpenAI
1209
+ const FormData = (await import('form-data')).default;
1210
+ const formData = new FormData();
1211
+ formData.append('file', req.file.buffer, {
1212
+ filename: req.file.originalname,
1213
+ contentType: req.file.mimetype
1214
+ });
1215
+ formData.append('model', 'whisper-1');
1216
+ formData.append('response_format', 'json');
1217
+ formData.append('language', 'en');
1218
+
1219
+ // Make request to OpenAI
1220
+ const response = await fetch('https://api.openai.com/v1/audio/transcriptions', {
1221
+ method: 'POST',
1222
+ headers: {
1223
+ 'Authorization': `Bearer ${apiKey}`,
1224
+ ...formData.getHeaders()
1225
+ },
1226
+ body: formData
1227
+ });
1228
+
1229
+ if (!response.ok) {
1230
+ const errorData = await response.json().catch(() => ({}));
1231
+ throw new Error(errorData.error?.message || `Whisper API error: ${response.status}`);
1232
+ }
1233
+
1234
+ const data = await response.json();
1235
+ let transcribedText = data.text || '';
1236
+
1237
+ // Check if enhancement mode is enabled
1238
+ const mode = req.body.mode || 'default';
1239
+
1240
+ // If no transcribed text, return empty
1241
+ if (!transcribedText) {
1242
+ return res.json({ text: '' });
1243
+ }
1244
+
1245
+ // If default mode, return transcribed text without enhancement
1246
+ if (mode === 'default') {
1247
+ return res.json({ text: transcribedText });
1248
+ }
1249
+
1250
+ // Handle different enhancement modes
1251
+ try {
1252
+ const OpenAI = (await import('openai')).default;
1253
+ const openai = new OpenAI({ apiKey });
1254
+
1255
+ let prompt, systemMessage, temperature = 0.7, maxTokens = 800;
1256
+
1257
+ switch (mode) {
1258
+ case 'prompt':
1259
+ systemMessage = 'You are an expert prompt engineer who creates clear, detailed, and effective prompts.';
1260
+ prompt = `You are an expert prompt engineer. Transform the following rough instruction into a clear, detailed, and context-aware AI prompt.
1261
+
1262
+ Your enhanced prompt should:
1263
+ 1. Be specific and unambiguous
1264
+ 2. Include relevant context and constraints
1265
+ 3. Specify the desired output format
1266
+ 4. Use clear, actionable language
1267
+ 5. Include examples where helpful
1268
+ 6. Consider edge cases and potential ambiguities
1269
+
1270
+ Transform this rough instruction into a well-crafted prompt:
1271
+ "${transcribedText}"
1272
+
1273
+ Enhanced prompt:`;
1274
+ break;
1275
+
1276
+ case 'vibe':
1277
+ case 'instructions':
1278
+ case 'architect':
1279
+ systemMessage = 'You are a helpful assistant that formats ideas into clear, actionable instructions for AI agents.';
1280
+ temperature = 0.5; // Lower temperature for more controlled output
1281
+ prompt = `Transform the following idea into clear, well-structured instructions that an AI agent can easily understand and execute.
1282
+
1283
+ IMPORTANT RULES:
1284
+ - Format as clear, step-by-step instructions
1285
+ - Add reasonable implementation details based on common patterns
1286
+ - Only include details directly related to what was asked
1287
+ - Do NOT add features or functionality not mentioned
1288
+ - Keep the original intent and scope intact
1289
+ - Use clear, actionable language an agent can follow
1290
+
1291
+ Transform this idea into agent-friendly instructions:
1292
+ "${transcribedText}"
1293
+
1294
+ Agent instructions:`;
1295
+ break;
1296
+
1297
+ default:
1298
+ // No enhancement needed
1299
+ break;
1300
+ }
1301
+
1302
+ // Only make GPT call if we have a prompt
1303
+ if (prompt) {
1304
+ const completion = await openai.chat.completions.create({
1305
+ model: 'gpt-4o-mini',
1306
+ messages: [
1307
+ { role: 'system', content: systemMessage },
1308
+ { role: 'user', content: prompt }
1309
+ ],
1310
+ temperature: temperature,
1311
+ max_tokens: maxTokens
1312
+ });
1313
+
1314
+ transcribedText = completion.choices[0].message.content || transcribedText;
1315
+ }
1316
+
1317
+ } catch (gptError) {
1318
+ console.error('GPT processing error:', gptError);
1319
+ // Fall back to original transcription if GPT fails
1320
+ }
1321
+
1322
+ res.json({ text: transcribedText });
1323
+
1324
+ } catch (error) {
1325
+ console.error('Transcription error:', error);
1326
+ res.status(500).json({ error: error.message });
1327
+ }
1328
+ });
1329
+ } catch (error) {
1330
+ console.error('Endpoint error:', error);
1331
+ res.status(500).json({ error: 'Internal server error' });
1332
+ }
1333
+ });
1334
+
1335
+ // Image upload endpoint
1336
+ app.post('/api/projects/:projectName/upload-images', authenticateToken, async (req, res) => {
1337
+ try {
1338
+ const multer = (await import('multer')).default;
1339
+ const path = (await import('path')).default;
1340
+ const fs = (await import('fs')).promises;
1341
+ const os = (await import('os')).default;
1342
+
1343
+ // Configure multer for image uploads
1344
+ const storage = multer.diskStorage({
1345
+ destination: async (req, file, cb) => {
1346
+ const uploadDir = path.join(os.tmpdir(), 'claude-ui-uploads', String(req.user.id));
1347
+ await fs.mkdir(uploadDir, { recursive: true });
1348
+ cb(null, uploadDir);
1349
+ },
1350
+ filename: (req, file, cb) => {
1351
+ const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
1352
+ const sanitizedName = file.originalname.replace(/[^a-zA-Z0-9.-]/g, '_');
1353
+ cb(null, uniqueSuffix + '-' + sanitizedName);
1354
+ }
1355
+ });
1356
+
1357
+ const fileFilter = (req, file, cb) => {
1358
+ const allowedMimes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp', 'image/svg+xml'];
1359
+ if (allowedMimes.includes(file.mimetype)) {
1360
+ cb(null, true);
1361
+ } else {
1362
+ cb(new Error('Invalid file type. Only JPEG, PNG, GIF, WebP, and SVG are allowed.'));
1363
+ }
1364
+ };
1365
+
1366
+ const upload = multer({
1367
+ storage,
1368
+ fileFilter,
1369
+ limits: {
1370
+ fileSize: 5 * 1024 * 1024, // 5MB
1371
+ files: 5
1372
+ }
1373
+ });
1374
+
1375
+ // Handle multipart form data
1376
+ upload.array('images', 5)(req, res, async (err) => {
1377
+ if (err) {
1378
+ return res.status(400).json({ error: err.message });
1379
+ }
1380
+
1381
+ if (!req.files || req.files.length === 0) {
1382
+ return res.status(400).json({ error: 'No image files provided' });
1383
+ }
1384
+
1385
+ try {
1386
+ // Process uploaded images
1387
+ const processedImages = await Promise.all(
1388
+ req.files.map(async (file) => {
1389
+ // Read file and convert to base64
1390
+ const buffer = await fs.readFile(file.path);
1391
+ const base64 = buffer.toString('base64');
1392
+ const mimeType = file.mimetype;
1393
+
1394
+ // Clean up temp file immediately
1395
+ await fs.unlink(file.path);
1396
+
1397
+ return {
1398
+ name: file.originalname,
1399
+ data: `data:${mimeType};base64,${base64}`,
1400
+ size: file.size,
1401
+ mimeType: mimeType
1402
+ };
1403
+ })
1404
+ );
1405
+
1406
+ res.json({ images: processedImages });
1407
+ } catch (error) {
1408
+ console.error('Error processing images:', error);
1409
+ // Clean up any remaining files
1410
+ await Promise.all(req.files.map(f => fs.unlink(f.path).catch(() => { })));
1411
+ res.status(500).json({ error: 'Failed to process images' });
1412
+ }
1413
+ });
1414
+ } catch (error) {
1415
+ console.error('Error in image upload endpoint:', error);
1416
+ res.status(500).json({ error: 'Internal server error' });
1417
+ }
1418
+ });
1419
+
1420
+ // Get token usage for a specific session
1421
+ app.get('/api/projects/:projectName/sessions/:sessionId/token-usage', authenticateToken, async (req, res) => {
1422
+ try {
1423
+ const { projectName, sessionId } = req.params;
1424
+ const { provider = 'claude' } = req.query;
1425
+ const homeDir = os.homedir();
1426
+
1427
+ // Allow only safe characters in sessionId
1428
+ const safeSessionId = String(sessionId).replace(/[^a-zA-Z0-9._-]/g, '');
1429
+ if (!safeSessionId) {
1430
+ return res.status(400).json({ error: 'Invalid sessionId' });
1431
+ }
1432
+
1433
+ // Handle Cursor sessions - they use SQLite and don't have token usage info
1434
+ if (provider === 'cursor') {
1435
+ return res.json({
1436
+ used: 0,
1437
+ total: 0,
1438
+ breakdown: { input: 0, cacheCreation: 0, cacheRead: 0 },
1439
+ unsupported: true,
1440
+ message: 'Token usage tracking not available for Cursor sessions'
1441
+ });
1442
+ }
1443
+
1444
+ // Handle Codex sessions
1445
+ if (provider === 'codex') {
1446
+ const codexSessionsDir = path.join(homeDir, '.codex', 'sessions');
1447
+
1448
+ // Find the session file by searching for the session ID
1449
+ const findSessionFile = async (dir) => {
1450
+ try {
1451
+ const entries = await fsPromises.readdir(dir, { withFileTypes: true });
1452
+ for (const entry of entries) {
1453
+ const fullPath = path.join(dir, entry.name);
1454
+ if (entry.isDirectory()) {
1455
+ const found = await findSessionFile(fullPath);
1456
+ if (found) return found;
1457
+ } else if (entry.name.includes(safeSessionId) && entry.name.endsWith('.jsonl')) {
1458
+ return fullPath;
1459
+ }
1460
+ }
1461
+ } catch (error) {
1462
+ // Skip directories we can't read
1463
+ }
1464
+ return null;
1465
+ };
1466
+
1467
+ const sessionFilePath = await findSessionFile(codexSessionsDir);
1468
+
1469
+ if (!sessionFilePath) {
1470
+ return res.status(404).json({ error: 'Codex session file not found', sessionId: safeSessionId });
1471
+ }
1472
+
1473
+ // Read and parse the Codex JSONL file
1474
+ let fileContent;
1475
+ try {
1476
+ fileContent = await fsPromises.readFile(sessionFilePath, 'utf8');
1477
+ } catch (error) {
1478
+ if (error.code === 'ENOENT') {
1479
+ return res.status(404).json({ error: 'Session file not found', path: sessionFilePath });
1480
+ }
1481
+ throw error;
1482
+ }
1483
+ const lines = fileContent.trim().split('\n');
1484
+ let totalTokens = 0;
1485
+ let contextWindow = 200000; // Default for Codex/OpenAI
1486
+
1487
+ // Find the latest token_count event with info (scan from end)
1488
+ for (let i = lines.length - 1; i >= 0; i--) {
1489
+ try {
1490
+ const entry = JSON.parse(lines[i]);
1491
+
1492
+ // Codex stores token info in event_msg with type: "token_count"
1493
+ if (entry.type === 'event_msg' && entry.payload?.type === 'token_count' && entry.payload?.info) {
1494
+ const tokenInfo = entry.payload.info;
1495
+ if (tokenInfo.total_token_usage) {
1496
+ totalTokens = tokenInfo.total_token_usage.total_tokens || 0;
1497
+ }
1498
+ if (tokenInfo.model_context_window) {
1499
+ contextWindow = tokenInfo.model_context_window;
1500
+ }
1501
+ break; // Stop after finding the latest token count
1502
+ }
1503
+ } catch (parseError) {
1504
+ // Skip lines that can't be parsed
1505
+ continue;
1506
+ }
1507
+ }
1508
+
1509
+ return res.json({
1510
+ used: totalTokens,
1511
+ total: contextWindow
1512
+ });
1513
+ }
1514
+
1515
+ // Handle Claude sessions (default)
1516
+ // Extract actual project path
1517
+ let projectPath;
1518
+ try {
1519
+ projectPath = await extractProjectDirectory(projectName);
1520
+ } catch (error) {
1521
+ console.error('Error extracting project directory:', error);
1522
+ return res.status(500).json({ error: 'Failed to determine project path' });
1523
+ }
1524
+
1525
+ // Construct the JSONL file path
1526
+ // Claude stores session files in ~/.claude/projects/[encoded-project-path]/[session-id].jsonl
1527
+ // The encoding replaces /, spaces, ~, and _ with -
1528
+ const encodedPath = projectPath.replace(/[\\/:\s~_]/g, '-');
1529
+ const projectDir = path.join(homeDir, '.claude', 'projects', encodedPath);
1530
+
1531
+ const jsonlPath = path.join(projectDir, `${safeSessionId}.jsonl`);
1532
+
1533
+ // Constrain to projectDir
1534
+ const rel = path.relative(path.resolve(projectDir), path.resolve(jsonlPath));
1535
+ if (rel.startsWith('..') || path.isAbsolute(rel)) {
1536
+ return res.status(400).json({ error: 'Invalid path' });
1537
+ }
1538
+
1539
+ // Read and parse the JSONL file
1540
+ let fileContent;
1541
+ try {
1542
+ fileContent = await fsPromises.readFile(jsonlPath, 'utf8');
1543
+ } catch (error) {
1544
+ if (error.code === 'ENOENT') {
1545
+ return res.status(404).json({ error: 'Session file not found', path: jsonlPath });
1546
+ }
1547
+ throw error; // Re-throw other errors to be caught by outer try-catch
1548
+ }
1549
+ const lines = fileContent.trim().split('\n');
1550
+
1551
+ const parsedContextWindow = parseInt(process.env.CONTEXT_WINDOW, 10);
1552
+ const contextWindow = Number.isFinite(parsedContextWindow) ? parsedContextWindow : 160000;
1553
+ let inputTokens = 0;
1554
+ let cacheCreationTokens = 0;
1555
+ let cacheReadTokens = 0;
1556
+
1557
+ // Find the latest assistant message with usage data (scan from end)
1558
+ for (let i = lines.length - 1; i >= 0; i--) {
1559
+ try {
1560
+ const entry = JSON.parse(lines[i]);
1561
+
1562
+ // Only count assistant messages which have usage data
1563
+ if (entry.type === 'assistant' && entry.message?.usage) {
1564
+ const usage = entry.message.usage;
1565
+
1566
+ // Use token counts from latest assistant message only
1567
+ inputTokens = usage.input_tokens || 0;
1568
+ cacheCreationTokens = usage.cache_creation_input_tokens || 0;
1569
+ cacheReadTokens = usage.cache_read_input_tokens || 0;
1570
+
1571
+ break; // Stop after finding the latest assistant message
1572
+ }
1573
+ } catch (parseError) {
1574
+ // Skip lines that can't be parsed
1575
+ continue;
1576
+ }
1577
+ }
1578
+
1579
+ // Calculate total context usage (excluding output_tokens, as per ccusage)
1580
+ const totalUsed = inputTokens + cacheCreationTokens + cacheReadTokens;
1581
+
1582
+ res.json({
1583
+ used: totalUsed,
1584
+ total: contextWindow,
1585
+ breakdown: {
1586
+ input: inputTokens,
1587
+ cacheCreation: cacheCreationTokens,
1588
+ cacheRead: cacheReadTokens
1589
+ }
1590
+ });
1591
+ } catch (error) {
1592
+ console.error('Error reading session token usage:', error);
1593
+ res.status(500).json({ error: 'Failed to read session token usage' });
1594
+ }
1595
+ });
1596
+
1597
+ // Serve React app for all other routes (excluding static files)
1598
+ app.get('*', (req, res) => {
1599
+ // Skip requests for static assets (files with extensions)
1600
+ if (path.extname(req.path)) {
1601
+ return res.status(404).send('Not found');
1602
+ }
1603
+
1604
+ // Only serve index.html for HTML routes, not for static assets
1605
+ // Static assets should already be handled by express.static middleware above
1606
+ const indexPath = path.join(__dirname, '../dist/index.html');
1607
+
1608
+ // Check if dist/index.html exists (production build available)
1609
+ if (fs.existsSync(indexPath)) {
1610
+ // Set no-cache headers for HTML to prevent service worker issues
1611
+ res.setHeader('Cache-Control', 'no-cache, no-store, must-revalidate');
1612
+ res.setHeader('Pragma', 'no-cache');
1613
+ res.setHeader('Expires', '0');
1614
+ res.sendFile(indexPath);
1615
+ } else {
1616
+ // In development, redirect to Vite dev server only if dist doesn't exist
1617
+ res.redirect(`http://localhost:${process.env.VITE_PORT || 5173}`);
1618
+ }
1619
+ });
1620
+
1621
+ // Helper function to convert permissions to rwx format
1622
+ function permToRwx(perm) {
1623
+ const r = perm & 4 ? 'r' : '-';
1624
+ const w = perm & 2 ? 'w' : '-';
1625
+ const x = perm & 1 ? 'x' : '-';
1626
+ return r + w + x;
1627
+ }
1628
+
1629
+ async function getFileTree(dirPath, maxDepth = 3, currentDepth = 0, showHidden = true) {
1630
+ // Using fsPromises from import
1631
+ const items = [];
1632
+
1633
+ try {
1634
+ const entries = await fsPromises.readdir(dirPath, { withFileTypes: true });
1635
+
1636
+ for (const entry of entries) {
1637
+ // Debug: log all entries including hidden files
1638
+
1639
+
1640
+ // Skip heavy build directories and VCS directories
1641
+ if (entry.name === 'node_modules' ||
1642
+ entry.name === 'dist' ||
1643
+ entry.name === 'build' ||
1644
+ entry.name === '.git' ||
1645
+ entry.name === '.svn' ||
1646
+ entry.name === '.hg') continue;
1647
+
1648
+ const itemPath = path.join(dirPath, entry.name);
1649
+ const item = {
1650
+ name: entry.name,
1651
+ path: itemPath,
1652
+ type: entry.isDirectory() ? 'directory' : 'file'
1653
+ };
1654
+
1655
+ // Get file stats for additional metadata
1656
+ try {
1657
+ const stats = await fsPromises.stat(itemPath);
1658
+ item.size = stats.size;
1659
+ item.modified = stats.mtime.toISOString();
1660
+
1661
+ // Convert permissions to rwx format
1662
+ const mode = stats.mode;
1663
+ const ownerPerm = (mode >> 6) & 7;
1664
+ const groupPerm = (mode >> 3) & 7;
1665
+ const otherPerm = mode & 7;
1666
+ item.permissions = ((mode >> 6) & 7).toString() + ((mode >> 3) & 7).toString() + (mode & 7).toString();
1667
+ item.permissionsRwx = permToRwx(ownerPerm) + permToRwx(groupPerm) + permToRwx(otherPerm);
1668
+ } catch (statError) {
1669
+ // If stat fails, provide default values
1670
+ item.size = 0;
1671
+ item.modified = null;
1672
+ item.permissions = '000';
1673
+ item.permissionsRwx = '---------';
1674
+ }
1675
+
1676
+ if (entry.isDirectory() && currentDepth < maxDepth) {
1677
+ // Recursively get subdirectories but limit depth
1678
+ try {
1679
+ // Check if we can access the directory before trying to read it
1680
+ await fsPromises.access(item.path, fs.constants.R_OK);
1681
+ item.children = await getFileTree(item.path, maxDepth, currentDepth + 1, showHidden);
1682
+ } catch (e) {
1683
+ // Silently skip directories we can't access (permission denied, etc.)
1684
+ item.children = [];
1685
+ }
1686
+ }
1687
+
1688
+ items.push(item);
1689
+ }
1690
+ } catch (error) {
1691
+ // Only log non-permission errors to avoid spam
1692
+ if (error.code !== 'EACCES' && error.code !== 'EPERM') {
1693
+ console.error('Error reading directory:', error);
1694
+ }
1695
+ }
1696
+
1697
+ return items.sort((a, b) => {
1698
+ if (a.type !== b.type) {
1699
+ return a.type === 'directory' ? -1 : 1;
1700
+ }
1701
+ return a.name.localeCompare(b.name);
1702
+ });
1703
+ }
1704
+
1705
+ const PORT = process.env.PORT || 3001;
1706
+
1707
+ // Initialize database and start server
1708
+ async function startServer() {
1709
+ try {
1710
+ // Initialize authentication database
1711
+ await initializeDatabase();
1712
+
1713
+ // Check if running in production mode (dist folder exists)
1714
+ const distIndexPath = path.join(__dirname, '../dist/index.html');
1715
+ const isProduction = fs.existsSync(distIndexPath);
1716
+
1717
+ // Log Claude implementation mode
1718
+ console.log(`${c.info('[INFO]')} Using Claude Agents SDK for Claude integration`);
1719
+ console.log(`${c.info('[INFO]')} Running in ${c.bright(isProduction ? 'PRODUCTION' : 'DEVELOPMENT')} mode`);
1720
+
1721
+ if (!isProduction) {
1722
+ console.log(`${c.warn('[WARN]')} Note: Requests will be proxied to Vite dev server at ${c.dim('http://localhost:' + (process.env.VITE_PORT || 5173))}`);
1723
+ }
1724
+
1725
+ server.listen(PORT, '0.0.0.0', async () => {
1726
+ const appInstallPath = path.join(__dirname, '..');
1727
+
1728
+ console.log('');
1729
+ console.log(c.dim('═'.repeat(63)));
1730
+ console.log(` ${c.bright('Claude Code UI Server - Ready')}`);
1731
+ console.log(c.dim('═'.repeat(63)));
1732
+ console.log('');
1733
+ console.log(`${c.info('[INFO]')} Server URL: ${c.bright('http://0.0.0.0:' + PORT)}`);
1734
+ console.log(`${c.info('[INFO]')} Installed at: ${c.dim(appInstallPath)}`);
1735
+ console.log(`${c.tip('[TIP]')} Run "cloudcli status" for full configuration details`);
1736
+ console.log('');
1737
+
1738
+ // Start watching the projects folder for changes
1739
+ await setupProjectsWatcher();
1740
+ });
1741
+ } catch (error) {
1742
+ console.error('[ERROR] Failed to start server:', error);
1743
+ process.exit(1);
1744
+ }
1745
+ }
1746
+
1747
+ startServer();