@radnine/claude-session-daemon 0.5.3 → 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 +272 -41
- package/src/daemon.js +15 -0
- package/src/index.js +6 -0
package/package.json
CHANGED
|
@@ -2,16 +2,20 @@
|
|
|
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');
|
|
9
|
+
const { getGitContext } = require('../git-context');
|
|
10
|
+
const daemonPkg = require('../../package.json');
|
|
7
11
|
|
|
8
12
|
/**
|
|
9
13
|
* ActionCable WebSocket client that connects to a Rails server.
|
|
10
14
|
*
|
|
11
15
|
* Implements the ActionCable protocol:
|
|
12
|
-
* 1. Connect to ws://<host>/cable?
|
|
16
|
+
* 1. Connect to ws://<host>/cable?pilot_id=<id>
|
|
13
17
|
* 2. Wait for {"type":"welcome"}
|
|
14
|
-
* 3. Subscribe to
|
|
18
|
+
* 3. Subscribe to PilotChannel
|
|
15
19
|
* 4. Exchange messages via ActionCable envelope wrapping
|
|
16
20
|
*
|
|
17
21
|
* Reconnects automatically with exponential backoff on connection loss.
|
|
@@ -46,6 +50,10 @@ class ActionCableClient extends BaseConnection {
|
|
|
46
50
|
this._maxReconnectDelay = 30000;
|
|
47
51
|
this._reconnectTimer = null;
|
|
48
52
|
|
|
53
|
+
// Auth failure tracking — stop reconnecting after repeated rejections
|
|
54
|
+
this._consecutiveRejections = 0;
|
|
55
|
+
this._maxConsecutiveRejections = 3;
|
|
56
|
+
|
|
49
57
|
// Heartbeat / ping tracking
|
|
50
58
|
this._lastPingAt = null;
|
|
51
59
|
this._heartbeatTimer = null;
|
|
@@ -53,6 +61,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
53
61
|
// Command tracking per session
|
|
54
62
|
this._activeCommands = new Map(); // sessionId -> commandId
|
|
55
63
|
this._sequences = new Map(); // sessionId -> sequence counter
|
|
64
|
+
this._cancelledSessions = new Set(); // sessionIds with pending cancel (suppress exit→complete)
|
|
56
65
|
|
|
57
66
|
// Store config for session activation
|
|
58
67
|
this._config = config;
|
|
@@ -68,7 +77,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
68
77
|
return this._connected;
|
|
69
78
|
}
|
|
70
79
|
|
|
71
|
-
/** Whether the
|
|
80
|
+
/** Whether the PilotChannel subscription is confirmed. */
|
|
72
81
|
get subscribed() {
|
|
73
82
|
return this._subscribed;
|
|
74
83
|
}
|
|
@@ -121,7 +130,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
121
130
|
}
|
|
122
131
|
|
|
123
132
|
// ---------------------------------------------------------------------------
|
|
124
|
-
// Outbound message methods (Rails
|
|
133
|
+
// Outbound message methods (Rails PilotChannel format)
|
|
125
134
|
// ---------------------------------------------------------------------------
|
|
126
135
|
|
|
127
136
|
/**
|
|
@@ -160,6 +169,13 @@ class ActionCableClient extends BaseConnection {
|
|
|
160
169
|
* @param {number} durationMs
|
|
161
170
|
*/
|
|
162
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
|
+
|
|
163
179
|
const resolvedCommandId = commandId || this._activeCommands.get(sessionId) || null;
|
|
164
180
|
|
|
165
181
|
this.sendDaemonMessage({
|
|
@@ -187,7 +203,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
187
203
|
type: 'error',
|
|
188
204
|
error_code: errorCode,
|
|
189
205
|
message: message,
|
|
190
|
-
context: {
|
|
206
|
+
context: { pilot_id: this._daemonId, session_id: sessionId },
|
|
191
207
|
severity: 'error',
|
|
192
208
|
timestamp: new Date().toISOString(),
|
|
193
209
|
});
|
|
@@ -201,12 +217,12 @@ class ActionCableClient extends BaseConnection {
|
|
|
201
217
|
* Wrap a daemon message in an ActionCable envelope and send it.
|
|
202
218
|
* The `identifier` and `data` fields are double-encoded (JSON string inside JSON).
|
|
203
219
|
*
|
|
204
|
-
* @param {object} messageData - The payload to send on the
|
|
220
|
+
* @param {object} messageData - The payload to send on the PilotChannel
|
|
205
221
|
*/
|
|
206
222
|
sendDaemonMessage(messageData) {
|
|
207
223
|
const identifier = JSON.stringify({
|
|
208
|
-
channel: '
|
|
209
|
-
|
|
224
|
+
channel: 'PilotChannel',
|
|
225
|
+
pilot_id: this._daemonId,
|
|
210
226
|
});
|
|
211
227
|
|
|
212
228
|
const envelope = {
|
|
@@ -224,13 +240,13 @@ class ActionCableClient extends BaseConnection {
|
|
|
224
240
|
|
|
225
241
|
/**
|
|
226
242
|
* Build the WebSocket URL from the Rails server URL.
|
|
227
|
-
* Converts http(s) to ws(s) and appends /cable?
|
|
243
|
+
* Converts http(s) to ws(s) and appends /cable?pilot_id=<id>.
|
|
228
244
|
* @returns {string}
|
|
229
245
|
*/
|
|
230
246
|
_buildWebSocketUrl() {
|
|
231
247
|
const url = new URL(this._railsUrl);
|
|
232
248
|
const protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
233
|
-
return `${protocol}//${url.host}/cable?
|
|
249
|
+
return `${protocol}//${url.host}/cable?pilot_id=${this._daemonId}`;
|
|
234
250
|
}
|
|
235
251
|
|
|
236
252
|
/**
|
|
@@ -245,7 +261,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
245
261
|
const headers = {};
|
|
246
262
|
if (this._authToken) {
|
|
247
263
|
headers['Authorization'] = `Bearer ${this._authToken}`;
|
|
248
|
-
headers['X-
|
|
264
|
+
headers['X-Pilot-Auth'] = this._authToken;
|
|
249
265
|
}
|
|
250
266
|
|
|
251
267
|
this._ws = new WebSocket(wsUrl, { headers });
|
|
@@ -261,11 +277,13 @@ class ActionCableClient extends BaseConnection {
|
|
|
261
277
|
*/
|
|
262
278
|
_onOpen() {
|
|
263
279
|
this._connected = true;
|
|
264
|
-
const wasReconnecting = this._reconnectAttempts > 0;
|
|
265
|
-
this._reconnectAttempts = 0;
|
|
266
280
|
|
|
267
|
-
|
|
268
|
-
|
|
281
|
+
// NOTE: Do NOT reset _reconnectAttempts here. The backoff counter is only
|
|
282
|
+
// reset once the subscription is confirmed (_handleSubscriptionConfirmed).
|
|
283
|
+
// Resetting on open would cause a tight reconnect loop when the WebSocket
|
|
284
|
+
// connects but the subscription is then rejected (e.g. invalid auth token).
|
|
285
|
+
if (this._reconnectAttempts > 0) {
|
|
286
|
+
this._logger.info('WebSocket reconnected, waiting for subscription confirmation');
|
|
269
287
|
} else {
|
|
270
288
|
this._logger.info('WebSocket connection opened, waiting for welcome');
|
|
271
289
|
}
|
|
@@ -358,10 +376,10 @@ class ActionCableClient extends BaseConnection {
|
|
|
358
376
|
// ---------------------------------------------------------------------------
|
|
359
377
|
|
|
360
378
|
/**
|
|
361
|
-
* Welcome received — subscribe to
|
|
379
|
+
* Welcome received — subscribe to PilotChannel.
|
|
362
380
|
*/
|
|
363
381
|
_handleWelcome() {
|
|
364
|
-
this._logger.info('Received welcome, subscribing to
|
|
382
|
+
this._logger.info('Received welcome, subscribing to PilotChannel');
|
|
365
383
|
this._subscribeToDaemonChannel();
|
|
366
384
|
}
|
|
367
385
|
|
|
@@ -370,7 +388,9 @@ class ActionCableClient extends BaseConnection {
|
|
|
370
388
|
*/
|
|
371
389
|
_handleSubscriptionConfirmed(msg) {
|
|
372
390
|
this._subscribed = true;
|
|
373
|
-
this.
|
|
391
|
+
this._reconnectAttempts = 0; // Backoff resets only after full connect+subscribe success
|
|
392
|
+
this._consecutiveRejections = 0; // Auth is valid — reset rejection counter
|
|
393
|
+
this._logger.info('PilotChannel subscription confirmed');
|
|
374
394
|
this.emit('subscribed');
|
|
375
395
|
this._sendDaemonRegistration();
|
|
376
396
|
}
|
|
@@ -380,7 +400,21 @@ class ActionCableClient extends BaseConnection {
|
|
|
380
400
|
*/
|
|
381
401
|
_handleSubscriptionRejected(msg) {
|
|
382
402
|
this._subscribed = false;
|
|
383
|
-
this.
|
|
403
|
+
this._consecutiveRejections += 1;
|
|
404
|
+
const reason = (msg && msg.reason) || 'unknown';
|
|
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.`);
|
|
417
|
+
// Do NOT reset _reconnectAttempts here — let backoff escalate to avoid tight loop
|
|
384
418
|
this._scheduleReconnect();
|
|
385
419
|
}
|
|
386
420
|
|
|
@@ -418,9 +452,21 @@ class ActionCableClient extends BaseConnection {
|
|
|
418
452
|
case 'session_recover':
|
|
419
453
|
this._handleSessionRecovery(inner);
|
|
420
454
|
break;
|
|
455
|
+
case 'session_pause':
|
|
456
|
+
this._handleSessionPause(inner);
|
|
457
|
+
break;
|
|
458
|
+
case 'command_cancel':
|
|
459
|
+
this._handleCommandCancel(inner);
|
|
460
|
+
break;
|
|
421
461
|
case 'session_deactivate':
|
|
422
462
|
this._handleSessionDeactivation(inner);
|
|
423
463
|
break;
|
|
464
|
+
case 'file_request':
|
|
465
|
+
this._handleFileRequest(inner);
|
|
466
|
+
break;
|
|
467
|
+
case 'auth_error':
|
|
468
|
+
this._handleAuthError(inner);
|
|
469
|
+
break;
|
|
424
470
|
default:
|
|
425
471
|
this._logger.warn(`Unknown channel message type: ${inner.type}`);
|
|
426
472
|
break;
|
|
@@ -430,6 +476,21 @@ class ActionCableClient extends BaseConnection {
|
|
|
430
476
|
this.emit('message', inner);
|
|
431
477
|
}
|
|
432
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
|
+
|
|
433
494
|
// ---------------------------------------------------------------------------
|
|
434
495
|
// Daemon registration and heartbeat
|
|
435
496
|
// ---------------------------------------------------------------------------
|
|
@@ -437,14 +498,17 @@ class ActionCableClient extends BaseConnection {
|
|
|
437
498
|
/**
|
|
438
499
|
* Send daemon registration message after subscription is confirmed.
|
|
439
500
|
*/
|
|
440
|
-
_sendDaemonRegistration() {
|
|
501
|
+
async _sendDaemonRegistration() {
|
|
441
502
|
this._logger.info('Sending daemon registration');
|
|
503
|
+
|
|
504
|
+
const gitContext = await this._getGitContext();
|
|
505
|
+
|
|
442
506
|
this.sendDaemonMessage({
|
|
443
|
-
type: '
|
|
444
|
-
version:
|
|
507
|
+
type: 'pilot_connect',
|
|
508
|
+
version: daemonPkg.version,
|
|
445
509
|
auth: {
|
|
446
510
|
token: this._authToken,
|
|
447
|
-
|
|
511
|
+
pilot_id: this._daemonId,
|
|
448
512
|
},
|
|
449
513
|
capabilities: this._capabilities,
|
|
450
514
|
system_info: {
|
|
@@ -453,6 +517,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
453
517
|
arch: process.arch,
|
|
454
518
|
working_directory: this._workingDir,
|
|
455
519
|
},
|
|
520
|
+
git_context: gitContext,
|
|
456
521
|
});
|
|
457
522
|
}
|
|
458
523
|
|
|
@@ -530,7 +595,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
530
595
|
* Handle command_execute and slash_command — send command text to a session process.
|
|
531
596
|
* @param {object} message
|
|
532
597
|
*/
|
|
533
|
-
_handleCommandExecution(message) {
|
|
598
|
+
async _handleCommandExecution(message) {
|
|
534
599
|
const sessionId = message.session_id;
|
|
535
600
|
const commandId = message.command_id;
|
|
536
601
|
const command = message.command;
|
|
@@ -545,14 +610,23 @@ class ActionCableClient extends BaseConnection {
|
|
|
545
610
|
try {
|
|
546
611
|
this._daemon.sendMessage(sessionId, command);
|
|
547
612
|
} catch (err) {
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
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
|
+
}
|
|
556
630
|
}
|
|
557
631
|
}
|
|
558
632
|
|
|
@@ -569,6 +643,67 @@ class ActionCableClient extends BaseConnection {
|
|
|
569
643
|
this._sendRecoveryStatus(sessionId, 'completed', 'recovery_finished');
|
|
570
644
|
}
|
|
571
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
|
+
|
|
691
|
+
/**
|
|
692
|
+
* Handle session_pause — cancel session gracefully, saving claudeSessionId for resume.
|
|
693
|
+
* @param {object} message
|
|
694
|
+
*/
|
|
695
|
+
async _handleSessionPause(message) {
|
|
696
|
+
const sessionId = message.session_id;
|
|
697
|
+
this._logger.info('Pausing session', { sessionId });
|
|
698
|
+
|
|
699
|
+
try {
|
|
700
|
+
await this._daemon.cancelSession(sessionId);
|
|
701
|
+
this._sendSessionStateUpdate(sessionId, { status: 'paused' });
|
|
702
|
+
} catch (err) {
|
|
703
|
+
this._logger.error('Failed to pause session', { sessionId, error: err.message });
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
572
707
|
/**
|
|
573
708
|
* Handle session_deactivate — terminate the session process.
|
|
574
709
|
* @param {object} message
|
|
@@ -585,6 +720,85 @@ class ActionCableClient extends BaseConnection {
|
|
|
585
720
|
}
|
|
586
721
|
}
|
|
587
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
|
+
|
|
588
802
|
// ---------------------------------------------------------------------------
|
|
589
803
|
// Outbound helper methods
|
|
590
804
|
// ---------------------------------------------------------------------------
|
|
@@ -634,7 +848,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
634
848
|
type: 'error',
|
|
635
849
|
error_code: errorCode,
|
|
636
850
|
message: errorMessage,
|
|
637
|
-
context: {
|
|
851
|
+
context: { pilot_id: this._daemonId, ...context },
|
|
638
852
|
severity: 'error',
|
|
639
853
|
timestamp: new Date().toISOString(),
|
|
640
854
|
});
|
|
@@ -671,17 +885,34 @@ class ActionCableClient extends BaseConnection {
|
|
|
671
885
|
/**
|
|
672
886
|
* Send a heartbeat message to the server.
|
|
673
887
|
*/
|
|
674
|
-
_sendHeartbeat() {
|
|
888
|
+
async _sendHeartbeat() {
|
|
889
|
+
const gitContext = await this._getGitContext();
|
|
890
|
+
|
|
675
891
|
this.sendDaemonMessage({
|
|
676
892
|
type: 'heartbeat',
|
|
677
|
-
|
|
893
|
+
pilot_id: this._daemonId,
|
|
894
|
+
version: daemonPkg.version,
|
|
678
895
|
status: 'healthy',
|
|
679
896
|
session_summary: this._getSessionSummary(),
|
|
680
897
|
resource_usage: this._getResourceUsage(),
|
|
898
|
+
git_context: gitContext,
|
|
681
899
|
timestamp: new Date().toISOString(),
|
|
682
900
|
});
|
|
683
901
|
}
|
|
684
902
|
|
|
903
|
+
/**
|
|
904
|
+
* Get git context (branch, PR, remote) for the working directory.
|
|
905
|
+
* Returns cached results (30s TTL via git-context module).
|
|
906
|
+
*/
|
|
907
|
+
async _getGitContext() {
|
|
908
|
+
try {
|
|
909
|
+
return await getGitContext(this._workingDir);
|
|
910
|
+
} catch (err) {
|
|
911
|
+
this._logger.warn('Failed to get git context', { error: err.message });
|
|
912
|
+
return null;
|
|
913
|
+
}
|
|
914
|
+
}
|
|
915
|
+
|
|
685
916
|
/**
|
|
686
917
|
* Get a summary of daemon sessions from the daemon health check.
|
|
687
918
|
* @returns {object}
|
|
@@ -728,12 +959,12 @@ class ActionCableClient extends BaseConnection {
|
|
|
728
959
|
// ---------------------------------------------------------------------------
|
|
729
960
|
|
|
730
961
|
/**
|
|
731
|
-
* Send a subscribe command for
|
|
962
|
+
* Send a subscribe command for PilotChannel.
|
|
732
963
|
*/
|
|
733
964
|
_subscribeToDaemonChannel() {
|
|
734
965
|
const identifier = JSON.stringify({
|
|
735
|
-
channel: '
|
|
736
|
-
|
|
966
|
+
channel: 'PilotChannel',
|
|
967
|
+
pilot_id: this._daemonId,
|
|
737
968
|
});
|
|
738
969
|
|
|
739
970
|
this._send({
|
|
@@ -743,12 +974,12 @@ class ActionCableClient extends BaseConnection {
|
|
|
743
974
|
}
|
|
744
975
|
|
|
745
976
|
/**
|
|
746
|
-
* Send an unsubscribe command for
|
|
977
|
+
* Send an unsubscribe command for PilotChannel.
|
|
747
978
|
*/
|
|
748
979
|
_unsubscribe() {
|
|
749
980
|
const identifier = JSON.stringify({
|
|
750
|
-
channel: '
|
|
751
|
-
|
|
981
|
+
channel: 'PilotChannel',
|
|
982
|
+
pilot_id: this._daemonId,
|
|
752
983
|
});
|
|
753
984
|
|
|
754
985
|
this._send({
|
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) {
|
|
@@ -374,6 +379,16 @@ class Daemon extends EventEmitter {
|
|
|
374
379
|
*/
|
|
375
380
|
_forwardEvents(sessionId, proc) {
|
|
376
381
|
proc.on('output', (data) => {
|
|
382
|
+
// Suppress informational rate_limit_event messages (status: "allowed")
|
|
383
|
+
// These are not actual rate limits — only forward when truly rate-limited
|
|
384
|
+
if (data?.type === 'rate_limit_event') {
|
|
385
|
+
const status = data?.rate_limit_info?.status;
|
|
386
|
+
if (status === 'allowed') {
|
|
387
|
+
this._logger.debug('Suppressing informational rate_limit_event', { sessionId, status });
|
|
388
|
+
return;
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
377
392
|
this.emit('session:output', { sessionId, data });
|
|
378
393
|
});
|
|
379
394
|
|
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();
|