@radnine/claude-session-daemon 0.6.0 → 0.6.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@radnine/claude-session-daemon",
3
- "version": "0.6.0",
3
+ "version": "0.6.2",
4
4
  "description": "Node.js daemon for managing Claude CLI sessions",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -38,6 +38,7 @@ class ClaudeProcess extends EventEmitter {
38
38
  this._logger = options.logger || _defaultLogger();
39
39
  this._claudeCommand = options.claudeCommand || 'claude';
40
40
  this._skipPermissions = options.skipPermissions || false;
41
+ this._permissionPort = options.permissionPort || null;
41
42
  this._spawnFn = options._spawnFn || defaultSpawn;
42
43
 
43
44
  this._state = 'idle';
@@ -82,6 +83,9 @@ class ClaudeProcess extends EventEmitter {
82
83
  }
83
84
 
84
85
  const env = { ...process.env, CLAUDE_SESSION_ID: this._sessionId };
86
+ if (this._permissionPort) {
87
+ env.CLAUDE_PERMISSION_PORT = String(this._permissionPort);
88
+ }
85
89
  delete env.CLAUDECODE; // Prevent nested session detection
86
90
 
87
91
  const opts = {
package/src/config.js CHANGED
@@ -54,6 +54,12 @@ function loadConfig() {
54
54
 
55
55
  // Skip Claude CLI permission prompts (only safe inside Docker containers)
56
56
  skipPermissions: env.CLAUDE_SKIP_PERMISSIONS === 'true',
57
+
58
+ // Permission approval timeout in seconds (0 = disabled)
59
+ permissionTimeout: intEnv(env.CLAUDE_PERMISSION_TIMEOUT, 60),
60
+
61
+ // Permission server port (0 = random, only used when skipPermissions is false)
62
+ permissionPort: intEnv(env.CLAUDE_PERMISSION_PORT, 0),
57
63
  };
58
64
 
59
65
  // Validate mode
@@ -2,9 +2,12 @@
2
2
 
3
3
  const crypto = require('node:crypto');
4
4
  const os = require('node:os');
5
+ const path = require('node:path');
6
+ const fs = require('node:fs').promises;
5
7
  const WebSocket = require('ws');
6
8
  const { BaseConnection } = require('./base-connection');
7
9
  const { getGitContext } = require('../git-context');
10
+ const daemonPkg = require('../../package.json');
8
11
 
9
12
  /**
10
13
  * ActionCable WebSocket client that connects to a Rails server.
@@ -47,6 +50,10 @@ class ActionCableClient extends BaseConnection {
47
50
  this._maxReconnectDelay = 30000;
48
51
  this._reconnectTimer = null;
49
52
 
53
+ // Auth failure tracking — stop reconnecting after repeated rejections
54
+ this._consecutiveRejections = 0;
55
+ this._maxConsecutiveRejections = 3;
56
+
50
57
  // Heartbeat / ping tracking
51
58
  this._lastPingAt = null;
52
59
  this._heartbeatTimer = null;
@@ -54,11 +61,36 @@ class ActionCableClient extends BaseConnection {
54
61
  // Command tracking per session
55
62
  this._activeCommands = new Map(); // sessionId -> commandId
56
63
  this._sequences = new Map(); // sessionId -> sequence counter
64
+ this._cancelledSessions = new Set(); // sessionIds with pending cancel (suppress exit→complete)
65
+
66
+ // Permission server reference (set externally via setPermissionServer)
67
+ this._permissionServer = null;
57
68
 
58
69
  // Store config for session activation
59
70
  this._config = config;
60
71
  }
61
72
 
73
+ /**
74
+ * Attach a PermissionServer instance for forwarding permission requests.
75
+ * @param {PermissionServer} server
76
+ */
77
+ setPermissionServer(server) {
78
+ this._permissionServer = server;
79
+
80
+ server.on('permission_request', (req) => {
81
+ this._forwardPermissionRequest(req);
82
+ });
83
+
84
+ server.on('permission_timeout', ({ requestId, sessionId }) => {
85
+ this.sendDaemonMessage({
86
+ type: 'permission_timeout',
87
+ request_id: requestId,
88
+ session_id: sessionId,
89
+ timestamp: new Date().toISOString(),
90
+ });
91
+ });
92
+ }
93
+
62
94
  /** The daemon ID used for channel subscriptions. */
63
95
  get daemonId() {
64
96
  return this._daemonId;
@@ -161,6 +193,13 @@ class ActionCableClient extends BaseConnection {
161
193
  * @param {number} durationMs
162
194
  */
163
195
  sendComplete(sessionId, commandId, exitCode, durationMs) {
196
+ // Suppress the exit→complete event for sessions that were cancelled.
197
+ // The command_cancelled message is sent separately by _handleCommandCancel.
198
+ if (this._cancelledSessions && this._cancelledSessions.has(sessionId)) {
199
+ this._cancelledSessions.delete(sessionId);
200
+ return;
201
+ }
202
+
164
203
  const resolvedCommandId = commandId || this._activeCommands.get(sessionId) || null;
165
204
 
166
205
  this.sendDaemonMessage({
@@ -374,6 +413,7 @@ class ActionCableClient extends BaseConnection {
374
413
  _handleSubscriptionConfirmed(msg) {
375
414
  this._subscribed = true;
376
415
  this._reconnectAttempts = 0; // Backoff resets only after full connect+subscribe success
416
+ this._consecutiveRejections = 0; // Auth is valid — reset rejection counter
377
417
  this._logger.info('PilotChannel subscription confirmed');
378
418
  this.emit('subscribed');
379
419
  this._sendDaemonRegistration();
@@ -384,8 +424,20 @@ class ActionCableClient extends BaseConnection {
384
424
  */
385
425
  _handleSubscriptionRejected(msg) {
386
426
  this._subscribed = false;
427
+ this._consecutiveRejections += 1;
387
428
  const reason = (msg && msg.reason) || 'unknown';
388
- this._logger.warn(`PilotChannel subscription rejected (reason: ${reason}, attempt: ${this._reconnectAttempts + 1}). Backoff will increase.`);
429
+
430
+ if (this._consecutiveRejections >= this._maxConsecutiveRejections) {
431
+ this._logger.error(
432
+ `PilotChannel subscription rejected ${this._consecutiveRejections} times consecutively. ` +
433
+ `This likely means the auth token is invalid or revoked. Stopping reconnection. ` +
434
+ `Check CLAUDE_AUTH_TOKEN and re-provision if needed.`
435
+ );
436
+ this.emit('auth_failed', { reason, attempts: this._consecutiveRejections });
437
+ return; // Do NOT schedule reconnect — auth won't self-heal
438
+ }
439
+
440
+ this._logger.warn(`PilotChannel subscription rejected (reason: ${reason}, rejection: ${this._consecutiveRejections}/${this._maxConsecutiveRejections}). Backoff will increase.`);
389
441
  // Do NOT reset _reconnectAttempts here — let backoff escalate to avoid tight loop
390
442
  this._scheduleReconnect();
391
443
  }
@@ -427,9 +479,21 @@ class ActionCableClient extends BaseConnection {
427
479
  case 'session_pause':
428
480
  this._handleSessionPause(inner);
429
481
  break;
482
+ case 'command_cancel':
483
+ this._handleCommandCancel(inner);
484
+ break;
430
485
  case 'session_deactivate':
431
486
  this._handleSessionDeactivation(inner);
432
487
  break;
488
+ case 'file_request':
489
+ this._handleFileRequest(inner);
490
+ break;
491
+ case 'permission_response':
492
+ this._handlePermissionResponse(inner);
493
+ break;
494
+ case 'auth_error':
495
+ this._handleAuthError(inner);
496
+ break;
433
497
  default:
434
498
  this._logger.warn(`Unknown channel message type: ${inner.type}`);
435
499
  break;
@@ -439,6 +503,21 @@ class ActionCableClient extends BaseConnection {
439
503
  this.emit('message', inner);
440
504
  }
441
505
 
506
+ /**
507
+ * Handle auth_error message from server — stop reconnecting immediately.
508
+ * The server sends this before rejecting the subscription when the token
509
+ * is invalid, revoked, or the pilot is suspended.
510
+ */
511
+ _handleAuthError(msg) {
512
+ const reason = msg.reason || 'unknown';
513
+ const message = msg.message || 'Authentication failed.';
514
+ this._logger.error(
515
+ `Server auth error: ${reason} — ${message} Stopping reconnection.`
516
+ );
517
+ this._shutdownRequested = true;
518
+ this.emit('auth_failed', { reason, message });
519
+ }
520
+
442
521
  // ---------------------------------------------------------------------------
443
522
  // Daemon registration and heartbeat
444
523
  // ---------------------------------------------------------------------------
@@ -453,7 +532,7 @@ class ActionCableClient extends BaseConnection {
453
532
 
454
533
  this.sendDaemonMessage({
455
534
  type: 'pilot_connect',
456
- version: '1.0',
535
+ version: daemonPkg.version,
457
536
  auth: {
458
537
  token: this._authToken,
459
538
  pilot_id: this._daemonId,
@@ -543,7 +622,7 @@ class ActionCableClient extends BaseConnection {
543
622
  * Handle command_execute and slash_command — send command text to a session process.
544
623
  * @param {object} message
545
624
  */
546
- _handleCommandExecution(message) {
625
+ async _handleCommandExecution(message) {
547
626
  const sessionId = message.session_id;
548
627
  const commandId = message.command_id;
549
628
  const command = message.command;
@@ -558,14 +637,23 @@ class ActionCableClient extends BaseConnection {
558
637
  try {
559
638
  this._daemon.sendMessage(sessionId, command);
560
639
  } catch (err) {
561
- this._logger.error('Command execution failed', { sessionId, error: err.message });
562
- this._sendError('COMMAND_EXECUTION_FAILED', err.message, {
563
- session_id: sessionId,
564
- command_id: commandId,
565
- command: command,
566
- });
567
- // Clear active command on failure
568
- this._activeCommands.delete(sessionId);
640
+ // Session process may be dead (e.g. after cancel). Try to re-activate
641
+ // and retry once before giving up.
642
+ this._logger.warn('Command execution failed, attempting re-activation', { sessionId, error: err.message });
643
+ try {
644
+ await this._daemon.activateSession(sessionId);
645
+ this._daemon.sendMessage(sessionId, command);
646
+ this._logger.info('Command sent after re-activation', { sessionId, commandId });
647
+ } catch (retryErr) {
648
+ this._logger.error('Command execution failed after re-activation', { sessionId, error: retryErr.message });
649
+ this._sendError('COMMAND_EXECUTION_FAILED', retryErr.message, {
650
+ session_id: sessionId,
651
+ command_id: commandId,
652
+ command: command,
653
+ });
654
+ // Clear active command on failure
655
+ this._activeCommands.delete(sessionId);
656
+ }
569
657
  }
570
658
  }
571
659
 
@@ -582,6 +670,94 @@ class ActionCableClient extends BaseConnection {
582
670
  this._sendRecoveryStatus(sessionId, 'completed', 'recovery_finished');
583
671
  }
584
672
 
673
+ /**
674
+ * Forward a permission request from the PermissionServer to Rails.
675
+ * @param {object} req - Permission request from PermissionServer
676
+ */
677
+ _forwardPermissionRequest(req) {
678
+ this._logger.info('Forwarding permission request to Rails', {
679
+ requestId: req.requestId,
680
+ sessionId: req.sessionId,
681
+ toolName: req.toolName,
682
+ });
683
+
684
+ this.sendDaemonMessage({
685
+ type: 'permission_request',
686
+ request_id: req.requestId,
687
+ session_id: req.sessionId,
688
+ command_id: this._activeCommands.get(req.sessionId) || null,
689
+ tool_name: req.toolName,
690
+ tool_input: req.toolInput,
691
+ file_path: req.filePath,
692
+ description: req.description,
693
+ risk_level: req.riskLevel,
694
+ timeout_seconds: req.timeoutSeconds,
695
+ timestamp: new Date().toISOString(),
696
+ });
697
+ }
698
+
699
+ /**
700
+ * Handle permission_response from Rails — route to PermissionServer.
701
+ * @param {object} message
702
+ */
703
+ _handlePermissionResponse(message) {
704
+ const requestId = message.request_id;
705
+ const decision = message.decision;
706
+
707
+ this._logger.info('Permission response received from Rails', { requestId, decision });
708
+
709
+ if (this._permissionServer) {
710
+ this._permissionServer.resolve(requestId, decision, message.reason);
711
+ } else {
712
+ this._logger.warn('No permission server to route response to', { requestId });
713
+ }
714
+ }
715
+
716
+ /**
717
+ * Handle command_cancel — cancel the active command for a session, preserving
718
+ * the Claude CLI session ID so the next command resumes the conversation.
719
+ * @param {object} message
720
+ */
721
+ async _handleCommandCancel(message) {
722
+ const sessionId = message.session_id;
723
+ const commandId = message.command_id;
724
+ this._logger.info('Cancelling command', { sessionId, commandId });
725
+
726
+ try {
727
+ // Mark session as cancelled before killing, so the session:exit event
728
+ // doesn't produce a spurious 'complete' message.
729
+ this._cancelledSessions.add(sessionId);
730
+
731
+ const result = await this._daemon.cancelSession(sessionId);
732
+
733
+ if (result.success) {
734
+ // Clear active command tracking
735
+ this._activeCommands.delete(sessionId);
736
+
737
+ // Notify Rails that the command was cancelled
738
+ this.sendDaemonMessage({
739
+ type: 'command_cancelled',
740
+ session_id: sessionId,
741
+ command_id: commandId,
742
+ timestamp: new Date().toISOString(),
743
+ });
744
+ } else {
745
+ this._cancelledSessions.delete(sessionId);
746
+ this._sendError('CANCEL_FAILED', result.message, {
747
+ session_id: sessionId,
748
+ command_id: commandId,
749
+ });
750
+ }
751
+ } catch (err) {
752
+ this._cancelledSessions.delete(sessionId);
753
+ this._logger.error('Failed to cancel command', { sessionId, error: err.message });
754
+ this._sendError('CANCEL_FAILED', err.message, {
755
+ session_id: sessionId,
756
+ command_id: commandId,
757
+ });
758
+ }
759
+ }
760
+
585
761
  /**
586
762
  * Handle session_pause — cancel session gracefully, saving claudeSessionId for resume.
587
763
  * @param {object} message
@@ -614,6 +790,85 @@ class ActionCableClient extends BaseConnection {
614
790
  }
615
791
  }
616
792
 
793
+ /**
794
+ * Handle file_request — read a file from the working directory and send its contents back.
795
+ * Only allows .md/.markdown files within the working directory (no path traversal).
796
+ * @param {object} message
797
+ */
798
+ async _handleFileRequest(message) {
799
+ const requestedPath = message.path;
800
+ const requestId = message.request_id;
801
+ const projectId = message.project_id;
802
+
803
+ this._logger.info('Received file_request', { path: requestedPath, requestId, projectId });
804
+
805
+ const sendError = (errorMessage) => {
806
+ this._logger.warn('File request failed', { path: requestedPath, error: errorMessage });
807
+ this.sendDaemonMessage({
808
+ type: 'file_response',
809
+ request_id: requestId,
810
+ project_id: projectId,
811
+ path: requestedPath,
812
+ error: errorMessage,
813
+ timestamp: new Date().toISOString(),
814
+ });
815
+ };
816
+
817
+ // Validate extension: must be .md or .markdown (case-insensitive)
818
+ const ext = path.extname(requestedPath).toLowerCase();
819
+ if (ext !== '.md' && ext !== '.markdown') {
820
+ sendError('Invalid file type: only .md and .markdown files are allowed');
821
+ return;
822
+ }
823
+
824
+ // Validate path security: no traversal outside working directory
825
+ const resolvedPath = path.resolve(this._workingDir, requestedPath);
826
+ if (!resolvedPath.startsWith(this._workingDir)) {
827
+ sendError('Access denied: path is outside the working directory');
828
+ return;
829
+ }
830
+
831
+ // Check for .. components in the relative path
832
+ const normalizedRelative = path.relative(this._workingDir, resolvedPath);
833
+ if (normalizedRelative.split(path.sep).includes('..')) {
834
+ sendError('Access denied: path contains directory traversal');
835
+ return;
836
+ }
837
+
838
+ try {
839
+ const stats = await fs.stat(resolvedPath);
840
+
841
+ // Check file size: reject files > 1MB
842
+ if (stats.size > 1048576) {
843
+ sendError(`File too large: ${stats.size} bytes exceeds 1MB limit`);
844
+ return;
845
+ }
846
+
847
+ const fileContent = await fs.readFile(resolvedPath, 'utf-8');
848
+
849
+ this._logger.info('File request fulfilled', { path: requestedPath, size: stats.size });
850
+
851
+ this.sendDaemonMessage({
852
+ type: 'file_response',
853
+ request_id: requestId,
854
+ project_id: projectId,
855
+ path: requestedPath,
856
+ content: fileContent,
857
+ updated_at: stats.mtime.toISOString(),
858
+ size_bytes: stats.size,
859
+ timestamp: new Date().toISOString(),
860
+ });
861
+ } catch (err) {
862
+ if (err.code === 'ENOENT') {
863
+ sendError('File not found');
864
+ } else if (err.code === 'EACCES') {
865
+ sendError('Permission denied');
866
+ } else {
867
+ sendError(`Failed to read file: ${err.message}`);
868
+ }
869
+ }
870
+ }
871
+
617
872
  // ---------------------------------------------------------------------------
618
873
  // Outbound helper methods
619
874
  // ---------------------------------------------------------------------------
@@ -706,6 +961,7 @@ class ActionCableClient extends BaseConnection {
706
961
  this.sendDaemonMessage({
707
962
  type: 'heartbeat',
708
963
  pilot_id: this._daemonId,
964
+ version: daemonPkg.version,
709
965
  status: 'healthy',
710
966
  session_summary: this._getSessionSummary(),
711
967
  resource_usage: this._getResourceUsage(),
package/src/daemon.js CHANGED
@@ -125,6 +125,7 @@ class Daemon extends EventEmitter {
125
125
  * @returns {Promise<ClaudeProcess>}
126
126
  */
127
127
  async activateSession(sessionId, options = {}) {
128
+ sessionId = String(sessionId); // Normalize — Rails sends integers, Map keys must match
128
129
  // If process exists and alive, return it
129
130
  const existing = this._processes.get(sessionId);
130
131
  if (existing && existing.isAlive()) {
@@ -157,6 +158,7 @@ class Daemon extends EventEmitter {
157
158
  claudeSessionId,
158
159
  resume: shouldResume,
159
160
  skipPermissions: this._config.skipPermissions,
161
+ permissionPort: this._permissionPort || null,
160
162
  logger: this._logger.child(`Session:${sessionId}`),
161
163
  });
162
164
 
@@ -181,6 +183,7 @@ class Daemon extends EventEmitter {
181
183
  * @returns {ClaudeProcess|null}
182
184
  */
183
185
  getProcess(sessionId) {
186
+ sessionId = String(sessionId);
184
187
  const proc = this._processes.get(sessionId);
185
188
  if (!proc) return null;
186
189
 
@@ -200,6 +203,7 @@ class Daemon extends EventEmitter {
200
203
  * @throws {Error} if session not found
201
204
  */
202
205
  sendMessage(sessionId, text) {
206
+ sessionId = String(sessionId);
203
207
  const proc = this.getProcess(sessionId);
204
208
  if (!proc) {
205
209
  throw new Error(`Session not found: "${sessionId}"`);
@@ -213,6 +217,7 @@ class Daemon extends EventEmitter {
213
217
  * @param {string} sessionId
214
218
  */
215
219
  async terminateSession(sessionId) {
220
+ sessionId = String(sessionId);
216
221
  const proc = this._processes.get(sessionId);
217
222
  if (!proc) return;
218
223
 
@@ -232,6 +237,7 @@ class Daemon extends EventEmitter {
232
237
  * @returns {Promise<{success: boolean, message: string}>}
233
238
  */
234
239
  async cancelSession(sessionId) {
240
+ sessionId = String(sessionId);
235
241
  const proc = this._processes.get(sessionId);
236
242
 
237
243
  if (!proc) {
package/src/index.js CHANGED
@@ -38,6 +38,28 @@ function main() {
38
38
  }
39
39
 
40
40
  const client = new ActionCableClient(daemon, config, logger);
41
+
42
+ // Start permission server if permissions are not skipped
43
+ if (!config.skipPermissions) {
44
+ const { PermissionServer } = require('./permission-server');
45
+ const permServer = new PermissionServer({
46
+ port: config.permissionPort,
47
+ timeout: config.permissionTimeout,
48
+ }, createLogger({ level: config.logLevel, module: 'PermissionServer' }));
49
+
50
+ permServer.start().then((port) => {
51
+ logger.info('Permission server started', { port });
52
+ client.setPermissionServer(permServer);
53
+
54
+ // Make port available to Claude CLI hook scripts
55
+ daemon._permissionPort = port;
56
+ });
57
+
58
+ daemon.on('stopped', () => {
59
+ permServer.stop();
60
+ });
61
+ }
62
+
41
63
  client.start();
42
64
 
43
65
  client.on('subscribed', () => {
@@ -52,6 +74,12 @@ function main() {
52
74
  logger.warn('Disconnected from Rails server');
53
75
  });
54
76
 
77
+ client.on('auth_failed', ({ reason, message }) => {
78
+ logger.error(`Authentication failed (${reason}): ${message}`);
79
+ logger.error('Daemon cannot operate without valid auth. Exiting.');
80
+ process.exit(1);
81
+ });
82
+
55
83
  // Graceful shutdown
56
84
  daemon.on('stopped', () => {
57
85
  client.stop();
@@ -0,0 +1,266 @@
1
+ 'use strict';
2
+
3
+ const http = require('node:http');
4
+ const { randomUUID } = require('node:crypto');
5
+ const { EventEmitter } = require('node:events');
6
+
7
+ /**
8
+ * Local HTTP server that receives permission requests from Claude CLI hooks
9
+ * and blocks until a decision is received from FlightDeck.
10
+ *
11
+ * The PreToolUse hook script POSTs to this server, which holds the connection
12
+ * open until the permission is approved/denied/timed out.
13
+ *
14
+ * Emits:
15
+ * 'permission_request' — { requestId, sessionId, toolName, toolInput, filePath, description, riskLevel }
16
+ *
17
+ * @example
18
+ * const server = new PermissionServer({ port: 0, timeout: 60 }, logger);
19
+ * server.on('permission_request', (req) => forwardToRails(req));
20
+ * server.start();
21
+ * // Later, when user responds:
22
+ * server.resolve('perm_abc123', 'approve');
23
+ */
24
+ class PermissionServer extends EventEmitter {
25
+ /**
26
+ * @param {object} config
27
+ * @param {number} [config.port=0] - Port to listen on (0 = random)
28
+ * @param {number} [config.timeout=60] - Default timeout in seconds
29
+ * @param {object} logger
30
+ */
31
+ constructor(config = {}, logger) {
32
+ super();
33
+ this._port = config.port || 0;
34
+ this._defaultTimeout = config.timeout || 60;
35
+ this._logger = logger;
36
+ this._server = null;
37
+
38
+ // Map of requestId -> { resolve, timer, sessionId }
39
+ this._pending = new Map();
40
+ }
41
+
42
+ /** Actual port the server is listening on. */
43
+ get port() {
44
+ const addr = this._server?.address();
45
+ return addr ? addr.port : this._port;
46
+ }
47
+
48
+ /**
49
+ * Start the HTTP server.
50
+ * @returns {Promise<number>} The port the server is listening on.
51
+ */
52
+ start() {
53
+ return new Promise((resolve) => {
54
+ this._server = http.createServer((req, res) => this._handleRequest(req, res));
55
+
56
+ this._server.listen(this._port, '127.0.0.1', () => {
57
+ const addr = this._server.address();
58
+ this._logger.info(`Permission server listening on 127.0.0.1:${addr.port}`);
59
+ resolve(addr.port);
60
+ });
61
+ });
62
+ }
63
+
64
+ /**
65
+ * Stop the server and deny all pending requests.
66
+ * @returns {Promise<void>}
67
+ */
68
+ async stop() {
69
+ // Deny all pending requests
70
+ for (const [requestId] of this._pending) {
71
+ this.resolve(requestId, 'deny', 'Daemon shutting down');
72
+ }
73
+
74
+ return new Promise((resolve) => {
75
+ if (this._server) {
76
+ this._server.close(() => resolve());
77
+ } else {
78
+ resolve();
79
+ }
80
+ });
81
+ }
82
+
83
+ /**
84
+ * Resolve a pending permission request.
85
+ * @param {string} requestId
86
+ * @param {string} decision - 'approve' or 'deny'
87
+ * @param {string} [reason] - Optional reason for denial
88
+ */
89
+ resolve(requestId, decision, reason) {
90
+ const pending = this._pending.get(requestId);
91
+ if (!pending) {
92
+ this._logger.warn('Permission response for unknown request', { requestId });
93
+ return;
94
+ }
95
+
96
+ clearTimeout(pending.timer);
97
+ this._pending.delete(requestId);
98
+
99
+ this._logger.info('Permission resolved', { requestId, decision });
100
+ pending.resolve({ decision, reason });
101
+ }
102
+
103
+ /**
104
+ * Deny all pending requests for a session (e.g., on disconnect).
105
+ * @param {string} sessionId
106
+ */
107
+ denyAllForSession(sessionId) {
108
+ for (const [requestId, pending] of this._pending) {
109
+ if (pending.sessionId === sessionId) {
110
+ this.resolve(requestId, 'deny', 'Session disconnected');
111
+ }
112
+ }
113
+ }
114
+
115
+ /** Number of pending requests. */
116
+ get pendingCount() {
117
+ return this._pending.size;
118
+ }
119
+
120
+ // ---------------------------------------------------------------------------
121
+ // Internal
122
+ // ---------------------------------------------------------------------------
123
+
124
+ /**
125
+ * Handle incoming HTTP request from the hook script.
126
+ */
127
+ _handleRequest(req, res) {
128
+ if (req.method !== 'POST' || !req.url.startsWith('/permissions/request')) {
129
+ res.writeHead(404, { 'Content-Type': 'application/json' });
130
+ res.end(JSON.stringify({ error: 'Not found' }));
131
+ return;
132
+ }
133
+
134
+ let body = '';
135
+ req.on('data', (chunk) => { body += chunk; });
136
+ req.on('end', () => {
137
+ try {
138
+ const data = JSON.parse(body);
139
+ this._handlePermissionRequest(data, res);
140
+ } catch (err) {
141
+ this._logger.error('Failed to parse permission request', { error: err.message });
142
+ res.writeHead(400, { 'Content-Type': 'application/json' });
143
+ res.end(JSON.stringify({ error: 'Invalid JSON' }));
144
+ }
145
+ });
146
+ }
147
+
148
+ /**
149
+ * Process a permission request and hold the connection open.
150
+ */
151
+ _handlePermissionRequest(data, res) {
152
+ const requestId = `perm_${randomUUID().slice(0, 12)}`;
153
+ const sessionId = data.session_id || 'unknown';
154
+ const toolName = data.tool_name || 'unknown';
155
+ const toolInput = data.tool_input || {};
156
+ const filePath = this._extractFilePath(toolName, toolInput);
157
+ const description = this._buildDescription(toolName, toolInput);
158
+ const riskLevel = this._classifyRisk(toolName, toolInput);
159
+ const timeoutSeconds = this._defaultTimeout;
160
+
161
+ this._logger.info('Permission request received', { requestId, sessionId, toolName, riskLevel });
162
+
163
+ // Create a promise that will be resolved when the user responds
164
+ const resultPromise = new Promise((resolve) => {
165
+ const timer = setTimeout(() => {
166
+ this._logger.warn('Permission request timed out', { requestId });
167
+ this._pending.delete(requestId);
168
+ resolve({ decision: 'deny', reason: 'Timed out waiting for approval' });
169
+ this.emit('permission_timeout', { requestId, sessionId });
170
+ }, timeoutSeconds * 1000);
171
+
172
+ this._pending.set(requestId, { resolve, timer, sessionId });
173
+ });
174
+
175
+ // Emit the request for the connection layer to forward to Rails
176
+ this.emit('permission_request', {
177
+ requestId,
178
+ sessionId,
179
+ toolName,
180
+ toolInput,
181
+ filePath,
182
+ description,
183
+ riskLevel,
184
+ timeoutSeconds,
185
+ });
186
+
187
+ // Hold the HTTP connection open until resolved
188
+ resultPromise.then(({ decision, reason }) => {
189
+ const hookResponse = this._buildHookResponse(decision, reason);
190
+ res.writeHead(200, { 'Content-Type': 'application/json' });
191
+ res.end(JSON.stringify(hookResponse));
192
+ });
193
+ }
194
+
195
+ /**
196
+ * Extract the file path from tool input if applicable.
197
+ */
198
+ _extractFilePath(toolName, toolInput) {
199
+ switch (toolName) {
200
+ case 'Write':
201
+ case 'Read':
202
+ case 'Edit':
203
+ return toolInput.file_path || toolInput.path || null;
204
+ case 'Bash':
205
+ return null;
206
+ default:
207
+ return toolInput.file_path || toolInput.path || null;
208
+ }
209
+ }
210
+
211
+ /**
212
+ * Build a human-readable description of the tool action.
213
+ */
214
+ _buildDescription(toolName, toolInput) {
215
+ switch (toolName) {
216
+ case 'Bash':
217
+ return `Execute: ${(toolInput.command || '').slice(0, 200)}`;
218
+ case 'Write':
219
+ return `Write file: ${toolInput.file_path || 'unknown'}`;
220
+ case 'Edit':
221
+ return `Edit file: ${toolInput.file_path || 'unknown'}`;
222
+ case 'Read':
223
+ return `Read file: ${toolInput.file_path || 'unknown'}`;
224
+ default:
225
+ return `${toolName}: ${JSON.stringify(toolInput).slice(0, 200)}`;
226
+ }
227
+ }
228
+
229
+ /**
230
+ * Classify risk level based on tool type and input.
231
+ */
232
+ _classifyRisk(toolName, toolInput) {
233
+ if (toolName === 'Bash') return 'high';
234
+ if (toolName === 'Write') {
235
+ // Overwriting existing files is higher risk
236
+ return 'medium';
237
+ }
238
+ if (toolName === 'Edit') return 'medium';
239
+ if (toolName === 'Read' || toolName === 'Glob' || toolName === 'Grep') return 'low';
240
+ return 'medium';
241
+ }
242
+
243
+ /**
244
+ * Build the hook response JSON that the hook script returns to Claude CLI.
245
+ */
246
+ _buildHookResponse(decision, reason) {
247
+ if (decision === 'approve') {
248
+ return {
249
+ hookSpecificOutput: {
250
+ hookEventName: 'PreToolUse',
251
+ permissionDecision: 'allow',
252
+ },
253
+ };
254
+ }
255
+
256
+ return {
257
+ hookSpecificOutput: {
258
+ hookEventName: 'PreToolUse',
259
+ permissionDecision: 'deny',
260
+ permissionDecisionReason: reason || 'Denied by user via FlightDeck',
261
+ },
262
+ };
263
+ }
264
+ }
265
+
266
+ module.exports = { PermissionServer };