@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 ADDED
@@ -0,0 +1,31 @@
1
+ Proprietary Software License
2
+
3
+ Copyright (c) 2025-2026 Rad Nine Software Inc.. All rights reserved.
4
+
5
+ This software and associated documentation files (the "Software") are the
6
+ proprietary and confidential property of Rad Nine Software Inc..
7
+
8
+ Permission is hereby granted to authorized licensees to use the Software
9
+ solely for their own internal purposes, subject to the following conditions:
10
+
11
+ 1. The Software may not be copied, modified, merged, published, distributed,
12
+ sublicensed, sold, or otherwise transferred to any third party without
13
+ the prior written consent of Rad Nine Software Inc..
14
+
15
+ 2. The Software may not be reverse-engineered, decompiled, or disassembled,
16
+ except to the extent that such activity is expressly permitted by
17
+ applicable law.
18
+
19
+ 3. This license does not grant any ownership rights in the Software. All
20
+ intellectual property rights in the Software remain with Rad Nine Software Inc..
21
+
22
+ 4. This license may be terminated by Rad Nine Software Inc. at any time upon written
23
+ notice. Upon termination, the licensee must cease all use of the Software
24
+ and destroy all copies.
25
+
26
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
27
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
28
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
29
+ RADIXHOUND BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
30
+ AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
31
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/package.json ADDED
@@ -0,0 +1,33 @@
1
+ {
2
+ "name": "@radnine/claude-session-daemon",
3
+ "version": "0.1.1",
4
+ "description": "Node.js daemon for managing Claude CLI sessions",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+ssh://git@github.com/radixhound/rad-project.git",
9
+ "directory": "daemon"
10
+ },
11
+ "main": "src/index.js",
12
+ "bin": {
13
+ "claude-session-daemon": "src/index.js"
14
+ },
15
+ "files": [
16
+ "src/**",
17
+ "LICENSE"
18
+ ],
19
+ "scripts": {
20
+ "start": "node src/index.js",
21
+ "test": "node --test test/*.test.js"
22
+ },
23
+ "publishConfig": {
24
+ "access": "public"
25
+ },
26
+ "engines": {
27
+ "node": ">=18.0.0"
28
+ },
29
+ "dependencies": {
30
+ "ws": "^8.16.0"
31
+ },
32
+ "devDependencies": {}
33
+ }
@@ -0,0 +1,277 @@
1
+ 'use strict';
2
+
3
+ const { EventEmitter } = require('node:events');
4
+ const { spawn: defaultSpawn } = require('node:child_process');
5
+ const { createInterface } = require('node:readline');
6
+ const { randomUUID } = require('node:crypto');
7
+
8
+ const MAX_CHUNK_SIZE = 50000; // 50KB — lines larger than this get flagged
9
+
10
+ /**
11
+ * Wraps a single Claude CLI child process.
12
+ *
13
+ * Emits:
14
+ * 'output' — (data) parsed JSON message from stdout
15
+ * 'error' — (line) unparseable stdout line
16
+ * 'stderr' — (line) stderr line
17
+ * 'exit' — (code, signal) process exited
18
+ * 'spawned' — process started successfully
19
+ */
20
+ class ClaudeProcess extends EventEmitter {
21
+ /**
22
+ * @param {string} sessionId - Logical session ID (from Rails or caller)
23
+ * @param {object} [options]
24
+ * @param {string} [options.workingDir] - cwd for the child process
25
+ * @param {string} [options.claudeSessionId] - UUID for --session-id flag
26
+ * @param {object} [options.logger] - Logger instance
27
+ * @param {string} [options.claudeCommand] - Path to claude binary
28
+ * @param {Function} [options._spawnFn] - For testing: replacement for child_process.spawn
29
+ */
30
+ constructor(sessionId, options = {}) {
31
+ super();
32
+
33
+ this._sessionId = sessionId;
34
+ this._claudeSessionId = options.claudeSessionId || randomUUID();
35
+ this._workingDir = options.workingDir || process.cwd();
36
+ this._logger = options.logger || _defaultLogger();
37
+ this._claudeCommand = options.claudeCommand || 'claude';
38
+ this._spawnFn = options._spawnFn || defaultSpawn;
39
+
40
+ this._state = 'idle';
41
+ this._child = null;
42
+ this._pid = null;
43
+ this._startedAt = null;
44
+ }
45
+
46
+ // -------------------------------------------------------------------------
47
+ // Public API
48
+ // -------------------------------------------------------------------------
49
+
50
+ /**
51
+ * Spawn the Claude CLI process.
52
+ * @throws {Error} if not in idle state
53
+ */
54
+ spawn() {
55
+ if (this._state !== 'idle') {
56
+ throw new Error(`Cannot spawn: process is not idle (state=${this._state})`);
57
+ }
58
+
59
+ this._state = 'spawning';
60
+
61
+ const args = [
62
+ '--verbose',
63
+ '--input-format', 'stream-json',
64
+ '--output-format', 'stream-json',
65
+ '--session-id', this._claudeSessionId,
66
+ '--replay-user-messages',
67
+ ];
68
+
69
+ const env = { ...process.env, CLAUDE_SESSION_ID: this._sessionId };
70
+ delete env.CLAUDECODE; // Prevent nested session detection
71
+
72
+ const opts = {
73
+ cwd: this._workingDir,
74
+ stdio: ['pipe', 'pipe', 'pipe'],
75
+ env,
76
+ };
77
+
78
+ this._logger.info(`Spawning Claude CLI: ${this._claudeCommand}`, {
79
+ sessionId: this._sessionId,
80
+ claudeSessionId: this._claudeSessionId,
81
+ cwd: this._workingDir,
82
+ });
83
+
84
+ this._child = this._spawnFn(this._claudeCommand, args, opts);
85
+ this._pid = this._child.pid;
86
+ this._startedAt = Date.now();
87
+ this._state = 'running';
88
+
89
+ this._setupStdout();
90
+ this._setupStderr();
91
+ this._setupClose();
92
+
93
+ this.emit('spawned');
94
+ }
95
+
96
+ /**
97
+ * Send a user message to the Claude CLI stdin.
98
+ * @param {string} text - The message content
99
+ * @returns {boolean} true if written, false if process not running
100
+ */
101
+ sendMessage(text) {
102
+ if (this._state !== 'running' || !this._child) {
103
+ this._logger.warn('Cannot send message: process not running');
104
+ return false;
105
+ }
106
+
107
+ const payload = JSON.stringify({
108
+ type: 'user',
109
+ message: { role: 'user', content: text },
110
+ }) + '\n';
111
+
112
+ this._child.stdin.write(payload);
113
+ this._logger.debug('Sent message to stdin', { length: payload.length });
114
+ return true;
115
+ }
116
+
117
+ /**
118
+ * Send a slash command (e.g., /compact, /status).
119
+ * @param {string} command - The slash command string
120
+ * @returns {boolean} true if written
121
+ */
122
+ sendSlashCommand(command) {
123
+ return this.sendMessage(command);
124
+ }
125
+
126
+ /**
127
+ * Graceful shutdown: close stdin, SIGTERM, wait, SIGKILL if needed.
128
+ * @param {number} [timeoutMs=5000]
129
+ * @returns {Promise<void>}
130
+ */
131
+ async kill(timeoutMs = 5000) {
132
+ if (this._state !== 'running' && this._state !== 'spawning') {
133
+ return;
134
+ }
135
+
136
+ this._state = 'stopping';
137
+ this._logger.info('Stopping Claude process', { pid: this._pid });
138
+
139
+ // Close stdin to signal EOF
140
+ try {
141
+ this._child.stdin.end();
142
+ } catch (_) { /* ignore */ }
143
+
144
+ // Send SIGTERM
145
+ try {
146
+ this._child.kill('SIGTERM');
147
+ } catch (_) { /* ignore if already dead */ }
148
+
149
+ // Wait for process to exit or timeout
150
+ const exited = await this._waitForExit(timeoutMs);
151
+
152
+ if (!exited) {
153
+ this._logger.warn('Process did not exit after SIGTERM, sending SIGKILL', {
154
+ pid: this._pid,
155
+ });
156
+ try {
157
+ this._child.kill('SIGKILL');
158
+ } catch (_) { /* ignore */ }
159
+
160
+ // Wait briefly for SIGKILL
161
+ await this._waitForExit(2000);
162
+ }
163
+
164
+ this._state = 'stopped';
165
+ }
166
+
167
+ /**
168
+ * Check if the underlying OS process is still alive.
169
+ * @returns {boolean}
170
+ */
171
+ isAlive() {
172
+ if (!this._child || !this._pid) return false;
173
+
174
+ try {
175
+ this._child.kill(0); // Signal 0 = check existence
176
+ return true;
177
+ } catch (_) {
178
+ return false;
179
+ }
180
+ }
181
+
182
+ // -------------------------------------------------------------------------
183
+ // Getters
184
+ // -------------------------------------------------------------------------
185
+
186
+ get pid() { return this._pid; }
187
+ get state() { return this._state; }
188
+ get claudeSessionId() { return this._claudeSessionId; }
189
+ get sessionId() { return this._sessionId; }
190
+ get startedAt() { return this._startedAt; }
191
+ get workingDir() { return this._workingDir; }
192
+
193
+ // -------------------------------------------------------------------------
194
+ // Internal
195
+ // -------------------------------------------------------------------------
196
+
197
+ _setupStdout() {
198
+ const rl = createInterface({ input: this._child.stdout });
199
+
200
+ rl.on('line', (line) => {
201
+ if (!line) return;
202
+
203
+ try {
204
+ const data = JSON.parse(line);
205
+
206
+ // Flag oversized lines for the transport layer
207
+ if (line.length > MAX_CHUNK_SIZE) {
208
+ data._oversized = true;
209
+ data._originalSize = line.length;
210
+ }
211
+
212
+ this.emit('output', data);
213
+ } catch (_) {
214
+ // Not valid JSON — emit as error
215
+ this._logger.warn('Unparseable stdout line', { line: line.slice(0, 200) });
216
+ this.emit('error', line);
217
+ }
218
+ });
219
+ }
220
+
221
+ _setupStderr() {
222
+ const rl = createInterface({ input: this._child.stderr });
223
+
224
+ rl.on('line', (line) => {
225
+ if (!line) return;
226
+ this._logger.error('Claude stderr', { line });
227
+ this.emit('stderr', line);
228
+ });
229
+ }
230
+
231
+ _setupClose() {
232
+ this._child.on('close', (code, signal) => {
233
+ this._logger.info('Claude process exited', { code, signal, pid: this._pid });
234
+ this._state = 'stopped';
235
+ this.emit('exit', code, signal);
236
+ });
237
+ }
238
+
239
+ /**
240
+ * Wait for the child process to emit 'close', up to timeoutMs.
241
+ * @param {number} timeoutMs
242
+ * @returns {Promise<boolean>} true if exited, false if timed out
243
+ */
244
+ _waitForExit(timeoutMs) {
245
+ return new Promise((resolve) => {
246
+ if (this._state === 'stopped') {
247
+ resolve(true);
248
+ return;
249
+ }
250
+
251
+ let timer;
252
+ const onClose = () => {
253
+ clearTimeout(timer);
254
+ resolve(true);
255
+ };
256
+
257
+ timer = setTimeout(() => {
258
+ this._child.removeListener('close', onClose);
259
+ resolve(false);
260
+ }, timeoutMs);
261
+
262
+ this._child.once('close', onClose);
263
+ });
264
+ }
265
+ }
266
+
267
+ function _defaultLogger() {
268
+ return {
269
+ debug: () => {},
270
+ info: () => {},
271
+ warn: () => {},
272
+ error: () => {},
273
+ child: () => _defaultLogger(),
274
+ };
275
+ }
276
+
277
+ module.exports = ClaudeProcess;
package/src/config.js ADDED
@@ -0,0 +1,73 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Load daemon configuration from environment variables.
5
+ * Returns a frozen object so config is immutable after load.
6
+ *
7
+ * @returns {Readonly<object>} Configuration object
8
+ */
9
+ function intEnv(value, defaultVal) {
10
+ if (value === undefined || value === '') return defaultVal;
11
+ const parsed = parseInt(value, 10);
12
+ return Number.isNaN(parsed) ? defaultVal : parsed;
13
+ }
14
+
15
+ function loadConfig() {
16
+ const env = process.env;
17
+
18
+ const config = {
19
+ // Operating mode: 'actioncable' connects to Rails, 'standalone' runs own WS server
20
+ mode: env.CLAUDE_DAEMON_MODE || 'actioncable',
21
+
22
+ // Working directory for Claude CLI processes
23
+ workingDir: env.CLAUDE_WORKING_DIR || process.cwd(),
24
+
25
+ // Maximum concurrent sessions
26
+ maxSessions: intEnv(env.CLAUDE_MAX_SESSIONS, 10),
27
+
28
+ // Anthropic API key passed through to Claude CLI
29
+ anthropicApiKey: env.ANTHROPIC_API_KEY || null,
30
+
31
+ // WebSocket server port for standalone mode
32
+ port: intEnv(env.CLAUDE_DAEMON_PORT, 3001),
33
+
34
+ // Rails server URL for actioncable mode
35
+ railsUrl: env.CLAUDE_RAILS_URL || 'http://localhost:3000',
36
+
37
+ // Authentication token
38
+ authToken: env.CLAUDE_AUTH_TOKEN || null,
39
+
40
+ // Log level
41
+ logLevel: env.CLAUDE_LOG_LEVEL || 'info',
42
+
43
+ // Heartbeat interval in seconds
44
+ heartbeatInterval: intEnv(env.CLAUDE_HEARTBEAT_INTERVAL, 30),
45
+
46
+ // Cleanup interval in seconds
47
+ cleanupInterval: intEnv(env.CLAUDE_CLEANUP_INTERVAL, 300),
48
+
49
+ // Startup timeout in seconds
50
+ startupTimeout: intEnv(env.CLAUDE_STARTUP_TIMEOUT, 5),
51
+
52
+ // Daemon identifier (generated at runtime if not set)
53
+ daemonId: env.CLAUDE_DAEMON_ID || null,
54
+ };
55
+
56
+ // Validate mode
57
+ if (config.mode !== 'actioncable' && config.mode !== 'standalone') {
58
+ throw new Error(`Invalid CLAUDE_DAEMON_MODE: "${config.mode}". Must be "actioncable" or "standalone".`);
59
+ }
60
+
61
+ // Validate numeric values
62
+ if (config.maxSessions < 1) {
63
+ throw new Error(`CLAUDE_MAX_SESSIONS must be >= 1, got ${config.maxSessions}`);
64
+ }
65
+
66
+ if (config.port < 1 || config.port > 65535) {
67
+ throw new Error(`CLAUDE_DAEMON_PORT must be 1-65535, got ${config.port}`);
68
+ }
69
+
70
+ return Object.freeze(config);
71
+ }
72
+
73
+ module.exports = { loadConfig };