@radnine/claude-session-daemon 0.6.3 → 0.6.5
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 +1 -1
- package/src/claude-process.js +1 -0
- package/src/config.js +9 -0
- package/src/connections/action-cable-client.js +31 -10
- package/src/daemon.js +78 -20
- package/src/git-reset.js +63 -0
package/package.json
CHANGED
package/src/claude-process.js
CHANGED
package/src/config.js
CHANGED
|
@@ -63,6 +63,11 @@ function loadConfig() {
|
|
|
63
63
|
|
|
64
64
|
// Path to the Claude CLI binary (override for testing)
|
|
65
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),
|
|
66
71
|
};
|
|
67
72
|
|
|
68
73
|
// Validate mode
|
|
@@ -79,6 +84,10 @@ function loadConfig() {
|
|
|
79
84
|
throw new Error(`CLAUDE_DAEMON_PORT must be 1-65535, got ${config.port}`);
|
|
80
85
|
}
|
|
81
86
|
|
|
87
|
+
if (config.staleSessionTimeout < 0) {
|
|
88
|
+
throw new Error(`CLAUDE_STALE_SESSION_TIMEOUT must be >= 0, got ${config.staleSessionTimeout}`);
|
|
89
|
+
}
|
|
90
|
+
|
|
82
91
|
return Object.freeze(config);
|
|
83
92
|
}
|
|
84
93
|
|
|
@@ -286,6 +286,23 @@ class ActionCableClient extends BaseConnection {
|
|
|
286
286
|
_connect() {
|
|
287
287
|
if (this._shutdownRequested) return;
|
|
288
288
|
|
|
289
|
+
// Close any prior socket before opening a new one. Some reconnect paths
|
|
290
|
+
// (e.g. subscription rejection) schedule a reconnect while the existing
|
|
291
|
+
// socket is still OPEN — without this, the old socket leaks with its
|
|
292
|
+
// listeners still attached.
|
|
293
|
+
if (this._ws) {
|
|
294
|
+
const prior = this._ws;
|
|
295
|
+
this._ws = null;
|
|
296
|
+
try {
|
|
297
|
+
prior.removeAllListeners();
|
|
298
|
+
if (prior.readyState === WebSocket.OPEN || prior.readyState === WebSocket.CONNECTING) {
|
|
299
|
+
prior.close();
|
|
300
|
+
}
|
|
301
|
+
} catch (_) {
|
|
302
|
+
// close() may throw if the socket is already closed — safe to ignore
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
|
|
289
306
|
const wsUrl = this._buildWebSocketUrl();
|
|
290
307
|
this._logger.info(`Connecting to ${wsUrl}`);
|
|
291
308
|
|
|
@@ -580,6 +597,12 @@ class ActionCableClient extends BaseConnection {
|
|
|
580
597
|
this._logger.info(`Updated server config - heartbeat: ${hbMs / 1000}s`);
|
|
581
598
|
}
|
|
582
599
|
|
|
600
|
+
// Send an immediate heartbeat so Rails can reconcile zombie sessions right away
|
|
601
|
+
// instead of waiting up to one heartbeat interval (30s) after reconnect.
|
|
602
|
+
this._sendHeartbeat().catch((err) => {
|
|
603
|
+
this._logger.error('Failed to send post-registration heartbeat', { error: err.message });
|
|
604
|
+
});
|
|
605
|
+
|
|
583
606
|
this._startHeartbeat();
|
|
584
607
|
this.emit('registered');
|
|
585
608
|
}
|
|
@@ -607,13 +630,15 @@ class ActionCableClient extends BaseConnection {
|
|
|
607
630
|
const sessionId = message.session_id;
|
|
608
631
|
const userId = message.user_id;
|
|
609
632
|
const claudeSessionId = message.claude_session_id || undefined;
|
|
633
|
+
const resetGit = !!message.reset_git_state;
|
|
610
634
|
|
|
611
|
-
this._logger.info('Received session_activate', { sessionId, userId, claudeSessionId });
|
|
635
|
+
this._logger.info('Received session_activate', { sessionId, userId, claudeSessionId, resetGit });
|
|
612
636
|
|
|
613
637
|
try {
|
|
614
638
|
await this._daemon.activateSession(sessionId, {
|
|
615
639
|
workingDir: this._config.workingDir,
|
|
616
640
|
claudeSessionId,
|
|
641
|
+
resetGit,
|
|
617
642
|
});
|
|
618
643
|
|
|
619
644
|
this.sendDaemonMessage({
|
|
@@ -972,11 +997,9 @@ class ActionCableClient extends BaseConnection {
|
|
|
972
997
|
return;
|
|
973
998
|
}
|
|
974
999
|
|
|
975
|
-
|
|
976
|
-
this._sendHeartbeat();
|
|
977
|
-
} catch (err) {
|
|
1000
|
+
this._sendHeartbeat().catch((err) => {
|
|
978
1001
|
this._logger.error('Heartbeat error', { error: err.message });
|
|
979
|
-
}
|
|
1002
|
+
});
|
|
980
1003
|
}, this._heartbeatInterval);
|
|
981
1004
|
|
|
982
1005
|
// Allow the Node.js process to exit even if the timer is active
|
|
@@ -989,7 +1012,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
989
1012
|
* Start the ping watchdog timer.
|
|
990
1013
|
*
|
|
991
1014
|
* Monitors _lastPingAt and forces a reconnect if no server ping has been
|
|
992
|
-
* received within
|
|
1015
|
+
* received within 3× the heartbeat interval. This catches "half-open"
|
|
993
1016
|
* connections where the WebSocket appears open but the server side is gone
|
|
994
1017
|
* (e.g., after a machine sleep/wake cycle or network change).
|
|
995
1018
|
*/
|
|
@@ -1030,11 +1053,9 @@ class ActionCableClient extends BaseConnection {
|
|
|
1030
1053
|
*/
|
|
1031
1054
|
_handleHealthCheckPing(msg) {
|
|
1032
1055
|
this._logger.info(`Health check ping received (reason: ${msg.reason || 'unknown'}), sending immediate heartbeat`);
|
|
1033
|
-
|
|
1034
|
-
this._sendHeartbeat();
|
|
1035
|
-
} catch (err) {
|
|
1056
|
+
this._sendHeartbeat().catch((err) => {
|
|
1036
1057
|
this._logger.error('Failed to respond to health check ping', { error: err.message });
|
|
1037
|
-
}
|
|
1058
|
+
});
|
|
1038
1059
|
}
|
|
1039
1060
|
|
|
1040
1061
|
/**
|
package/src/daemon.js
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
const { EventEmitter } = require('node:events');
|
|
4
4
|
const ClaudeProcess = require('./claude-process');
|
|
5
|
+
const { resetGitState } = require('./git-reset');
|
|
5
6
|
|
|
6
7
|
/**
|
|
7
8
|
* Process pool manager for Claude CLI sessions.
|
|
@@ -36,6 +37,7 @@ class Daemon extends EventEmitter {
|
|
|
36
37
|
this._healthCheckTimer = null;
|
|
37
38
|
this._createProcess = options._createProcess || this._defaultCreateProcess.bind(this);
|
|
38
39
|
this._shutdownHandler = null;
|
|
40
|
+
this._cleanupRunning = false;
|
|
39
41
|
}
|
|
40
42
|
|
|
41
43
|
// -------------------------------------------------------------------------
|
|
@@ -73,6 +75,7 @@ class Daemon extends EventEmitter {
|
|
|
73
75
|
maxSessions: this._config.maxSessions,
|
|
74
76
|
cleanupInterval: this._config.cleanupInterval,
|
|
75
77
|
heartbeatInterval: this._config.heartbeatInterval,
|
|
78
|
+
staleSessionTimeout: this._config.staleSessionTimeout,
|
|
76
79
|
});
|
|
77
80
|
|
|
78
81
|
this.emit('started');
|
|
@@ -153,6 +156,13 @@ class Daemon extends EventEmitter {
|
|
|
153
156
|
const shouldResume = !!claudeSessionId;
|
|
154
157
|
this._cancelledSessionIds.delete(sessionId);
|
|
155
158
|
|
|
159
|
+
// Reset git state to clean main when requested (scheduled sessions)
|
|
160
|
+
if (options.resetGit) {
|
|
161
|
+
const cwd = options.workingDir || this._config.workingDir;
|
|
162
|
+
this._logger.info('Resetting git state before activation', { sessionId, cwd });
|
|
163
|
+
resetGitState(cwd, this._logger);
|
|
164
|
+
}
|
|
165
|
+
|
|
156
166
|
// Create new process
|
|
157
167
|
const proc = this._createProcess(sessionId, {
|
|
158
168
|
workingDir: options.workingDir || this._config.workingDir,
|
|
@@ -276,7 +286,10 @@ class Daemon extends EventEmitter {
|
|
|
276
286
|
* @returns {number}
|
|
277
287
|
*/
|
|
278
288
|
get activeCount() {
|
|
279
|
-
|
|
289
|
+
// Remove only dead processes synchronously (stale reaping is async, handled by timer)
|
|
290
|
+
for (const [sessionId, proc] of this._processes) {
|
|
291
|
+
if (!proc.isAlive()) this._processes.delete(sessionId);
|
|
292
|
+
}
|
|
280
293
|
return this._processes.size;
|
|
281
294
|
}
|
|
282
295
|
|
|
@@ -323,42 +336,87 @@ class Daemon extends EventEmitter {
|
|
|
323
336
|
// -------------------------------------------------------------------------
|
|
324
337
|
|
|
325
338
|
/**
|
|
326
|
-
* Clean up dead processes from the pool.
|
|
339
|
+
* Clean up dead processes and reap stale alive processes from the pool.
|
|
340
|
+
*
|
|
341
|
+
* Dead processes are removed immediately.
|
|
342
|
+
* Stale processes (alive but no activity beyond staleSessionTimeout) are
|
|
343
|
+
* killed then removed — this is the safety net for when WebSocket-based
|
|
344
|
+
* deactivation messages are lost during connection drops.
|
|
327
345
|
*/
|
|
328
|
-
_cleanupDeadProcesses() {
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
346
|
+
async _cleanupDeadProcesses() {
|
|
347
|
+
if (this._cleanupRunning) return;
|
|
348
|
+
this._cleanupRunning = true;
|
|
349
|
+
|
|
350
|
+
try {
|
|
351
|
+
const deadSessions = [];
|
|
352
|
+
const staleSessions = [];
|
|
353
|
+
const staleTimeoutMs = (this._config.staleSessionTimeout || 0) * 1000;
|
|
354
|
+
const now = Date.now();
|
|
355
|
+
|
|
356
|
+
for (const [sessionId, proc] of this._processes) {
|
|
357
|
+
if (!proc.isAlive()) {
|
|
358
|
+
deadSessions.push(sessionId);
|
|
359
|
+
} else if (staleTimeoutMs > 0 && proc.lastActivityAt) {
|
|
360
|
+
const idleMs = now - proc.lastActivityAt;
|
|
361
|
+
if (idleMs > staleTimeoutMs) {
|
|
362
|
+
staleSessions.push({ sessionId, idleMs, pid: proc.pid });
|
|
363
|
+
}
|
|
364
|
+
}
|
|
333
365
|
}
|
|
334
|
-
}
|
|
335
366
|
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
367
|
+
// Remove dead processes
|
|
368
|
+
for (const sessionId of deadSessions) {
|
|
369
|
+
this._processes.delete(sessionId);
|
|
370
|
+
this._cancelledSessionIds.delete(sessionId);
|
|
371
|
+
this._logger.info('Cleaned up dead session', { sessionId });
|
|
372
|
+
}
|
|
340
373
|
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
374
|
+
// Kill and remove stale processes
|
|
375
|
+
for (const { sessionId, idleMs, pid } of staleSessions) {
|
|
376
|
+
this._logger.warn('Killing stale session — no activity', {
|
|
377
|
+
sessionId,
|
|
378
|
+
pid,
|
|
379
|
+
idleSeconds: Math.round(idleMs / 1000),
|
|
380
|
+
threshold: this._config.staleSessionTimeout,
|
|
381
|
+
});
|
|
382
|
+
const proc = this._processes.get(sessionId);
|
|
383
|
+
if (proc) {
|
|
384
|
+
try {
|
|
385
|
+
await proc.kill();
|
|
386
|
+
} catch (err) {
|
|
387
|
+
this._logger.error('Failed to kill stale session', { sessionId, error: err.message });
|
|
388
|
+
}
|
|
389
|
+
this._processes.delete(sessionId);
|
|
390
|
+
this._cancelledSessionIds.delete(sessionId);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
const removed = deadSessions.length + staleSessions.length;
|
|
395
|
+
if (removed > 0) {
|
|
396
|
+
this._logger.info('Cleanup complete', {
|
|
397
|
+
deadRemoved: deadSessions.length,
|
|
398
|
+
staleKilled: staleSessions.length,
|
|
399
|
+
remaining: this._processes.size,
|
|
400
|
+
});
|
|
401
|
+
}
|
|
402
|
+
} finally {
|
|
403
|
+
this._cleanupRunning = false;
|
|
346
404
|
}
|
|
347
405
|
}
|
|
348
406
|
|
|
349
407
|
/**
|
|
350
408
|
* Run periodic health check and log status.
|
|
351
409
|
*/
|
|
352
|
-
_runHealthCheck() {
|
|
410
|
+
async _runHealthCheck() {
|
|
353
411
|
const health = this.healthCheck();
|
|
354
412
|
const alive = health.filter((h) => h.alive).length;
|
|
355
413
|
const dead = health.filter((h) => !h.alive).length;
|
|
356
414
|
|
|
357
415
|
this._logger.debug('Health check', { alive, dead, total: health.length });
|
|
358
416
|
|
|
359
|
-
// Clean up any dead processes found during health check
|
|
417
|
+
// Clean up any dead or stale processes found during health check
|
|
360
418
|
if (dead > 0) {
|
|
361
|
-
this._cleanupDeadProcesses();
|
|
419
|
+
await this._cleanupDeadProcesses();
|
|
362
420
|
}
|
|
363
421
|
}
|
|
364
422
|
|
package/src/git-reset.js
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { execFileSync } = require('node:child_process');
|
|
4
|
+
|
|
5
|
+
const EXEC_TIMEOUT = 15000; // 15 seconds per git command
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Reset git state to a clean main branch.
|
|
9
|
+
*
|
|
10
|
+
* Runs: stash → checkout main → pull origin main.
|
|
11
|
+
* Each step logs its result. Failures are logged but never thrown —
|
|
12
|
+
* session activation must not be blocked by git problems.
|
|
13
|
+
*
|
|
14
|
+
* @param {string} workingDir - The repo directory to reset
|
|
15
|
+
* @param {object} logger - Logger with .info() and .warn() methods
|
|
16
|
+
* @returns {{ stash: boolean, checkout: boolean, pull: boolean }} step results
|
|
17
|
+
*/
|
|
18
|
+
function resetGitState(workingDir, logger) {
|
|
19
|
+
const results = { stash: false, checkout: false, pull: false };
|
|
20
|
+
|
|
21
|
+
// Step 1: stash uncommitted changes
|
|
22
|
+
try {
|
|
23
|
+
const out = execFileSync('git', ['stash', '--include-untracked'], {
|
|
24
|
+
cwd: workingDir,
|
|
25
|
+
timeout: EXEC_TIMEOUT,
|
|
26
|
+
encoding: 'utf8',
|
|
27
|
+
});
|
|
28
|
+
results.stash = true;
|
|
29
|
+
logger.info('git stash completed', { output: out.trim() });
|
|
30
|
+
} catch (err) {
|
|
31
|
+
logger.warn('git stash failed (continuing)', { error: err.message });
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// Step 2: checkout main
|
|
35
|
+
try {
|
|
36
|
+
const out = execFileSync('git', ['checkout', 'main'], {
|
|
37
|
+
cwd: workingDir,
|
|
38
|
+
timeout: EXEC_TIMEOUT,
|
|
39
|
+
encoding: 'utf8',
|
|
40
|
+
});
|
|
41
|
+
results.checkout = true;
|
|
42
|
+
logger.info('git checkout main completed', { output: out.trim() });
|
|
43
|
+
} catch (err) {
|
|
44
|
+
logger.warn('git checkout main failed (continuing)', { error: err.message });
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// Step 3: pull latest
|
|
48
|
+
try {
|
|
49
|
+
const out = execFileSync('git', ['pull', 'origin', 'main'], {
|
|
50
|
+
cwd: workingDir,
|
|
51
|
+
timeout: EXEC_TIMEOUT,
|
|
52
|
+
encoding: 'utf8',
|
|
53
|
+
});
|
|
54
|
+
results.pull = true;
|
|
55
|
+
logger.info('git pull completed', { output: out.trim() });
|
|
56
|
+
} catch (err) {
|
|
57
|
+
logger.warn('git pull failed (continuing)', { error: err.message });
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return results;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
module.exports = { resetGitState };
|