@radnine/claude-session-daemon 0.1.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/LICENSE +31 -0
- package/package.json +33 -0
- package/src/claude-process.js +277 -0
- package/src/config.js +73 -0
- package/src/connections/action-cable-client.js +808 -0
- package/src/connections/base-connection.js +91 -0
- package/src/connections/standalone-server.js +344 -0
- package/src/daemon.js +343 -0
- package/src/index.js +71 -0
- package/src/logger.js +53 -0
- package/src/message-parser.js +177 -0
- package/src/session-store.js +113 -0
|
@@ -0,0 +1,808 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('node:crypto');
|
|
4
|
+
const os = require('node:os');
|
|
5
|
+
const WebSocket = require('ws');
|
|
6
|
+
const { BaseConnection } = require('./base-connection');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* ActionCable WebSocket client that connects to a Rails server.
|
|
10
|
+
*
|
|
11
|
+
* Implements the ActionCable protocol:
|
|
12
|
+
* 1. Connect to ws://<host>/cable?daemon_id=<id>
|
|
13
|
+
* 2. Wait for {"type":"welcome"}
|
|
14
|
+
* 3. Subscribe to DaemonChannel
|
|
15
|
+
* 4. Exchange messages via ActionCable envelope wrapping
|
|
16
|
+
*
|
|
17
|
+
* Reconnects automatically with exponential backoff on connection loss.
|
|
18
|
+
*/
|
|
19
|
+
class ActionCableClient extends BaseConnection {
|
|
20
|
+
/**
|
|
21
|
+
* @param {Daemon} daemon - The daemon instance to bridge
|
|
22
|
+
* @param {object} config - Must include `railsUrl`, `authToken`; may include `daemonId`, `heartbeatInterval`
|
|
23
|
+
* @param {object} logger - Logger instance
|
|
24
|
+
*/
|
|
25
|
+
constructor(daemon, config, logger) {
|
|
26
|
+
super(daemon, logger);
|
|
27
|
+
|
|
28
|
+
this._railsUrl = config.railsUrl || 'http://localhost:3000';
|
|
29
|
+
this._authToken = config.authToken || null;
|
|
30
|
+
this._daemonId = config.daemonId || crypto.randomUUID();
|
|
31
|
+
this._heartbeatInterval = (config.heartbeatInterval || 30) * 1000;
|
|
32
|
+
this._capabilities = config.capabilities || {};
|
|
33
|
+
this._workingDir = config.workingDir || process.cwd();
|
|
34
|
+
|
|
35
|
+
// Connection state
|
|
36
|
+
this._ws = null;
|
|
37
|
+
this._connected = false;
|
|
38
|
+
this._authenticated = false;
|
|
39
|
+
this._subscribed = false;
|
|
40
|
+
this._shutdownRequested = false;
|
|
41
|
+
|
|
42
|
+
// Reconnection backoff
|
|
43
|
+
this._reconnectAttempts = 0;
|
|
44
|
+
this._baseReconnectDelay = 1000;
|
|
45
|
+
this._reconnectMultiplier = 2;
|
|
46
|
+
this._maxReconnectDelay = 30000;
|
|
47
|
+
this._reconnectTimer = null;
|
|
48
|
+
|
|
49
|
+
// Heartbeat / ping tracking
|
|
50
|
+
this._lastPingAt = null;
|
|
51
|
+
this._heartbeatTimer = null;
|
|
52
|
+
|
|
53
|
+
// Command tracking per session
|
|
54
|
+
this._activeCommands = new Map(); // sessionId -> commandId
|
|
55
|
+
this._sequences = new Map(); // sessionId -> sequence counter
|
|
56
|
+
|
|
57
|
+
// Store config for session activation
|
|
58
|
+
this._config = config;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** The daemon ID used for channel subscriptions. */
|
|
62
|
+
get daemonId() {
|
|
63
|
+
return this._daemonId;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** Whether the WebSocket is currently connected. */
|
|
67
|
+
get connected() {
|
|
68
|
+
return this._connected;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Whether the DaemonChannel subscription is confirmed. */
|
|
72
|
+
get subscribed() {
|
|
73
|
+
return this._subscribed;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// ---------------------------------------------------------------------------
|
|
77
|
+
// BaseConnection interface
|
|
78
|
+
// ---------------------------------------------------------------------------
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Open the WebSocket connection to the Rails server.
|
|
82
|
+
*/
|
|
83
|
+
start() {
|
|
84
|
+
this._shutdownRequested = false;
|
|
85
|
+
this._connect();
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Gracefully disconnect and stop reconnecting.
|
|
90
|
+
* @returns {Promise<void>}
|
|
91
|
+
*/
|
|
92
|
+
async stop() {
|
|
93
|
+
this._shutdownRequested = true;
|
|
94
|
+
|
|
95
|
+
if (this._reconnectTimer) {
|
|
96
|
+
clearTimeout(this._reconnectTimer);
|
|
97
|
+
this._reconnectTimer = null;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (this._heartbeatTimer) {
|
|
101
|
+
clearInterval(this._heartbeatTimer);
|
|
102
|
+
this._heartbeatTimer = null;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
if (this._subscribed) {
|
|
106
|
+
this._unsubscribe();
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (this._ws) {
|
|
110
|
+
try {
|
|
111
|
+
this._ws.close(1000, 'Client shutting down');
|
|
112
|
+
} catch (_) {
|
|
113
|
+
// Ignore close errors
|
|
114
|
+
}
|
|
115
|
+
this._ws = null;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
this._connected = false;
|
|
119
|
+
this._authenticated = false;
|
|
120
|
+
this._subscribed = false;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// ---------------------------------------------------------------------------
|
|
124
|
+
// Outbound message methods (Rails DaemonChannel format)
|
|
125
|
+
// ---------------------------------------------------------------------------
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* Send command output to the Rails server.
|
|
129
|
+
* Tracks sequence numbers per session for ordering.
|
|
130
|
+
*
|
|
131
|
+
* @param {string} sessionId
|
|
132
|
+
* @param {string|null} commandId
|
|
133
|
+
* @param {string} data
|
|
134
|
+
*/
|
|
135
|
+
sendOutput(sessionId, commandId, data) {
|
|
136
|
+
const seq = (this._sequences.get(sessionId) || 0) + 1;
|
|
137
|
+
this._sequences.set(sessionId, seq);
|
|
138
|
+
|
|
139
|
+
// Use tracked commandId if none provided
|
|
140
|
+
const resolvedCommandId = commandId || this._activeCommands.get(sessionId) || null;
|
|
141
|
+
|
|
142
|
+
this.sendDaemonMessage({
|
|
143
|
+
type: 'command_output',
|
|
144
|
+
session_id: sessionId,
|
|
145
|
+
command_id: resolvedCommandId,
|
|
146
|
+
stream: 'stdout',
|
|
147
|
+
data: typeof data === 'string' ? data : JSON.stringify(data),
|
|
148
|
+
sequence: seq,
|
|
149
|
+
is_complete: true,
|
|
150
|
+
timestamp: new Date().toISOString(),
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/**
|
|
155
|
+
* Send command completion to the Rails server.
|
|
156
|
+
*
|
|
157
|
+
* @param {string} sessionId
|
|
158
|
+
* @param {string|null} commandId
|
|
159
|
+
* @param {number} exitCode
|
|
160
|
+
* @param {number} durationMs
|
|
161
|
+
*/
|
|
162
|
+
sendComplete(sessionId, commandId, exitCode, durationMs) {
|
|
163
|
+
const resolvedCommandId = commandId || this._activeCommands.get(sessionId) || null;
|
|
164
|
+
|
|
165
|
+
this.sendDaemonMessage({
|
|
166
|
+
type: 'command_complete',
|
|
167
|
+
session_id: sessionId,
|
|
168
|
+
command_id: resolvedCommandId,
|
|
169
|
+
exit_code: exitCode,
|
|
170
|
+
execution_time_ms: durationMs,
|
|
171
|
+
timestamp: new Date().toISOString(),
|
|
172
|
+
});
|
|
173
|
+
|
|
174
|
+
// Clear active command on completion
|
|
175
|
+
this._activeCommands.delete(sessionId);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Send error to the Rails server.
|
|
180
|
+
*
|
|
181
|
+
* @param {string} sessionId
|
|
182
|
+
* @param {string} errorCode
|
|
183
|
+
* @param {string} message
|
|
184
|
+
*/
|
|
185
|
+
sendError(sessionId, errorCode, message) {
|
|
186
|
+
this.sendDaemonMessage({
|
|
187
|
+
type: 'error',
|
|
188
|
+
error_code: errorCode,
|
|
189
|
+
message: message,
|
|
190
|
+
context: { daemon_id: this._daemonId, session_id: sessionId },
|
|
191
|
+
severity: 'error',
|
|
192
|
+
timestamp: new Date().toISOString(),
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ---------------------------------------------------------------------------
|
|
197
|
+
// ActionCable protocol: outbound
|
|
198
|
+
// ---------------------------------------------------------------------------
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Wrap a daemon message in an ActionCable envelope and send it.
|
|
202
|
+
* The `identifier` and `data` fields are double-encoded (JSON string inside JSON).
|
|
203
|
+
*
|
|
204
|
+
* @param {object} messageData - The payload to send on the DaemonChannel
|
|
205
|
+
*/
|
|
206
|
+
sendDaemonMessage(messageData) {
|
|
207
|
+
const identifier = JSON.stringify({
|
|
208
|
+
channel: 'DaemonChannel',
|
|
209
|
+
daemon_id: this._daemonId,
|
|
210
|
+
});
|
|
211
|
+
|
|
212
|
+
const envelope = {
|
|
213
|
+
command: 'message',
|
|
214
|
+
identifier,
|
|
215
|
+
data: JSON.stringify(messageData),
|
|
216
|
+
};
|
|
217
|
+
|
|
218
|
+
this._send(envelope);
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// ---------------------------------------------------------------------------
|
|
222
|
+
// Internal: connection lifecycle
|
|
223
|
+
// ---------------------------------------------------------------------------
|
|
224
|
+
|
|
225
|
+
/**
|
|
226
|
+
* Build the WebSocket URL from the Rails server URL.
|
|
227
|
+
* Converts http(s) to ws(s) and appends /cable?daemon_id=<id>.
|
|
228
|
+
* @returns {string}
|
|
229
|
+
*/
|
|
230
|
+
_buildWebSocketUrl() {
|
|
231
|
+
const url = new URL(this._railsUrl);
|
|
232
|
+
const protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
233
|
+
return `${protocol}//${url.host}/cable?daemon_id=${this._daemonId}`;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Establish the WebSocket connection with auth headers.
|
|
238
|
+
*/
|
|
239
|
+
_connect() {
|
|
240
|
+
if (this._shutdownRequested) return;
|
|
241
|
+
|
|
242
|
+
const wsUrl = this._buildWebSocketUrl();
|
|
243
|
+
this._logger.info(`Connecting to ${wsUrl}`);
|
|
244
|
+
|
|
245
|
+
const headers = {};
|
|
246
|
+
if (this._authToken) {
|
|
247
|
+
headers['Authorization'] = `Bearer ${this._authToken}`;
|
|
248
|
+
headers['X-Daemon-Auth'] = this._authToken;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
this._ws = new WebSocket(wsUrl, { headers });
|
|
252
|
+
|
|
253
|
+
this._ws.on('open', () => this._onOpen());
|
|
254
|
+
this._ws.on('message', (raw) => this._onMessage(raw));
|
|
255
|
+
this._ws.on('close', (code, reason) => this._onClose(code, reason));
|
|
256
|
+
this._ws.on('error', (err) => this._onError(err));
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* Handle WebSocket open — reset reconnect attempts, wait for welcome.
|
|
261
|
+
*/
|
|
262
|
+
_onOpen() {
|
|
263
|
+
this._connected = true;
|
|
264
|
+
const wasReconnecting = this._reconnectAttempts > 0;
|
|
265
|
+
this._reconnectAttempts = 0;
|
|
266
|
+
|
|
267
|
+
if (wasReconnecting) {
|
|
268
|
+
this._logger.info('Reconnected successfully');
|
|
269
|
+
} else {
|
|
270
|
+
this._logger.info('WebSocket connection opened, waiting for welcome');
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
this.emit('connected');
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/**
|
|
277
|
+
* Handle inbound WebSocket message — route protocol vs channel messages.
|
|
278
|
+
* @param {Buffer|string} raw
|
|
279
|
+
*/
|
|
280
|
+
_onMessage(raw) {
|
|
281
|
+
let msg;
|
|
282
|
+
try {
|
|
283
|
+
msg = JSON.parse(raw.toString());
|
|
284
|
+
} catch (err) {
|
|
285
|
+
this._logger.error('Failed to parse inbound message', { error: err.message });
|
|
286
|
+
return;
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// Channel message: has `identifier` and `message` fields
|
|
290
|
+
if (msg.identifier && msg.message !== undefined) {
|
|
291
|
+
this._handleChannelMessage(msg);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// Protocol message: has `type` field
|
|
296
|
+
const type = msg.type;
|
|
297
|
+
switch (type) {
|
|
298
|
+
case 'welcome':
|
|
299
|
+
this._handleWelcome();
|
|
300
|
+
break;
|
|
301
|
+
|
|
302
|
+
case 'ping':
|
|
303
|
+
this._handlePing(msg);
|
|
304
|
+
break;
|
|
305
|
+
|
|
306
|
+
case 'confirm_subscription':
|
|
307
|
+
this._handleSubscriptionConfirmed(msg);
|
|
308
|
+
break;
|
|
309
|
+
|
|
310
|
+
case 'reject_subscription':
|
|
311
|
+
this._handleSubscriptionRejected(msg);
|
|
312
|
+
break;
|
|
313
|
+
|
|
314
|
+
case 'disconnect':
|
|
315
|
+
this._logger.info('Server sent disconnect message');
|
|
316
|
+
break;
|
|
317
|
+
|
|
318
|
+
default:
|
|
319
|
+
this._logger.warn(`Unknown protocol message type: ${type}`);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Handle WebSocket close — emit event and schedule reconnect if not shutting down.
|
|
325
|
+
*/
|
|
326
|
+
_onClose(code, reason) {
|
|
327
|
+
const wasConnected = this._connected;
|
|
328
|
+
this._connected = false;
|
|
329
|
+
this._authenticated = false;
|
|
330
|
+
this._subscribed = false;
|
|
331
|
+
|
|
332
|
+
if (this._heartbeatTimer) {
|
|
333
|
+
clearInterval(this._heartbeatTimer);
|
|
334
|
+
this._heartbeatTimer = null;
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
const reasonStr = reason ? reason.toString() : '';
|
|
338
|
+
if (wasConnected) {
|
|
339
|
+
this._logger.info(`WebSocket closed: code=${code} reason=${reasonStr}`);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
this.emit('disconnected', { code, reason: reasonStr });
|
|
343
|
+
|
|
344
|
+
if (!this._shutdownRequested) {
|
|
345
|
+
this._scheduleReconnect();
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
/**
|
|
350
|
+
* Handle WebSocket error — log it (close event will follow).
|
|
351
|
+
*/
|
|
352
|
+
_onError(err) {
|
|
353
|
+
this._logger.error('WebSocket error', { error: err.message });
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
// ---------------------------------------------------------------------------
|
|
357
|
+
// ActionCable protocol: inbound handlers
|
|
358
|
+
// ---------------------------------------------------------------------------
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Welcome received — subscribe to DaemonChannel.
|
|
362
|
+
*/
|
|
363
|
+
_handleWelcome() {
|
|
364
|
+
this._logger.info('Received welcome, subscribing to DaemonChannel');
|
|
365
|
+
this._subscribeToDaemonChannel();
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
/**
|
|
369
|
+
* Subscription confirmed — mark subscribed, send registration, and emit event.
|
|
370
|
+
*/
|
|
371
|
+
_handleSubscriptionConfirmed(msg) {
|
|
372
|
+
this._subscribed = true;
|
|
373
|
+
this._logger.info('DaemonChannel subscription confirmed');
|
|
374
|
+
this.emit('subscribed');
|
|
375
|
+
this._sendDaemonRegistration();
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Subscription rejected — log and schedule reconnect.
|
|
380
|
+
*/
|
|
381
|
+
_handleSubscriptionRejected(msg) {
|
|
382
|
+
this._subscribed = false;
|
|
383
|
+
this._logger.warn('DaemonChannel subscription rejected');
|
|
384
|
+
this._scheduleReconnect();
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
/**
|
|
388
|
+
* Ping received — track freshness, no response needed.
|
|
389
|
+
*/
|
|
390
|
+
_handlePing(msg) {
|
|
391
|
+
this._lastPingAt = msg.message || Date.now();
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Channel message received — unwrap, route daemon messages, and emit.
|
|
396
|
+
*/
|
|
397
|
+
_handleChannelMessage(msg) {
|
|
398
|
+
const inner = typeof msg.message === 'string'
|
|
399
|
+
? JSON.parse(msg.message)
|
|
400
|
+
: msg.message;
|
|
401
|
+
|
|
402
|
+
// Route known daemon message types
|
|
403
|
+
if (inner && inner.type) {
|
|
404
|
+
switch (inner.type) {
|
|
405
|
+
case 'registration_success':
|
|
406
|
+
this._handleRegistrationSuccess(inner);
|
|
407
|
+
break;
|
|
408
|
+
case 'heartbeat_ack':
|
|
409
|
+
this._handleHeartbeatAck(inner);
|
|
410
|
+
break;
|
|
411
|
+
case 'session_activate':
|
|
412
|
+
this._handleSessionActivation(inner);
|
|
413
|
+
break;
|
|
414
|
+
case 'command_execute':
|
|
415
|
+
case 'slash_command':
|
|
416
|
+
this._handleCommandExecution(inner);
|
|
417
|
+
break;
|
|
418
|
+
case 'session_recover':
|
|
419
|
+
this._handleSessionRecovery(inner);
|
|
420
|
+
break;
|
|
421
|
+
case 'session_deactivate':
|
|
422
|
+
this._handleSessionDeactivation(inner);
|
|
423
|
+
break;
|
|
424
|
+
default:
|
|
425
|
+
this._logger.warn(`Unknown channel message type: ${inner.type}`);
|
|
426
|
+
break;
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
this.emit('message', inner);
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// ---------------------------------------------------------------------------
|
|
434
|
+
// Daemon registration and heartbeat
|
|
435
|
+
// ---------------------------------------------------------------------------
|
|
436
|
+
|
|
437
|
+
/**
|
|
438
|
+
* Send daemon registration message after subscription is confirmed.
|
|
439
|
+
*/
|
|
440
|
+
_sendDaemonRegistration() {
|
|
441
|
+
this._logger.info('Sending daemon registration');
|
|
442
|
+
this.sendDaemonMessage({
|
|
443
|
+
type: 'daemon_connect',
|
|
444
|
+
version: '1.0',
|
|
445
|
+
auth: {
|
|
446
|
+
token: this._authToken,
|
|
447
|
+
daemon_id: this._daemonId,
|
|
448
|
+
},
|
|
449
|
+
capabilities: this._capabilities,
|
|
450
|
+
system_info: {
|
|
451
|
+
hostname: os.hostname(),
|
|
452
|
+
platform: process.platform,
|
|
453
|
+
arch: process.arch,
|
|
454
|
+
working_directory: this._workingDir,
|
|
455
|
+
},
|
|
456
|
+
});
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Handle registration_success message from server.
|
|
461
|
+
* Starts heartbeat timer with server-provided interval.
|
|
462
|
+
*/
|
|
463
|
+
_handleRegistrationSuccess(message) {
|
|
464
|
+
this._authenticated = true;
|
|
465
|
+
this._logger.info('Successfully registered with server');
|
|
466
|
+
|
|
467
|
+
if (message.server_config) {
|
|
468
|
+
const hbMs = message.server_config.heartbeat_interval || 30000;
|
|
469
|
+
this._heartbeatInterval = hbMs;
|
|
470
|
+
this._maxIdleTime = message.server_config.max_idle_time || 300000;
|
|
471
|
+
this._logger.info(`Updated server config - heartbeat: ${hbMs / 1000}s`);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
this._startHeartbeat();
|
|
475
|
+
this.emit('registered');
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* Handle heartbeat_ack from server — process any pending commands.
|
|
480
|
+
*/
|
|
481
|
+
_handleHeartbeatAck(message) {
|
|
482
|
+
if (Array.isArray(message.pending_commands)) {
|
|
483
|
+
for (const cmd of message.pending_commands) {
|
|
484
|
+
this.emit('message', cmd);
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
// ---------------------------------------------------------------------------
|
|
490
|
+
// Inbound message handlers (commands from Rails server)
|
|
491
|
+
// ---------------------------------------------------------------------------
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* Handle session_activate — spawn or reuse a Claude process for the session.
|
|
495
|
+
* @param {object} message
|
|
496
|
+
*/
|
|
497
|
+
async _handleSessionActivation(message) {
|
|
498
|
+
const sessionId = message.session_id;
|
|
499
|
+
const userId = message.user_id;
|
|
500
|
+
|
|
501
|
+
this._logger.info('Received session_activate', { sessionId, userId });
|
|
502
|
+
|
|
503
|
+
try {
|
|
504
|
+
await this._daemon.activateSession(sessionId, {
|
|
505
|
+
workingDir: this._config.workingDir,
|
|
506
|
+
});
|
|
507
|
+
|
|
508
|
+
this.sendDaemonMessage({
|
|
509
|
+
type: 'session_activated',
|
|
510
|
+
session_id: sessionId,
|
|
511
|
+
stream_config: {
|
|
512
|
+
buffer_mode: 'line',
|
|
513
|
+
max_message_size: 8192,
|
|
514
|
+
compression: 'none',
|
|
515
|
+
},
|
|
516
|
+
session_state: {
|
|
517
|
+
working_directory: this._config.workingDir || process.cwd(),
|
|
518
|
+
last_output: 'claude@session:~$ ',
|
|
519
|
+
cursor_position: { line: 1, col: 15 },
|
|
520
|
+
},
|
|
521
|
+
timestamp: new Date().toISOString(),
|
|
522
|
+
});
|
|
523
|
+
} catch (err) {
|
|
524
|
+
this._logger.error('Failed to activate session', { sessionId, error: err.message });
|
|
525
|
+
this._sendError('SESSION_ACTIVATION_FAILED', err.message, { session_id: sessionId });
|
|
526
|
+
}
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* Handle command_execute and slash_command — send command text to a session process.
|
|
531
|
+
* @param {object} message
|
|
532
|
+
*/
|
|
533
|
+
_handleCommandExecution(message) {
|
|
534
|
+
const sessionId = message.session_id;
|
|
535
|
+
const commandId = message.command_id;
|
|
536
|
+
const command = message.command;
|
|
537
|
+
|
|
538
|
+
this._logger.info('Executing command', { sessionId, commandId });
|
|
539
|
+
|
|
540
|
+
// Track active command for this session
|
|
541
|
+
if (commandId) {
|
|
542
|
+
this._activeCommands.set(sessionId, commandId);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
try {
|
|
546
|
+
this._daemon.sendMessage(sessionId, command);
|
|
547
|
+
} catch (err) {
|
|
548
|
+
this._logger.error('Command execution failed', { sessionId, error: err.message });
|
|
549
|
+
this._sendError('COMMAND_EXECUTION_FAILED', err.message, {
|
|
550
|
+
session_id: sessionId,
|
|
551
|
+
command_id: commandId,
|
|
552
|
+
command: command,
|
|
553
|
+
});
|
|
554
|
+
// Clear active command on failure
|
|
555
|
+
this._activeCommands.delete(sessionId);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
|
|
559
|
+
/**
|
|
560
|
+
* Handle session_recover — send recovery status updates.
|
|
561
|
+
* @param {object} message
|
|
562
|
+
*/
|
|
563
|
+
_handleSessionRecovery(message) {
|
|
564
|
+
const sessionId = message.session_id;
|
|
565
|
+
|
|
566
|
+
this._logger.info('Recovering session', { sessionId });
|
|
567
|
+
|
|
568
|
+
this._sendRecoveryStatus(sessionId, 'in_progress', 'process_cleanup');
|
|
569
|
+
this._sendRecoveryStatus(sessionId, 'completed', 'recovery_finished');
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
/**
|
|
573
|
+
* Handle session_deactivate — terminate the session process.
|
|
574
|
+
* @param {object} message
|
|
575
|
+
*/
|
|
576
|
+
async _handleSessionDeactivation(message) {
|
|
577
|
+
const sessionId = message.session_id;
|
|
578
|
+
this._logger.info('Deactivating session', { sessionId });
|
|
579
|
+
|
|
580
|
+
try {
|
|
581
|
+
await this._daemon.terminateSession(sessionId);
|
|
582
|
+
this._sendSessionStateUpdate(sessionId, { status: 'deactivated' });
|
|
583
|
+
} catch (err) {
|
|
584
|
+
this._logger.error('Failed to deactivate session', { sessionId, error: err.message });
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
// ---------------------------------------------------------------------------
|
|
589
|
+
// Outbound helper methods
|
|
590
|
+
// ---------------------------------------------------------------------------
|
|
591
|
+
|
|
592
|
+
/**
|
|
593
|
+
* Send a session state update to the Rails server.
|
|
594
|
+
* @param {string} sessionId
|
|
595
|
+
* @param {object} state
|
|
596
|
+
*/
|
|
597
|
+
_sendSessionStateUpdate(sessionId, state) {
|
|
598
|
+
this.sendDaemonMessage({
|
|
599
|
+
type: 'session_state_update',
|
|
600
|
+
session_id: sessionId,
|
|
601
|
+
state: state,
|
|
602
|
+
timestamp: new Date().toISOString(),
|
|
603
|
+
});
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Send a recovery status update to the Rails server.
|
|
608
|
+
* @param {string} sessionId
|
|
609
|
+
* @param {string} status
|
|
610
|
+
* @param {string} step
|
|
611
|
+
*/
|
|
612
|
+
_sendRecoveryStatus(sessionId, status, step) {
|
|
613
|
+
this.sendDaemonMessage({
|
|
614
|
+
type: 'recovery_status',
|
|
615
|
+
session_id: sessionId,
|
|
616
|
+
status: status,
|
|
617
|
+
progress: {
|
|
618
|
+
step: step,
|
|
619
|
+
completed_steps: [],
|
|
620
|
+
remaining_steps: [],
|
|
621
|
+
},
|
|
622
|
+
timestamp: new Date().toISOString(),
|
|
623
|
+
});
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* Send an error message to the Rails server (internal helper).
|
|
628
|
+
* @param {string} errorCode
|
|
629
|
+
* @param {string} errorMessage
|
|
630
|
+
* @param {object} context
|
|
631
|
+
*/
|
|
632
|
+
_sendError(errorCode, errorMessage, context = {}) {
|
|
633
|
+
this.sendDaemonMessage({
|
|
634
|
+
type: 'error',
|
|
635
|
+
error_code: errorCode,
|
|
636
|
+
message: errorMessage,
|
|
637
|
+
context: { daemon_id: this._daemonId, ...context },
|
|
638
|
+
severity: 'error',
|
|
639
|
+
timestamp: new Date().toISOString(),
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* Start the heartbeat interval timer.
|
|
645
|
+
*/
|
|
646
|
+
_startHeartbeat() {
|
|
647
|
+
if (this._heartbeatTimer) {
|
|
648
|
+
clearInterval(this._heartbeatTimer);
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
this._heartbeatTimer = setInterval(() => {
|
|
652
|
+
if (!this._connected || !this._authenticated) {
|
|
653
|
+
clearInterval(this._heartbeatTimer);
|
|
654
|
+
this._heartbeatTimer = null;
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
try {
|
|
659
|
+
this._sendHeartbeat();
|
|
660
|
+
} catch (err) {
|
|
661
|
+
this._logger.error('Heartbeat error', { error: err.message });
|
|
662
|
+
}
|
|
663
|
+
}, this._heartbeatInterval);
|
|
664
|
+
|
|
665
|
+
// Allow the Node.js process to exit even if the timer is active
|
|
666
|
+
if (this._heartbeatTimer.unref) {
|
|
667
|
+
this._heartbeatTimer.unref();
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* Send a heartbeat message to the server.
|
|
673
|
+
*/
|
|
674
|
+
_sendHeartbeat() {
|
|
675
|
+
this.sendDaemonMessage({
|
|
676
|
+
type: 'heartbeat',
|
|
677
|
+
daemon_id: this._daemonId,
|
|
678
|
+
status: 'healthy',
|
|
679
|
+
session_summary: this._getSessionSummary(),
|
|
680
|
+
resource_usage: this._getResourceUsage(),
|
|
681
|
+
timestamp: new Date().toISOString(),
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
|
|
685
|
+
/**
|
|
686
|
+
* Get a summary of daemon sessions from the daemon health check.
|
|
687
|
+
* @returns {object}
|
|
688
|
+
*/
|
|
689
|
+
_getSessionSummary() {
|
|
690
|
+
if (!this._daemon || typeof this._daemon.healthCheck !== 'function') {
|
|
691
|
+
return { total_sessions: 0, active_sessions: 0, idle_sessions: 0 };
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
try {
|
|
695
|
+
const healthResults = this._daemon.healthCheck();
|
|
696
|
+
const active = healthResults.filter((h) => h.alive).length;
|
|
697
|
+
return {
|
|
698
|
+
total_sessions: healthResults.length,
|
|
699
|
+
active_sessions: active,
|
|
700
|
+
idle_sessions: healthResults.length - active,
|
|
701
|
+
};
|
|
702
|
+
} catch (_) {
|
|
703
|
+
return { total_sessions: 0, active_sessions: 0, idle_sessions: 0 };
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
/**
|
|
708
|
+
* Get resource usage stats for this process.
|
|
709
|
+
* @returns {object}
|
|
710
|
+
*/
|
|
711
|
+
_getResourceUsage() {
|
|
712
|
+
try {
|
|
713
|
+
const rss = typeof process.memoryUsage.rss === 'function'
|
|
714
|
+
? process.memoryUsage.rss()
|
|
715
|
+
: process.memoryUsage().rss;
|
|
716
|
+
return {
|
|
717
|
+
memory_mb: Math.round(rss / 1024 / 1024),
|
|
718
|
+
cpu_percent: 0,
|
|
719
|
+
disk_usage_mb: 0,
|
|
720
|
+
};
|
|
721
|
+
} catch (_) {
|
|
722
|
+
return { memory_mb: 0, cpu_percent: 0, disk_usage_mb: 0 };
|
|
723
|
+
}
|
|
724
|
+
}
|
|
725
|
+
|
|
726
|
+
// ---------------------------------------------------------------------------
|
|
727
|
+
// ActionCable protocol: subscription
|
|
728
|
+
// ---------------------------------------------------------------------------
|
|
729
|
+
|
|
730
|
+
/**
|
|
731
|
+
* Send a subscribe command for DaemonChannel.
|
|
732
|
+
*/
|
|
733
|
+
_subscribeToDaemonChannel() {
|
|
734
|
+
const identifier = JSON.stringify({
|
|
735
|
+
channel: 'DaemonChannel',
|
|
736
|
+
daemon_id: this._daemonId,
|
|
737
|
+
});
|
|
738
|
+
|
|
739
|
+
this._send({
|
|
740
|
+
command: 'subscribe',
|
|
741
|
+
identifier,
|
|
742
|
+
});
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/**
|
|
746
|
+
* Send an unsubscribe command for DaemonChannel.
|
|
747
|
+
*/
|
|
748
|
+
_unsubscribe() {
|
|
749
|
+
const identifier = JSON.stringify({
|
|
750
|
+
channel: 'DaemonChannel',
|
|
751
|
+
daemon_id: this._daemonId,
|
|
752
|
+
});
|
|
753
|
+
|
|
754
|
+
this._send({
|
|
755
|
+
command: 'unsubscribe',
|
|
756
|
+
identifier,
|
|
757
|
+
});
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
// ---------------------------------------------------------------------------
|
|
761
|
+
// Reconnection with exponential backoff
|
|
762
|
+
// ---------------------------------------------------------------------------
|
|
763
|
+
|
|
764
|
+
/**
|
|
765
|
+
* Schedule a reconnect with exponential backoff.
|
|
766
|
+
* Delay = min(base * 2^(attempts-1), maxDelay)
|
|
767
|
+
*/
|
|
768
|
+
_scheduleReconnect() {
|
|
769
|
+
if (this._shutdownRequested) return;
|
|
770
|
+
|
|
771
|
+
this._reconnectAttempts += 1;
|
|
772
|
+
const delay = Math.min(
|
|
773
|
+
this._baseReconnectDelay * Math.pow(this._reconnectMultiplier, this._reconnectAttempts - 1),
|
|
774
|
+
this._maxReconnectDelay
|
|
775
|
+
);
|
|
776
|
+
|
|
777
|
+
if (this._reconnectAttempts === 1) {
|
|
778
|
+
this._logger.info(`Disconnected, reconnecting in ${delay}ms`);
|
|
779
|
+
} else {
|
|
780
|
+
this._logger.warn(`Reconnect failed, retrying in ${delay}ms (attempt ${this._reconnectAttempts})`);
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
this._reconnectTimer = setTimeout(() => {
|
|
784
|
+
this._reconnectTimer = null;
|
|
785
|
+
if (!this._shutdownRequested) {
|
|
786
|
+
this._connect();
|
|
787
|
+
}
|
|
788
|
+
}, delay);
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
// ---------------------------------------------------------------------------
|
|
792
|
+
// Internal: low-level send
|
|
793
|
+
// ---------------------------------------------------------------------------
|
|
794
|
+
|
|
795
|
+
/**
|
|
796
|
+
* Send a JSON message over the WebSocket.
|
|
797
|
+
* @param {object} msg
|
|
798
|
+
*/
|
|
799
|
+
_send(msg) {
|
|
800
|
+
if (!this._ws || this._ws.readyState !== WebSocket.OPEN) {
|
|
801
|
+
this._logger.warn('Cannot send: WebSocket not open');
|
|
802
|
+
return;
|
|
803
|
+
}
|
|
804
|
+
this._ws.send(JSON.stringify(msg));
|
|
805
|
+
}
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
module.exports = { ActionCableClient };
|