tacticremote 1.6.5 → 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.
- package/lib/authChallengeManager.js +1 -134
- package/lib/claudeSessionManager.js +1 -0
- package/lib/claudeTransport.js +1 -0
- package/lib/errorCodes.js +1 -127
- package/lib/execSafe.js +1 -218
- package/lib/fileService.js +1 -177
- package/lib/hookInstaller.js +21 -7
- package/lib/outputParser.js +1 -106
- package/lib/pushClient.js +1 -0
- package/lib/rateLimiter.js +1 -111
- package/lib/serverIdentity.js +1 -0
- package/lib/streamJsonParser.js +1 -0
- package/lib/tmuxManager.js +1 -671
- package/lib/uploadService.js +1 -366
- package/lib/validators.js +1 -350
- package/package.json +2 -1
- package/routes/httpHandler.js +3 -1
- package/routes/wsHandler.js +418 -364
- package/server.js +67 -152
- package/shared/server-core/authChallengeManager.js +108 -0
- package/shared/server-core/claudeSessionManager.js +222 -0
- package/shared/server-core/claudeTransport.js +176 -0
- package/shared/server-core/errorCodes.js +91 -0
- package/shared/server-core/execSafe.js +185 -0
- package/shared/server-core/fileService.js +155 -0
- package/shared/server-core/outputParser.js +174 -0
- package/shared/server-core/protocol-manifest.json +59 -0
- package/shared/server-core/protocol-manifest.schema.json +90 -0
- package/shared/server-core/protocolManifest.js +42 -0
- package/shared/server-core/pushClient.js +198 -0
- package/shared/server-core/rateLimiter.js +98 -0
- package/shared/server-core/serverConnectionLifecycle.js +118 -0
- package/shared/server-core/serverHandshake.js +72 -0
- package/shared/server-core/serverIdentity.js +102 -0
- package/shared/server-core/streamJsonParser.js +321 -0
- package/shared/server-core/tmuxManager.js +596 -0
- package/shared/server-core/unixProcessLifecycle.js +96 -0
- package/shared/server-core/unixServerHooks.js +148 -0
- package/shared/server-core/unixWsRuntime.js +412 -0
- package/shared/server-core/uploadService.js +321 -0
- package/shared/server-core/validators.js +274 -0
- package/shared/server-core/windowsServerHooks.js +174 -0
- 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
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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,79 +154,28 @@ class ClaudeRemoteServer {
|
|
|
130
154
|
}
|
|
131
155
|
|
|
132
156
|
handleConnection(ws, req) {
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
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
|
+
};
|
|
144
178
|
}
|
|
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);
|
|
184
|
-
}
|
|
185
|
-
});
|
|
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
179
|
});
|
|
207
180
|
}
|
|
208
181
|
|
|
@@ -211,59 +184,19 @@ class ClaudeRemoteServer {
|
|
|
211
184
|
* Format: __CLIENT_COUNT__:<external>:<total>
|
|
212
185
|
*/
|
|
213
186
|
emitClientCount() {
|
|
214
|
-
|
|
187
|
+
emitClientCount(this);
|
|
215
188
|
}
|
|
216
189
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
// Broadcast in both legacy and event-frame formats for compatibility.
|
|
222
|
-
this.wsHandler.broadcast({
|
|
223
|
-
type: 'hook_event',
|
|
224
|
-
event: hookData.event,
|
|
225
|
-
project: hookData.project,
|
|
226
|
-
session: hookData.tmux_session,
|
|
227
|
-
timestamp: hookData.timestamp
|
|
228
|
-
});
|
|
229
|
-
this.wsHandler.broadcastEvent('hook_event', {
|
|
230
|
-
event: hookData.event,
|
|
231
|
-
project: hookData.project,
|
|
232
|
-
session: hookData.tmux_session,
|
|
233
|
-
timestamp: hookData.timestamp
|
|
234
|
-
});
|
|
235
|
-
|
|
236
|
-
if (hookData.event === 'Stop') {
|
|
237
|
-
console.log(`✅ Claude task completed in ${hookData.project}`);
|
|
238
|
-
if (hookData.tmux_session) {
|
|
239
|
-
this.wsHandler.captureAndBroadcast(hookData.tmux_session, 'completed');
|
|
240
|
-
}
|
|
241
|
-
}
|
|
190
|
+
getForegroundMatchingClients(sessionName) {
|
|
191
|
+
return getForegroundMatchingClients(this, sessionName);
|
|
192
|
+
}
|
|
242
193
|
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
const toolEvent = {
|
|
247
|
-
event: hookEventName,
|
|
248
|
-
tool_name: hookData.tool_name,
|
|
249
|
-
tool_use_id: hookData.tool_use_id,
|
|
250
|
-
tool_detail: extractToolDetail(hookData.tool_name, hookData.tool_input),
|
|
251
|
-
project: hookData.project,
|
|
252
|
-
session: hookData.tmux_session,
|
|
253
|
-
timestamp: hookData.timestamp || Date.now()
|
|
254
|
-
};
|
|
255
|
-
this.wsHandler.broadcastEvent('tool_use', toolEvent);
|
|
256
|
-
}
|
|
194
|
+
getLegacyExternalClients() {
|
|
195
|
+
return getLegacyExternalClients(this);
|
|
196
|
+
}
|
|
257
197
|
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
title: 'Claude',
|
|
261
|
-
body: hookData.data.message,
|
|
262
|
-
project: hookData.project,
|
|
263
|
-
event: 'notification',
|
|
264
|
-
timestamp: hookData.timestamp
|
|
265
|
-
});
|
|
266
|
-
}
|
|
198
|
+
async handleHookEvent(hookData) {
|
|
199
|
+
return handleUnixHookEvent(this, hookData, { extractToolDetail });
|
|
267
200
|
}
|
|
268
201
|
|
|
269
202
|
getLocalIP() {
|
|
@@ -279,25 +212,7 @@ class ClaudeRemoteServer {
|
|
|
279
212
|
}
|
|
280
213
|
|
|
281
214
|
startHeartbeat() {
|
|
282
|
-
this
|
|
283
|
-
this.wss.clients.forEach((ws) => {
|
|
284
|
-
if (ws.isAlive === false) {
|
|
285
|
-
if (ws.missedHeartbeats === undefined) {
|
|
286
|
-
ws.missedHeartbeats = 0;
|
|
287
|
-
}
|
|
288
|
-
ws.missedHeartbeats++;
|
|
289
|
-
if (ws.missedHeartbeats >= 2) {
|
|
290
|
-
console.log(`💔 Client heartbeat timeout, terminating (${ws._clientId || 'unknown'})`);
|
|
291
|
-
return ws.terminate(); // triggers 'close' event -> cleanup + emitClientCount
|
|
292
|
-
}
|
|
293
|
-
} else {
|
|
294
|
-
ws.missedHeartbeats = 0;
|
|
295
|
-
}
|
|
296
|
-
ws.isAlive = false;
|
|
297
|
-
ws.ping();
|
|
298
|
-
this.wsHandler.sendToClient(ws, { type: 'ping', timestamp: Date.now() });
|
|
299
|
-
});
|
|
300
|
-
}, 45000);
|
|
215
|
+
startServerHeartbeat(this);
|
|
301
216
|
}
|
|
302
217
|
|
|
303
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 };
|