@radnine/claude-session-daemon 0.6.2 → 0.6.4

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.4",
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
 
@@ -242,6 +308,7 @@ class ClaudeProcess extends EventEmitter {
242
308
 
243
309
  rl.on('line', (line) => {
244
310
  if (!line) return;
311
+ this._lastActivityAt = Date.now();
245
312
  this._logger.error('Claude stderr', { line });
246
313
  this.emit('stderr', line);
247
314
  });
package/src/config.js CHANGED
@@ -60,6 +60,14 @@ 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',
66
+
67
+ // Stale session timeout in seconds — kill alive processes with no activity beyond this threshold.
68
+ // Safety net for when WebSocket-based deactivation messages are lost.
69
+ // Default: 30 minutes (1800s). Set to 0 to disable.
70
+ staleSessionTimeout: intEnv(env.CLAUDE_STALE_SESSION_TIMEOUT, 1800),
63
71
  };
64
72
 
65
73
  // Validate mode
@@ -76,6 +84,10 @@ function loadConfig() {
76
84
  throw new Error(`CLAUDE_DAEMON_PORT must be 1-65535, got ${config.port}`);
77
85
  }
78
86
 
87
+ if (config.staleSessionTimeout < 0) {
88
+ throw new Error(`CLAUDE_STALE_SESSION_TIMEOUT must be >= 0, got ${config.staleSessionTimeout}`);
89
+ }
90
+
79
91
  return Object.freeze(config);
80
92
  }
81
93
 
@@ -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;
@@ -563,6 +580,12 @@ class ActionCableClient extends BaseConnection {
563
580
  this._logger.info(`Updated server config - heartbeat: ${hbMs / 1000}s`);
564
581
  }
565
582
 
583
+ // Send an immediate heartbeat so Rails can reconcile zombie sessions right away
584
+ // instead of waiting up to one heartbeat interval (30s) after reconnect.
585
+ this._sendHeartbeat().catch((err) => {
586
+ this._logger.error('Failed to send post-registration heartbeat', { error: err.message });
587
+ });
588
+
566
589
  this._startHeartbeat();
567
590
  this.emit('registered');
568
591
  }
@@ -589,12 +612,14 @@ class ActionCableClient extends BaseConnection {
589
612
  async _handleSessionActivation(message) {
590
613
  const sessionId = message.session_id;
591
614
  const userId = message.user_id;
615
+ const claudeSessionId = message.claude_session_id || undefined;
592
616
 
593
- this._logger.info('Received session_activate', { sessionId, userId });
617
+ this._logger.info('Received session_activate', { sessionId, userId, claudeSessionId });
594
618
 
595
619
  try {
596
620
  await this._daemon.activateSession(sessionId, {
597
621
  workingDir: this._config.workingDir,
622
+ claudeSessionId,
598
623
  });
599
624
 
600
625
  this.sendDaemonMessage({
@@ -939,11 +964,23 @@ class ActionCableClient extends BaseConnection {
939
964
  return;
940
965
  }
941
966
 
942
- try {
943
- this._sendHeartbeat();
944
- } catch (err) {
945
- this._logger.error('Heartbeat error', { error: err.message });
967
+ // Check WebSocket readyState before sending — if the underlying socket
968
+ // is in CLOSING/CLOSED state but our flags haven't caught up, force
969
+ // reconnect instead of silently failing.
970
+ if (this._ws && this._ws.readyState !== WebSocket.OPEN) {
971
+ this._logger.warn('Heartbeat: WebSocket not OPEN (readyState=%d), forcing reconnect', this._ws.readyState);
972
+ clearInterval(this._heartbeatTimer);
973
+ this._heartbeatTimer = null;
974
+ this._connected = false;
975
+ this._authenticated = false;
976
+ this._subscribed = false;
977
+ this._scheduleReconnect();
978
+ return;
946
979
  }
980
+
981
+ this._sendHeartbeat().catch((err) => {
982
+ this._logger.error('Heartbeat error', { error: err.message });
983
+ });
947
984
  }, this._heartbeatInterval);
948
985
 
949
986
  // Allow the Node.js process to exit even if the timer is active
@@ -952,6 +989,71 @@ class ActionCableClient extends BaseConnection {
952
989
  }
953
990
  }
954
991
 
992
+ /**
993
+ * Start the ping watchdog timer.
994
+ *
995
+ * Monitors _lastPingAt and forces a reconnect if no server ping has been
996
+ * received within 3× the heartbeat interval. This catches "half-open"
997
+ * connections where the WebSocket appears open but the server side is gone
998
+ * (e.g., after a machine sleep/wake cycle or network change).
999
+ */
1000
+ _startPingWatchdog() {
1001
+ if (this._pingWatchdogTimer) {
1002
+ clearInterval(this._pingWatchdogTimer);
1003
+ }
1004
+
1005
+ this._pingWatchdogTimer = setInterval(() => {
1006
+ if (!this._connected || !this._subscribed) {
1007
+ return; // Not fully connected — reconnect logic handles this
1008
+ }
1009
+
1010
+ if (!this._lastPingAt) {
1011
+ return; // No pings yet — subscription just started
1012
+ }
1013
+
1014
+ const elapsed = Date.now() - this._lastPingAt;
1015
+ if (elapsed > this._pingWatchdogInterval) {
1016
+ this._logger.warn(
1017
+ `Ping watchdog: no server ping in ${Math.round(elapsed / 1000)}s ` +
1018
+ `(threshold: ${Math.round(this._pingWatchdogInterval / 1000)}s). ` +
1019
+ 'Connection may be stale — forcing reconnect.'
1020
+ );
1021
+ this._forceReconnect();
1022
+ }
1023
+ }, this._heartbeatInterval); // Check every heartbeat interval (30s)
1024
+
1025
+ if (this._pingWatchdogTimer.unref) {
1026
+ this._pingWatchdogTimer.unref();
1027
+ }
1028
+ }
1029
+
1030
+ /**
1031
+ * Handle server-initiated health_check_ping — respond with an immediate
1032
+ * heartbeat to prove liveness. This is sent by Rails when a scheduled job
1033
+ * finds its pilot unhealthy and wants to reinvigorate the connection.
1034
+ */
1035
+ _handleHealthCheckPing(msg) {
1036
+ this._logger.info(`Health check ping received (reason: ${msg.reason || 'unknown'}), sending immediate heartbeat`);
1037
+ this._sendHeartbeat().catch((err) => {
1038
+ this._logger.error('Failed to respond to health check ping', { error: err.message });
1039
+ });
1040
+ }
1041
+
1042
+ /**
1043
+ * Force close the current WebSocket and trigger reconnection.
1044
+ * Used by the ping watchdog when the connection appears stale.
1045
+ */
1046
+ _forceReconnect() {
1047
+ if (this._ws) {
1048
+ try {
1049
+ this._ws.close(4000, 'Stale connection detected');
1050
+ } catch (_) {
1051
+ // close() may throw if socket is already closed
1052
+ }
1053
+ }
1054
+ // _onClose handler will fire and call _scheduleReconnect
1055
+ }
1056
+
955
1057
  /**
956
1058
  * Send a heartbeat message to the server.
957
1059
  */
@@ -999,6 +1101,7 @@ class ActionCableClient extends BaseConnection {
999
1101
  total_sessions: healthResults.length,
1000
1102
  active_sessions: active,
1001
1103
  idle_sessions: healthResults.length - active,
1104
+ session_ids: healthResults.map((h) => String(h.sessionId)),
1002
1105
  };
1003
1106
  } catch (_) {
1004
1107
  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
@@ -36,6 +36,7 @@ class Daemon extends EventEmitter {
36
36
  this._healthCheckTimer = null;
37
37
  this._createProcess = options._createProcess || this._defaultCreateProcess.bind(this);
38
38
  this._shutdownHandler = null;
39
+ this._cleanupRunning = false;
39
40
  }
40
41
 
41
42
  // -------------------------------------------------------------------------
@@ -73,6 +74,7 @@ class Daemon extends EventEmitter {
73
74
  maxSessions: this._config.maxSessions,
74
75
  cleanupInterval: this._config.cleanupInterval,
75
76
  heartbeatInterval: this._config.heartbeatInterval,
77
+ staleSessionTimeout: this._config.staleSessionTimeout,
76
78
  });
77
79
 
78
80
  this.emit('started');
@@ -146,10 +148,11 @@ class Daemon extends EventEmitter {
146
148
  }
147
149
 
148
150
  // 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.
151
+ // conversation context, or use the one provided in options (e.g. from Rails DB
152
+ // after daemon restart), or generate new.
150
153
  const savedClaudeSessionId = this._cancelledSessionIds.get(sessionId);
151
- const claudeSessionId = options.claudeSessionId || savedClaudeSessionId || undefined;
152
- const shouldResume = !!savedClaudeSessionId && !options.claudeSessionId;
154
+ const claudeSessionId = savedClaudeSessionId || options.claudeSessionId || undefined;
155
+ const shouldResume = !!claudeSessionId;
153
156
  this._cancelledSessionIds.delete(sessionId);
154
157
 
155
158
  // Create new process
@@ -157,8 +160,10 @@ class Daemon extends EventEmitter {
157
160
  workingDir: options.workingDir || this._config.workingDir,
158
161
  claudeSessionId,
159
162
  resume: shouldResume,
163
+ claudeCommand: this._config.claudeCommand || 'claude',
160
164
  skipPermissions: this._config.skipPermissions,
161
165
  permissionPort: this._permissionPort || null,
166
+ sessionEnv: options.sessionEnv || {},
162
167
  logger: this._logger.child(`Session:${sessionId}`),
163
168
  });
164
169
 
@@ -273,7 +278,10 @@ class Daemon extends EventEmitter {
273
278
  * @returns {number}
274
279
  */
275
280
  get activeCount() {
276
- this._cleanupDeadProcesses();
281
+ // Remove only dead processes synchronously (stale reaping is async, handled by timer)
282
+ for (const [sessionId, proc] of this._processes) {
283
+ if (!proc.isAlive()) this._processes.delete(sessionId);
284
+ }
277
285
  return this._processes.size;
278
286
  }
279
287
 
@@ -320,42 +328,87 @@ class Daemon extends EventEmitter {
320
328
  // -------------------------------------------------------------------------
321
329
 
322
330
  /**
323
- * Clean up dead processes from the pool.
331
+ * Clean up dead processes and reap stale alive processes from the pool.
332
+ *
333
+ * Dead processes are removed immediately.
334
+ * Stale processes (alive but no activity beyond staleSessionTimeout) are
335
+ * killed then removed — this is the safety net for when WebSocket-based
336
+ * deactivation messages are lost during connection drops.
324
337
  */
325
- _cleanupDeadProcesses() {
326
- const deadSessions = [];
327
- for (const [sessionId, proc] of this._processes) {
328
- if (!proc.isAlive()) {
329
- deadSessions.push(sessionId);
338
+ async _cleanupDeadProcesses() {
339
+ if (this._cleanupRunning) return;
340
+ this._cleanupRunning = true;
341
+
342
+ try {
343
+ const deadSessions = [];
344
+ const staleSessions = [];
345
+ const staleTimeoutMs = (this._config.staleSessionTimeout || 0) * 1000;
346
+ const now = Date.now();
347
+
348
+ for (const [sessionId, proc] of this._processes) {
349
+ if (!proc.isAlive()) {
350
+ deadSessions.push(sessionId);
351
+ } else if (staleTimeoutMs > 0 && proc.lastActivityAt) {
352
+ const idleMs = now - proc.lastActivityAt;
353
+ if (idleMs > staleTimeoutMs) {
354
+ staleSessions.push({ sessionId, idleMs, pid: proc.pid });
355
+ }
356
+ }
330
357
  }
331
- }
332
358
 
333
- for (const sessionId of deadSessions) {
334
- this._processes.delete(sessionId);
335
- this._logger.info('Cleaned up dead session', { sessionId });
336
- }
359
+ // Remove dead processes
360
+ for (const sessionId of deadSessions) {
361
+ this._processes.delete(sessionId);
362
+ this._cancelledSessionIds.delete(sessionId);
363
+ this._logger.info('Cleaned up dead session', { sessionId });
364
+ }
337
365
 
338
- if (deadSessions.length > 0) {
339
- this._logger.info('Cleanup complete', {
340
- removed: deadSessions.length,
341
- remaining: this._processes.size,
342
- });
366
+ // Kill and remove stale processes
367
+ for (const { sessionId, idleMs, pid } of staleSessions) {
368
+ this._logger.warn('Killing stale session — no activity', {
369
+ sessionId,
370
+ pid,
371
+ idleSeconds: Math.round(idleMs / 1000),
372
+ threshold: this._config.staleSessionTimeout,
373
+ });
374
+ const proc = this._processes.get(sessionId);
375
+ if (proc) {
376
+ try {
377
+ await proc.kill();
378
+ } catch (err) {
379
+ this._logger.error('Failed to kill stale session', { sessionId, error: err.message });
380
+ }
381
+ this._processes.delete(sessionId);
382
+ this._cancelledSessionIds.delete(sessionId);
383
+ }
384
+ }
385
+
386
+ const removed = deadSessions.length + staleSessions.length;
387
+ if (removed > 0) {
388
+ this._logger.info('Cleanup complete', {
389
+ deadRemoved: deadSessions.length,
390
+ staleKilled: staleSessions.length,
391
+ remaining: this._processes.size,
392
+ });
393
+ }
394
+ } finally {
395
+ this._cleanupRunning = false;
343
396
  }
344
397
  }
345
398
 
346
399
  /**
347
400
  * Run periodic health check and log status.
348
401
  */
349
- _runHealthCheck() {
402
+ async _runHealthCheck() {
350
403
  const health = this.healthCheck();
351
404
  const alive = health.filter((h) => h.alive).length;
352
405
  const dead = health.filter((h) => !h.alive).length;
353
406
 
354
407
  this._logger.debug('Health check', { alive, dead, total: health.length });
355
408
 
356
- // Clean up any dead processes found during health check
409
+ // Clean up any dead or stale processes found during health check
357
410
  if (dead > 0) {
358
- this._cleanupDeadProcesses();
411
+ await this._cleanupDeadProcesses();
359
412
  }
360
413
  }
361
414
 
@@ -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
  };