@radnine/claude-session-daemon 0.6.2 → 0.6.3

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.
@@ -0,0 +1,40 @@
1
+ #!/bin/bash
2
+ # permission-gate.sh — PreToolUse hook that gates tool execution on FlightDeck approval.
3
+ #
4
+ # Reads the hook JSON from stdin, POSTs it to the daemon's local permission server,
5
+ # and returns the approval/denial decision to Claude CLI.
6
+ #
7
+ # Environment:
8
+ # CLAUDE_PERMISSION_PORT — port of the daemon's permission server (required)
9
+ # CLAUDE_SESSION_ID — session ID (set by daemon when spawning CLI)
10
+
11
+ set -e
12
+
13
+ INPUT=$(cat)
14
+
15
+ PORT="${CLAUDE_PERMISSION_PORT:-}"
16
+ if [ -z "$PORT" ]; then
17
+ # No permission server configured — allow by default
18
+ exit 0
19
+ fi
20
+
21
+ SESSION_ID="${CLAUDE_SESSION_ID:-unknown}"
22
+
23
+ # Add session_id to the hook input
24
+ PAYLOAD=$(echo "$INPUT" | jq --arg sid "$SESSION_ID" '. + {session_id: $sid}')
25
+
26
+ # POST to daemon permission server and wait for response (blocking)
27
+ RESPONSE=$(curl -s --max-time 120 \
28
+ -X POST \
29
+ -H "Content-Type: application/json" \
30
+ -d "$PAYLOAD" \
31
+ "http://127.0.0.1:${PORT}/permissions/request" 2>/dev/null)
32
+
33
+ if [ $? -ne 0 ] || [ -z "$RESPONSE" ]; then
34
+ # If we can't reach the permission server, allow (fail-open for safety)
35
+ exit 0
36
+ fi
37
+
38
+ # Return the hook response to Claude CLI
39
+ echo "$RESPONSE"
40
+ exit 0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@radnine/claude-session-daemon",
3
- "version": "0.6.2",
3
+ "version": "0.6.3",
4
4
  "description": "Node.js daemon for managing Claude CLI sessions",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -14,6 +14,7 @@
14
14
  },
15
15
  "files": [
16
16
  "src/**",
17
+ "hooks/**",
17
18
  "LICENSE",
18
19
  "Dockerfile",
19
20
  "docker-entrypoint.sh",
@@ -4,6 +4,8 @@ const { EventEmitter } = require('node:events');
4
4
  const { spawn: defaultSpawn } = require('node:child_process');
5
5
  const { createInterface } = require('node:readline');
6
6
  const { randomUUID } = require('node:crypto');
7
+ const fs = require('node:fs');
8
+ const path = require('node:path');
7
9
 
8
10
  const MAX_CHUNK_SIZE = 50000; // 50KB — lines larger than this get flagged
9
11
 
@@ -27,6 +29,7 @@ class ClaudeProcess extends EventEmitter {
27
29
  * @param {string} [options.claudeCommand] - Path to claude binary
28
30
  * @param {boolean} [options.skipPermissions] - Pass --dangerously-skip-permissions (only safe in Docker)
29
31
  * @param {Function} [options._spawnFn] - For testing: replacement for child_process.spawn
32
+ * @param {object} [options.sessionEnv] - Extra env vars to inject into the spawned process
30
33
  */
31
34
  constructor(sessionId, options = {}) {
32
35
  super();
@@ -40,6 +43,7 @@ class ClaudeProcess extends EventEmitter {
40
43
  this._skipPermissions = options.skipPermissions || false;
41
44
  this._permissionPort = options.permissionPort || null;
42
45
  this._spawnFn = options._spawnFn || defaultSpawn;
46
+ this._sessionEnv = options.sessionEnv || {};
43
47
 
44
48
  this._state = 'idle';
45
49
  this._child = null;
@@ -62,6 +66,11 @@ class ClaudeProcess extends EventEmitter {
62
66
 
63
67
  this._state = 'spawning';
64
68
 
69
+ // If permissions are enabled, install the PreToolUse hook before spawning
70
+ if (this._permissionPort && !this._skipPermissions) {
71
+ this._ensurePermissionHook();
72
+ }
73
+
65
74
  const args = [
66
75
  '--verbose',
67
76
  '--input-format', 'stream-json',
@@ -82,7 +91,7 @@ class ClaudeProcess extends EventEmitter {
82
91
  args.push('--dangerously-skip-permissions');
83
92
  }
84
93
 
85
- const env = { ...process.env, CLAUDE_SESSION_ID: this._sessionId };
94
+ const env = { ...process.env, ...this._sessionEnv, CLAUDE_SESSION_ID: this._sessionId };
86
95
  if (this._permissionPort) {
87
96
  env.CLAUDE_PERMISSION_PORT = String(this._permissionPort);
88
97
  }
@@ -213,6 +222,63 @@ class ClaudeProcess extends EventEmitter {
213
222
  // Internal
214
223
  // -------------------------------------------------------------------------
215
224
 
225
+ /**
226
+ * Install the permission-gate hook into the project's .claude/settings.local.json.
227
+ * This tells Claude CLI to call our hook script for every PreToolUse event.
228
+ */
229
+ _ensurePermissionHook() {
230
+ const hookScript = path.resolve(__dirname, '..', 'hooks', 'permission-gate.sh');
231
+
232
+ if (!fs.existsSync(hookScript)) {
233
+ this._logger.warn('Permission hook script not found, skipping hook registration', {
234
+ expected: hookScript,
235
+ });
236
+ return;
237
+ }
238
+
239
+ // Ensure the hook is executable
240
+ try {
241
+ fs.chmodSync(hookScript, 0o755);
242
+ } catch (_) { /* ignore — may already be executable */ }
243
+
244
+ const claudeDir = path.join(this._workingDir, '.claude');
245
+ const settingsPath = path.join(claudeDir, 'settings.local.json');
246
+
247
+ // Ensure .claude/ directory exists
248
+ if (!fs.existsSync(claudeDir)) {
249
+ fs.mkdirSync(claudeDir, { recursive: true });
250
+ }
251
+
252
+ // Read existing settings or start fresh
253
+ let settings = {};
254
+ try {
255
+ const raw = fs.readFileSync(settingsPath, 'utf8');
256
+ settings = JSON.parse(raw);
257
+ } catch (_) { /* file doesn't exist or isn't valid JSON */ }
258
+
259
+ // Ensure hooks.PreToolUse array exists
260
+ if (!settings.hooks) settings.hooks = {};
261
+ if (!Array.isArray(settings.hooks.PreToolUse)) settings.hooks.PreToolUse = [];
262
+
263
+ // Check if our hook is already registered (avoid duplicates)
264
+ const alreadyRegistered = settings.hooks.PreToolUse.some(
265
+ (h) => h.command && h.command.includes('permission-gate.sh')
266
+ );
267
+
268
+ if (!alreadyRegistered) {
269
+ settings.hooks.PreToolUse.push({
270
+ matcher: '',
271
+ command: hookScript,
272
+ });
273
+
274
+ fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + '\n');
275
+ this._logger.info('Registered permission hook in project settings', {
276
+ settingsPath,
277
+ hookScript,
278
+ });
279
+ }
280
+ }
281
+
216
282
  _setupStdout() {
217
283
  const rl = createInterface({ input: this._child.stdout });
218
284
 
package/src/config.js CHANGED
@@ -60,6 +60,9 @@ function loadConfig() {
60
60
 
61
61
  // Permission server port (0 = random, only used when skipPermissions is false)
62
62
  permissionPort: intEnv(env.CLAUDE_PERMISSION_PORT, 0),
63
+
64
+ // Path to the Claude CLI binary (override for testing)
65
+ claudeCommand: env.CLAUDE_COMMAND || 'claude',
63
66
  };
64
67
 
65
68
  // Validate mode
@@ -57,6 +57,8 @@ class ActionCableClient extends BaseConnection {
57
57
  // Heartbeat / ping tracking
58
58
  this._lastPingAt = null;
59
59
  this._heartbeatTimer = null;
60
+ this._pingWatchdogTimer = null;
61
+ this._pingWatchdogInterval = this._heartbeatInterval * 2; // 2x heartbeat = 60s default
60
62
 
61
63
  // Command tracking per session
62
64
  this._activeCommands = new Map(); // sessionId -> commandId
@@ -135,6 +137,11 @@ class ActionCableClient extends BaseConnection {
135
137
  this._heartbeatTimer = null;
136
138
  }
137
139
 
140
+ if (this._pingWatchdogTimer) {
141
+ clearInterval(this._pingWatchdogTimer);
142
+ this._pingWatchdogTimer = null;
143
+ }
144
+
138
145
  if (this._subscribed) {
139
146
  this._unsubscribe();
140
147
  }
@@ -376,6 +383,11 @@ class ActionCableClient extends BaseConnection {
376
383
  this._heartbeatTimer = null;
377
384
  }
378
385
 
386
+ if (this._pingWatchdogTimer) {
387
+ clearInterval(this._pingWatchdogTimer);
388
+ this._pingWatchdogTimer = null;
389
+ }
390
+
379
391
  const reasonStr = reason ? reason.toString() : '';
380
392
  if (wasConnected) {
381
393
  this._logger.info(`WebSocket closed: code=${code} reason=${reasonStr}`);
@@ -414,9 +426,11 @@ class ActionCableClient extends BaseConnection {
414
426
  this._subscribed = true;
415
427
  this._reconnectAttempts = 0; // Backoff resets only after full connect+subscribe success
416
428
  this._consecutiveRejections = 0; // Auth is valid — reset rejection counter
429
+ this._lastPingAt = Date.now(); // Initialize so watchdog doesn't fire immediately
417
430
  this._logger.info('PilotChannel subscription confirmed');
418
431
  this.emit('subscribed');
419
432
  this._sendDaemonRegistration();
433
+ this._startPingWatchdog();
420
434
  }
421
435
 
422
436
  /**
@@ -443,10 +457,10 @@ class ActionCableClient extends BaseConnection {
443
457
  }
444
458
 
445
459
  /**
446
- * Ping received — track freshness, no response needed.
460
+ * Ping received — track freshness timestamp for watchdog monitoring.
447
461
  */
448
462
  _handlePing(msg) {
449
- this._lastPingAt = msg.message || Date.now();
463
+ this._lastPingAt = Date.now();
450
464
  }
451
465
 
452
466
  /**
@@ -494,6 +508,9 @@ class ActionCableClient extends BaseConnection {
494
508
  case 'auth_error':
495
509
  this._handleAuthError(inner);
496
510
  break;
511
+ case 'health_check_ping':
512
+ this._handleHealthCheckPing(inner);
513
+ break;
497
514
  default:
498
515
  this._logger.warn(`Unknown channel message type: ${inner.type}`);
499
516
  break;
@@ -589,12 +606,14 @@ class ActionCableClient extends BaseConnection {
589
606
  async _handleSessionActivation(message) {
590
607
  const sessionId = message.session_id;
591
608
  const userId = message.user_id;
609
+ const claudeSessionId = message.claude_session_id || undefined;
592
610
 
593
- this._logger.info('Received session_activate', { sessionId, userId });
611
+ this._logger.info('Received session_activate', { sessionId, userId, claudeSessionId });
594
612
 
595
613
  try {
596
614
  await this._daemon.activateSession(sessionId, {
597
615
  workingDir: this._config.workingDir,
616
+ claudeSessionId,
598
617
  });
599
618
 
600
619
  this.sendDaemonMessage({
@@ -939,6 +958,20 @@ class ActionCableClient extends BaseConnection {
939
958
  return;
940
959
  }
941
960
 
961
+ // Check WebSocket readyState before sending — if the underlying socket
962
+ // is in CLOSING/CLOSED state but our flags haven't caught up, force
963
+ // reconnect instead of silently failing.
964
+ if (this._ws && this._ws.readyState !== WebSocket.OPEN) {
965
+ this._logger.warn('Heartbeat: WebSocket not OPEN (readyState=%d), forcing reconnect', this._ws.readyState);
966
+ clearInterval(this._heartbeatTimer);
967
+ this._heartbeatTimer = null;
968
+ this._connected = false;
969
+ this._authenticated = false;
970
+ this._subscribed = false;
971
+ this._scheduleReconnect();
972
+ return;
973
+ }
974
+
942
975
  try {
943
976
  this._sendHeartbeat();
944
977
  } catch (err) {
@@ -952,6 +985,73 @@ class ActionCableClient extends BaseConnection {
952
985
  }
953
986
  }
954
987
 
988
+ /**
989
+ * Start the ping watchdog timer.
990
+ *
991
+ * Monitors _lastPingAt and forces a reconnect if no server ping has been
992
+ * received within 2× the heartbeat interval. This catches "half-open"
993
+ * connections where the WebSocket appears open but the server side is gone
994
+ * (e.g., after a machine sleep/wake cycle or network change).
995
+ */
996
+ _startPingWatchdog() {
997
+ if (this._pingWatchdogTimer) {
998
+ clearInterval(this._pingWatchdogTimer);
999
+ }
1000
+
1001
+ this._pingWatchdogTimer = setInterval(() => {
1002
+ if (!this._connected || !this._subscribed) {
1003
+ return; // Not fully connected — reconnect logic handles this
1004
+ }
1005
+
1006
+ if (!this._lastPingAt) {
1007
+ return; // No pings yet — subscription just started
1008
+ }
1009
+
1010
+ const elapsed = Date.now() - this._lastPingAt;
1011
+ if (elapsed > this._pingWatchdogInterval) {
1012
+ this._logger.warn(
1013
+ `Ping watchdog: no server ping in ${Math.round(elapsed / 1000)}s ` +
1014
+ `(threshold: ${Math.round(this._pingWatchdogInterval / 1000)}s). ` +
1015
+ 'Connection may be stale — forcing reconnect.'
1016
+ );
1017
+ this._forceReconnect();
1018
+ }
1019
+ }, this._heartbeatInterval); // Check every heartbeat interval (30s)
1020
+
1021
+ if (this._pingWatchdogTimer.unref) {
1022
+ this._pingWatchdogTimer.unref();
1023
+ }
1024
+ }
1025
+
1026
+ /**
1027
+ * Handle server-initiated health_check_ping — respond with an immediate
1028
+ * heartbeat to prove liveness. This is sent by Rails when a scheduled job
1029
+ * finds its pilot unhealthy and wants to reinvigorate the connection.
1030
+ */
1031
+ _handleHealthCheckPing(msg) {
1032
+ this._logger.info(`Health check ping received (reason: ${msg.reason || 'unknown'}), sending immediate heartbeat`);
1033
+ try {
1034
+ this._sendHeartbeat();
1035
+ } catch (err) {
1036
+ this._logger.error('Failed to respond to health check ping', { error: err.message });
1037
+ }
1038
+ }
1039
+
1040
+ /**
1041
+ * Force close the current WebSocket and trigger reconnection.
1042
+ * Used by the ping watchdog when the connection appears stale.
1043
+ */
1044
+ _forceReconnect() {
1045
+ if (this._ws) {
1046
+ try {
1047
+ this._ws.close(4000, 'Stale connection detected');
1048
+ } catch (_) {
1049
+ // close() may throw if socket is already closed
1050
+ }
1051
+ }
1052
+ // _onClose handler will fire and call _scheduleReconnect
1053
+ }
1054
+
955
1055
  /**
956
1056
  * Send a heartbeat message to the server.
957
1057
  */
@@ -999,6 +1099,7 @@ class ActionCableClient extends BaseConnection {
999
1099
  total_sessions: healthResults.length,
1000
1100
  active_sessions: active,
1001
1101
  idle_sessions: healthResults.length - active,
1102
+ session_ids: healthResults.map((h) => String(h.sessionId)),
1002
1103
  };
1003
1104
  } catch (_) {
1004
1105
  return { total_sessions: 0, active_sessions: 0, idle_sessions: 0 };
@@ -190,6 +190,29 @@ class StandaloneServer extends BaseConnection {
190
190
  }
191
191
  }
192
192
 
193
+ // Build per-session env from X-Session-* headers
194
+ const sessionEnv = {};
195
+ const ghToken = req.headers['x-session-github-token'];
196
+ if (ghToken) {
197
+ sessionEnv.GITHUB_TOKEN = ghToken;
198
+ sessionEnv.GH_TOKEN = ghToken;
199
+ }
200
+ const gitName = req.headers['x-session-git-author-name'];
201
+ if (gitName) {
202
+ sessionEnv.GIT_AUTHOR_NAME = gitName;
203
+ sessionEnv.GIT_COMMITTER_NAME = gitName;
204
+ }
205
+ const gitEmail = req.headers['x-session-git-author-email'];
206
+ if (gitEmail) {
207
+ sessionEnv.GIT_AUTHOR_EMAIL = gitEmail;
208
+ sessionEnv.GIT_COMMITTER_EMAIL = gitEmail;
209
+ }
210
+ const gitLogin = req.headers['x-session-git-login'];
211
+ if (gitLogin) {
212
+ sessionEnv.GIT_USER_LOGIN = gitLogin;
213
+ }
214
+ ws._sessionEnv = sessionEnv;
215
+
193
216
  // Track the authenticated client
194
217
  this._clients.set(ws, { authenticated: true });
195
218
  this._logger.info('Client connected', { localhost: isLocalhost });
@@ -281,7 +304,7 @@ class StandaloneServer extends BaseConnection {
281
304
  }
282
305
 
283
306
  try {
284
- await this._daemon.activateSession(sessionId, { workingDir });
307
+ await this._daemon.activateSession(sessionId, { workingDir, sessionEnv: ws._sessionEnv });
285
308
 
286
309
  // Track this client as watching this session
287
310
  if (!this._sessions.has(sessionId)) {
package/src/daemon.js CHANGED
@@ -146,10 +146,11 @@ class Daemon extends EventEmitter {
146
146
  }
147
147
 
148
148
  // Reuse the Claude CLI session ID from a cancelled session to preserve
149
- // conversation context, or use the one provided in options, or generate new.
149
+ // conversation context, or use the one provided in options (e.g. from Rails DB
150
+ // after daemon restart), or generate new.
150
151
  const savedClaudeSessionId = this._cancelledSessionIds.get(sessionId);
151
- const claudeSessionId = options.claudeSessionId || savedClaudeSessionId || undefined;
152
- const shouldResume = !!savedClaudeSessionId && !options.claudeSessionId;
152
+ const claudeSessionId = savedClaudeSessionId || options.claudeSessionId || undefined;
153
+ const shouldResume = !!claudeSessionId;
153
154
  this._cancelledSessionIds.delete(sessionId);
154
155
 
155
156
  // Create new process
@@ -157,8 +158,10 @@ class Daemon extends EventEmitter {
157
158
  workingDir: options.workingDir || this._config.workingDir,
158
159
  claudeSessionId,
159
160
  resume: shouldResume,
161
+ claudeCommand: this._config.claudeCommand || 'claude',
160
162
  skipPermissions: this._config.skipPermissions,
161
163
  permissionPort: this._permissionPort || null,
164
+ sessionEnv: options.sessionEnv || {},
162
165
  logger: this._logger.child(`Session:${sessionId}`),
163
166
  });
164
167
 
@@ -7,6 +7,8 @@
7
7
  * from the Rails daemon_channel.rb into Node.js.
8
8
  */
9
9
 
10
+ const SUBAGENT_TOOL_NAMES = new Set(['Agent', 'Task']);
11
+
10
12
  /**
11
13
  * Check whether a message's content array contains a tool_use block.
12
14
  * @param {object} data - Parsed message object
@@ -29,6 +31,18 @@ function hasToolResult(data) {
29
31
  return content.some((item) => item?.type === 'tool_result');
30
32
  }
31
33
 
34
+ /**
35
+ * Check whether a message's content array contains a tool_use block
36
+ * for a subagent tool (Agent or Task).
37
+ * @param {object} data - Parsed message object
38
+ * @returns {boolean}
39
+ */
40
+ function hasAgentToolUse(data) {
41
+ const content = data?.message?.content;
42
+ if (!Array.isArray(content)) return false;
43
+ return content.some((item) => item?.type === 'tool_use' && SUBAGENT_TOOL_NAMES.has(item?.name));
44
+ }
45
+
32
46
  /**
33
47
  * Determine the broadcast type for a message.
34
48
  *
@@ -46,6 +60,7 @@ function classifyMessage(data) {
46
60
 
47
61
  switch (messageType) {
48
62
  case 'assistant':
63
+ if (hasAgentToolUse(data)) return 'subagent';
49
64
  return hasToolUse(data) ? 'tool_use' : 'assistant';
50
65
  case 'user':
51
66
  return hasToolResult(data) ? 'tool_result' : 'user';
@@ -174,4 +189,5 @@ module.exports = {
174
189
  extractContent,
175
190
  hasToolUse,
176
191
  hasToolResult,
192
+ hasAgentToolUse,
177
193
  };