notioncode 0.1.1 → 0.1.2

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 (77) hide show
  1. package/README.md +10 -4
  2. package/agent-runtime-server/package-lock.json +4377 -0
  3. package/agent-runtime-server/package.json +36 -0
  4. package/agent-runtime-server/scripts/fix-node-pty.js +67 -0
  5. package/agent-runtime-server/server/agent-session-service.js +816 -0
  6. package/agent-runtime-server/server/claude-sdk.js +836 -0
  7. package/agent-runtime-server/server/cli.js +330 -0
  8. package/agent-runtime-server/server/constants/config.js +5 -0
  9. package/agent-runtime-server/server/cursor-cli.js +335 -0
  10. package/agent-runtime-server/server/database/db.js +653 -0
  11. package/agent-runtime-server/server/database/init.sql +99 -0
  12. package/agent-runtime-server/server/gemini-cli.js +460 -0
  13. package/agent-runtime-server/server/gemini-response-handler.js +79 -0
  14. package/agent-runtime-server/server/index.js +2569 -0
  15. package/agent-runtime-server/server/load-env.js +32 -0
  16. package/agent-runtime-server/server/middleware/auth.js +132 -0
  17. package/agent-runtime-server/server/openai-codex.js +512 -0
  18. package/agent-runtime-server/server/projects.js +2594 -0
  19. package/agent-runtime-server/server/providers/claude/adapter.js +278 -0
  20. package/agent-runtime-server/server/providers/codex/adapter.js +248 -0
  21. package/agent-runtime-server/server/providers/cursor/adapter.js +353 -0
  22. package/agent-runtime-server/server/providers/gemini/adapter.js +186 -0
  23. package/agent-runtime-server/server/providers/registry.js +44 -0
  24. package/agent-runtime-server/server/providers/types.js +119 -0
  25. package/agent-runtime-server/server/providers/utils.js +29 -0
  26. package/agent-runtime-server/server/routes/agent-sessions.js +238 -0
  27. package/agent-runtime-server/server/routes/agent.js +1244 -0
  28. package/agent-runtime-server/server/routes/auth.js +144 -0
  29. package/agent-runtime-server/server/routes/cli-auth.js +478 -0
  30. package/agent-runtime-server/server/routes/codex.js +329 -0
  31. package/agent-runtime-server/server/routes/commands.js +596 -0
  32. package/agent-runtime-server/server/routes/cursor.js +798 -0
  33. package/agent-runtime-server/server/routes/gemini.js +24 -0
  34. package/agent-runtime-server/server/routes/git.js +1508 -0
  35. package/agent-runtime-server/server/routes/mcp-utils.js +48 -0
  36. package/agent-runtime-server/server/routes/mcp.js +552 -0
  37. package/agent-runtime-server/server/routes/messages.js +61 -0
  38. package/agent-runtime-server/server/routes/plugins.js +307 -0
  39. package/agent-runtime-server/server/routes/projects.js +548 -0
  40. package/agent-runtime-server/server/routes/settings.js +276 -0
  41. package/agent-runtime-server/server/routes/taskmaster.js +1963 -0
  42. package/agent-runtime-server/server/routes/user.js +123 -0
  43. package/agent-runtime-server/server/services/notification-orchestrator.js +227 -0
  44. package/agent-runtime-server/server/services/vapid-keys.js +35 -0
  45. package/agent-runtime-server/server/sessionManager.js +226 -0
  46. package/agent-runtime-server/server/utils/commandParser.js +303 -0
  47. package/agent-runtime-server/server/utils/frontmatter.js +18 -0
  48. package/agent-runtime-server/server/utils/gitConfig.js +34 -0
  49. package/agent-runtime-server/server/utils/mcp-detector.js +198 -0
  50. package/agent-runtime-server/server/utils/plugin-loader.js +457 -0
  51. package/agent-runtime-server/server/utils/plugin-process-manager.js +184 -0
  52. package/agent-runtime-server/server/utils/taskmaster-websocket.js +129 -0
  53. package/agent-runtime-server/shared/modelConstants.js +12 -0
  54. package/agent-runtime-server/shared/modelConstants.test.js +34 -0
  55. package/agent-runtime-server/shared/networkHosts.js +22 -0
  56. package/agent-runtime-server/test_sdk.mjs +16 -0
  57. package/bin/bridges/darwin-x64/nocode-bridge +0 -0
  58. package/bin/{nocode-local.js → notioncode.js} +0 -0
  59. package/dist/assets/icon-CQtd7WEB.png +0 -0
  60. package/dist/assets/index-D_1ZrHDe.js +1 -0
  61. package/dist/assets/index-DhCWie1Z.css +1 -0
  62. package/dist/assets/index-DkGqIiwF.js +689 -0
  63. package/dist/index.html +46 -0
  64. package/dist/onboarding/step1_create.png +0 -0
  65. package/dist/onboarding/step2_capabilities.png +0 -0
  66. package/dist/onboarding/step2b_content_access.png +0 -0
  67. package/dist/onboarding/step2c_page_access.png +0 -0
  68. package/dist/onboarding/step3_token.png +0 -0
  69. package/dist/onboarding/step4_webhook.png +0 -0
  70. package/dist/onboarding/step6a_verify.png +0 -0
  71. package/dist/onboarding/step6b_copy_verify_token.png +0 -0
  72. package/dist/tinyfish-fish-only.png +0 -0
  73. package/lib/install.js +33 -2
  74. package/lib/start.js +157 -25
  75. package/package.json +7 -4
  76. package/src/shared/modelRegistry.d.ts +24 -0
  77. package/src/shared/modelRegistry.js +163 -0
@@ -0,0 +1,330 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Claude Code UI CLI
4
+ *
5
+ * Provides command-line utilities for managing Claude Code UI
6
+ *
7
+ * Commands:
8
+ * (no args) - Start the server (default)
9
+ * start - Start the server
10
+ * status - Show configuration and data locations
11
+ * help - Show help information
12
+ * version - Show version information
13
+ */
14
+
15
+ import fs from 'fs';
16
+ import path from 'path';
17
+ import os from 'os';
18
+ import { fileURLToPath } from 'url';
19
+ import { dirname } from 'path';
20
+
21
+ const __filename = fileURLToPath(import.meta.url);
22
+ const __dirname = dirname(__filename);
23
+
24
+ // ANSI color codes for terminal output
25
+ const colors = {
26
+ reset: '\x1b[0m',
27
+ bright: '\x1b[1m',
28
+ dim: '\x1b[2m',
29
+
30
+ // Foreground colors
31
+ cyan: '\x1b[36m',
32
+ green: '\x1b[32m',
33
+ yellow: '\x1b[33m',
34
+ blue: '\x1b[34m',
35
+ magenta: '\x1b[35m',
36
+ white: '\x1b[37m',
37
+ gray: '\x1b[90m',
38
+ };
39
+
40
+ // Helper to colorize text
41
+ const c = {
42
+ info: (text) => `${colors.cyan}${text}${colors.reset}`,
43
+ ok: (text) => `${colors.green}${text}${colors.reset}`,
44
+ warn: (text) => `${colors.yellow}${text}${colors.reset}`,
45
+ error: (text) => `${colors.yellow}${text}${colors.reset}`,
46
+ tip: (text) => `${colors.blue}${text}${colors.reset}`,
47
+ bright: (text) => `${colors.bright}${text}${colors.reset}`,
48
+ dim: (text) => `${colors.dim}${text}${colors.reset}`,
49
+ };
50
+
51
+ // Load package.json for version info
52
+ const packageJsonPath = path.join(__dirname, '../package.json');
53
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
54
+
55
+ // Load environment variables from .env file if it exists
56
+ function loadEnvFile() {
57
+ try {
58
+ const envPath = path.join(__dirname, '../.env');
59
+ const envFile = fs.readFileSync(envPath, 'utf8');
60
+ envFile.split('\n').forEach(line => {
61
+ const trimmedLine = line.trim();
62
+ if (trimmedLine && !trimmedLine.startsWith('#')) {
63
+ const [key, ...valueParts] = trimmedLine.split('=');
64
+ if (key && valueParts.length > 0 && !process.env[key]) {
65
+ process.env[key] = valueParts.join('=').trim();
66
+ }
67
+ }
68
+ });
69
+ } catch (e) {
70
+ // .env file is optional
71
+ }
72
+ }
73
+
74
+ // Get the database path (same logic as db.js)
75
+ function getDatabasePath() {
76
+ loadEnvFile();
77
+ return process.env.DATABASE_PATH || path.join(__dirname, 'database', 'auth.db');
78
+ }
79
+
80
+ // Get the installation directory
81
+ function getInstallDir() {
82
+ return path.join(__dirname, '..');
83
+ }
84
+
85
+ // Show status command
86
+ function showStatus() {
87
+ console.log(`\n${c.bright('Claude Code UI - Status')}\n`);
88
+ console.log(c.dim('═'.repeat(60)));
89
+
90
+ // Version info
91
+ console.log(`\n${c.info('[INFO]')} Version: ${c.bright(packageJson.version)}`);
92
+
93
+ // Installation location
94
+ const installDir = getInstallDir();
95
+ console.log(`\n${c.info('[INFO]')} Installation Directory:`);
96
+ console.log(` ${c.dim(installDir)}`);
97
+
98
+ // Database location
99
+ const dbPath = getDatabasePath();
100
+ const dbExists = fs.existsSync(dbPath);
101
+ console.log(`\n${c.info('[INFO]')} Database Location:`);
102
+ console.log(` ${c.dim(dbPath)}`);
103
+ console.log(` Status: ${dbExists ? c.ok('[OK] Exists') : c.warn('[WARN] Not created yet (will be created on first run)')}`);
104
+
105
+ if (dbExists) {
106
+ const stats = fs.statSync(dbPath);
107
+ console.log(` Size: ${c.dim((stats.size / 1024).toFixed(2) + ' KB')}`);
108
+ console.log(` Modified: ${c.dim(stats.mtime.toLocaleString())}`);
109
+ }
110
+
111
+ // Environment variables
112
+ console.log(`\n${c.info('[INFO]')} Configuration:`);
113
+ console.log(` SERVER_PORT: ${c.bright(process.env.SERVER_PORT || process.env.PORT || '3001')} ${c.dim(process.env.SERVER_PORT || process.env.PORT ? '' : '(default)')}`);
114
+ console.log(` DATABASE_PATH: ${c.dim(process.env.DATABASE_PATH || '(using default location)')}`);
115
+ console.log(` CLAUDE_CLI_PATH: ${c.dim(process.env.CLAUDE_CLI_PATH || 'claude (default)')}`);
116
+ console.log(` CONTEXT_WINDOW: ${c.dim(process.env.CONTEXT_WINDOW || '160000 (default)')}`);
117
+
118
+ // Claude projects folder
119
+ const claudeProjectsPath = path.join(os.homedir(), '.claude', 'projects');
120
+ const projectsExists = fs.existsSync(claudeProjectsPath);
121
+ console.log(`\n${c.info('[INFO]')} Claude Projects Folder:`);
122
+ console.log(` ${c.dim(claudeProjectsPath)}`);
123
+ console.log(` Status: ${projectsExists ? c.ok('[OK] Exists') : c.warn('[WARN] Not found')}`);
124
+
125
+ // Config file location
126
+ const envFilePath = path.join(__dirname, '../.env');
127
+ const envExists = fs.existsSync(envFilePath);
128
+ console.log(`\n${c.info('[INFO]')} Configuration File:`);
129
+ console.log(` ${c.dim(envFilePath)}`);
130
+ console.log(` Status: ${envExists ? c.ok('[OK] Exists') : c.warn('[WARN] Not found (using defaults)')}`);
131
+
132
+ console.log('\n' + c.dim('═'.repeat(60)));
133
+ console.log(`\n${c.tip('[TIP]')} Hints:`);
134
+ console.log(` ${c.dim('>')} Use ${c.bright('notion-code-agent --port 8080')} to run on a custom port`);
135
+ console.log(` ${c.dim('>')} Use ${c.bright('notion-code-agent --database-path /path/to/db')} for custom database`);
136
+ console.log(` ${c.dim('>')} Run ${c.bright('notion-code-agent help')} for all options`);
137
+ console.log(` ${c.dim('>')} Access the UI at http://localhost:${process.env.SERVER_PORT || process.env.PORT || '3001'}\n`);
138
+ }
139
+
140
+ // Show help
141
+ function showHelp() {
142
+ console.log(`
143
+ ╔═══════════════════════════════════════════════════════════════╗
144
+ ║ Claude Code UI - Command Line Tool ║
145
+ ╚═══════════════════════════════════════════════════════════════╝
146
+
147
+ Usage:
148
+ claude-code-ui [command] [options]
149
+ notion-code-agent [command] [options]
150
+
151
+ Commands:
152
+ start Start the Claude Code UI server (default)
153
+ status Show configuration and data locations
154
+ update Update to the latest version
155
+ help Show this help information
156
+ version Show version information
157
+
158
+ Options:
159
+ -p, --port <port> Set server port (default: 3001)
160
+ --database-path <path> Set custom database location
161
+ -h, --help Show this help information
162
+ -v, --version Show version information
163
+
164
+ Examples:
165
+ $ notion-code-agent # Start with defaults
166
+ $ notion-code-agent --port 8080 # Start on port 8080
167
+ $ notion-code-agent -p 3000 # Short form for port
168
+ $ notion-code-agent start --port 4000 # Explicit start command
169
+ $ notion-code-agent status # Show configuration
170
+
171
+ Environment Variables:
172
+ SERVER_PORT Set server port (default: 3001)
173
+ PORT Set server port (default: 3001) (LEGACY)
174
+ DATABASE_PATH Set custom database location
175
+ CLAUDE_CLI_PATH Set custom Claude CLI path
176
+ CONTEXT_WINDOW Set context window size (default: 160000)
177
+
178
+ Documentation:
179
+ ${packageJson.homepage || 'https://github.com/siteboon/claudecodeui'}
180
+
181
+ Report Issues:
182
+ ${packageJson.bugs?.url || 'https://github.com/siteboon/claudecodeui/issues'}
183
+ `);
184
+ }
185
+
186
+ // Show version
187
+ function showVersion() {
188
+ console.log(`${packageJson.version}`);
189
+ }
190
+
191
+ // Compare semver versions, returns true if v1 > v2
192
+ function isNewerVersion(v1, v2) {
193
+ const parts1 = v1.split('.').map(Number);
194
+ const parts2 = v2.split('.').map(Number);
195
+ for (let i = 0; i < 3; i++) {
196
+ if (parts1[i] > parts2[i]) return true;
197
+ if (parts1[i] < parts2[i]) return false;
198
+ }
199
+ return false;
200
+ }
201
+
202
+ // Check for updates
203
+ async function checkForUpdates(silent = false) {
204
+ try {
205
+ const { execSync } = await import('child_process');
206
+ const latestVersion = execSync('npm show @siteboon/claude-code-ui version', { encoding: 'utf8' }).trim();
207
+ const currentVersion = packageJson.version;
208
+
209
+ if (isNewerVersion(latestVersion, currentVersion)) {
210
+ console.log(`\n${c.warn('[UPDATE]')} New version available: ${c.bright(latestVersion)} (current: ${currentVersion})`);
211
+ console.log(` Run ${c.bright('notion-code-agent update')} to update\n`);
212
+ return { hasUpdate: true, latestVersion, currentVersion };
213
+ } else if (!silent) {
214
+ console.log(`${c.ok('[OK]')} You are on the latest version (${currentVersion})`);
215
+ }
216
+ return { hasUpdate: false, latestVersion, currentVersion };
217
+ } catch (e) {
218
+ if (!silent) {
219
+ console.log(`${c.warn('[WARN]')} Could not check for updates`);
220
+ }
221
+ return { hasUpdate: false, error: e.message };
222
+ }
223
+ }
224
+
225
+ // Update the package
226
+ async function updatePackage() {
227
+ try {
228
+ const { execSync } = await import('child_process');
229
+ console.log(`${c.info('[INFO]')} Checking for updates...`);
230
+
231
+ const { hasUpdate, latestVersion, currentVersion } = await checkForUpdates(true);
232
+
233
+ if (!hasUpdate) {
234
+ console.log(`${c.ok('[OK]')} Already on the latest version (${currentVersion})`);
235
+ return;
236
+ }
237
+
238
+ console.log(`${c.info('[INFO]')} Updating from ${currentVersion} to ${latestVersion}...`);
239
+ execSync('npm update -g @siteboon/claude-code-ui', { stdio: 'inherit' });
240
+ console.log(`${c.ok('[OK]')} Update complete! Restart notion-code-agent to use the new version.`);
241
+ } catch (e) {
242
+ console.error(`${c.error('[ERROR]')} Update failed: ${e.message}`);
243
+ console.log(`${c.tip('[TIP]')} Try running manually: npm update -g @siteboon/claude-code-ui`);
244
+ }
245
+ }
246
+
247
+ // Start the server
248
+ async function startServer() {
249
+ // Check for updates silently on startup
250
+ checkForUpdates(true);
251
+
252
+ // Import and run the server
253
+ await import('./index.js');
254
+ }
255
+
256
+ // Parse CLI arguments
257
+ function parseArgs(args) {
258
+ const parsed = { command: 'start', options: {} };
259
+
260
+ for (let i = 0; i < args.length; i++) {
261
+ const arg = args[i];
262
+
263
+ if (arg === '--port' || arg === '-p') {
264
+ parsed.options.serverPort = args[++i];
265
+ } else if (arg.startsWith('--port=')) {
266
+ parsed.options.serverPort = arg.split('=')[1];
267
+ } else if (arg === '--database-path') {
268
+ parsed.options.databasePath = args[++i];
269
+ } else if (arg.startsWith('--database-path=')) {
270
+ parsed.options.databasePath = arg.split('=')[1];
271
+ } else if (arg === '--help' || arg === '-h') {
272
+ parsed.command = 'help';
273
+ } else if (arg === '--version' || arg === '-v') {
274
+ parsed.command = 'version';
275
+ } else if (!arg.startsWith('-')) {
276
+ parsed.command = arg;
277
+ }
278
+ }
279
+
280
+ return parsed;
281
+ }
282
+
283
+ // Main CLI handler
284
+ async function main() {
285
+ const args = process.argv.slice(2);
286
+ const { command, options } = parseArgs(args);
287
+
288
+ // Apply CLI options to environment variables
289
+ if (options.serverPort) {
290
+ process.env.SERVER_PORT = options.serverPort;
291
+ } else if (!process.env.SERVER_PORT && process.env.PORT) {
292
+ process.env.SERVER_PORT = process.env.PORT;
293
+ }
294
+ if (options.databasePath) {
295
+ process.env.DATABASE_PATH = options.databasePath;
296
+ }
297
+
298
+ switch (command) {
299
+ case 'start':
300
+ await startServer();
301
+ break;
302
+ case 'status':
303
+ case 'info':
304
+ showStatus();
305
+ break;
306
+ case 'help':
307
+ case '-h':
308
+ case '--help':
309
+ showHelp();
310
+ break;
311
+ case 'version':
312
+ case '-v':
313
+ case '--version':
314
+ showVersion();
315
+ break;
316
+ case 'update':
317
+ await updatePackage();
318
+ break;
319
+ default:
320
+ console.error(`\n❌ Unknown command: ${command}`);
321
+ console.log(' Run "notion-code-agent help" for usage information.\n');
322
+ process.exit(1);
323
+ }
324
+ }
325
+
326
+ // Run the CLI
327
+ main().catch(error => {
328
+ console.error('\n❌ Error:', error.message);
329
+ process.exit(1);
330
+ });
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Environment Flag: Is Platform / Single User Local Mode
3
+ * Indicates if the app is running in a controlled container (Platform) or bypasses auth for local dev (Single User Mode)
4
+ */
5
+ export const IS_PLATFORM = process.env.VITE_IS_PLATFORM === 'true' || process.env.VITE_SINGLE_USER_MODE === 'true';
@@ -0,0 +1,335 @@
1
+ import { spawn } from 'child_process';
2
+ import crossSpawn from 'cross-spawn';
3
+ import { notifyRunFailed, notifyRunStopped } from './services/notification-orchestrator.js';
4
+ import { cursorAdapter } from './providers/cursor/adapter.js';
5
+ import { createNormalizedMessage } from './providers/types.js';
6
+
7
+ // Use cross-spawn on Windows for better command execution
8
+ const spawnFunction = process.platform === 'win32' ? crossSpawn : spawn;
9
+
10
+ let activeCursorProcesses = new Map(); // Track active processes by session ID
11
+
12
+ const WORKSPACE_TRUST_PATTERNS = [
13
+ /workspace trust required/i,
14
+ /do you trust the contents of this directory/i,
15
+ /working with untrusted contents/i,
16
+ /pass --trust,\s*--yolo,\s*or -f/i
17
+ ];
18
+
19
+ function isWorkspaceTrustPrompt(text = '') {
20
+ if (!text || typeof text !== 'string') {
21
+ return false;
22
+ }
23
+
24
+ return WORKSPACE_TRUST_PATTERNS.some((pattern) => pattern.test(text));
25
+ }
26
+
27
+ async function spawnCursor(command, options = {}, ws) {
28
+ return new Promise(async (resolve, reject) => {
29
+ const { sessionId, projectPath, cwd, resume, toolsSettings, skipPermissions, model, sessionSummary } = options;
30
+ let capturedSessionId = sessionId; // Track session ID throughout the process
31
+ let sessionCreatedSent = false; // Track if we've already sent session-created event
32
+ let hasRetriedWithTrust = false;
33
+ let settled = false;
34
+
35
+ // Use tools settings passed from frontend, or defaults
36
+ const settings = toolsSettings || {
37
+ allowedShellCommands: [],
38
+ skipPermissions: false
39
+ };
40
+
41
+ // Build Cursor CLI command
42
+ const baseArgs = [];
43
+
44
+ // Build flags allowing both resume and prompt together (reply in existing session)
45
+ // Treat presence of sessionId as intention to resume, regardless of resume flag
46
+ if (sessionId) {
47
+ baseArgs.push('--resume=' + sessionId);
48
+ }
49
+
50
+ if (command && command.trim()) {
51
+ // Provide a prompt (works for both new and resumed sessions)
52
+ baseArgs.push('-p', command);
53
+
54
+ // Add model flag if specified (only meaningful for new sessions; harmless on resume)
55
+ if (!sessionId && model) {
56
+ baseArgs.push('--model', model);
57
+ }
58
+
59
+ // Request streaming JSON when we are providing a prompt
60
+ baseArgs.push('--output-format', 'stream-json');
61
+ }
62
+
63
+ // Add skip permissions flag if enabled
64
+ if (skipPermissions || settings.skipPermissions) {
65
+ baseArgs.push('-f');
66
+ console.log('Using -f flag (skip permissions)');
67
+ }
68
+
69
+ // Use cwd (actual project directory) instead of projectPath
70
+ const workingDir = cwd || projectPath || process.cwd();
71
+
72
+ // Store process reference for potential abort
73
+ const processKey = capturedSessionId || Date.now().toString();
74
+
75
+ const settleOnce = (callback) => {
76
+ if (settled) {
77
+ return;
78
+ }
79
+ settled = true;
80
+ callback();
81
+ };
82
+
83
+ const runCursorProcess = (args, runReason = 'initial') => {
84
+ const isTrustRetry = runReason === 'trust-retry';
85
+ let runSawWorkspaceTrustPrompt = false;
86
+ let stdoutLineBuffer = '';
87
+ let terminalNotificationSent = false;
88
+
89
+ const notifyTerminalState = ({ code = null, error = null } = {}) => {
90
+ if (terminalNotificationSent) {
91
+ return;
92
+ }
93
+
94
+ terminalNotificationSent = true;
95
+
96
+ const finalSessionId = capturedSessionId || sessionId || processKey;
97
+ if (code === 0 && !error) {
98
+ notifyRunStopped({
99
+ userId: ws?.userId || null,
100
+ provider: 'cursor',
101
+ sessionId: finalSessionId,
102
+ sessionName: sessionSummary,
103
+ stopReason: 'completed'
104
+ });
105
+ return;
106
+ }
107
+
108
+ notifyRunFailed({
109
+ userId: ws?.userId || null,
110
+ provider: 'cursor',
111
+ sessionId: finalSessionId,
112
+ sessionName: sessionSummary,
113
+ error: error || `Cursor CLI exited with code ${code}`
114
+ });
115
+ };
116
+
117
+ if (isTrustRetry) {
118
+ console.log('Retrying Cursor CLI with --trust after workspace trust prompt');
119
+ }
120
+
121
+ console.log('Spawning Cursor CLI:', 'cursor-agent', args.join(' '));
122
+ console.log('Working directory:', workingDir);
123
+ console.log('Session info - Input sessionId:', sessionId, 'Resume:', resume);
124
+
125
+ const cursorProcess = spawnFunction('cursor-agent', args, {
126
+ cwd: workingDir,
127
+ stdio: ['pipe', 'pipe', 'pipe'],
128
+ env: { ...process.env } // Inherit all environment variables
129
+ });
130
+
131
+ activeCursorProcesses.set(processKey, cursorProcess);
132
+
133
+ const shouldSuppressForTrustRetry = (text) => {
134
+ if (hasRetriedWithTrust || args.includes('--trust')) {
135
+ return false;
136
+ }
137
+ if (!isWorkspaceTrustPrompt(text)) {
138
+ return false;
139
+ }
140
+
141
+ runSawWorkspaceTrustPrompt = true;
142
+ return true;
143
+ };
144
+
145
+ const processCursorOutputLine = (line) => {
146
+ if (!line || !line.trim()) {
147
+ return;
148
+ }
149
+
150
+ try {
151
+ const response = JSON.parse(line);
152
+ console.log('Parsed JSON response:', response);
153
+
154
+ // Handle different message types
155
+ switch (response.type) {
156
+ case 'system':
157
+ if (response.subtype === 'init') {
158
+ // Capture session ID
159
+ if (response.session_id && !capturedSessionId) {
160
+ capturedSessionId = response.session_id;
161
+ console.log('Captured session ID:', capturedSessionId);
162
+
163
+ // Update process key with captured session ID
164
+ if (processKey !== capturedSessionId) {
165
+ activeCursorProcesses.delete(processKey);
166
+ activeCursorProcesses.set(capturedSessionId, cursorProcess);
167
+ }
168
+
169
+ // Set session ID on writer (for API endpoint compatibility)
170
+ if (ws.setSessionId && typeof ws.setSessionId === 'function') {
171
+ ws.setSessionId(capturedSessionId);
172
+ }
173
+
174
+ // Send session-created event only once for new sessions
175
+ if (!sessionId && !sessionCreatedSent) {
176
+ sessionCreatedSent = true;
177
+ ws.send(createNormalizedMessage({ kind: 'session_created', newSessionId: capturedSessionId, model: response.model, cwd: response.cwd, sessionId: capturedSessionId, provider: 'cursor' }));
178
+ }
179
+ }
180
+
181
+ // System info — no longer needed by the frontend (session-lifecycle 'created' handles nav).
182
+ }
183
+ break;
184
+
185
+ case 'user':
186
+ // User messages are not displayed in the UI — skip.
187
+ break;
188
+
189
+ case 'assistant':
190
+ // Accumulate assistant message chunks
191
+ if (response.message && response.message.content && response.message.content.length > 0) {
192
+ const normalized = cursorAdapter.normalizeMessage(response, capturedSessionId || sessionId || null);
193
+ for (const msg of normalized) ws.send(msg);
194
+ }
195
+ break;
196
+
197
+ case 'result': {
198
+ // Session complete — send stream end + lifecycle complete with result payload
199
+ console.log('Cursor session result:', response);
200
+ const resultText = typeof response.result === 'string' ? response.result : '';
201
+ ws.send(createNormalizedMessage({
202
+ kind: 'complete',
203
+ exitCode: response.subtype === 'success' ? 0 : 1,
204
+ resultText,
205
+ isError: response.subtype !== 'success',
206
+ sessionId: capturedSessionId || sessionId, provider: 'cursor',
207
+ }));
208
+ break;
209
+ }
210
+
211
+ default:
212
+ // Unknown message types — ignore.
213
+ }
214
+ } catch (parseError) {
215
+ console.log('Non-JSON response:', line);
216
+
217
+ if (shouldSuppressForTrustRetry(line)) {
218
+ return;
219
+ }
220
+
221
+ // If not JSON, send as stream delta via adapter
222
+ const normalized = cursorAdapter.normalizeMessage(line, capturedSessionId || sessionId || null);
223
+ for (const msg of normalized) ws.send(msg);
224
+ }
225
+ };
226
+
227
+ // Handle stdout (streaming JSON responses)
228
+ cursorProcess.stdout.on('data', (data) => {
229
+ const rawOutput = data.toString();
230
+ console.log('Cursor CLI stdout:', rawOutput);
231
+
232
+ // Stream chunks can split JSON objects across packets; keep trailing partial line.
233
+ stdoutLineBuffer += rawOutput;
234
+ const completeLines = stdoutLineBuffer.split(/\r?\n/);
235
+ stdoutLineBuffer = completeLines.pop() || '';
236
+
237
+ completeLines.forEach((line) => {
238
+ processCursorOutputLine(line.trim());
239
+ });
240
+ });
241
+
242
+ // Handle stderr
243
+ cursorProcess.stderr.on('data', (data) => {
244
+ const stderrText = data.toString();
245
+ console.error('Cursor CLI stderr:', stderrText);
246
+
247
+ if (shouldSuppressForTrustRetry(stderrText)) {
248
+ return;
249
+ }
250
+
251
+ ws.send(createNormalizedMessage({ kind: 'error', content: stderrText, sessionId: capturedSessionId || sessionId || null, provider: 'cursor' }));
252
+ });
253
+
254
+ // Handle process completion
255
+ cursorProcess.on('close', async (code) => {
256
+ console.log(`Cursor CLI process exited with code ${code}`);
257
+
258
+ const finalSessionId = capturedSessionId || sessionId || processKey;
259
+ activeCursorProcesses.delete(finalSessionId);
260
+
261
+ // Flush any final unterminated stdout line before completion handling.
262
+ if (stdoutLineBuffer.trim()) {
263
+ processCursorOutputLine(stdoutLineBuffer.trim());
264
+ stdoutLineBuffer = '';
265
+ }
266
+
267
+ if (
268
+ runSawWorkspaceTrustPrompt &&
269
+ code !== 0 &&
270
+ !hasRetriedWithTrust &&
271
+ !args.includes('--trust')
272
+ ) {
273
+ hasRetriedWithTrust = true;
274
+ runCursorProcess([...args, '--trust'], 'trust-retry');
275
+ return;
276
+ }
277
+
278
+ ws.send(createNormalizedMessage({ kind: 'complete', exitCode: code, isNewSession: !sessionId && !!command, sessionId: finalSessionId, provider: 'cursor' }));
279
+
280
+ if (code === 0) {
281
+ notifyTerminalState({ code });
282
+ settleOnce(() => resolve());
283
+ } else {
284
+ notifyTerminalState({ code });
285
+ settleOnce(() => reject(new Error(`Cursor CLI exited with code ${code}`)));
286
+ }
287
+ });
288
+
289
+ // Handle process errors
290
+ cursorProcess.on('error', (error) => {
291
+ console.error('Cursor CLI process error:', error);
292
+
293
+ // Clean up process reference on error
294
+ const finalSessionId = capturedSessionId || sessionId || processKey;
295
+ activeCursorProcesses.delete(finalSessionId);
296
+
297
+ ws.send(createNormalizedMessage({ kind: 'error', content: error.message, sessionId: capturedSessionId || sessionId || null, provider: 'cursor' }));
298
+ notifyTerminalState({ error });
299
+
300
+ settleOnce(() => reject(error));
301
+ });
302
+
303
+ // Close stdin since Cursor doesn't need interactive input
304
+ cursorProcess.stdin.end();
305
+ };
306
+
307
+ runCursorProcess(baseArgs, 'initial');
308
+ });
309
+ }
310
+
311
+ function abortCursorSession(sessionId) {
312
+ const process = activeCursorProcesses.get(sessionId);
313
+ if (process) {
314
+ console.log(`Aborting Cursor session: ${sessionId}`);
315
+ process.kill('SIGTERM');
316
+ activeCursorProcesses.delete(sessionId);
317
+ return true;
318
+ }
319
+ return false;
320
+ }
321
+
322
+ function isCursorSessionActive(sessionId) {
323
+ return activeCursorProcesses.has(sessionId);
324
+ }
325
+
326
+ function getActiveCursorSessions() {
327
+ return Array.from(activeCursorProcesses.keys());
328
+ }
329
+
330
+ export {
331
+ spawnCursor,
332
+ abortCursorSession,
333
+ isCursorSessionActive,
334
+ getActiveCursorSessions
335
+ };