tacticremote 1.7.0 → 1.8.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 +28 -0
- package/README.md +33 -41
- package/bin/tacticremote.js +41 -101
- package/package.json +30 -42
- package/bin/tactic-remote-server.js +0 -636
- package/lib/authChallengeManager.js +0 -1
- package/lib/bonjourPublisher.js +0 -68
- package/lib/claudeSessionManager.js +0 -1
- package/lib/claudeTransport.js +0 -1
- package/lib/errorCodes.js +0 -1
- package/lib/execSafe.js +0 -1
- package/lib/fileService.js +0 -1
- package/lib/hookInstaller.js +0 -253
- package/lib/outputParser.js +0 -1
- package/lib/pushClient.js +0 -1
- package/lib/rateLimiter.js +0 -1
- package/lib/serverIdentity.js +0 -1
- package/lib/streamJsonParser.js +0 -1
- package/lib/tmuxManager.js +0 -1
- package/lib/uploadService.js +0 -1
- package/lib/validators.js +0 -1
- package/middleware/authMiddleware.js +0 -152
- package/routes/httpHandler.js +0 -111
- package/routes/wsHandler.js +0 -1094
- package/server.js +0 -236
- package/shared/server-core/authChallengeManager.js +0 -108
- package/shared/server-core/claudeSessionManager.js +0 -222
- package/shared/server-core/claudeTransport.js +0 -176
- package/shared/server-core/errorCodes.js +0 -91
- package/shared/server-core/execSafe.js +0 -185
- package/shared/server-core/fileService.js +0 -155
- package/shared/server-core/outputParser.js +0 -174
- package/shared/server-core/protocol-manifest.json +0 -59
- package/shared/server-core/protocol-manifest.schema.json +0 -90
- package/shared/server-core/protocolManifest.js +0 -42
- package/shared/server-core/pushClient.js +0 -198
- package/shared/server-core/rateLimiter.js +0 -98
- package/shared/server-core/serverConnectionLifecycle.js +0 -118
- package/shared/server-core/serverHandshake.js +0 -72
- package/shared/server-core/serverIdentity.js +0 -102
- package/shared/server-core/streamJsonParser.js +0 -321
- package/shared/server-core/tmuxManager.js +0 -596
- package/shared/server-core/unixProcessLifecycle.js +0 -96
- package/shared/server-core/unixServerHooks.js +0 -148
- package/shared/server-core/unixWsRuntime.js +0 -412
- package/shared/server-core/uploadService.js +0 -321
- package/shared/server-core/validators.js +0 -274
- package/shared/server-core/windowsServerHooks.js +0 -174
- package/shared/server-core/windowsWsRuntime.js +0 -413
|
@@ -1,596 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Tmux session manager shared across tmux-based server variants.
|
|
3
|
-
*/
|
|
4
|
-
|
|
5
|
-
const {
|
|
6
|
-
execTmux,
|
|
7
|
-
tmuxSessionExists,
|
|
8
|
-
tmuxCapture,
|
|
9
|
-
tmuxSendKeys,
|
|
10
|
-
tmuxNewSession,
|
|
11
|
-
tmuxKillSession,
|
|
12
|
-
tmuxListSessions,
|
|
13
|
-
tmuxGetPanePath,
|
|
14
|
-
tmuxResizeWindow
|
|
15
|
-
} = require('./execSafe');
|
|
16
|
-
const { validateSessionName, validateTmuxKey, validateClaudeCommand, escapeForTmux, validateLineCount, validatePath } = require('./validators');
|
|
17
|
-
const { ErrorCodes, createError, createSessionNotFoundError } = require('./errorCodes');
|
|
18
|
-
const { parseClaudeOutput, isClaudeRunning, isWaitingForInput } = require('./outputParser');
|
|
19
|
-
const os = require('os');
|
|
20
|
-
|
|
21
|
-
const DEFAULT_SESSION = 'claude-remote';
|
|
22
|
-
|
|
23
|
-
function sleep(ms) {
|
|
24
|
-
return new Promise(resolve => setTimeout(resolve, ms));
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
async function isSessionManaged(sessionName) {
|
|
28
|
-
try {
|
|
29
|
-
const value = await execTmux('show-option', ['-t', sessionName, '-v', '@claude_remote_managed']);
|
|
30
|
-
return value.trim() === '1';
|
|
31
|
-
} catch {
|
|
32
|
-
return false;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
|
|
36
|
-
async function markSessionManaged(sessionName) {
|
|
37
|
-
await execTmux('set-option', ['-t', sessionName, '@claude_remote_managed', '1']);
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
/**
|
|
41
|
-
* Persist the canonical project path for this session as a tmux user option.
|
|
42
|
-
* tmux's `#{pane_current_path}` drifts when the shell or agent cd's
|
|
43
|
-
* elsewhere; this option is set once at creation and survives cd, making it
|
|
44
|
-
* the stable source of truth for "which project does this session belong to".
|
|
45
|
-
*/
|
|
46
|
-
async function markSessionPath(sessionName, projectPath) {
|
|
47
|
-
try {
|
|
48
|
-
await execTmux('set-option', ['-t', sessionName, '@tactic_session_path', projectPath]);
|
|
49
|
-
} catch (err) {
|
|
50
|
-
console.warn(`[markSessionPath] failed for ${sessionName}: ${err.message}`);
|
|
51
|
-
}
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
async function captureOutput(sessionName, lines = 500, preserveANSI = true) {
|
|
55
|
-
const validation = validateSessionName(sessionName);
|
|
56
|
-
if (!validation.valid) {
|
|
57
|
-
return { success: false, error: validation.error };
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
try {
|
|
61
|
-
const output = await tmuxCapture(sessionName, lines);
|
|
62
|
-
const parsed = parseClaudeOutput(output, { preserveANSI, maxLines: lines });
|
|
63
|
-
return {
|
|
64
|
-
success: true,
|
|
65
|
-
content: parsed.display,
|
|
66
|
-
rawContent: parsed.raw,
|
|
67
|
-
lineCount: parsed.lineCount,
|
|
68
|
-
hasANSI: parsed.hasANSI,
|
|
69
|
-
session: sessionName
|
|
70
|
-
};
|
|
71
|
-
} catch (error) {
|
|
72
|
-
return { success: false, error: error.message };
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
async function getSessionOutput(sessionName = DEFAULT_SESSION) {
|
|
77
|
-
const validation = validateSessionName(sessionName);
|
|
78
|
-
if (!validation.valid) {
|
|
79
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, validation.error) };
|
|
80
|
-
}
|
|
81
|
-
|
|
82
|
-
const exists = await tmuxSessionExists(sessionName);
|
|
83
|
-
if (!exists) {
|
|
84
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
85
|
-
}
|
|
86
|
-
|
|
87
|
-
const result = await captureOutput(sessionName, 500);
|
|
88
|
-
if (!result.success) {
|
|
89
|
-
return result;
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
const running = isClaudeRunning(result.rawContent || result.content || '');
|
|
93
|
-
return {
|
|
94
|
-
...result,
|
|
95
|
-
isRunning: running
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
|
|
99
|
-
async function getFullSessionOutput(sessionName = DEFAULT_SESSION, lines = 2000) {
|
|
100
|
-
const sessionValidation = validateSessionName(sessionName);
|
|
101
|
-
if (!sessionValidation.valid) {
|
|
102
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, sessionValidation.error) };
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
const linesValidation = validateLineCount(lines);
|
|
106
|
-
const safeLines = linesValidation.sanitized;
|
|
107
|
-
|
|
108
|
-
const exists = await tmuxSessionExists(sessionName);
|
|
109
|
-
if (!exists) {
|
|
110
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
return captureOutput(sessionName, safeLines);
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
async function listSessions() {
|
|
117
|
-
try {
|
|
118
|
-
const output = await tmuxListSessions();
|
|
119
|
-
const sessions = output.split('\n')
|
|
120
|
-
.filter(line => line.trim())
|
|
121
|
-
.map(line => {
|
|
122
|
-
// Format is name:attached:pane_current_path:@tactic_session_path
|
|
123
|
-
// Prefer the canonical path (set once at creation, doesn't drift
|
|
124
|
-
// with cd) over pane_current_path. Empty canonical falls back.
|
|
125
|
-
const parts = line.split(':');
|
|
126
|
-
const name = parts[0];
|
|
127
|
-
const attached = parts[1];
|
|
128
|
-
const panePath = parts[2];
|
|
129
|
-
const canonicalPath = parts[3];
|
|
130
|
-
return {
|
|
131
|
-
name,
|
|
132
|
-
attached: attached === '1',
|
|
133
|
-
path: (canonicalPath && canonicalPath.length > 0) ? canonicalPath : (panePath || os.homedir())
|
|
134
|
-
};
|
|
135
|
-
});
|
|
136
|
-
const managedSessions = [];
|
|
137
|
-
for (const s of sessions) {
|
|
138
|
-
if (await isSessionManaged(s.name)) {
|
|
139
|
-
managedSessions.push(s);
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
for (const s of managedSessions) {
|
|
143
|
-
try {
|
|
144
|
-
const captured = await tmuxCapture(s.name, 20);
|
|
145
|
-
s.running = isClaudeRunning(captured);
|
|
146
|
-
} catch {
|
|
147
|
-
s.running = false;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
return { success: true, sessions: managedSessions };
|
|
151
|
-
} catch {
|
|
152
|
-
return { success: true, sessions: [] };
|
|
153
|
-
}
|
|
154
|
-
}
|
|
155
|
-
|
|
156
|
-
async function createClaudeSession(sessionName, workingDir, claudeCommand = 'claude', cols, rows) {
|
|
157
|
-
await tmuxNewSession(sessionName, os.homedir(), cols, rows);
|
|
158
|
-
await markSessionManaged(sessionName);
|
|
159
|
-
await markSessionPath(sessionName, workingDir);
|
|
160
|
-
await waitForShellReady(sessionName);
|
|
161
|
-
await tmuxSendKeys(sessionName, ['-l', `cd '${workingDir.replace(/'/g, "'\\''")}'`]);
|
|
162
|
-
await tmuxSendKeys(sessionName, ['C-m']);
|
|
163
|
-
await waitForShellReady(sessionName);
|
|
164
|
-
await tmuxSendKeys(sessionName, ['-l', claudeCommand]);
|
|
165
|
-
await tmuxSendKeys(sessionName, ['C-m']);
|
|
166
|
-
await sleep(2000);
|
|
167
|
-
console.log(`✅ Created tmux session: ${sessionName} with command: ${claudeCommand}`);
|
|
168
|
-
}
|
|
169
|
-
|
|
170
|
-
async function createSession(name, sessionPath, allowedBasePath, currentPath) {
|
|
171
|
-
console.log(`[DEBUG createSession] name=${name}, sessionPath=${sessionPath}, allowedBasePath=${allowedBasePath}, currentPath=${currentPath}`);
|
|
172
|
-
const nameValidation = validateSessionName(name);
|
|
173
|
-
if (!nameValidation.valid) {
|
|
174
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, nameValidation.error) };
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
const pathValidation = validatePath(sessionPath, { allowedBasePath, currentPath });
|
|
178
|
-
if (!pathValidation.valid) {
|
|
179
|
-
return { success: false, error: createError(ErrorCodes.PATH_INVALID, pathValidation.error) };
|
|
180
|
-
}
|
|
181
|
-
|
|
182
|
-
const fs = require('fs');
|
|
183
|
-
const pathExists = fs.existsSync(pathValidation.path);
|
|
184
|
-
if (!pathExists) {
|
|
185
|
-
return { success: false, error: createError(ErrorCodes.PATH_NOT_FOUND, `Path does not exist: ${sessionPath}`) };
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
try {
|
|
189
|
-
const exists = await tmuxSessionExists(name);
|
|
190
|
-
if (exists) {
|
|
191
|
-
// Cross-check with `list-sessions`: tmux's `has-session` can linger
|
|
192
|
-
// for a few seconds after kill_session while list-sessions has
|
|
193
|
-
// already removed the entry. That mismatch previously caused a
|
|
194
|
-
// "phantom short-circuit" — createSession returned success for a
|
|
195
|
-
// session that no longer exists, and the iOS client got stuck
|
|
196
|
-
// waiting for the session name to appear in its refreshed list.
|
|
197
|
-
let listedLive = false;
|
|
198
|
-
try {
|
|
199
|
-
const listOut = await tmuxListSessions();
|
|
200
|
-
listedLive = listOut.split('\n').some(line => {
|
|
201
|
-
const firstCol = line.split(':')[0];
|
|
202
|
-
return firstCol === name;
|
|
203
|
-
});
|
|
204
|
-
} catch {
|
|
205
|
-
// If list-sessions fails, fall back to the has-session answer.
|
|
206
|
-
listedLive = true;
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
if (listedLive && await isSessionManaged(name)) {
|
|
210
|
-
// Truly alive managed session — treat as success, flag it so
|
|
211
|
-
// the client can distinguish "attached existing" from "created
|
|
212
|
-
// fresh" and skip waiting for tmuxSessions.contains to update.
|
|
213
|
-
return { success: true, path: pathValidation.path, alreadyExisted: true };
|
|
214
|
-
}
|
|
215
|
-
if (listedLive) {
|
|
216
|
-
return {
|
|
217
|
-
success: false,
|
|
218
|
-
error: createError(
|
|
219
|
-
ErrorCodes.SESSION_CREATE_FAILED,
|
|
220
|
-
`Session name "${name}" is already in use. Please choose a different name.`
|
|
221
|
-
)
|
|
222
|
-
};
|
|
223
|
-
}
|
|
224
|
-
// Phantom: has-session said yes but list-sessions said no. Force
|
|
225
|
-
// clean-up and fall through to normal creation.
|
|
226
|
-
console.log(`[createSession] phantom "${name}" detected (has-session=true, list-sessions=false), killing before re-create`);
|
|
227
|
-
try { await tmuxKillSession(name); } catch { /* ignore — already dead */ }
|
|
228
|
-
}
|
|
229
|
-
await tmuxNewSession(name, os.homedir());
|
|
230
|
-
await markSessionManaged(name);
|
|
231
|
-
await markSessionPath(name, pathValidation.path);
|
|
232
|
-
await waitForShellReady(name);
|
|
233
|
-
await tmuxSendKeys(name, ['-l', `cd '${pathValidation.path.replace(/'/g, "'\\''")}'`]);
|
|
234
|
-
await tmuxSendKeys(name, ['C-m']);
|
|
235
|
-
console.log(`✅ Created session: ${name} at ${pathValidation.path}`);
|
|
236
|
-
return { success: true, path: pathValidation.path };
|
|
237
|
-
} catch (error) {
|
|
238
|
-
return { success: false, error: createError(ErrorCodes.SESSION_CREATE_FAILED, error.message) };
|
|
239
|
-
}
|
|
240
|
-
}
|
|
241
|
-
|
|
242
|
-
async function attachSession(sessionName) {
|
|
243
|
-
const validation = validateSessionName(sessionName);
|
|
244
|
-
if (!validation.valid) {
|
|
245
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, validation.error) };
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
const exists = await tmuxSessionExists(sessionName);
|
|
249
|
-
if (!exists) {
|
|
250
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
251
|
-
}
|
|
252
|
-
|
|
253
|
-
if (!await isSessionManaged(sessionName)) {
|
|
254
|
-
return { success: false, error: createError(ErrorCodes.SESSION_NOT_FOUND, 'Session not managed by TacticRemote') };
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
try {
|
|
258
|
-
const sessionPath = await tmuxGetPanePath(sessionName);
|
|
259
|
-
const output = await tmuxCapture(sessionName, 500);
|
|
260
|
-
const running = isClaudeRunning(output);
|
|
261
|
-
const parsedOutput = await captureOutput(sessionName, 500);
|
|
262
|
-
|
|
263
|
-
return {
|
|
264
|
-
success: true,
|
|
265
|
-
path: sessionPath.trim(),
|
|
266
|
-
isRunning: running,
|
|
267
|
-
output: parsedOutput
|
|
268
|
-
};
|
|
269
|
-
} catch (error) {
|
|
270
|
-
return { success: false, error: error.message };
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
async function deleteSession(sessionName) {
|
|
275
|
-
const validation = validateSessionName(sessionName);
|
|
276
|
-
if (!validation.valid) {
|
|
277
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, validation.error) };
|
|
278
|
-
}
|
|
279
|
-
|
|
280
|
-
const exists = await tmuxSessionExists(sessionName);
|
|
281
|
-
if (!exists) {
|
|
282
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
try {
|
|
286
|
-
await tmuxKillSession(sessionName);
|
|
287
|
-
console.log(`🗑️ Deleted session: ${sessionName}`);
|
|
288
|
-
return { success: true };
|
|
289
|
-
} catch (error) {
|
|
290
|
-
return { success: false, error: error.message };
|
|
291
|
-
}
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
async function killSession(sessionName) {
|
|
295
|
-
const validation = validateSessionName(sessionName);
|
|
296
|
-
if (!validation.valid) {
|
|
297
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, validation.error) };
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
const exists = await tmuxSessionExists(sessionName);
|
|
301
|
-
if (!exists) {
|
|
302
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
try {
|
|
306
|
-
await tmuxSendKeys(sessionName, ['C-c']);
|
|
307
|
-
await sleep(500);
|
|
308
|
-
await tmuxSendKeys(sessionName, ['-l', 'exit']);
|
|
309
|
-
await tmuxSendKeys(sessionName, ['C-m']);
|
|
310
|
-
await sleep(500);
|
|
311
|
-
try {
|
|
312
|
-
await tmuxKillSession(sessionName);
|
|
313
|
-
} catch (_err) {
|
|
314
|
-
// Ignore if already dead.
|
|
315
|
-
}
|
|
316
|
-
console.log(`💀 Killed session: ${sessionName}`);
|
|
317
|
-
return { success: true };
|
|
318
|
-
} catch (error) {
|
|
319
|
-
return { success: false, error: error.message };
|
|
320
|
-
}
|
|
321
|
-
}
|
|
322
|
-
|
|
323
|
-
async function sendToClaude(content, sessionName = DEFAULT_SESSION, currentPath, cols, rows, claudeCommand = 'claude') {
|
|
324
|
-
const sessionValidation = validateSessionName(sessionName);
|
|
325
|
-
if (!sessionValidation.valid) {
|
|
326
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, sessionValidation.error) };
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
try {
|
|
330
|
-
const sessionExists = await tmuxSessionExists(sessionName);
|
|
331
|
-
if (!sessionExists) {
|
|
332
|
-
await createClaudeSession(sessionName, currentPath, claudeCommand, cols, rows);
|
|
333
|
-
await sleep(3000);
|
|
334
|
-
}
|
|
335
|
-
|
|
336
|
-
const escapedContent = escapeForTmux(content);
|
|
337
|
-
await tmuxSendKeys(sessionName, ['C-u']);
|
|
338
|
-
await sleep(200);
|
|
339
|
-
|
|
340
|
-
const lines = escapedContent.split('\n');
|
|
341
|
-
for (let i = 0; i < lines.length; i++) {
|
|
342
|
-
if (lines[i].length > 0) {
|
|
343
|
-
await tmuxSendKeys(sessionName, ['-l', lines[i]]);
|
|
344
|
-
}
|
|
345
|
-
if (i < lines.length - 1) {
|
|
346
|
-
await tmuxSendKeys(sessionName, ['Enter']);
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
await sleep(200);
|
|
350
|
-
await tmuxSendKeys(sessionName, ['C-m']);
|
|
351
|
-
|
|
352
|
-
console.log(`📤 Sent to Claude [${sessionName}]: ${content.substring(0, 50)}...`);
|
|
353
|
-
return { success: true };
|
|
354
|
-
} catch (error) {
|
|
355
|
-
return { success: false, error: error.message };
|
|
356
|
-
}
|
|
357
|
-
}
|
|
358
|
-
|
|
359
|
-
async function startClaude(sessionName = DEFAULT_SESSION, claudeCommand = 'claude', currentPath, cols, rows) {
|
|
360
|
-
const sessionValidation = validateSessionName(sessionName);
|
|
361
|
-
if (!sessionValidation.valid) {
|
|
362
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, sessionValidation.error) };
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
const cmdValidation = validateClaudeCommand(claudeCommand);
|
|
366
|
-
if (!cmdValidation.valid) {
|
|
367
|
-
return { success: false, error: createError(ErrorCodes.COMMAND_INVALID, cmdValidation.error) };
|
|
368
|
-
}
|
|
369
|
-
const safeCommand = cmdValidation.sanitized;
|
|
370
|
-
|
|
371
|
-
try {
|
|
372
|
-
const sessionExists = await tmuxSessionExists(sessionName);
|
|
373
|
-
if (!sessionExists) {
|
|
374
|
-
await createClaudeSession(sessionName, currentPath, safeCommand, cols, rows);
|
|
375
|
-
console.log(`🚀 Started Claude in session: ${sessionName} with command: ${claudeCommand}`);
|
|
376
|
-
return { success: true, isRunning: true, alreadyRunning: false };
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
if (cols && rows) {
|
|
380
|
-
try { await tmuxResizeWindow(sessionName, cols, rows); } catch (_err) { /* ignore */ }
|
|
381
|
-
}
|
|
382
|
-
const output = await tmuxCapture(sessionName, 120);
|
|
383
|
-
const running = isClaudeRunning(output);
|
|
384
|
-
if (running) {
|
|
385
|
-
console.log(`ℹ️ Claude already running in session: ${sessionName}`);
|
|
386
|
-
return { success: true, isRunning: true, alreadyRunning: true };
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
console.log('[DEBUG startClaude] waiting for shell ready...');
|
|
390
|
-
await waitForShellReady(sessionName);
|
|
391
|
-
console.log(`[DEBUG startClaude] shell ready, sending command: ${safeCommand}`);
|
|
392
|
-
await tmuxSendKeys(sessionName, ['-l', safeCommand]);
|
|
393
|
-
await tmuxSendKeys(sessionName, ['C-m']);
|
|
394
|
-
|
|
395
|
-
console.log(`🚀 Started Claude in session: ${sessionName} with command: ${claudeCommand}`);
|
|
396
|
-
return { success: true, isRunning: true, alreadyRunning: false };
|
|
397
|
-
} catch (error) {
|
|
398
|
-
return { success: false, error: error.message };
|
|
399
|
-
}
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
async function waitForShellReady(sessionName, timeoutMs = 8000) {
|
|
403
|
-
const startTime = Date.now();
|
|
404
|
-
const pollInterval = 300;
|
|
405
|
-
const promptPattern = /[$%>#→❯➜]\s*$/m;
|
|
406
|
-
|
|
407
|
-
console.log(`🔍 [waitForShellReady] START for session: ${sessionName}, timeout: ${timeoutMs}ms`);
|
|
408
|
-
while (Date.now() - startTime < timeoutMs) {
|
|
409
|
-
await sleep(pollInterval);
|
|
410
|
-
try {
|
|
411
|
-
const output = await tmuxCapture(sessionName, 5);
|
|
412
|
-
const trimmed = output.trim();
|
|
413
|
-
const lastLine = trimmed.split('\n').pop() || '';
|
|
414
|
-
const matches = promptPattern.test(trimmed);
|
|
415
|
-
console.log(`🔍 [waitForShellReady] ${Date.now() - startTime}ms | lastLine=${JSON.stringify(lastLine)} | matches=${matches}`);
|
|
416
|
-
if (trimmed.length > 0 && matches) {
|
|
417
|
-
console.log(`✅ [waitForShellReady] shell ready after ${Date.now() - startTime}ms`);
|
|
418
|
-
return;
|
|
419
|
-
}
|
|
420
|
-
} catch (e) {
|
|
421
|
-
console.log(`🔍 [waitForShellReady] capture error: ${e.message}`);
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
console.log(`⚠️ [waitForShellReady] TIMEOUT for session: ${sessionName} after ${timeoutMs}ms, proceeding anyway`);
|
|
425
|
-
}
|
|
426
|
-
|
|
427
|
-
async function stopClaude(sessionName = DEFAULT_SESSION) {
|
|
428
|
-
const validation = validateSessionName(sessionName);
|
|
429
|
-
if (!validation.valid) {
|
|
430
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, validation.error) };
|
|
431
|
-
}
|
|
432
|
-
|
|
433
|
-
try {
|
|
434
|
-
await tmuxSendKeys(sessionName, ['C-c']);
|
|
435
|
-
await sleep(200);
|
|
436
|
-
await tmuxSendKeys(sessionName, ['C-c']);
|
|
437
|
-
await sleep(200);
|
|
438
|
-
await tmuxSendKeys(sessionName, ['-l', '/exit']);
|
|
439
|
-
await tmuxSendKeys(sessionName, ['C-m']);
|
|
440
|
-
console.log(`🛑 Stopped Claude in session: ${sessionName}`);
|
|
441
|
-
return { success: true };
|
|
442
|
-
} catch (error) {
|
|
443
|
-
return { success: false, error: error.message };
|
|
444
|
-
}
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
const TMUX_KEY_MAP = {
|
|
448
|
-
'Enter': 'Enter',
|
|
449
|
-
'Escape': 'Escape',
|
|
450
|
-
'Up': 'Up',
|
|
451
|
-
'Down': 'Down',
|
|
452
|
-
'Left': 'Left',
|
|
453
|
-
'Right': 'Right',
|
|
454
|
-
'Tab': 'Tab',
|
|
455
|
-
'S-Tab': 'BTab',
|
|
456
|
-
'Space': 'Space',
|
|
457
|
-
'C-c': 'C-c',
|
|
458
|
-
'C-d': 'C-d',
|
|
459
|
-
'C-u': 'C-u',
|
|
460
|
-
'C-z': 'C-z',
|
|
461
|
-
'C-a': 'C-a',
|
|
462
|
-
'C-b': 'C-b',
|
|
463
|
-
'C-e': 'C-e',
|
|
464
|
-
'C-k': 'C-k',
|
|
465
|
-
'C-l': 'C-l',
|
|
466
|
-
'C-r': 'C-r',
|
|
467
|
-
'C-w': 'C-w',
|
|
468
|
-
'Home': 'Home',
|
|
469
|
-
'End': 'End',
|
|
470
|
-
'PageUp': 'PPage',
|
|
471
|
-
'PageDown': 'NPage',
|
|
472
|
-
'PPage': 'PPage',
|
|
473
|
-
'NPage': 'NPage',
|
|
474
|
-
'F1': 'F1',
|
|
475
|
-
'F2': 'F2',
|
|
476
|
-
'F3': 'F3',
|
|
477
|
-
'F4': 'F4',
|
|
478
|
-
'F5': 'F5',
|
|
479
|
-
'F6': 'F6',
|
|
480
|
-
'y': 'y',
|
|
481
|
-
'n': 'n',
|
|
482
|
-
'1': '1',
|
|
483
|
-
'2': '2'
|
|
484
|
-
};
|
|
485
|
-
|
|
486
|
-
async function sendKeyToSession(key, sessionName = DEFAULT_SESSION) {
|
|
487
|
-
const sessionValidation = validateSessionName(sessionName);
|
|
488
|
-
if (!sessionValidation.valid) {
|
|
489
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, sessionValidation.error) };
|
|
490
|
-
}
|
|
491
|
-
|
|
492
|
-
const keyValidation = validateTmuxKey(key);
|
|
493
|
-
if (!keyValidation.valid) {
|
|
494
|
-
return { success: false, error: createError(ErrorCodes.COMMAND_INVALID, keyValidation.error) };
|
|
495
|
-
}
|
|
496
|
-
|
|
497
|
-
try {
|
|
498
|
-
const sessionExists = await tmuxSessionExists(sessionName);
|
|
499
|
-
if (!sessionExists) {
|
|
500
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
const HEX_KEY_MAP = { 'S-Tab': ['1b', '5b', '5a'] };
|
|
504
|
-
if (HEX_KEY_MAP[key]) {
|
|
505
|
-
await tmuxSendKeys(sessionName, ['-H', ...HEX_KEY_MAP[key]]);
|
|
506
|
-
} else {
|
|
507
|
-
const tmuxKey = TMUX_KEY_MAP[key] || key;
|
|
508
|
-
await tmuxSendKeys(sessionName, [tmuxKey]);
|
|
509
|
-
}
|
|
510
|
-
console.log(`⌨️ Sent key [${sessionName}]: ${key}`);
|
|
511
|
-
return { success: true };
|
|
512
|
-
} catch (error) {
|
|
513
|
-
return { success: false, error: error.message };
|
|
514
|
-
}
|
|
515
|
-
}
|
|
516
|
-
|
|
517
|
-
async function sendKeySequence(sessionName, keys) {
|
|
518
|
-
const sessionValidation = validateSessionName(sessionName);
|
|
519
|
-
if (!sessionValidation.valid) {
|
|
520
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, sessionValidation.error) };
|
|
521
|
-
}
|
|
522
|
-
|
|
523
|
-
for (const key of keys) {
|
|
524
|
-
const keyValidation = validateTmuxKey(key);
|
|
525
|
-
if (!keyValidation.valid) {
|
|
526
|
-
return { success: false, error: createError(ErrorCodes.COMMAND_INVALID, keyValidation.error) };
|
|
527
|
-
}
|
|
528
|
-
}
|
|
529
|
-
|
|
530
|
-
try {
|
|
531
|
-
const sessionExists = await tmuxSessionExists(sessionName);
|
|
532
|
-
if (!sessionExists) {
|
|
533
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
534
|
-
}
|
|
535
|
-
|
|
536
|
-
const HEX_KEY_MAP = { 'S-Tab': ['1b', '5b', '5a'] };
|
|
537
|
-
for (const key of keys) {
|
|
538
|
-
if (HEX_KEY_MAP[key]) {
|
|
539
|
-
await tmuxSendKeys(sessionName, ['-H', ...HEX_KEY_MAP[key]]);
|
|
540
|
-
} else {
|
|
541
|
-
const tmuxKey = TMUX_KEY_MAP[key] || key;
|
|
542
|
-
await tmuxSendKeys(sessionName, [tmuxKey]);
|
|
543
|
-
}
|
|
544
|
-
await sleep(50);
|
|
545
|
-
}
|
|
546
|
-
console.log(`⌨️ Sent key sequence [${sessionName}]: ${keys.join(', ')}`);
|
|
547
|
-
return { success: true };
|
|
548
|
-
} catch (error) {
|
|
549
|
-
return { success: false, error: error.message };
|
|
550
|
-
}
|
|
551
|
-
}
|
|
552
|
-
|
|
553
|
-
async function resizeSession(sessionName, cols, rows) {
|
|
554
|
-
const validation = validateSessionName(sessionName);
|
|
555
|
-
if (!validation.valid) {
|
|
556
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, validation.error) };
|
|
557
|
-
}
|
|
558
|
-
|
|
559
|
-
const safeCols = Math.max(40, Math.min(500, parseInt(cols, 10) || 80));
|
|
560
|
-
const safeRows = Math.max(10, Math.min(200, parseInt(rows, 10) || 50));
|
|
561
|
-
|
|
562
|
-
const exists = await tmuxSessionExists(sessionName);
|
|
563
|
-
if (!exists) {
|
|
564
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
565
|
-
}
|
|
566
|
-
|
|
567
|
-
try {
|
|
568
|
-
await tmuxResizeWindow(sessionName, safeCols, safeRows);
|
|
569
|
-
console.log(`📐 Resized session ${sessionName} to ${safeCols}x${safeRows}`);
|
|
570
|
-
return { success: true, cols: safeCols, rows: safeRows };
|
|
571
|
-
} catch (error) {
|
|
572
|
-
return { success: false, error: error.message };
|
|
573
|
-
}
|
|
574
|
-
}
|
|
575
|
-
|
|
576
|
-
module.exports = {
|
|
577
|
-
DEFAULT_SESSION,
|
|
578
|
-
sleep,
|
|
579
|
-
captureOutput,
|
|
580
|
-
getSessionOutput,
|
|
581
|
-
getFullSessionOutput,
|
|
582
|
-
listSessions,
|
|
583
|
-
createClaudeSession,
|
|
584
|
-
createSession,
|
|
585
|
-
attachSession,
|
|
586
|
-
deleteSession,
|
|
587
|
-
killSession,
|
|
588
|
-
sendToClaude,
|
|
589
|
-
startClaude,
|
|
590
|
-
stopClaude,
|
|
591
|
-
sendKeyToSession,
|
|
592
|
-
sendKeySequence,
|
|
593
|
-
resizeSession,
|
|
594
|
-
isClaudeRunning,
|
|
595
|
-
isWaitingForInput
|
|
596
|
-
};
|
|
@@ -1,96 +0,0 @@
|
|
|
1
|
-
async function shutdownUnixServer(server, options = {}) {
|
|
2
|
-
const {
|
|
3
|
-
authRateLimiter,
|
|
4
|
-
killSession,
|
|
5
|
-
logManagedSessions = true
|
|
6
|
-
} = options;
|
|
7
|
-
|
|
8
|
-
if (server.heartbeatInterval) {
|
|
9
|
-
clearInterval(server.heartbeatInterval);
|
|
10
|
-
server.heartbeatInterval = null;
|
|
11
|
-
}
|
|
12
|
-
|
|
13
|
-
if (server.wsHandler && server.wsHandler.outputMonitors) {
|
|
14
|
-
for (const [, monitor] of server.wsHandler.outputMonitors.entries()) {
|
|
15
|
-
clearInterval(monitor.intervalId);
|
|
16
|
-
}
|
|
17
|
-
server.wsHandler.outputMonitors.clear();
|
|
18
|
-
}
|
|
19
|
-
|
|
20
|
-
if (server.wsHandler && server.wsHandler.claudeSessionManager) {
|
|
21
|
-
const sm = server.wsHandler.claudeSessionManager;
|
|
22
|
-
const structuredCount = sm.listSessions().length;
|
|
23
|
-
if (structuredCount > 0) {
|
|
24
|
-
console.log(`🧹 Cleaning up ${structuredCount} structured session(s)...`);
|
|
25
|
-
await sm.shutdownAll();
|
|
26
|
-
}
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
if (server.managedSessions.size > 0) {
|
|
30
|
-
if (logManagedSessions) {
|
|
31
|
-
console.log(`🧹 Cleaning up ${server.managedSessions.size} managed tmux session(s)...`);
|
|
32
|
-
}
|
|
33
|
-
for (const name of server.managedSessions) {
|
|
34
|
-
try {
|
|
35
|
-
await killSession(name);
|
|
36
|
-
if (logManagedSessions) {
|
|
37
|
-
console.log(` Killed session: ${name}`);
|
|
38
|
-
}
|
|
39
|
-
} catch (_error) {
|
|
40
|
-
// Best effort during shutdown.
|
|
41
|
-
}
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
authRateLimiter.destroy();
|
|
46
|
-
if (server.httpServer) {
|
|
47
|
-
server.httpServer.close();
|
|
48
|
-
}
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
function installUnixProcessHandlers(server, options) {
|
|
52
|
-
const {
|
|
53
|
-
authRateLimiter,
|
|
54
|
-
createError,
|
|
55
|
-
ErrorCodes,
|
|
56
|
-
killSession,
|
|
57
|
-
logManagedSessions = true
|
|
58
|
-
} = options;
|
|
59
|
-
|
|
60
|
-
const gracefulShutdown = async (signal) => {
|
|
61
|
-
console.log(`\n🛑 Received ${signal}, shutting down server...`);
|
|
62
|
-
await shutdownUnixServer(server, {
|
|
63
|
-
authRateLimiter,
|
|
64
|
-
killSession,
|
|
65
|
-
logManagedSessions
|
|
66
|
-
});
|
|
67
|
-
process.exit(0);
|
|
68
|
-
};
|
|
69
|
-
|
|
70
|
-
process.on('SIGINT', () => gracefulShutdown('SIGINT'));
|
|
71
|
-
process.on('SIGTERM', () => gracefulShutdown('SIGTERM'));
|
|
72
|
-
|
|
73
|
-
process.on('unhandledRejection', (reason) => {
|
|
74
|
-
console.error('❌ Unhandled Promise Rejection:', reason);
|
|
75
|
-
try {
|
|
76
|
-
server.wsHandler.broadcast(createError(ErrorCodes.INTERNAL_ERROR, 'Internal server error'));
|
|
77
|
-
} catch (_error) {
|
|
78
|
-
// Best effort: process-level errors can fire before wsHandler is ready.
|
|
79
|
-
}
|
|
80
|
-
});
|
|
81
|
-
|
|
82
|
-
process.on('uncaughtException', (error) => {
|
|
83
|
-
console.error('❌ Uncaught Exception:', error);
|
|
84
|
-
try {
|
|
85
|
-
server.wsHandler.broadcast(createError(ErrorCodes.INTERNAL_ERROR, 'Internal server error'));
|
|
86
|
-
} catch (_error) {
|
|
87
|
-
// Best effort: process-level errors can fire before wsHandler is ready.
|
|
88
|
-
}
|
|
89
|
-
setTimeout(() => process.exit(1), 1000);
|
|
90
|
-
});
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
module.exports = {
|
|
94
|
-
installUnixProcessHandlers,
|
|
95
|
-
shutdownUnixServer
|
|
96
|
-
};
|