@radnine/claude-session-daemon 0.6.1 → 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.
- package/hooks/permission-gate.sh +40 -0
- package/package.json +2 -1
- package/src/claude-process.js +71 -1
- package/src/config.js +9 -0
- package/src/connections/action-cable-client.js +174 -3
- package/src/connections/standalone-server.js +24 -1
- package/src/daemon.js +7 -3
- package/src/index.js +22 -0
- package/src/message-parser.js +16 -0
- package/src/permission-server.js +266 -0
|
@@ -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.
|
|
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",
|
package/src/claude-process.js
CHANGED
|
@@ -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();
|
|
@@ -38,7 +41,9 @@ class ClaudeProcess extends EventEmitter {
|
|
|
38
41
|
this._logger = options.logger || _defaultLogger();
|
|
39
42
|
this._claudeCommand = options.claudeCommand || 'claude';
|
|
40
43
|
this._skipPermissions = options.skipPermissions || false;
|
|
44
|
+
this._permissionPort = options.permissionPort || null;
|
|
41
45
|
this._spawnFn = options._spawnFn || defaultSpawn;
|
|
46
|
+
this._sessionEnv = options.sessionEnv || {};
|
|
42
47
|
|
|
43
48
|
this._state = 'idle';
|
|
44
49
|
this._child = null;
|
|
@@ -61,6 +66,11 @@ class ClaudeProcess extends EventEmitter {
|
|
|
61
66
|
|
|
62
67
|
this._state = 'spawning';
|
|
63
68
|
|
|
69
|
+
// If permissions are enabled, install the PreToolUse hook before spawning
|
|
70
|
+
if (this._permissionPort && !this._skipPermissions) {
|
|
71
|
+
this._ensurePermissionHook();
|
|
72
|
+
}
|
|
73
|
+
|
|
64
74
|
const args = [
|
|
65
75
|
'--verbose',
|
|
66
76
|
'--input-format', 'stream-json',
|
|
@@ -81,7 +91,10 @@ class ClaudeProcess extends EventEmitter {
|
|
|
81
91
|
args.push('--dangerously-skip-permissions');
|
|
82
92
|
}
|
|
83
93
|
|
|
84
|
-
const env = { ...process.env, CLAUDE_SESSION_ID: this._sessionId };
|
|
94
|
+
const env = { ...process.env, ...this._sessionEnv, CLAUDE_SESSION_ID: this._sessionId };
|
|
95
|
+
if (this._permissionPort) {
|
|
96
|
+
env.CLAUDE_PERMISSION_PORT = String(this._permissionPort);
|
|
97
|
+
}
|
|
85
98
|
delete env.CLAUDECODE; // Prevent nested session detection
|
|
86
99
|
|
|
87
100
|
const opts = {
|
|
@@ -209,6 +222,63 @@ class ClaudeProcess extends EventEmitter {
|
|
|
209
222
|
// Internal
|
|
210
223
|
// -------------------------------------------------------------------------
|
|
211
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
|
+
|
|
212
282
|
_setupStdout() {
|
|
213
283
|
const rl = createInterface({ input: this._child.stdout });
|
|
214
284
|
|
package/src/config.js
CHANGED
|
@@ -54,6 +54,15 @@ function loadConfig() {
|
|
|
54
54
|
|
|
55
55
|
// Skip Claude CLI permission prompts (only safe inside Docker containers)
|
|
56
56
|
skipPermissions: env.CLAUDE_SKIP_PERMISSIONS === 'true',
|
|
57
|
+
|
|
58
|
+
// Permission approval timeout in seconds (0 = disabled)
|
|
59
|
+
permissionTimeout: intEnv(env.CLAUDE_PERMISSION_TIMEOUT, 60),
|
|
60
|
+
|
|
61
|
+
// Permission server port (0 = random, only used when skipPermissions is false)
|
|
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',
|
|
57
66
|
};
|
|
58
67
|
|
|
59
68
|
// Validate mode
|
|
@@ -57,16 +57,42 @@ 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
|
|
63
65
|
this._sequences = new Map(); // sessionId -> sequence counter
|
|
64
66
|
this._cancelledSessions = new Set(); // sessionIds with pending cancel (suppress exit→complete)
|
|
65
67
|
|
|
68
|
+
// Permission server reference (set externally via setPermissionServer)
|
|
69
|
+
this._permissionServer = null;
|
|
70
|
+
|
|
66
71
|
// Store config for session activation
|
|
67
72
|
this._config = config;
|
|
68
73
|
}
|
|
69
74
|
|
|
75
|
+
/**
|
|
76
|
+
* Attach a PermissionServer instance for forwarding permission requests.
|
|
77
|
+
* @param {PermissionServer} server
|
|
78
|
+
*/
|
|
79
|
+
setPermissionServer(server) {
|
|
80
|
+
this._permissionServer = server;
|
|
81
|
+
|
|
82
|
+
server.on('permission_request', (req) => {
|
|
83
|
+
this._forwardPermissionRequest(req);
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
server.on('permission_timeout', ({ requestId, sessionId }) => {
|
|
87
|
+
this.sendDaemonMessage({
|
|
88
|
+
type: 'permission_timeout',
|
|
89
|
+
request_id: requestId,
|
|
90
|
+
session_id: sessionId,
|
|
91
|
+
timestamp: new Date().toISOString(),
|
|
92
|
+
});
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
|
|
70
96
|
/** The daemon ID used for channel subscriptions. */
|
|
71
97
|
get daemonId() {
|
|
72
98
|
return this._daemonId;
|
|
@@ -111,6 +137,11 @@ class ActionCableClient extends BaseConnection {
|
|
|
111
137
|
this._heartbeatTimer = null;
|
|
112
138
|
}
|
|
113
139
|
|
|
140
|
+
if (this._pingWatchdogTimer) {
|
|
141
|
+
clearInterval(this._pingWatchdogTimer);
|
|
142
|
+
this._pingWatchdogTimer = null;
|
|
143
|
+
}
|
|
144
|
+
|
|
114
145
|
if (this._subscribed) {
|
|
115
146
|
this._unsubscribe();
|
|
116
147
|
}
|
|
@@ -352,6 +383,11 @@ class ActionCableClient extends BaseConnection {
|
|
|
352
383
|
this._heartbeatTimer = null;
|
|
353
384
|
}
|
|
354
385
|
|
|
386
|
+
if (this._pingWatchdogTimer) {
|
|
387
|
+
clearInterval(this._pingWatchdogTimer);
|
|
388
|
+
this._pingWatchdogTimer = null;
|
|
389
|
+
}
|
|
390
|
+
|
|
355
391
|
const reasonStr = reason ? reason.toString() : '';
|
|
356
392
|
if (wasConnected) {
|
|
357
393
|
this._logger.info(`WebSocket closed: code=${code} reason=${reasonStr}`);
|
|
@@ -390,9 +426,11 @@ class ActionCableClient extends BaseConnection {
|
|
|
390
426
|
this._subscribed = true;
|
|
391
427
|
this._reconnectAttempts = 0; // Backoff resets only after full connect+subscribe success
|
|
392
428
|
this._consecutiveRejections = 0; // Auth is valid — reset rejection counter
|
|
429
|
+
this._lastPingAt = Date.now(); // Initialize so watchdog doesn't fire immediately
|
|
393
430
|
this._logger.info('PilotChannel subscription confirmed');
|
|
394
431
|
this.emit('subscribed');
|
|
395
432
|
this._sendDaemonRegistration();
|
|
433
|
+
this._startPingWatchdog();
|
|
396
434
|
}
|
|
397
435
|
|
|
398
436
|
/**
|
|
@@ -419,10 +457,10 @@ class ActionCableClient extends BaseConnection {
|
|
|
419
457
|
}
|
|
420
458
|
|
|
421
459
|
/**
|
|
422
|
-
* Ping received — track freshness
|
|
460
|
+
* Ping received — track freshness timestamp for watchdog monitoring.
|
|
423
461
|
*/
|
|
424
462
|
_handlePing(msg) {
|
|
425
|
-
this._lastPingAt =
|
|
463
|
+
this._lastPingAt = Date.now();
|
|
426
464
|
}
|
|
427
465
|
|
|
428
466
|
/**
|
|
@@ -464,9 +502,15 @@ class ActionCableClient extends BaseConnection {
|
|
|
464
502
|
case 'file_request':
|
|
465
503
|
this._handleFileRequest(inner);
|
|
466
504
|
break;
|
|
505
|
+
case 'permission_response':
|
|
506
|
+
this._handlePermissionResponse(inner);
|
|
507
|
+
break;
|
|
467
508
|
case 'auth_error':
|
|
468
509
|
this._handleAuthError(inner);
|
|
469
510
|
break;
|
|
511
|
+
case 'health_check_ping':
|
|
512
|
+
this._handleHealthCheckPing(inner);
|
|
513
|
+
break;
|
|
470
514
|
default:
|
|
471
515
|
this._logger.warn(`Unknown channel message type: ${inner.type}`);
|
|
472
516
|
break;
|
|
@@ -562,12 +606,14 @@ class ActionCableClient extends BaseConnection {
|
|
|
562
606
|
async _handleSessionActivation(message) {
|
|
563
607
|
const sessionId = message.session_id;
|
|
564
608
|
const userId = message.user_id;
|
|
609
|
+
const claudeSessionId = message.claude_session_id || undefined;
|
|
565
610
|
|
|
566
|
-
this._logger.info('Received session_activate', { sessionId, userId });
|
|
611
|
+
this._logger.info('Received session_activate', { sessionId, userId, claudeSessionId });
|
|
567
612
|
|
|
568
613
|
try {
|
|
569
614
|
await this._daemon.activateSession(sessionId, {
|
|
570
615
|
workingDir: this._config.workingDir,
|
|
616
|
+
claudeSessionId,
|
|
571
617
|
});
|
|
572
618
|
|
|
573
619
|
this.sendDaemonMessage({
|
|
@@ -643,6 +689,49 @@ class ActionCableClient extends BaseConnection {
|
|
|
643
689
|
this._sendRecoveryStatus(sessionId, 'completed', 'recovery_finished');
|
|
644
690
|
}
|
|
645
691
|
|
|
692
|
+
/**
|
|
693
|
+
* Forward a permission request from the PermissionServer to Rails.
|
|
694
|
+
* @param {object} req - Permission request from PermissionServer
|
|
695
|
+
*/
|
|
696
|
+
_forwardPermissionRequest(req) {
|
|
697
|
+
this._logger.info('Forwarding permission request to Rails', {
|
|
698
|
+
requestId: req.requestId,
|
|
699
|
+
sessionId: req.sessionId,
|
|
700
|
+
toolName: req.toolName,
|
|
701
|
+
});
|
|
702
|
+
|
|
703
|
+
this.sendDaemonMessage({
|
|
704
|
+
type: 'permission_request',
|
|
705
|
+
request_id: req.requestId,
|
|
706
|
+
session_id: req.sessionId,
|
|
707
|
+
command_id: this._activeCommands.get(req.sessionId) || null,
|
|
708
|
+
tool_name: req.toolName,
|
|
709
|
+
tool_input: req.toolInput,
|
|
710
|
+
file_path: req.filePath,
|
|
711
|
+
description: req.description,
|
|
712
|
+
risk_level: req.riskLevel,
|
|
713
|
+
timeout_seconds: req.timeoutSeconds,
|
|
714
|
+
timestamp: new Date().toISOString(),
|
|
715
|
+
});
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* Handle permission_response from Rails — route to PermissionServer.
|
|
720
|
+
* @param {object} message
|
|
721
|
+
*/
|
|
722
|
+
_handlePermissionResponse(message) {
|
|
723
|
+
const requestId = message.request_id;
|
|
724
|
+
const decision = message.decision;
|
|
725
|
+
|
|
726
|
+
this._logger.info('Permission response received from Rails', { requestId, decision });
|
|
727
|
+
|
|
728
|
+
if (this._permissionServer) {
|
|
729
|
+
this._permissionServer.resolve(requestId, decision, message.reason);
|
|
730
|
+
} else {
|
|
731
|
+
this._logger.warn('No permission server to route response to', { requestId });
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
|
|
646
735
|
/**
|
|
647
736
|
* Handle command_cancel — cancel the active command for a session, preserving
|
|
648
737
|
* the Claude CLI session ID so the next command resumes the conversation.
|
|
@@ -869,6 +958,20 @@ class ActionCableClient extends BaseConnection {
|
|
|
869
958
|
return;
|
|
870
959
|
}
|
|
871
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
|
+
|
|
872
975
|
try {
|
|
873
976
|
this._sendHeartbeat();
|
|
874
977
|
} catch (err) {
|
|
@@ -882,6 +985,73 @@ class ActionCableClient extends BaseConnection {
|
|
|
882
985
|
}
|
|
883
986
|
}
|
|
884
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
|
+
|
|
885
1055
|
/**
|
|
886
1056
|
* Send a heartbeat message to the server.
|
|
887
1057
|
*/
|
|
@@ -929,6 +1099,7 @@ class ActionCableClient extends BaseConnection {
|
|
|
929
1099
|
total_sessions: healthResults.length,
|
|
930
1100
|
active_sessions: active,
|
|
931
1101
|
idle_sessions: healthResults.length - active,
|
|
1102
|
+
session_ids: healthResults.map((h) => String(h.sessionId)),
|
|
932
1103
|
};
|
|
933
1104
|
} catch (_) {
|
|
934
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
|
|
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 ||
|
|
152
|
-
const shouldResume = !!
|
|
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,7 +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,
|
|
163
|
+
permissionPort: this._permissionPort || null,
|
|
164
|
+
sessionEnv: options.sessionEnv || {},
|
|
161
165
|
logger: this._logger.child(`Session:${sessionId}`),
|
|
162
166
|
});
|
|
163
167
|
|
package/src/index.js
CHANGED
|
@@ -38,6 +38,28 @@ function main() {
|
|
|
38
38
|
}
|
|
39
39
|
|
|
40
40
|
const client = new ActionCableClient(daemon, config, logger);
|
|
41
|
+
|
|
42
|
+
// Start permission server if permissions are not skipped
|
|
43
|
+
if (!config.skipPermissions) {
|
|
44
|
+
const { PermissionServer } = require('./permission-server');
|
|
45
|
+
const permServer = new PermissionServer({
|
|
46
|
+
port: config.permissionPort,
|
|
47
|
+
timeout: config.permissionTimeout,
|
|
48
|
+
}, createLogger({ level: config.logLevel, module: 'PermissionServer' }));
|
|
49
|
+
|
|
50
|
+
permServer.start().then((port) => {
|
|
51
|
+
logger.info('Permission server started', { port });
|
|
52
|
+
client.setPermissionServer(permServer);
|
|
53
|
+
|
|
54
|
+
// Make port available to Claude CLI hook scripts
|
|
55
|
+
daemon._permissionPort = port;
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
daemon.on('stopped', () => {
|
|
59
|
+
permServer.stop();
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
|
|
41
63
|
client.start();
|
|
42
64
|
|
|
43
65
|
client.on('subscribed', () => {
|
package/src/message-parser.js
CHANGED
|
@@ -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
|
};
|
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const http = require('node:http');
|
|
4
|
+
const { randomUUID } = require('node:crypto');
|
|
5
|
+
const { EventEmitter } = require('node:events');
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Local HTTP server that receives permission requests from Claude CLI hooks
|
|
9
|
+
* and blocks until a decision is received from FlightDeck.
|
|
10
|
+
*
|
|
11
|
+
* The PreToolUse hook script POSTs to this server, which holds the connection
|
|
12
|
+
* open until the permission is approved/denied/timed out.
|
|
13
|
+
*
|
|
14
|
+
* Emits:
|
|
15
|
+
* 'permission_request' — { requestId, sessionId, toolName, toolInput, filePath, description, riskLevel }
|
|
16
|
+
*
|
|
17
|
+
* @example
|
|
18
|
+
* const server = new PermissionServer({ port: 0, timeout: 60 }, logger);
|
|
19
|
+
* server.on('permission_request', (req) => forwardToRails(req));
|
|
20
|
+
* server.start();
|
|
21
|
+
* // Later, when user responds:
|
|
22
|
+
* server.resolve('perm_abc123', 'approve');
|
|
23
|
+
*/
|
|
24
|
+
class PermissionServer extends EventEmitter {
|
|
25
|
+
/**
|
|
26
|
+
* @param {object} config
|
|
27
|
+
* @param {number} [config.port=0] - Port to listen on (0 = random)
|
|
28
|
+
* @param {number} [config.timeout=60] - Default timeout in seconds
|
|
29
|
+
* @param {object} logger
|
|
30
|
+
*/
|
|
31
|
+
constructor(config = {}, logger) {
|
|
32
|
+
super();
|
|
33
|
+
this._port = config.port || 0;
|
|
34
|
+
this._defaultTimeout = config.timeout || 60;
|
|
35
|
+
this._logger = logger;
|
|
36
|
+
this._server = null;
|
|
37
|
+
|
|
38
|
+
// Map of requestId -> { resolve, timer, sessionId }
|
|
39
|
+
this._pending = new Map();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Actual port the server is listening on. */
|
|
43
|
+
get port() {
|
|
44
|
+
const addr = this._server?.address();
|
|
45
|
+
return addr ? addr.port : this._port;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Start the HTTP server.
|
|
50
|
+
* @returns {Promise<number>} The port the server is listening on.
|
|
51
|
+
*/
|
|
52
|
+
start() {
|
|
53
|
+
return new Promise((resolve) => {
|
|
54
|
+
this._server = http.createServer((req, res) => this._handleRequest(req, res));
|
|
55
|
+
|
|
56
|
+
this._server.listen(this._port, '127.0.0.1', () => {
|
|
57
|
+
const addr = this._server.address();
|
|
58
|
+
this._logger.info(`Permission server listening on 127.0.0.1:${addr.port}`);
|
|
59
|
+
resolve(addr.port);
|
|
60
|
+
});
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Stop the server and deny all pending requests.
|
|
66
|
+
* @returns {Promise<void>}
|
|
67
|
+
*/
|
|
68
|
+
async stop() {
|
|
69
|
+
// Deny all pending requests
|
|
70
|
+
for (const [requestId] of this._pending) {
|
|
71
|
+
this.resolve(requestId, 'deny', 'Daemon shutting down');
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
return new Promise((resolve) => {
|
|
75
|
+
if (this._server) {
|
|
76
|
+
this._server.close(() => resolve());
|
|
77
|
+
} else {
|
|
78
|
+
resolve();
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Resolve a pending permission request.
|
|
85
|
+
* @param {string} requestId
|
|
86
|
+
* @param {string} decision - 'approve' or 'deny'
|
|
87
|
+
* @param {string} [reason] - Optional reason for denial
|
|
88
|
+
*/
|
|
89
|
+
resolve(requestId, decision, reason) {
|
|
90
|
+
const pending = this._pending.get(requestId);
|
|
91
|
+
if (!pending) {
|
|
92
|
+
this._logger.warn('Permission response for unknown request', { requestId });
|
|
93
|
+
return;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
clearTimeout(pending.timer);
|
|
97
|
+
this._pending.delete(requestId);
|
|
98
|
+
|
|
99
|
+
this._logger.info('Permission resolved', { requestId, decision });
|
|
100
|
+
pending.resolve({ decision, reason });
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Deny all pending requests for a session (e.g., on disconnect).
|
|
105
|
+
* @param {string} sessionId
|
|
106
|
+
*/
|
|
107
|
+
denyAllForSession(sessionId) {
|
|
108
|
+
for (const [requestId, pending] of this._pending) {
|
|
109
|
+
if (pending.sessionId === sessionId) {
|
|
110
|
+
this.resolve(requestId, 'deny', 'Session disconnected');
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Number of pending requests. */
|
|
116
|
+
get pendingCount() {
|
|
117
|
+
return this._pending.size;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ---------------------------------------------------------------------------
|
|
121
|
+
// Internal
|
|
122
|
+
// ---------------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Handle incoming HTTP request from the hook script.
|
|
126
|
+
*/
|
|
127
|
+
_handleRequest(req, res) {
|
|
128
|
+
if (req.method !== 'POST' || !req.url.startsWith('/permissions/request')) {
|
|
129
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
130
|
+
res.end(JSON.stringify({ error: 'Not found' }));
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
let body = '';
|
|
135
|
+
req.on('data', (chunk) => { body += chunk; });
|
|
136
|
+
req.on('end', () => {
|
|
137
|
+
try {
|
|
138
|
+
const data = JSON.parse(body);
|
|
139
|
+
this._handlePermissionRequest(data, res);
|
|
140
|
+
} catch (err) {
|
|
141
|
+
this._logger.error('Failed to parse permission request', { error: err.message });
|
|
142
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
143
|
+
res.end(JSON.stringify({ error: 'Invalid JSON' }));
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Process a permission request and hold the connection open.
|
|
150
|
+
*/
|
|
151
|
+
_handlePermissionRequest(data, res) {
|
|
152
|
+
const requestId = `perm_${randomUUID().slice(0, 12)}`;
|
|
153
|
+
const sessionId = data.session_id || 'unknown';
|
|
154
|
+
const toolName = data.tool_name || 'unknown';
|
|
155
|
+
const toolInput = data.tool_input || {};
|
|
156
|
+
const filePath = this._extractFilePath(toolName, toolInput);
|
|
157
|
+
const description = this._buildDescription(toolName, toolInput);
|
|
158
|
+
const riskLevel = this._classifyRisk(toolName, toolInput);
|
|
159
|
+
const timeoutSeconds = this._defaultTimeout;
|
|
160
|
+
|
|
161
|
+
this._logger.info('Permission request received', { requestId, sessionId, toolName, riskLevel });
|
|
162
|
+
|
|
163
|
+
// Create a promise that will be resolved when the user responds
|
|
164
|
+
const resultPromise = new Promise((resolve) => {
|
|
165
|
+
const timer = setTimeout(() => {
|
|
166
|
+
this._logger.warn('Permission request timed out', { requestId });
|
|
167
|
+
this._pending.delete(requestId);
|
|
168
|
+
resolve({ decision: 'deny', reason: 'Timed out waiting for approval' });
|
|
169
|
+
this.emit('permission_timeout', { requestId, sessionId });
|
|
170
|
+
}, timeoutSeconds * 1000);
|
|
171
|
+
|
|
172
|
+
this._pending.set(requestId, { resolve, timer, sessionId });
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
// Emit the request for the connection layer to forward to Rails
|
|
176
|
+
this.emit('permission_request', {
|
|
177
|
+
requestId,
|
|
178
|
+
sessionId,
|
|
179
|
+
toolName,
|
|
180
|
+
toolInput,
|
|
181
|
+
filePath,
|
|
182
|
+
description,
|
|
183
|
+
riskLevel,
|
|
184
|
+
timeoutSeconds,
|
|
185
|
+
});
|
|
186
|
+
|
|
187
|
+
// Hold the HTTP connection open until resolved
|
|
188
|
+
resultPromise.then(({ decision, reason }) => {
|
|
189
|
+
const hookResponse = this._buildHookResponse(decision, reason);
|
|
190
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
191
|
+
res.end(JSON.stringify(hookResponse));
|
|
192
|
+
});
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
/**
|
|
196
|
+
* Extract the file path from tool input if applicable.
|
|
197
|
+
*/
|
|
198
|
+
_extractFilePath(toolName, toolInput) {
|
|
199
|
+
switch (toolName) {
|
|
200
|
+
case 'Write':
|
|
201
|
+
case 'Read':
|
|
202
|
+
case 'Edit':
|
|
203
|
+
return toolInput.file_path || toolInput.path || null;
|
|
204
|
+
case 'Bash':
|
|
205
|
+
return null;
|
|
206
|
+
default:
|
|
207
|
+
return toolInput.file_path || toolInput.path || null;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/**
|
|
212
|
+
* Build a human-readable description of the tool action.
|
|
213
|
+
*/
|
|
214
|
+
_buildDescription(toolName, toolInput) {
|
|
215
|
+
switch (toolName) {
|
|
216
|
+
case 'Bash':
|
|
217
|
+
return `Execute: ${(toolInput.command || '').slice(0, 200)}`;
|
|
218
|
+
case 'Write':
|
|
219
|
+
return `Write file: ${toolInput.file_path || 'unknown'}`;
|
|
220
|
+
case 'Edit':
|
|
221
|
+
return `Edit file: ${toolInput.file_path || 'unknown'}`;
|
|
222
|
+
case 'Read':
|
|
223
|
+
return `Read file: ${toolInput.file_path || 'unknown'}`;
|
|
224
|
+
default:
|
|
225
|
+
return `${toolName}: ${JSON.stringify(toolInput).slice(0, 200)}`;
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Classify risk level based on tool type and input.
|
|
231
|
+
*/
|
|
232
|
+
_classifyRisk(toolName, toolInput) {
|
|
233
|
+
if (toolName === 'Bash') return 'high';
|
|
234
|
+
if (toolName === 'Write') {
|
|
235
|
+
// Overwriting existing files is higher risk
|
|
236
|
+
return 'medium';
|
|
237
|
+
}
|
|
238
|
+
if (toolName === 'Edit') return 'medium';
|
|
239
|
+
if (toolName === 'Read' || toolName === 'Glob' || toolName === 'Grep') return 'low';
|
|
240
|
+
return 'medium';
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Build the hook response JSON that the hook script returns to Claude CLI.
|
|
245
|
+
*/
|
|
246
|
+
_buildHookResponse(decision, reason) {
|
|
247
|
+
if (decision === 'approve') {
|
|
248
|
+
return {
|
|
249
|
+
hookSpecificOutput: {
|
|
250
|
+
hookEventName: 'PreToolUse',
|
|
251
|
+
permissionDecision: 'allow',
|
|
252
|
+
},
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
return {
|
|
257
|
+
hookSpecificOutput: {
|
|
258
|
+
hookEventName: 'PreToolUse',
|
|
259
|
+
permissionDecision: 'deny',
|
|
260
|
+
permissionDecisionReason: reason || 'Denied by user via FlightDeck',
|
|
261
|
+
},
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
module.exports = { PermissionServer };
|