@radnine/claude-session-daemon 0.6.0 → 0.6.1
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/connections/action-cable-client.js +197 -11
- package/src/daemon.js +5 -0
- package/src/index.js +6 -0
package/package.json
CHANGED
|
@@ -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,6 +61,7 @@ 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)
|
|
57
65
|
|
|
58
66
|
// Store config for session activation
|
|
59
67
|
this._config = config;
|
|
@@ -161,6 +169,13 @@ class ActionCableClient extends BaseConnection {
|
|
|
161
169
|
* @param {number} durationMs
|
|
162
170
|
*/
|
|
163
171
|
sendComplete(sessionId, commandId, exitCode, durationMs) {
|
|
172
|
+
// Suppress the exit→complete event for sessions that were cancelled.
|
|
173
|
+
// The command_cancelled message is sent separately by _handleCommandCancel.
|
|
174
|
+
if (this._cancelledSessions && this._cancelledSessions.has(sessionId)) {
|
|
175
|
+
this._cancelledSessions.delete(sessionId);
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
|
|
164
179
|
const resolvedCommandId = commandId || this._activeCommands.get(sessionId) || null;
|
|
165
180
|
|
|
166
181
|
this.sendDaemonMessage({
|
|
@@ -374,6 +389,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
374
389
|
_handleSubscriptionConfirmed(msg) {
|
|
375
390
|
this._subscribed = true;
|
|
376
391
|
this._reconnectAttempts = 0; // Backoff resets only after full connect+subscribe success
|
|
392
|
+
this._consecutiveRejections = 0; // Auth is valid — reset rejection counter
|
|
377
393
|
this._logger.info('PilotChannel subscription confirmed');
|
|
378
394
|
this.emit('subscribed');
|
|
379
395
|
this._sendDaemonRegistration();
|
|
@@ -384,8 +400,20 @@ class ActionCableClient extends BaseConnection {
|
|
|
384
400
|
*/
|
|
385
401
|
_handleSubscriptionRejected(msg) {
|
|
386
402
|
this._subscribed = false;
|
|
403
|
+
this._consecutiveRejections += 1;
|
|
387
404
|
const reason = (msg && msg.reason) || 'unknown';
|
|
388
|
-
|
|
405
|
+
|
|
406
|
+
if (this._consecutiveRejections >= this._maxConsecutiveRejections) {
|
|
407
|
+
this._logger.error(
|
|
408
|
+
`PilotChannel subscription rejected ${this._consecutiveRejections} times consecutively. ` +
|
|
409
|
+
`This likely means the auth token is invalid or revoked. Stopping reconnection. ` +
|
|
410
|
+
`Check CLAUDE_AUTH_TOKEN and re-provision if needed.`
|
|
411
|
+
);
|
|
412
|
+
this.emit('auth_failed', { reason, attempts: this._consecutiveRejections });
|
|
413
|
+
return; // Do NOT schedule reconnect — auth won't self-heal
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
this._logger.warn(`PilotChannel subscription rejected (reason: ${reason}, rejection: ${this._consecutiveRejections}/${this._maxConsecutiveRejections}). Backoff will increase.`);
|
|
389
417
|
// Do NOT reset _reconnectAttempts here — let backoff escalate to avoid tight loop
|
|
390
418
|
this._scheduleReconnect();
|
|
391
419
|
}
|
|
@@ -427,9 +455,18 @@ class ActionCableClient extends BaseConnection {
|
|
|
427
455
|
case 'session_pause':
|
|
428
456
|
this._handleSessionPause(inner);
|
|
429
457
|
break;
|
|
458
|
+
case 'command_cancel':
|
|
459
|
+
this._handleCommandCancel(inner);
|
|
460
|
+
break;
|
|
430
461
|
case 'session_deactivate':
|
|
431
462
|
this._handleSessionDeactivation(inner);
|
|
432
463
|
break;
|
|
464
|
+
case 'file_request':
|
|
465
|
+
this._handleFileRequest(inner);
|
|
466
|
+
break;
|
|
467
|
+
case 'auth_error':
|
|
468
|
+
this._handleAuthError(inner);
|
|
469
|
+
break;
|
|
433
470
|
default:
|
|
434
471
|
this._logger.warn(`Unknown channel message type: ${inner.type}`);
|
|
435
472
|
break;
|
|
@@ -439,6 +476,21 @@ class ActionCableClient extends BaseConnection {
|
|
|
439
476
|
this.emit('message', inner);
|
|
440
477
|
}
|
|
441
478
|
|
|
479
|
+
/**
|
|
480
|
+
* Handle auth_error message from server — stop reconnecting immediately.
|
|
481
|
+
* The server sends this before rejecting the subscription when the token
|
|
482
|
+
* is invalid, revoked, or the pilot is suspended.
|
|
483
|
+
*/
|
|
484
|
+
_handleAuthError(msg) {
|
|
485
|
+
const reason = msg.reason || 'unknown';
|
|
486
|
+
const message = msg.message || 'Authentication failed.';
|
|
487
|
+
this._logger.error(
|
|
488
|
+
`Server auth error: ${reason} — ${message} Stopping reconnection.`
|
|
489
|
+
);
|
|
490
|
+
this._shutdownRequested = true;
|
|
491
|
+
this.emit('auth_failed', { reason, message });
|
|
492
|
+
}
|
|
493
|
+
|
|
442
494
|
// ---------------------------------------------------------------------------
|
|
443
495
|
// Daemon registration and heartbeat
|
|
444
496
|
// ---------------------------------------------------------------------------
|
|
@@ -453,7 +505,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
453
505
|
|
|
454
506
|
this.sendDaemonMessage({
|
|
455
507
|
type: 'pilot_connect',
|
|
456
|
-
version:
|
|
508
|
+
version: daemonPkg.version,
|
|
457
509
|
auth: {
|
|
458
510
|
token: this._authToken,
|
|
459
511
|
pilot_id: this._daemonId,
|
|
@@ -543,7 +595,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
543
595
|
* Handle command_execute and slash_command — send command text to a session process.
|
|
544
596
|
* @param {object} message
|
|
545
597
|
*/
|
|
546
|
-
_handleCommandExecution(message) {
|
|
598
|
+
async _handleCommandExecution(message) {
|
|
547
599
|
const sessionId = message.session_id;
|
|
548
600
|
const commandId = message.command_id;
|
|
549
601
|
const command = message.command;
|
|
@@ -558,14 +610,23 @@ class ActionCableClient extends BaseConnection {
|
|
|
558
610
|
try {
|
|
559
611
|
this._daemon.sendMessage(sessionId, command);
|
|
560
612
|
} catch (err) {
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
613
|
+
// Session process may be dead (e.g. after cancel). Try to re-activate
|
|
614
|
+
// and retry once before giving up.
|
|
615
|
+
this._logger.warn('Command execution failed, attempting re-activation', { sessionId, error: err.message });
|
|
616
|
+
try {
|
|
617
|
+
await this._daemon.activateSession(sessionId);
|
|
618
|
+
this._daemon.sendMessage(sessionId, command);
|
|
619
|
+
this._logger.info('Command sent after re-activation', { sessionId, commandId });
|
|
620
|
+
} catch (retryErr) {
|
|
621
|
+
this._logger.error('Command execution failed after re-activation', { sessionId, error: retryErr.message });
|
|
622
|
+
this._sendError('COMMAND_EXECUTION_FAILED', retryErr.message, {
|
|
623
|
+
session_id: sessionId,
|
|
624
|
+
command_id: commandId,
|
|
625
|
+
command: command,
|
|
626
|
+
});
|
|
627
|
+
// Clear active command on failure
|
|
628
|
+
this._activeCommands.delete(sessionId);
|
|
629
|
+
}
|
|
569
630
|
}
|
|
570
631
|
}
|
|
571
632
|
|
|
@@ -582,6 +643,51 @@ class ActionCableClient extends BaseConnection {
|
|
|
582
643
|
this._sendRecoveryStatus(sessionId, 'completed', 'recovery_finished');
|
|
583
644
|
}
|
|
584
645
|
|
|
646
|
+
/**
|
|
647
|
+
* Handle command_cancel — cancel the active command for a session, preserving
|
|
648
|
+
* the Claude CLI session ID so the next command resumes the conversation.
|
|
649
|
+
* @param {object} message
|
|
650
|
+
*/
|
|
651
|
+
async _handleCommandCancel(message) {
|
|
652
|
+
const sessionId = message.session_id;
|
|
653
|
+
const commandId = message.command_id;
|
|
654
|
+
this._logger.info('Cancelling command', { sessionId, commandId });
|
|
655
|
+
|
|
656
|
+
try {
|
|
657
|
+
// Mark session as cancelled before killing, so the session:exit event
|
|
658
|
+
// doesn't produce a spurious 'complete' message.
|
|
659
|
+
this._cancelledSessions.add(sessionId);
|
|
660
|
+
|
|
661
|
+
const result = await this._daemon.cancelSession(sessionId);
|
|
662
|
+
|
|
663
|
+
if (result.success) {
|
|
664
|
+
// Clear active command tracking
|
|
665
|
+
this._activeCommands.delete(sessionId);
|
|
666
|
+
|
|
667
|
+
// Notify Rails that the command was cancelled
|
|
668
|
+
this.sendDaemonMessage({
|
|
669
|
+
type: 'command_cancelled',
|
|
670
|
+
session_id: sessionId,
|
|
671
|
+
command_id: commandId,
|
|
672
|
+
timestamp: new Date().toISOString(),
|
|
673
|
+
});
|
|
674
|
+
} else {
|
|
675
|
+
this._cancelledSessions.delete(sessionId);
|
|
676
|
+
this._sendError('CANCEL_FAILED', result.message, {
|
|
677
|
+
session_id: sessionId,
|
|
678
|
+
command_id: commandId,
|
|
679
|
+
});
|
|
680
|
+
}
|
|
681
|
+
} catch (err) {
|
|
682
|
+
this._cancelledSessions.delete(sessionId);
|
|
683
|
+
this._logger.error('Failed to cancel command', { sessionId, error: err.message });
|
|
684
|
+
this._sendError('CANCEL_FAILED', err.message, {
|
|
685
|
+
session_id: sessionId,
|
|
686
|
+
command_id: commandId,
|
|
687
|
+
});
|
|
688
|
+
}
|
|
689
|
+
}
|
|
690
|
+
|
|
585
691
|
/**
|
|
586
692
|
* Handle session_pause — cancel session gracefully, saving claudeSessionId for resume.
|
|
587
693
|
* @param {object} message
|
|
@@ -614,6 +720,85 @@ class ActionCableClient extends BaseConnection {
|
|
|
614
720
|
}
|
|
615
721
|
}
|
|
616
722
|
|
|
723
|
+
/**
|
|
724
|
+
* Handle file_request — read a file from the working directory and send its contents back.
|
|
725
|
+
* Only allows .md/.markdown files within the working directory (no path traversal).
|
|
726
|
+
* @param {object} message
|
|
727
|
+
*/
|
|
728
|
+
async _handleFileRequest(message) {
|
|
729
|
+
const requestedPath = message.path;
|
|
730
|
+
const requestId = message.request_id;
|
|
731
|
+
const projectId = message.project_id;
|
|
732
|
+
|
|
733
|
+
this._logger.info('Received file_request', { path: requestedPath, requestId, projectId });
|
|
734
|
+
|
|
735
|
+
const sendError = (errorMessage) => {
|
|
736
|
+
this._logger.warn('File request failed', { path: requestedPath, error: errorMessage });
|
|
737
|
+
this.sendDaemonMessage({
|
|
738
|
+
type: 'file_response',
|
|
739
|
+
request_id: requestId,
|
|
740
|
+
project_id: projectId,
|
|
741
|
+
path: requestedPath,
|
|
742
|
+
error: errorMessage,
|
|
743
|
+
timestamp: new Date().toISOString(),
|
|
744
|
+
});
|
|
745
|
+
};
|
|
746
|
+
|
|
747
|
+
// Validate extension: must be .md or .markdown (case-insensitive)
|
|
748
|
+
const ext = path.extname(requestedPath).toLowerCase();
|
|
749
|
+
if (ext !== '.md' && ext !== '.markdown') {
|
|
750
|
+
sendError('Invalid file type: only .md and .markdown files are allowed');
|
|
751
|
+
return;
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
// Validate path security: no traversal outside working directory
|
|
755
|
+
const resolvedPath = path.resolve(this._workingDir, requestedPath);
|
|
756
|
+
if (!resolvedPath.startsWith(this._workingDir)) {
|
|
757
|
+
sendError('Access denied: path is outside the working directory');
|
|
758
|
+
return;
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
// Check for .. components in the relative path
|
|
762
|
+
const normalizedRelative = path.relative(this._workingDir, resolvedPath);
|
|
763
|
+
if (normalizedRelative.split(path.sep).includes('..')) {
|
|
764
|
+
sendError('Access denied: path contains directory traversal');
|
|
765
|
+
return;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
try {
|
|
769
|
+
const stats = await fs.stat(resolvedPath);
|
|
770
|
+
|
|
771
|
+
// Check file size: reject files > 1MB
|
|
772
|
+
if (stats.size > 1048576) {
|
|
773
|
+
sendError(`File too large: ${stats.size} bytes exceeds 1MB limit`);
|
|
774
|
+
return;
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
const fileContent = await fs.readFile(resolvedPath, 'utf-8');
|
|
778
|
+
|
|
779
|
+
this._logger.info('File request fulfilled', { path: requestedPath, size: stats.size });
|
|
780
|
+
|
|
781
|
+
this.sendDaemonMessage({
|
|
782
|
+
type: 'file_response',
|
|
783
|
+
request_id: requestId,
|
|
784
|
+
project_id: projectId,
|
|
785
|
+
path: requestedPath,
|
|
786
|
+
content: fileContent,
|
|
787
|
+
updated_at: stats.mtime.toISOString(),
|
|
788
|
+
size_bytes: stats.size,
|
|
789
|
+
timestamp: new Date().toISOString(),
|
|
790
|
+
});
|
|
791
|
+
} catch (err) {
|
|
792
|
+
if (err.code === 'ENOENT') {
|
|
793
|
+
sendError('File not found');
|
|
794
|
+
} else if (err.code === 'EACCES') {
|
|
795
|
+
sendError('Permission denied');
|
|
796
|
+
} else {
|
|
797
|
+
sendError(`Failed to read file: ${err.message}`);
|
|
798
|
+
}
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
617
802
|
// ---------------------------------------------------------------------------
|
|
618
803
|
// Outbound helper methods
|
|
619
804
|
// ---------------------------------------------------------------------------
|
|
@@ -706,6 +891,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
706
891
|
this.sendDaemonMessage({
|
|
707
892
|
type: 'heartbeat',
|
|
708
893
|
pilot_id: this._daemonId,
|
|
894
|
+
version: daemonPkg.version,
|
|
709
895
|
status: 'healthy',
|
|
710
896
|
session_summary: this._getSessionSummary(),
|
|
711
897
|
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()) {
|
|
@@ -181,6 +182,7 @@ class Daemon extends EventEmitter {
|
|
|
181
182
|
* @returns {ClaudeProcess|null}
|
|
182
183
|
*/
|
|
183
184
|
getProcess(sessionId) {
|
|
185
|
+
sessionId = String(sessionId);
|
|
184
186
|
const proc = this._processes.get(sessionId);
|
|
185
187
|
if (!proc) return null;
|
|
186
188
|
|
|
@@ -200,6 +202,7 @@ class Daemon extends EventEmitter {
|
|
|
200
202
|
* @throws {Error} if session not found
|
|
201
203
|
*/
|
|
202
204
|
sendMessage(sessionId, text) {
|
|
205
|
+
sessionId = String(sessionId);
|
|
203
206
|
const proc = this.getProcess(sessionId);
|
|
204
207
|
if (!proc) {
|
|
205
208
|
throw new Error(`Session not found: "${sessionId}"`);
|
|
@@ -213,6 +216,7 @@ class Daemon extends EventEmitter {
|
|
|
213
216
|
* @param {string} sessionId
|
|
214
217
|
*/
|
|
215
218
|
async terminateSession(sessionId) {
|
|
219
|
+
sessionId = String(sessionId);
|
|
216
220
|
const proc = this._processes.get(sessionId);
|
|
217
221
|
if (!proc) return;
|
|
218
222
|
|
|
@@ -232,6 +236,7 @@ class Daemon extends EventEmitter {
|
|
|
232
236
|
* @returns {Promise<{success: boolean, message: string}>}
|
|
233
237
|
*/
|
|
234
238
|
async cancelSession(sessionId) {
|
|
239
|
+
sessionId = String(sessionId);
|
|
235
240
|
const proc = this._processes.get(sessionId);
|
|
236
241
|
|
|
237
242
|
if (!proc) {
|
package/src/index.js
CHANGED
|
@@ -52,6 +52,12 @@ function main() {
|
|
|
52
52
|
logger.warn('Disconnected from Rails server');
|
|
53
53
|
});
|
|
54
54
|
|
|
55
|
+
client.on('auth_failed', ({ reason, message }) => {
|
|
56
|
+
logger.error(`Authentication failed (${reason}): ${message}`);
|
|
57
|
+
logger.error('Daemon cannot operate without valid auth. Exiting.');
|
|
58
|
+
process.exit(1);
|
|
59
|
+
});
|
|
60
|
+
|
|
55
61
|
// Graceful shutdown
|
|
56
62
|
daemon.on('stopped', () => {
|
|
57
63
|
client.stop();
|