@radnine/claude-session-daemon 0.6.1 → 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.1",
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
@@ -63,10 +63,34 @@ class ActionCableClient extends BaseConnection {
63
63
  this._sequences = new Map(); // sessionId -> sequence counter
64
64
  this._cancelledSessions = new Set(); // sessionIds with pending cancel (suppress exit→complete)
65
65
 
66
+ // Permission server reference (set externally via setPermissionServer)
67
+ this._permissionServer = null;
68
+
66
69
  // Store config for session activation
67
70
  this._config = config;
68
71
  }
69
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
+
70
94
  /** The daemon ID used for channel subscriptions. */
71
95
  get daemonId() {
72
96
  return this._daemonId;
@@ -464,6 +488,9 @@ class ActionCableClient extends BaseConnection {
464
488
  case 'file_request':
465
489
  this._handleFileRequest(inner);
466
490
  break;
491
+ case 'permission_response':
492
+ this._handlePermissionResponse(inner);
493
+ break;
467
494
  case 'auth_error':
468
495
  this._handleAuthError(inner);
469
496
  break;
@@ -643,6 +670,49 @@ class ActionCableClient extends BaseConnection {
643
670
  this._sendRecoveryStatus(sessionId, 'completed', 'recovery_finished');
644
671
  }
645
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
+
646
716
  /**
647
717
  * Handle command_cancel — cancel the active command for a session, preserving
648
718
  * the Claude CLI session ID so the next command resumes the conversation.
package/src/daemon.js CHANGED
@@ -158,6 +158,7 @@ class Daemon extends EventEmitter {
158
158
  claudeSessionId,
159
159
  resume: shouldResume,
160
160
  skipPermissions: this._config.skipPermissions,
161
+ permissionPort: this._permissionPort || null,
161
162
  logger: this._logger.child(`Session:${sessionId}`),
162
163
  });
163
164
 
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', () => {
@@ -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 };