@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
package/src/daemon.js
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { EventEmitter } = require('node:events');
|
|
4
|
+
const ClaudeProcess = require('./claude-process');
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Process pool manager for Claude CLI sessions.
|
|
8
|
+
*
|
|
9
|
+
* Manages a pool of ClaudeProcess instances, enforces max capacity,
|
|
10
|
+
* runs periodic cleanup and health checks, and handles graceful shutdown.
|
|
11
|
+
*
|
|
12
|
+
* Emits:
|
|
13
|
+
* 'started' — daemon started
|
|
14
|
+
* 'stopped' — daemon stopped
|
|
15
|
+
* 'session:output' — { sessionId, data } from a process
|
|
16
|
+
* 'session:error' — { sessionId, data } from a process
|
|
17
|
+
* 'session:stderr' — { sessionId, data } from a process
|
|
18
|
+
* 'session:exit' — { sessionId, code, signal } from a process
|
|
19
|
+
*/
|
|
20
|
+
class Daemon extends EventEmitter {
|
|
21
|
+
/**
|
|
22
|
+
* @param {object} config - Frozen config from loadConfig()
|
|
23
|
+
* @param {object} logger - Logger instance
|
|
24
|
+
* @param {object} [options]
|
|
25
|
+
* @param {Function} [options._createProcess] - Factory for creating ClaudeProcess (for testing)
|
|
26
|
+
*/
|
|
27
|
+
constructor(config, logger, options = {}) {
|
|
28
|
+
super();
|
|
29
|
+
|
|
30
|
+
this._processes = new Map(); // sessionId -> ClaudeProcess
|
|
31
|
+
this._config = config;
|
|
32
|
+
this._logger = logger;
|
|
33
|
+
this._running = false;
|
|
34
|
+
this._cleanupTimer = null;
|
|
35
|
+
this._healthCheckTimer = null;
|
|
36
|
+
this._createProcess = options._createProcess || this._defaultCreateProcess.bind(this);
|
|
37
|
+
this._shutdownHandler = null;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// -------------------------------------------------------------------------
|
|
41
|
+
// Public API
|
|
42
|
+
// -------------------------------------------------------------------------
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Start the daemon — begin cleanup/health timers, register signal handlers.
|
|
46
|
+
*/
|
|
47
|
+
start() {
|
|
48
|
+
this._running = true;
|
|
49
|
+
|
|
50
|
+
// Periodic cleanup of dead processes
|
|
51
|
+
this._cleanupTimer = setInterval(
|
|
52
|
+
() => this._cleanupDeadProcesses(),
|
|
53
|
+
this._config.cleanupInterval * 1000,
|
|
54
|
+
);
|
|
55
|
+
|
|
56
|
+
// Periodic health check
|
|
57
|
+
this._healthCheckTimer = setInterval(
|
|
58
|
+
() => this._runHealthCheck(),
|
|
59
|
+
this._config.heartbeatInterval * 1000,
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
// Don't let timers prevent process exit
|
|
63
|
+
if (this._cleanupTimer.unref) this._cleanupTimer.unref();
|
|
64
|
+
if (this._healthCheckTimer.unref) this._healthCheckTimer.unref();
|
|
65
|
+
|
|
66
|
+
// Signal handlers for graceful shutdown
|
|
67
|
+
this._shutdownHandler = (signal) => this._handleShutdown(signal);
|
|
68
|
+
process.on('SIGTERM', this._shutdownHandler);
|
|
69
|
+
process.on('SIGINT', this._shutdownHandler);
|
|
70
|
+
|
|
71
|
+
this._logger.info('Daemon started', {
|
|
72
|
+
maxSessions: this._config.maxSessions,
|
|
73
|
+
cleanupInterval: this._config.cleanupInterval,
|
|
74
|
+
heartbeatInterval: this._config.heartbeatInterval,
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
this.emit('started');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Stop the daemon — kill all processes, clear timers.
|
|
82
|
+
*/
|
|
83
|
+
async stop() {
|
|
84
|
+
this._running = false;
|
|
85
|
+
|
|
86
|
+
// Clear timers
|
|
87
|
+
if (this._cleanupTimer) {
|
|
88
|
+
clearInterval(this._cleanupTimer);
|
|
89
|
+
this._cleanupTimer = null;
|
|
90
|
+
}
|
|
91
|
+
if (this._healthCheckTimer) {
|
|
92
|
+
clearInterval(this._healthCheckTimer);
|
|
93
|
+
this._healthCheckTimer = null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// Remove signal handlers
|
|
97
|
+
if (this._shutdownHandler) {
|
|
98
|
+
process.removeListener('SIGTERM', this._shutdownHandler);
|
|
99
|
+
process.removeListener('SIGINT', this._shutdownHandler);
|
|
100
|
+
this._shutdownHandler = null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Kill all active processes
|
|
104
|
+
const killPromises = [];
|
|
105
|
+
for (const [sessionId, proc] of this._processes) {
|
|
106
|
+
this._logger.info('Stopping session', { sessionId });
|
|
107
|
+
killPromises.push(proc.kill());
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
await Promise.all(killPromises);
|
|
111
|
+
this._processes.clear();
|
|
112
|
+
|
|
113
|
+
this._logger.info('Daemon stopped');
|
|
114
|
+
this.emit('stopped');
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Get or spawn a Claude process for a session.
|
|
119
|
+
*
|
|
120
|
+
* @param {string} sessionId
|
|
121
|
+
* @param {object} [options]
|
|
122
|
+
* @param {string} [options.workingDir]
|
|
123
|
+
* @param {string} [options.claudeSessionId]
|
|
124
|
+
* @returns {Promise<ClaudeProcess>}
|
|
125
|
+
*/
|
|
126
|
+
async activateSession(sessionId, options = {}) {
|
|
127
|
+
// If process exists and alive, return it
|
|
128
|
+
const existing = this._processes.get(sessionId);
|
|
129
|
+
if (existing && existing.isAlive()) {
|
|
130
|
+
this._logger.debug('Reusing existing session', { sessionId });
|
|
131
|
+
return existing;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Clean up dead process if it exists
|
|
135
|
+
if (existing) {
|
|
136
|
+
this._processes.delete(sessionId);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
// Check capacity
|
|
140
|
+
if (this._processes.size >= this._config.maxSessions) {
|
|
141
|
+
throw new Error(
|
|
142
|
+
`Max session capacity reached (${this._config.maxSessions}). Cannot create session "${sessionId}".`
|
|
143
|
+
);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Create new process
|
|
147
|
+
const proc = this._createProcess(sessionId, {
|
|
148
|
+
workingDir: options.workingDir || this._config.workingDir,
|
|
149
|
+
claudeSessionId: options.claudeSessionId,
|
|
150
|
+
logger: this._logger.child(`Session:${sessionId}`),
|
|
151
|
+
});
|
|
152
|
+
|
|
153
|
+
// Wire up event forwarding
|
|
154
|
+
this._forwardEvents(sessionId, proc);
|
|
155
|
+
|
|
156
|
+
// Spawn the process
|
|
157
|
+
proc.spawn();
|
|
158
|
+
|
|
159
|
+
// Store in pool
|
|
160
|
+
this._processes.set(sessionId, proc);
|
|
161
|
+
|
|
162
|
+
this._logger.info('Session activated', { sessionId, activeCount: this._processes.size });
|
|
163
|
+
|
|
164
|
+
return proc;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Find process by session ID. Returns null if not found or dead.
|
|
169
|
+
*
|
|
170
|
+
* @param {string} sessionId
|
|
171
|
+
* @returns {ClaudeProcess|null}
|
|
172
|
+
*/
|
|
173
|
+
getProcess(sessionId) {
|
|
174
|
+
const proc = this._processes.get(sessionId);
|
|
175
|
+
if (!proc) return null;
|
|
176
|
+
|
|
177
|
+
if (!proc.isAlive()) {
|
|
178
|
+
this._processes.delete(sessionId);
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
return proc;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Send a message to a session's process.
|
|
187
|
+
*
|
|
188
|
+
* @param {string} sessionId
|
|
189
|
+
* @param {string} text
|
|
190
|
+
* @throws {Error} if session not found
|
|
191
|
+
*/
|
|
192
|
+
sendMessage(sessionId, text) {
|
|
193
|
+
const proc = this.getProcess(sessionId);
|
|
194
|
+
if (!proc) {
|
|
195
|
+
throw new Error(`Session not found: "${sessionId}"`);
|
|
196
|
+
}
|
|
197
|
+
return proc.sendMessage(text);
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Terminate a specific session's process.
|
|
202
|
+
*
|
|
203
|
+
* @param {string} sessionId
|
|
204
|
+
*/
|
|
205
|
+
async terminateSession(sessionId) {
|
|
206
|
+
const proc = this._processes.get(sessionId);
|
|
207
|
+
if (!proc) return;
|
|
208
|
+
|
|
209
|
+
this._logger.info('Terminating session', { sessionId });
|
|
210
|
+
await proc.kill();
|
|
211
|
+
this._processes.delete(sessionId);
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* Count of active processes.
|
|
216
|
+
* @returns {number}
|
|
217
|
+
*/
|
|
218
|
+
get activeCount() {
|
|
219
|
+
this._cleanupDeadProcesses();
|
|
220
|
+
return this._processes.size;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* All active session IDs.
|
|
225
|
+
* @returns {string[]}
|
|
226
|
+
*/
|
|
227
|
+
get activeSessions() {
|
|
228
|
+
return Array.from(this._processes.keys());
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Health check — returns status of all processes.
|
|
233
|
+
* @returns {Array<{sessionId: string, alive: boolean, pid: number, state: string}>}
|
|
234
|
+
*/
|
|
235
|
+
healthCheck() {
|
|
236
|
+
const results = [];
|
|
237
|
+
for (const [sessionId, proc] of this._processes) {
|
|
238
|
+
results.push({
|
|
239
|
+
sessionId,
|
|
240
|
+
alive: proc.isAlive(),
|
|
241
|
+
pid: proc.pid,
|
|
242
|
+
state: proc.state,
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
return results;
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Get daemon status object.
|
|
250
|
+
* @returns {object}
|
|
251
|
+
*/
|
|
252
|
+
status() {
|
|
253
|
+
return {
|
|
254
|
+
running: this._running,
|
|
255
|
+
activeProcesses: this._processes.size,
|
|
256
|
+
maxSessions: this._config.maxSessions,
|
|
257
|
+
mode: this._config.mode,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
// -------------------------------------------------------------------------
|
|
262
|
+
// Internal
|
|
263
|
+
// -------------------------------------------------------------------------
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Clean up dead processes from the pool.
|
|
267
|
+
*/
|
|
268
|
+
_cleanupDeadProcesses() {
|
|
269
|
+
const deadSessions = [];
|
|
270
|
+
for (const [sessionId, proc] of this._processes) {
|
|
271
|
+
if (!proc.isAlive()) {
|
|
272
|
+
deadSessions.push(sessionId);
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
for (const sessionId of deadSessions) {
|
|
277
|
+
this._processes.delete(sessionId);
|
|
278
|
+
this._logger.info('Cleaned up dead session', { sessionId });
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
if (deadSessions.length > 0) {
|
|
282
|
+
this._logger.info('Cleanup complete', {
|
|
283
|
+
removed: deadSessions.length,
|
|
284
|
+
remaining: this._processes.size,
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* Run periodic health check and log status.
|
|
291
|
+
*/
|
|
292
|
+
_runHealthCheck() {
|
|
293
|
+
const health = this.healthCheck();
|
|
294
|
+
const alive = health.filter((h) => h.alive).length;
|
|
295
|
+
const dead = health.filter((h) => !h.alive).length;
|
|
296
|
+
|
|
297
|
+
this._logger.debug('Health check', { alive, dead, total: health.length });
|
|
298
|
+
|
|
299
|
+
// Clean up any dead processes found during health check
|
|
300
|
+
if (dead > 0) {
|
|
301
|
+
this._cleanupDeadProcesses();
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/**
|
|
306
|
+
* Handle graceful shutdown on SIGTERM/SIGINT.
|
|
307
|
+
*/
|
|
308
|
+
async _handleShutdown(signal) {
|
|
309
|
+
this._logger.info('Received shutdown signal', { signal });
|
|
310
|
+
await this.stop();
|
|
311
|
+
process.exit(0);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* Default factory for creating ClaudeProcess instances.
|
|
316
|
+
*/
|
|
317
|
+
_defaultCreateProcess(sessionId, options) {
|
|
318
|
+
return new ClaudeProcess(sessionId, options);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/**
|
|
322
|
+
* Wire up event forwarding from a process to the daemon.
|
|
323
|
+
*/
|
|
324
|
+
_forwardEvents(sessionId, proc) {
|
|
325
|
+
proc.on('output', (data) => {
|
|
326
|
+
this.emit('session:output', { sessionId, data });
|
|
327
|
+
});
|
|
328
|
+
|
|
329
|
+
proc.on('error', (data) => {
|
|
330
|
+
this.emit('session:error', { sessionId, data });
|
|
331
|
+
});
|
|
332
|
+
|
|
333
|
+
proc.on('stderr', (data) => {
|
|
334
|
+
this.emit('session:stderr', { sessionId, data });
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
proc.on('exit', (code, signal) => {
|
|
338
|
+
this.emit('session:exit', { sessionId, code, signal });
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
module.exports = Daemon;
|
package/src/index.js
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
|
|
4
|
+
const { loadConfig } = require('./config');
|
|
5
|
+
const { createLogger } = require('./logger');
|
|
6
|
+
const Daemon = require('./daemon');
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* CLI entrypoint for the Claude Session Daemon.
|
|
10
|
+
*
|
|
11
|
+
* Starts the daemon and, depending on config.mode, wires up the
|
|
12
|
+
* appropriate connection layer (standalone WebSocket or ActionCable).
|
|
13
|
+
*/
|
|
14
|
+
function main() {
|
|
15
|
+
const config = loadConfig();
|
|
16
|
+
const logger = createLogger({ level: config.logLevel, module: 'Main' });
|
|
17
|
+
|
|
18
|
+
logger.info('Starting Claude Session Daemon', {
|
|
19
|
+
mode: config.mode,
|
|
20
|
+
maxSessions: config.maxSessions,
|
|
21
|
+
workingDir: config.workingDir,
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const daemon = new Daemon(config, logger);
|
|
25
|
+
daemon.start();
|
|
26
|
+
|
|
27
|
+
if (config.mode === 'standalone') {
|
|
28
|
+
const { StandaloneServer } = require('./connections/standalone-server');
|
|
29
|
+
const server = new StandaloneServer(daemon, config, logger);
|
|
30
|
+
server.start();
|
|
31
|
+
logger.info('Standalone WebSocket server started', { port: server.port });
|
|
32
|
+
} else if (config.mode === 'actioncable') {
|
|
33
|
+
const { ActionCableClient } = require('./connections/action-cable-client');
|
|
34
|
+
|
|
35
|
+
if (!config.authToken) {
|
|
36
|
+
logger.error('CLAUDE_AUTH_TOKEN is required for ActionCable mode');
|
|
37
|
+
process.exit(1);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const client = new ActionCableClient(daemon, config, logger);
|
|
41
|
+
client.start();
|
|
42
|
+
|
|
43
|
+
client.on('subscribed', () => {
|
|
44
|
+
logger.info('Connected to Rails server and subscribed to DaemonChannel');
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
client.on('registered', () => {
|
|
48
|
+
logger.info('Registered with Rails server');
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
client.on('disconnected', () => {
|
|
52
|
+
logger.warn('Disconnected from Rails server');
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
// Graceful shutdown
|
|
56
|
+
daemon.on('stopped', () => {
|
|
57
|
+
client.stop();
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
daemon.on('stopped', () => {
|
|
62
|
+
logger.info('Daemon stopped');
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
module.exports = { main };
|
|
67
|
+
|
|
68
|
+
// Run if executed directly
|
|
69
|
+
if (require.main === module) {
|
|
70
|
+
main();
|
|
71
|
+
}
|
package/src/logger.js
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const LOG_LEVELS = {
|
|
4
|
+
debug: 0,
|
|
5
|
+
info: 1,
|
|
6
|
+
warn: 2,
|
|
7
|
+
error: 3,
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Create a structured logger with configurable level.
|
|
12
|
+
*
|
|
13
|
+
* Output format: [TIMESTAMP] LEVEL: [MODULE] message
|
|
14
|
+
*
|
|
15
|
+
* @param {object} options
|
|
16
|
+
* @param {string} options.level - Minimum log level (debug|info|warn|error)
|
|
17
|
+
* @param {string} options.module - Module name shown in brackets
|
|
18
|
+
* @returns {object} Logger with debug/info/warn/error methods
|
|
19
|
+
*/
|
|
20
|
+
function createLogger({ level = 'info', module = 'Daemon' } = {}) {
|
|
21
|
+
const minLevel = LOG_LEVELS[level] ?? LOG_LEVELS.info;
|
|
22
|
+
|
|
23
|
+
function log(msgLevel, message, data) {
|
|
24
|
+
if (LOG_LEVELS[msgLevel] < minLevel) return;
|
|
25
|
+
|
|
26
|
+
const timestamp = new Date().toISOString();
|
|
27
|
+
const tag = msgLevel.toUpperCase().padEnd(5);
|
|
28
|
+
let line = `[${timestamp}] ${tag}: [${module}] ${message}`;
|
|
29
|
+
|
|
30
|
+
if (data !== undefined) {
|
|
31
|
+
const extra = typeof data === 'string' ? data : JSON.stringify(data);
|
|
32
|
+
line += ` ${extra}`;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (msgLevel === 'error') {
|
|
36
|
+
process.stderr.write(line + '\n');
|
|
37
|
+
} else {
|
|
38
|
+
process.stdout.write(line + '\n');
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
return {
|
|
43
|
+
debug: (msg, data) => log('debug', msg, data),
|
|
44
|
+
info: (msg, data) => log('info', msg, data),
|
|
45
|
+
warn: (msg, data) => log('warn', msg, data),
|
|
46
|
+
error: (msg, data) => log('error', msg, data),
|
|
47
|
+
child(childModule) {
|
|
48
|
+
return createLogger({ level, module: childModule });
|
|
49
|
+
},
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
module.exports = { createLogger, LOG_LEVELS };
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Message parser for Claude CLI streaming output.
|
|
5
|
+
*
|
|
6
|
+
* Ports the message classification and content extraction logic
|
|
7
|
+
* from the Rails daemon_channel.rb into Node.js.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Check whether a message's content array contains a tool_use block.
|
|
12
|
+
* @param {object} data - Parsed message object
|
|
13
|
+
* @returns {boolean}
|
|
14
|
+
*/
|
|
15
|
+
function hasToolUse(data) {
|
|
16
|
+
const content = data?.message?.content;
|
|
17
|
+
if (!Array.isArray(content)) return false;
|
|
18
|
+
return content.some((item) => item?.type === 'tool_use');
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Check whether a message's content array contains a tool_result block.
|
|
23
|
+
* @param {object} data - Parsed message object
|
|
24
|
+
* @returns {boolean}
|
|
25
|
+
*/
|
|
26
|
+
function hasToolResult(data) {
|
|
27
|
+
const content = data?.message?.content;
|
|
28
|
+
if (!Array.isArray(content)) return false;
|
|
29
|
+
return content.some((item) => item?.type === 'tool_result');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Determine the broadcast type for a message.
|
|
34
|
+
*
|
|
35
|
+
* - assistant messages with tool_use content -> "tool_use"
|
|
36
|
+
* - user messages with tool_result content -> "tool_result"
|
|
37
|
+
* - everything else -> pass through the type field as-is
|
|
38
|
+
*
|
|
39
|
+
* @param {object} data - Parsed message object
|
|
40
|
+
* @returns {string|undefined} Broadcast type
|
|
41
|
+
*/
|
|
42
|
+
function classifyMessage(data) {
|
|
43
|
+
if (!data || typeof data !== 'object') return undefined;
|
|
44
|
+
|
|
45
|
+
const messageType = data.type;
|
|
46
|
+
|
|
47
|
+
switch (messageType) {
|
|
48
|
+
case 'assistant':
|
|
49
|
+
return hasToolUse(data) ? 'tool_use' : 'assistant';
|
|
50
|
+
case 'user':
|
|
51
|
+
return hasToolResult(data) ? 'tool_result' : 'user';
|
|
52
|
+
default:
|
|
53
|
+
return messageType;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Extract human-readable content from a message.
|
|
59
|
+
*
|
|
60
|
+
* Tries data.message.content first, then data.content.
|
|
61
|
+
* Handles arrays, hashes, plain strings, and falls back to JSON.
|
|
62
|
+
*
|
|
63
|
+
* @param {object} data - Parsed message object
|
|
64
|
+
* @returns {string} Human-readable content string
|
|
65
|
+
*/
|
|
66
|
+
function extractContent(data) {
|
|
67
|
+
if (!data || typeof data !== 'object') return '';
|
|
68
|
+
|
|
69
|
+
const content = data?.message?.content ?? data?.content;
|
|
70
|
+
|
|
71
|
+
if (Array.isArray(content)) {
|
|
72
|
+
return extractContentFromArray(content);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if (content !== null && typeof content === 'object') {
|
|
76
|
+
return extractContentFromHash(content);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (content !== undefined && content !== null && content !== '') {
|
|
80
|
+
return String(content);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Fallback: entire data as JSON
|
|
84
|
+
return JSON.stringify(data);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* Extract content from an array of content blocks (Claude API format).
|
|
89
|
+
* @param {Array} contentArray
|
|
90
|
+
* @returns {string}
|
|
91
|
+
*/
|
|
92
|
+
function extractContentFromArray(contentArray) {
|
|
93
|
+
if (contentArray.length === 0) return '';
|
|
94
|
+
|
|
95
|
+
const firstItem = contentArray[0];
|
|
96
|
+
if (firstItem === null || typeof firstItem !== 'object') return '';
|
|
97
|
+
|
|
98
|
+
switch (firstItem.type) {
|
|
99
|
+
case 'text':
|
|
100
|
+
return firstItem.text || '';
|
|
101
|
+
|
|
102
|
+
case 'tool_use': {
|
|
103
|
+
const toolName = firstItem.name;
|
|
104
|
+
const toolInput = firstItem.input || {};
|
|
105
|
+
const params = Object.entries(toolInput)
|
|
106
|
+
.slice(0, 3)
|
|
107
|
+
.map(([k, v]) => `${k}: ${v}`)
|
|
108
|
+
.join(', ');
|
|
109
|
+
return `Used tool: ${toolName} (${params})`;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
case 'tool_result': {
|
|
113
|
+
const resultContent = firstItem.content || firstItem.output || '';
|
|
114
|
+
const resultStr = String(resultContent);
|
|
115
|
+
const firstLine = resultStr.split('\n')[0] || '';
|
|
116
|
+
|
|
117
|
+
if (firstLine === '') {
|
|
118
|
+
return 'Result: (empty)';
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const truncated = firstLine.length > 100
|
|
122
|
+
? firstLine.slice(0, 100) + '...'
|
|
123
|
+
: firstLine;
|
|
124
|
+
return `Result: ${truncated}`;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
default:
|
|
128
|
+
return JSON.stringify(contentArray);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Extract content from a hash/object content block.
|
|
134
|
+
* @param {object} contentHash
|
|
135
|
+
* @returns {string}
|
|
136
|
+
*/
|
|
137
|
+
function extractContentFromHash(contentHash) {
|
|
138
|
+
switch (contentHash.type) {
|
|
139
|
+
case 'text':
|
|
140
|
+
return contentHash.text || '';
|
|
141
|
+
|
|
142
|
+
case 'tool_use': {
|
|
143
|
+
const toolName = contentHash.name;
|
|
144
|
+
const toolInput = contentHash.input || {};
|
|
145
|
+
const params = Object.entries(toolInput)
|
|
146
|
+
.slice(0, 3)
|
|
147
|
+
.map(([k, v]) => `${k}: ${v}`)
|
|
148
|
+
.join(', ');
|
|
149
|
+
return `Used tool: ${toolName} (${params})`;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
case 'tool_result': {
|
|
153
|
+
const resultContent = contentHash.content || contentHash.output || '';
|
|
154
|
+
const resultStr = String(resultContent);
|
|
155
|
+
const firstLine = resultStr.split('\n')[0] || '';
|
|
156
|
+
|
|
157
|
+
if (firstLine === '') {
|
|
158
|
+
return 'Result: (empty)';
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const truncated = firstLine.length > 100
|
|
162
|
+
? firstLine.slice(0, 100) + '...'
|
|
163
|
+
: firstLine;
|
|
164
|
+
return `Result: ${truncated}`;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
default:
|
|
168
|
+
return JSON.stringify(contentHash);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
module.exports = {
|
|
173
|
+
classifyMessage,
|
|
174
|
+
extractContent,
|
|
175
|
+
hasToolUse,
|
|
176
|
+
hasToolResult,
|
|
177
|
+
};
|