@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,91 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { EventEmitter } = require('node:events');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Abstract base class for connection modes.
|
|
7
|
+
*
|
|
8
|
+
* The Daemon communicates with clients through this interface only.
|
|
9
|
+
* Subclasses implement the send methods; event forwarding from the
|
|
10
|
+
* daemon is wired up automatically in the constructor.
|
|
11
|
+
*
|
|
12
|
+
* @abstract
|
|
13
|
+
*/
|
|
14
|
+
class BaseConnection extends EventEmitter {
|
|
15
|
+
/**
|
|
16
|
+
* @param {Daemon} daemon - The daemon instance to bridge
|
|
17
|
+
* @param {object} logger - Logger instance
|
|
18
|
+
*/
|
|
19
|
+
constructor(daemon, logger) {
|
|
20
|
+
super();
|
|
21
|
+
this._daemon = daemon;
|
|
22
|
+
this._logger = logger;
|
|
23
|
+
|
|
24
|
+
// Wire daemon events to the send methods so subclasses get
|
|
25
|
+
// automatic forwarding without extra setup.
|
|
26
|
+
this._daemon.on('session:output', ({ sessionId, data }) => {
|
|
27
|
+
this.sendOutput(sessionId, null, data);
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
this._daemon.on('session:exit', ({ sessionId, code, signal }) => {
|
|
31
|
+
this.sendComplete(sessionId, null, code, 0);
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
this._daemon.on('session:error', ({ sessionId, data }) => {
|
|
35
|
+
this.sendError(sessionId, 'PROCESS_ERROR', data);
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Start accepting connections.
|
|
41
|
+
* @abstract
|
|
42
|
+
*/
|
|
43
|
+
start() {
|
|
44
|
+
throw new Error('Not implemented');
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Stop accepting connections and close all existing ones.
|
|
49
|
+
* @abstract
|
|
50
|
+
* @returns {Promise<void>}
|
|
51
|
+
*/
|
|
52
|
+
async stop() {
|
|
53
|
+
throw new Error('Not implemented');
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Send Claude output to client(s) watching a session.
|
|
58
|
+
* @abstract
|
|
59
|
+
* @param {string} sessionId
|
|
60
|
+
* @param {string|null} commandId
|
|
61
|
+
* @param {string} data
|
|
62
|
+
*/
|
|
63
|
+
sendOutput(sessionId, commandId, data) {
|
|
64
|
+
throw new Error('Not implemented');
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Send command completion to client(s).
|
|
69
|
+
* @abstract
|
|
70
|
+
* @param {string} sessionId
|
|
71
|
+
* @param {string|null} commandId
|
|
72
|
+
* @param {number} exitCode
|
|
73
|
+
* @param {number} durationMs
|
|
74
|
+
*/
|
|
75
|
+
sendComplete(sessionId, commandId, exitCode, durationMs) {
|
|
76
|
+
throw new Error('Not implemented');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Send error to client(s).
|
|
81
|
+
* @abstract
|
|
82
|
+
* @param {string} sessionId
|
|
83
|
+
* @param {string} errorCode
|
|
84
|
+
* @param {string} message
|
|
85
|
+
*/
|
|
86
|
+
sendError(sessionId, errorCode, message) {
|
|
87
|
+
throw new Error('Not implemented');
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
module.exports = { BaseConnection };
|
|
@@ -0,0 +1,344 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const crypto = require('node:crypto');
|
|
4
|
+
const { URL } = require('node:url');
|
|
5
|
+
const { WebSocketServer, WebSocket } = require('ws');
|
|
6
|
+
const { BaseConnection } = require('./base-connection');
|
|
7
|
+
const { SessionStore } = require('../session-store');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Standalone WebSocket server that accepts direct client connections.
|
|
11
|
+
*
|
|
12
|
+
* Clients connect via: ws://localhost:PORT/?token=AUTH_TOKEN
|
|
13
|
+
*
|
|
14
|
+
* Message protocol (client -> server):
|
|
15
|
+
* { type: 'activate', sessionId, workingDir }
|
|
16
|
+
* { type: 'command', sessionId, commandId, text }
|
|
17
|
+
* { type: 'ping' }
|
|
18
|
+
*
|
|
19
|
+
* Message protocol (server -> client):
|
|
20
|
+
* { type: 'session_activated', sessionId }
|
|
21
|
+
* { type: 'output', sessionId, commandId, data, timestamp }
|
|
22
|
+
* { type: 'complete', sessionId, commandId, exitCode, durationMs, timestamp }
|
|
23
|
+
* { type: 'error', sessionId, code, message, timestamp }
|
|
24
|
+
* { type: 'pong' }
|
|
25
|
+
*/
|
|
26
|
+
class StandaloneServer extends BaseConnection {
|
|
27
|
+
/**
|
|
28
|
+
* @param {Daemon} daemon
|
|
29
|
+
* @param {object} config - Must include `port`; may include `authToken`
|
|
30
|
+
* @param {object} logger
|
|
31
|
+
*/
|
|
32
|
+
constructor(daemon, config, logger, options = {}) {
|
|
33
|
+
super(daemon, logger);
|
|
34
|
+
this._port = config.port != null ? config.port : 3001;
|
|
35
|
+
this._token = config.authToken || crypto.randomUUID();
|
|
36
|
+
this._wss = null;
|
|
37
|
+
this._sessions = new Map(); // sessionId -> Set<WebSocket>
|
|
38
|
+
this._clients = new Map(); // WebSocket -> { authenticated: boolean }
|
|
39
|
+
this._sessionStore = options.sessionStore || new SessionStore();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** Actual port the server is listening on (useful when started with port 0). */
|
|
43
|
+
get port() {
|
|
44
|
+
if (this._wss) {
|
|
45
|
+
const addr = this._wss.address();
|
|
46
|
+
return addr ? addr.port : this._port;
|
|
47
|
+
}
|
|
48
|
+
return this._port;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The auth token in use. */
|
|
52
|
+
get token() {
|
|
53
|
+
return this._token;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Start the WebSocket server.
|
|
58
|
+
*/
|
|
59
|
+
start() {
|
|
60
|
+
this._wss = new WebSocketServer({ port: this._port });
|
|
61
|
+
|
|
62
|
+
this._wss.on('connection', (ws, req) => this._handleConnection(ws, req));
|
|
63
|
+
|
|
64
|
+
this._wss.on('listening', () => {
|
|
65
|
+
const addr = this._wss.address();
|
|
66
|
+
this._logger.info(`WebSocket server listening on port ${addr.port}`);
|
|
67
|
+
this._logger.info(`Auth token: ${this._token}`);
|
|
68
|
+
this.emit('listening', addr);
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
this._wss.on('error', (err) => {
|
|
72
|
+
this._logger.error('WebSocket server error', { error: err.message });
|
|
73
|
+
this.emit('error', err);
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Stop the server and close all connections.
|
|
79
|
+
* @returns {Promise<void>}
|
|
80
|
+
*/
|
|
81
|
+
async stop() {
|
|
82
|
+
if (!this._wss) return;
|
|
83
|
+
|
|
84
|
+
// Close all client connections
|
|
85
|
+
for (const ws of this._clients.keys()) {
|
|
86
|
+
try {
|
|
87
|
+
ws.close(1000, 'Server shutting down');
|
|
88
|
+
} catch (_) {
|
|
89
|
+
// Ignore errors on close
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
this._clients.clear();
|
|
94
|
+
this._sessions.clear();
|
|
95
|
+
|
|
96
|
+
return new Promise((resolve) => {
|
|
97
|
+
this._wss.close(() => {
|
|
98
|
+
this._wss = null;
|
|
99
|
+
this._logger.info('WebSocket server stopped');
|
|
100
|
+
resolve();
|
|
101
|
+
});
|
|
102
|
+
});
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
// Send methods (called by BaseConnection event wiring and directly)
|
|
107
|
+
// ---------------------------------------------------------------------------
|
|
108
|
+
|
|
109
|
+
sendOutput(sessionId, commandId, data) {
|
|
110
|
+
const msg = {
|
|
111
|
+
type: 'output',
|
|
112
|
+
sessionId,
|
|
113
|
+
commandId,
|
|
114
|
+
data,
|
|
115
|
+
timestamp: Date.now(),
|
|
116
|
+
};
|
|
117
|
+
this._broadcast(sessionId, msg);
|
|
118
|
+
this._sessionStore.append(sessionId, msg);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
sendComplete(sessionId, commandId, exitCode, durationMs) {
|
|
122
|
+
const msg = {
|
|
123
|
+
type: 'complete',
|
|
124
|
+
sessionId,
|
|
125
|
+
commandId,
|
|
126
|
+
exitCode,
|
|
127
|
+
durationMs,
|
|
128
|
+
timestamp: Date.now(),
|
|
129
|
+
};
|
|
130
|
+
this._broadcast(sessionId, msg);
|
|
131
|
+
this._sessionStore.append(sessionId, msg);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
sendError(sessionId, errorCode, message) {
|
|
135
|
+
const msg = {
|
|
136
|
+
type: 'error',
|
|
137
|
+
sessionId,
|
|
138
|
+
code: errorCode,
|
|
139
|
+
message,
|
|
140
|
+
timestamp: Date.now(),
|
|
141
|
+
};
|
|
142
|
+
this._broadcast(sessionId, msg);
|
|
143
|
+
this._sessionStore.append(sessionId, msg);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// ---------------------------------------------------------------------------
|
|
147
|
+
// Internal: connection handling
|
|
148
|
+
// ---------------------------------------------------------------------------
|
|
149
|
+
|
|
150
|
+
_handleConnection(ws, req) {
|
|
151
|
+
// Validate auth token from query param
|
|
152
|
+
let token = null;
|
|
153
|
+
try {
|
|
154
|
+
const url = new URL(req.url, `http://localhost:${this.port}`);
|
|
155
|
+
token = url.searchParams.get('token');
|
|
156
|
+
} catch (_) {
|
|
157
|
+
// If URL parsing fails, token stays null
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (token !== this._token) {
|
|
161
|
+
this._sendToClient(ws, {
|
|
162
|
+
type: 'error',
|
|
163
|
+
code: 'AUTH_FAILED',
|
|
164
|
+
message: 'Invalid or missing auth token',
|
|
165
|
+
timestamp: Date.now(),
|
|
166
|
+
});
|
|
167
|
+
ws.close(4001, 'Authentication failed');
|
|
168
|
+
this._logger.warn('Connection rejected: invalid auth token');
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// Track the authenticated client
|
|
173
|
+
this._clients.set(ws, { authenticated: true });
|
|
174
|
+
this._logger.info('Client connected');
|
|
175
|
+
|
|
176
|
+
ws.on('message', (raw) => this._handleMessage(ws, raw));
|
|
177
|
+
ws.on('close', () => this._handleDisconnect(ws));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
_handleMessage(ws, raw) {
|
|
181
|
+
let msg;
|
|
182
|
+
try {
|
|
183
|
+
msg = JSON.parse(raw.toString());
|
|
184
|
+
} catch (_) {
|
|
185
|
+
this._sendToClient(ws, {
|
|
186
|
+
type: 'error',
|
|
187
|
+
code: 'PARSE_ERROR',
|
|
188
|
+
message: 'Invalid JSON',
|
|
189
|
+
timestamp: Date.now(),
|
|
190
|
+
});
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
if (!msg || typeof msg.type !== 'string') {
|
|
195
|
+
this._sendToClient(ws, {
|
|
196
|
+
type: 'error',
|
|
197
|
+
code: 'INVALID_MESSAGE',
|
|
198
|
+
message: 'Message must have a "type" field',
|
|
199
|
+
timestamp: Date.now(),
|
|
200
|
+
});
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
switch (msg.type) {
|
|
205
|
+
case 'activate':
|
|
206
|
+
this._handleActivate(ws, msg);
|
|
207
|
+
break;
|
|
208
|
+
|
|
209
|
+
case 'command':
|
|
210
|
+
this._handleCommand(ws, msg);
|
|
211
|
+
break;
|
|
212
|
+
|
|
213
|
+
case 'ping':
|
|
214
|
+
this._sendToClient(ws, { type: 'pong' });
|
|
215
|
+
break;
|
|
216
|
+
|
|
217
|
+
default:
|
|
218
|
+
this._sendToClient(ws, {
|
|
219
|
+
type: 'error',
|
|
220
|
+
code: 'UNKNOWN_TYPE',
|
|
221
|
+
message: `Unknown message type: "${msg.type}"`,
|
|
222
|
+
timestamp: Date.now(),
|
|
223
|
+
});
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
async _handleActivate(ws, msg) {
|
|
228
|
+
const { sessionId, workingDir } = msg;
|
|
229
|
+
|
|
230
|
+
if (!sessionId) {
|
|
231
|
+
this._sendToClient(ws, {
|
|
232
|
+
type: 'error',
|
|
233
|
+
code: 'INVALID_MESSAGE',
|
|
234
|
+
message: 'activate requires sessionId',
|
|
235
|
+
timestamp: Date.now(),
|
|
236
|
+
});
|
|
237
|
+
return;
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
try {
|
|
241
|
+
await this._daemon.activateSession(sessionId, { workingDir });
|
|
242
|
+
|
|
243
|
+
// Track this client as watching this session
|
|
244
|
+
if (!this._sessions.has(sessionId)) {
|
|
245
|
+
this._sessions.set(sessionId, new Set());
|
|
246
|
+
}
|
|
247
|
+
this._sessions.get(sessionId).add(ws);
|
|
248
|
+
|
|
249
|
+
this._sendToClient(ws, {
|
|
250
|
+
type: 'session_activated',
|
|
251
|
+
sessionId,
|
|
252
|
+
});
|
|
253
|
+
|
|
254
|
+
// Replay stored history to the connecting client (not broadcast)
|
|
255
|
+
if (this._sessionStore.hasHistory(sessionId)) {
|
|
256
|
+
const history = this._sessionStore.readAll(sessionId);
|
|
257
|
+
for (const entry of history) {
|
|
258
|
+
this._sendToClient(ws, { ...entry.data, replay: true });
|
|
259
|
+
}
|
|
260
|
+
this._logger.info('Replayed session history', { sessionId, messageCount: history.length });
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
this._logger.info('Session activated', { sessionId });
|
|
264
|
+
} catch (err) {
|
|
265
|
+
this._sendToClient(ws, {
|
|
266
|
+
type: 'error',
|
|
267
|
+
code: 'ACTIVATE_FAILED',
|
|
268
|
+
message: err.message,
|
|
269
|
+
timestamp: Date.now(),
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
_handleCommand(ws, msg) {
|
|
275
|
+
const { sessionId, commandId, text } = msg;
|
|
276
|
+
|
|
277
|
+
if (!sessionId || !text) {
|
|
278
|
+
this._sendToClient(ws, {
|
|
279
|
+
type: 'error',
|
|
280
|
+
code: 'INVALID_MESSAGE',
|
|
281
|
+
message: 'command requires sessionId and text',
|
|
282
|
+
timestamp: Date.now(),
|
|
283
|
+
});
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
// Track client as watching this session if not already
|
|
288
|
+
if (!this._sessions.has(sessionId)) {
|
|
289
|
+
this._sessions.set(sessionId, new Set());
|
|
290
|
+
}
|
|
291
|
+
this._sessions.get(sessionId).add(ws);
|
|
292
|
+
|
|
293
|
+
try {
|
|
294
|
+
this._daemon.sendMessage(sessionId, text);
|
|
295
|
+
} catch (err) {
|
|
296
|
+
this._sendToClient(ws, {
|
|
297
|
+
type: 'error',
|
|
298
|
+
code: 'COMMAND_FAILED',
|
|
299
|
+
message: err.message,
|
|
300
|
+
timestamp: Date.now(),
|
|
301
|
+
});
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
_handleDisconnect(ws) {
|
|
306
|
+
// Remove from all session sets
|
|
307
|
+
for (const [sessionId, clients] of this._sessions) {
|
|
308
|
+
clients.delete(ws);
|
|
309
|
+
if (clients.size === 0) {
|
|
310
|
+
this._sessions.delete(sessionId);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Remove from clients map
|
|
315
|
+
this._clients.delete(ws);
|
|
316
|
+
|
|
317
|
+
// Do NOT kill Claude processes — keep them alive for reconnection
|
|
318
|
+
this._logger.info('Client disconnected');
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
// ---------------------------------------------------------------------------
|
|
322
|
+
// Internal: helpers
|
|
323
|
+
// ---------------------------------------------------------------------------
|
|
324
|
+
|
|
325
|
+
_broadcast(sessionId, msg) {
|
|
326
|
+
const clients = this._sessions.get(sessionId);
|
|
327
|
+
if (!clients) return;
|
|
328
|
+
|
|
329
|
+
const json = JSON.stringify(msg);
|
|
330
|
+
for (const ws of clients) {
|
|
331
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
332
|
+
ws.send(json);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
_sendToClient(ws, msg) {
|
|
338
|
+
if (ws.readyState === WebSocket.OPEN) {
|
|
339
|
+
ws.send(JSON.stringify(msg));
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
module.exports = { StandaloneServer };
|