tacticremote 1.6.6 → 1.7.0

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.
Files changed (42) hide show
  1. package/lib/authChallengeManager.js +1 -134
  2. package/lib/claudeSessionManager.js +1 -0
  3. package/lib/claudeTransport.js +1 -0
  4. package/lib/errorCodes.js +1 -127
  5. package/lib/execSafe.js +1 -218
  6. package/lib/fileService.js +1 -177
  7. package/lib/hookInstaller.js +21 -7
  8. package/lib/outputParser.js +1 -106
  9. package/lib/pushClient.js +1 -0
  10. package/lib/rateLimiter.js +1 -111
  11. package/lib/serverIdentity.js +1 -0
  12. package/lib/streamJsonParser.js +1 -0
  13. package/lib/tmuxManager.js +1 -671
  14. package/lib/uploadService.js +1 -366
  15. package/lib/validators.js +1 -350
  16. package/package.json +2 -1
  17. package/routes/wsHandler.js +418 -364
  18. package/server.js +67 -173
  19. package/shared/server-core/authChallengeManager.js +108 -0
  20. package/shared/server-core/claudeSessionManager.js +222 -0
  21. package/shared/server-core/claudeTransport.js +176 -0
  22. package/shared/server-core/errorCodes.js +91 -0
  23. package/shared/server-core/execSafe.js +185 -0
  24. package/shared/server-core/fileService.js +155 -0
  25. package/shared/server-core/outputParser.js +174 -0
  26. package/shared/server-core/protocol-manifest.json +59 -0
  27. package/shared/server-core/protocol-manifest.schema.json +90 -0
  28. package/shared/server-core/protocolManifest.js +42 -0
  29. package/shared/server-core/pushClient.js +198 -0
  30. package/shared/server-core/rateLimiter.js +98 -0
  31. package/shared/server-core/serverConnectionLifecycle.js +118 -0
  32. package/shared/server-core/serverHandshake.js +72 -0
  33. package/shared/server-core/serverIdentity.js +102 -0
  34. package/shared/server-core/streamJsonParser.js +321 -0
  35. package/shared/server-core/tmuxManager.js +596 -0
  36. package/shared/server-core/unixProcessLifecycle.js +96 -0
  37. package/shared/server-core/unixServerHooks.js +148 -0
  38. package/shared/server-core/unixWsRuntime.js +412 -0
  39. package/shared/server-core/uploadService.js +321 -0
  40. package/shared/server-core/validators.js +274 -0
  41. package/shared/server-core/windowsServerHooks.js +174 -0
  42. package/shared/server-core/windowsWsRuntime.js +413 -0
package/server.js CHANGED
@@ -14,18 +14,14 @@ const { checkWsAuth, authRateLimiter } = require('./middleware/authMiddleware');
14
14
  const { createHttpHandler } = require('./routes/httpHandler');
15
15
  const { createWsHandler } = require('./routes/wsHandler');
16
16
  const { ErrorCodes, createError } = require('./lib/errorCodes');
17
-
18
- function extractToolDetail(toolName, toolInput) {
19
- if (!toolInput || typeof toolInput !== 'object') return '';
20
- switch (toolName) {
21
- case 'Read': case 'Write': case 'Edit': return toolInput.file_path || '';
22
- case 'Bash': return (toolInput.command || '').substring(0, 100);
23
- case 'Glob': return toolInput.pattern || '';
24
- case 'Grep': return toolInput.pattern || '';
25
- case 'Agent': return toolInput.description || '';
26
- default: return '';
27
- }
28
- }
17
+ const { extractToolDetail } = require('./lib/streamJsonParser');
18
+ const pushClient = require('./lib/pushClient');
19
+ const serverIdentity = require('./lib/serverIdentity');
20
+ const { getForegroundMatchingClients, getLegacyExternalClients, handleUnixHookEvent } = require('./shared/server-core/unixServerHooks');
21
+ const { emitClientCount, handleServerConnection, startServerHeartbeat } = require('./shared/server-core/serverConnectionLifecycle');
22
+ const { buildServerHandshake } = require('./shared/server-core/serverHandshake');
23
+ // NOTE: read `./package.json` (1.6.7), NOT `./package.npm.json` (1.6.0, stale thin wrapper).
24
+ const { version: APP_VERSION } = require('./package.json');
29
25
 
30
26
  const MAX_WS_PAYLOAD = 512 * 1024; // 512KB
31
27
 
@@ -64,12 +60,40 @@ class ClaudeRemoteServer {
64
60
  this._clientIdCounter = 0;
65
61
  this.managedSessions = new Set();
66
62
  this._onReady = options.onReady || null;
63
+ this.tmuxAvailable = false;
64
+ this.claudeAvailable = false;
65
+ this.serverIdentity = null;
66
+ this.pushEnabled = false;
67
67
  }
68
68
 
69
69
  start() {
70
70
  // Set process working directory to user's path (not the server install directory)
71
71
  try { process.chdir(this.currentPath); } catch (_e) { /* ignore */ }
72
72
 
73
+ // Check available tools
74
+ this.tmuxAvailable = checkCommand('tmux');
75
+ this.claudeAvailable = checkCommand('claude');
76
+
77
+ if (!this.tmuxAvailable && !this.claudeAvailable) {
78
+ throw new Error('Neither tmux nor claude CLI found');
79
+ }
80
+
81
+ if (!this.tmuxAvailable) {
82
+ console.log('⚠️ tmux not found — terminal mode disabled, structured JSON mode only');
83
+ }
84
+ if (!this.claudeAvailable) {
85
+ console.log('⚠️ claude CLI not found — structured JSON mode disabled, terminal mode only');
86
+ }
87
+
88
+ // Load server identity and configure push client
89
+ this.serverIdentity = serverIdentity.loadOrCreate();
90
+ const pushServiceUrl = process.env.PUSH_SERVICE_URL;
91
+ if (pushServiceUrl) {
92
+ pushClient.configure(pushServiceUrl);
93
+ this.pushEnabled = true;
94
+ console.log(`🔔 Push notifications enabled → ${pushServiceUrl}`);
95
+ }
96
+
73
97
  this.setupProcessHandlers();
74
98
 
75
99
  // Initialize WebSocket handler
@@ -130,80 +154,29 @@ class ClaudeRemoteServer {
130
154
  }
131
155
 
132
156
  handleConnection(ws, req) {
133
- const clientIP = req.socket.remoteAddress || 'unknown';
134
- const isInternal = clientIP === '127.0.0.1' || clientIP === '::1' || clientIP === '::ffff:127.0.0.1';
135
-
136
- // Authentication
137
- if (this.apiKey) {
138
- const authResult = checkWsAuth(req, this.apiKey, clientIP);
139
- if (!authResult.authenticated) {
140
- const msg = authResult.rateLimited ? 'Too many failed attempts' : 'Unauthorized';
141
- console.log(`🔒 ${msg} from ${clientIP}`);
142
- ws.close(1008, msg);
143
- return;
144
- }
145
- console.log(`🔓 Authenticated connection from ${clientIP}`);
146
- }
147
-
148
- const clientId = `${Date.now()}-${++this._clientIdCounter}`;
149
- this.clients.set(clientId, ws);
150
- if (!isInternal) {
151
- this.externalClients.set(clientId, ws);
152
- }
153
- ws._clientId = clientId;
154
- ws._isInternal = isInternal;
155
-
156
- // Initialize per-client state
157
- this.clientState.set(clientId, {
158
- currentPath: this.currentPath
159
- });
160
-
161
- console.log(`✅ ${isInternal ? 'Internal' : 'iOS'} client connected: ${clientId} (${clientIP})`);
162
- this.emitClientCount();
163
-
164
- ws.isAlive = true;
165
- ws.on('pong', () => { ws.isAlive = true; });
166
-
167
- const capabilities = [];
168
- if (this.claudeAvailable) capabilities.push('structured_json');
169
- if (this.tmuxAvailable) capabilities.push('tmux');
170
-
171
- this.wsHandler.sendToClient(ws, {
172
- type: 'connected',
173
- path: this.clientState.get(clientId).currentPath,
174
- status: 'ready',
175
- capabilities
176
- });
177
-
178
- ws.on('message', (data) => {
179
- try {
180
- const message = JSON.parse(data.toString());
181
- this.wsHandler.handleMessage(ws, message);
182
- } catch (error) {
183
- console.error('Failed to parse message:', error);
157
+ handleServerConnection(this, ws, req, {
158
+ checkWsAuth,
159
+ generateClientId: () => `${Date.now()}-${++this._clientIdCounter}`,
160
+ buildConnectedPayload: ({ clientState }) => {
161
+ const capabilities = [];
162
+ if (this.claudeAvailable) capabilities.push('structured_json');
163
+ if (this.tmuxAvailable) capabilities.push('tmux');
164
+ capabilities.push('client_state');
165
+ if (this.pushEnabled) capabilities.push('register_push');
166
+ capabilities.push('worktree');
167
+
168
+ return {
169
+ type: 'connected',
170
+ path: clientState.currentPath,
171
+ status: 'ready',
172
+ capabilities,
173
+ server: buildServerHandshake({
174
+ platform: 'npm',
175
+ appVersion: APP_VERSION
176
+ })
177
+ };
184
178
  }
185
179
  });
186
-
187
- let connectionCleaned = false;
188
- const cleanupConnection = (reason) => {
189
- if (connectionCleaned) return;
190
- connectionCleaned = true;
191
- this.clients.delete(clientId);
192
- this.externalClients.delete(clientId);
193
- this.clientState.delete(clientId);
194
- if (this.wsHandler.cleanupClient) this.wsHandler.cleanupClient(ws);
195
- if (reason === 'close') {
196
- console.log(`❌ ${isInternal ? 'Internal' : 'iOS'} client disconnected: ${clientId}`);
197
- }
198
- this.emitClientCount();
199
- };
200
-
201
- ws.on('close', () => cleanupConnection('close'));
202
-
203
- ws.on('error', (error) => {
204
- console.error(`WebSocket error (${clientId}):`, error.message);
205
- cleanupConnection('error');
206
- });
207
180
  }
208
181
 
209
182
  /**
@@ -211,80 +184,19 @@ class ClaudeRemoteServer {
211
184
  * Format: __CLIENT_COUNT__:<external>:<total>
212
185
  */
213
186
  emitClientCount() {
214
- console.log(`__CLIENT_COUNT__:${this.externalClients.size}:${this.clients.size}`);
187
+ emitClientCount(this);
215
188
  }
216
189
 
217
- async handleHookEvent(hookData) {
218
- console.log(`🔔 Hook event: ${hookData.event} (${hookData.project})`);
219
-
220
- // Fallback: if hook didn't provide tmux_session, try to find it by matching project to session cwd
221
- if (!hookData.tmux_session && hookData.project) {
222
- try {
223
- const path = require('path');
224
- const { listSessions } = require('./lib/tmuxManager');
225
- const result = await listSessions();
226
- if (result && result.sessions) {
227
- const running = result.sessions.find(s => s.running && path.basename(s.path || '') === hookData.project);
228
- const match = running || result.sessions.find(s => path.basename(s.path || '') === hookData.project);
229
- if (match) {
230
- hookData.tmux_session = match.name;
231
- console.log(`[notify][hook] inferred tmux_session=${match.name} from project=${hookData.project}`);
232
- }
233
- }
234
- } catch (err) {
235
- console.warn(`[notify][hook] session inference failed: ${err.message}`);
236
- }
237
- }
238
-
239
- this.lastHookEvent = hookData;
240
-
241
- // Broadcast in both legacy and event-frame formats for compatibility.
242
- this.wsHandler.broadcast({
243
- type: 'hook_event',
244
- event: hookData.event,
245
- project: hookData.project,
246
- session: hookData.tmux_session,
247
- timestamp: hookData.timestamp
248
- });
249
- this.wsHandler.broadcastEvent('hook_event', {
250
- event: hookData.event,
251
- project: hookData.project,
252
- session: hookData.tmux_session,
253
- timestamp: hookData.timestamp
254
- });
255
-
256
- if (hookData.event === 'Stop') {
257
- console.log(`✅ Claude task completed in ${hookData.project}`);
258
- if (hookData.tmux_session) {
259
- this.wsHandler.captureAndBroadcast(hookData.tmux_session, 'completed');
260
- }
261
- }
190
+ getForegroundMatchingClients(sessionName) {
191
+ return getForegroundMatchingClients(this, sessionName);
192
+ }
262
193
 
263
- // PreToolUse / PostToolUse — broadcast structured tool data to iOS
264
- const hookEventName = hookData.hook_event_name || hookData.event;
265
- if (hookEventName === 'PreToolUse' || hookEventName === 'PostToolUse') {
266
- const toolEvent = {
267
- event: hookEventName,
268
- tool_name: hookData.tool_name,
269
- tool_use_id: hookData.tool_use_id,
270
- tool_detail: extractToolDetail(hookData.tool_name, hookData.tool_input),
271
- project: hookData.project,
272
- session: hookData.tmux_session,
273
- timestamp: hookData.timestamp || Date.now()
274
- };
275
- this.wsHandler.broadcastEvent('tool_use', toolEvent);
276
- }
194
+ getLegacyExternalClients() {
195
+ return getLegacyExternalClients(this);
196
+ }
277
197
 
278
- if (hookData.event === 'Notification' && hookData.data?.message) {
279
- this.wsHandler.broadcastEvent('notification', {
280
- title: 'Claude',
281
- body: hookData.data.message,
282
- project: hookData.project,
283
- session: hookData.tmux_session,
284
- event: 'notification',
285
- timestamp: hookData.timestamp
286
- });
287
- }
198
+ async handleHookEvent(hookData) {
199
+ return handleUnixHookEvent(this, hookData, { extractToolDetail });
288
200
  }
289
201
 
290
202
  getLocalIP() {
@@ -300,25 +212,7 @@ class ClaudeRemoteServer {
300
212
  }
301
213
 
302
214
  startHeartbeat() {
303
- this.heartbeatInterval = setInterval(() => {
304
- this.wss.clients.forEach((ws) => {
305
- if (ws.isAlive === false) {
306
- if (ws.missedHeartbeats === undefined) {
307
- ws.missedHeartbeats = 0;
308
- }
309
- ws.missedHeartbeats++;
310
- if (ws.missedHeartbeats >= 2) {
311
- console.log(`💔 Client heartbeat timeout, terminating (${ws._clientId || 'unknown'})`);
312
- return ws.terminate(); // triggers 'close' event -> cleanup + emitClientCount
313
- }
314
- } else {
315
- ws.missedHeartbeats = 0;
316
- }
317
- ws.isAlive = false;
318
- ws.ping();
319
- this.wsHandler.sendToClient(ws, { type: 'ping', timestamp: Date.now() });
320
- });
321
- }, 45000);
215
+ startServerHeartbeat(this);
322
216
  }
323
217
 
324
218
  setupProcessHandlers() {
@@ -0,0 +1,108 @@
1
+ /**
2
+ * Auth Challenge Manager
3
+ * Manages challenge-response lifecycle for sensitive directory access.
4
+ * Server sends auth_challenge events to iOS, iOS responds with auth_response.
5
+ * Grants are cached per-client per-sensitiveDir with a TTL.
6
+ */
7
+
8
+ const crypto = require('crypto');
9
+
10
+ const CHALLENGE_TIMEOUT = 30_000;
11
+ const GRANT_TTL = 5 * 60_000;
12
+
13
+ const pendingChallenges = new Map();
14
+ const grantCache = new Map();
15
+ const pendingByDir = new Map();
16
+
17
+ function isGranted(ws, sensitiveDir) {
18
+ const clientGrants = grantCache.get(ws);
19
+ if (!clientGrants) return false;
20
+ const expiresAt = clientGrants.get(sensitiveDir);
21
+ if (!expiresAt) return false;
22
+ if (Date.now() >= expiresAt) {
23
+ clientGrants.delete(sensitiveDir);
24
+ return false;
25
+ }
26
+ return true;
27
+ }
28
+
29
+ function addGrant(ws, sensitiveDir) {
30
+ if (!grantCache.has(ws)) grantCache.set(ws, new Map());
31
+ grantCache.get(ws).set(sensitiveDir, Date.now() + GRANT_TTL);
32
+ }
33
+
34
+ /**
35
+ * Create an auth challenge and return a promise that resolves when the client responds.
36
+ * Deduplicates: if there's already a pending challenge for the same (ws, sensitiveDir),
37
+ * reuses the same promise.
38
+ *
39
+ * @returns {{ challengeId: string, expiresAt: number, promise: Promise<boolean> }}
40
+ */
41
+ function createChallenge(ws, path, sensitiveDir, method) {
42
+ if (!pendingByDir.has(ws)) pendingByDir.set(ws, new Map());
43
+ const dirMap = pendingByDir.get(ws);
44
+ if (dirMap.has(sensitiveDir)) {
45
+ return dirMap.get(sensitiveDir);
46
+ }
47
+
48
+ const challengeId = crypto.randomUUID();
49
+ const expiresAt = Date.now() + CHALLENGE_TIMEOUT;
50
+
51
+ const promise = new Promise((resolve, reject) => {
52
+ const timer = setTimeout(() => {
53
+ pendingChallenges.delete(challengeId);
54
+ dirMap.delete(sensitiveDir);
55
+ resolve(false);
56
+ }, CHALLENGE_TIMEOUT);
57
+
58
+ pendingChallenges.set(challengeId, {
59
+ ws, resolve, reject, timer, path, sensitiveDir, method
60
+ });
61
+ });
62
+
63
+ const result = { challengeId, expiresAt, promise };
64
+ dirMap.set(sensitiveDir, result);
65
+
66
+ promise.finally(() => {
67
+ dirMap.delete(sensitiveDir);
68
+ });
69
+
70
+ return result;
71
+ }
72
+
73
+ function resolveChallenge(challengeId, granted) {
74
+ const challenge = pendingChallenges.get(challengeId);
75
+ if (!challenge) return false;
76
+
77
+ clearTimeout(challenge.timer);
78
+ pendingChallenges.delete(challengeId);
79
+
80
+ if (granted) {
81
+ addGrant(challenge.ws, challenge.sensitiveDir);
82
+ }
83
+
84
+ challenge.resolve(granted);
85
+ return true;
86
+ }
87
+
88
+ function cleanupClient(ws) {
89
+ for (const [challengeId, challenge] of pendingChallenges) {
90
+ if (challenge.ws === ws) {
91
+ clearTimeout(challenge.timer);
92
+ challenge.resolve(false);
93
+ pendingChallenges.delete(challengeId);
94
+ }
95
+ }
96
+ grantCache.delete(ws);
97
+ pendingByDir.delete(ws);
98
+ }
99
+
100
+ module.exports = {
101
+ createChallenge,
102
+ resolveChallenge,
103
+ isGranted,
104
+ addGrant,
105
+ cleanupClient,
106
+ CHALLENGE_TIMEOUT,
107
+ GRANT_TTL
108
+ };
@@ -0,0 +1,222 @@
1
+ /**
2
+ * ClaudeSessionManager — manages multiple structured Claude sessions.
3
+ */
4
+
5
+ const { randomUUID } = require('crypto');
6
+ const { ClaudeTransport } = require('./claudeTransport');
7
+ const { translateEvent } = require('./streamJsonParser');
8
+
9
+ class ClaudeSessionManager {
10
+ constructor({ broadcastToSubscribers, allowedBasePath }) {
11
+ this.broadcastToSubscribers = broadcastToSubscribers;
12
+ this.allowedBasePath = allowedBasePath;
13
+ this.sessions = new Map();
14
+ }
15
+
16
+ createSession(cwd, ws, additionalArgs = []) {
17
+ const sessionId = randomUUID();
18
+
19
+ const transport = new ClaudeTransport({
20
+ cwd,
21
+ sessionId,
22
+ additionalArgs
23
+ });
24
+
25
+ const entry = {
26
+ transport,
27
+ sessionId,
28
+ cwd,
29
+ subscribers: new Set([ws]),
30
+ isRunning: false,
31
+ pendingApprovalRequestId: null,
32
+ createdAt: Date.now()
33
+ };
34
+
35
+ this.sessions.set(sessionId, entry);
36
+
37
+ transport.on('json_event', (claudeEvent) => {
38
+ const wsEvents = translateEvent(claudeEvent, sessionId);
39
+ for (const wsEvent of wsEvents) {
40
+ this.broadcastToSubscribers(entry.subscribers, wsEvent.event, wsEvent.payload);
41
+
42
+ if (wsEvent.event === 'structured_init') {
43
+ entry.isRunning = false;
44
+ }
45
+ if (wsEvent.event === 'structured_result') {
46
+ entry.isRunning = false;
47
+ entry.pendingApprovalRequestId = null;
48
+ }
49
+ if (wsEvent.event === 'structured_approval_request') {
50
+ entry.pendingApprovalRequestId = wsEvent.payload.requestId || null;
51
+ }
52
+ }
53
+ });
54
+
55
+ transport.on('crash', ({ code, signal, stderr, reason }) => {
56
+ console.error(`[StructuredSession] ${sessionId} crashed: code=${code} signal=${signal} reason=${reason}`);
57
+ this.broadcastToSubscribers(entry.subscribers, 'structured_crash', {
58
+ sessionId,
59
+ code,
60
+ signal,
61
+ stderr: stderr ? stderr.substring(0, 500) : '',
62
+ reason
63
+ });
64
+ entry.isRunning = false;
65
+ this.sessions.delete(sessionId);
66
+ });
67
+
68
+ transport.on('shutdown', ({ clean }) => {
69
+ this.broadcastToSubscribers(entry.subscribers, 'structured_shutdown', {
70
+ sessionId,
71
+ clean
72
+ });
73
+ entry.isRunning = false;
74
+ this.sessions.delete(sessionId);
75
+ });
76
+
77
+ transport.start();
78
+ return { sessionId, cwd };
79
+ }
80
+
81
+ sendMessage(sessionId, content) {
82
+ const entry = this.sessions.get(sessionId);
83
+ if (!entry) return false;
84
+
85
+ const sent = entry.transport.send({
86
+ type: 'user',
87
+ message: {
88
+ role: 'user',
89
+ content
90
+ }
91
+ });
92
+
93
+ if (sent) {
94
+ entry.isRunning = true;
95
+ }
96
+
97
+ return sent;
98
+ }
99
+
100
+ respondApproval(sessionId, requestId, behavior, updatedInput, message) {
101
+ const entry = this.sessions.get(sessionId);
102
+ if (!entry) return false;
103
+
104
+ const responsePayload = behavior === 'allow'
105
+ ? { behavior: 'allow', updatedInput: updatedInput || {} }
106
+ : { behavior: 'deny', message: message || 'User denied this action' };
107
+
108
+ const sent = entry.transport.send({
109
+ type: 'control_response',
110
+ response: {
111
+ subtype: 'success',
112
+ request_id: requestId,
113
+ response: responsePayload
114
+ }
115
+ });
116
+
117
+ if (sent) {
118
+ entry.pendingApprovalRequestId = null;
119
+ }
120
+
121
+ return sent;
122
+ }
123
+
124
+ steerMessage(sessionId, content) {
125
+ const entry = this.sessions.get(sessionId);
126
+ if (!entry) return false;
127
+
128
+ return entry.transport.send({
129
+ type: 'user',
130
+ message: {
131
+ role: 'user',
132
+ content
133
+ }
134
+ });
135
+ }
136
+
137
+ hasPendingApproval(sessionId) {
138
+ const entry = this.sessions.get(sessionId);
139
+ if (!entry) return false;
140
+ return entry.pendingApprovalRequestId != null;
141
+ }
142
+
143
+ hasAnyPendingApproval() {
144
+ for (const [, entry] of this.sessions) {
145
+ if (entry.pendingApprovalRequestId != null) return true;
146
+ }
147
+ return false;
148
+ }
149
+
150
+ stopSession(sessionId) {
151
+ const entry = this.sessions.get(sessionId);
152
+ if (!entry) return;
153
+ entry.transport.shutdown();
154
+ }
155
+
156
+ destroySession(sessionId) {
157
+ const entry = this.sessions.get(sessionId);
158
+ if (!entry) return;
159
+ entry.transport.shutdown();
160
+ this.sessions.delete(sessionId);
161
+ }
162
+
163
+ addSubscriber(sessionId, ws) {
164
+ const entry = this.sessions.get(sessionId);
165
+ if (!entry) return false;
166
+ entry.subscribers.add(ws);
167
+ return true;
168
+ }
169
+
170
+ removeSubscriber(sessionId, ws) {
171
+ const entry = this.sessions.get(sessionId);
172
+ if (!entry) return;
173
+ entry.subscribers.delete(ws);
174
+ }
175
+
176
+ removeSubscriberFromAll(ws) {
177
+ for (const [, entry] of this.sessions) {
178
+ entry.subscribers.delete(ws);
179
+ }
180
+ }
181
+
182
+ getSession(sessionId) {
183
+ const entry = this.sessions.get(sessionId);
184
+ if (!entry) return null;
185
+ return {
186
+ sessionId: entry.sessionId,
187
+ cwd: entry.cwd,
188
+ isRunning: entry.isRunning,
189
+ subscriberCount: entry.subscribers.size
190
+ };
191
+ }
192
+
193
+ listSessions() {
194
+ const result = [];
195
+ for (const [, entry] of this.sessions) {
196
+ result.push({
197
+ sessionId: entry.sessionId,
198
+ cwd: entry.cwd,
199
+ isRunning: entry.isRunning
200
+ });
201
+ }
202
+ return result;
203
+ }
204
+
205
+ async shutdownAll() {
206
+ const promises = [];
207
+ for (const [, entry] of this.sessions) {
208
+ promises.push(new Promise((resolve) => {
209
+ let resolved = false;
210
+ const done = () => { if (!resolved) { resolved = true; resolve(); } };
211
+ entry.transport.once('shutdown', done);
212
+ entry.transport.once('crash', done);
213
+ setTimeout(done, 12000);
214
+ entry.transport.shutdown();
215
+ }));
216
+ }
217
+ await Promise.all(promises);
218
+ this.sessions.clear();
219
+ }
220
+ }
221
+
222
+ module.exports = { ClaudeSessionManager };