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.
- 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/wsHandler.js +418 -364
- package/server.js +67 -173
- 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/lib/tmuxManager.js
CHANGED
|
@@ -1,671 +1 @@
|
|
|
1
|
-
|
|
2
|
-
* Tmux session manager for MacServer
|
|
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 } = 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
|
-
/**
|
|
24
|
-
* Sleep utility
|
|
25
|
-
* @param {number} ms - Milliseconds to sleep
|
|
26
|
-
*/
|
|
27
|
-
function sleep(ms) {
|
|
28
|
-
return new Promise(resolve => setTimeout(resolve, ms));
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
/**
|
|
32
|
-
* Check if a tmux session is managed by TacticRemote
|
|
33
|
-
* @param {string} sessionName - Session name (must be pre-validated)
|
|
34
|
-
* @returns {Promise<boolean>}
|
|
35
|
-
*/
|
|
36
|
-
async function isSessionManaged(sessionName) {
|
|
37
|
-
try {
|
|
38
|
-
const value = await execTmux('show-option', ['-t', sessionName, '-v', '@claude_remote_managed']);
|
|
39
|
-
return value.trim() === '1';
|
|
40
|
-
} catch {
|
|
41
|
-
return false;
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Mark a tmux session as managed by TacticRemote
|
|
47
|
-
* @param {string} sessionName - Session name (must be pre-validated)
|
|
48
|
-
*/
|
|
49
|
-
async function markSessionManaged(sessionName) {
|
|
50
|
-
await execTmux('set-option', ['-t', sessionName, '@claude_remote_managed', '1']);
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
/**
|
|
54
|
-
* Capture and parse tmux output
|
|
55
|
-
* @param {string} sessionName - Session to capture from
|
|
56
|
-
* @param {number} lines - Number of lines to capture
|
|
57
|
-
* @returns {Object} Parsed output or error
|
|
58
|
-
*/
|
|
59
|
-
async function captureOutput(sessionName, lines = 500, preserveANSI = true) {
|
|
60
|
-
const validation = validateSessionName(sessionName);
|
|
61
|
-
if (!validation.valid) {
|
|
62
|
-
return { success: false, error: validation.error };
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
try {
|
|
66
|
-
const output = await tmuxCapture(sessionName, lines);
|
|
67
|
-
const parsed = parseClaudeOutput(output, { preserveANSI, maxLines: lines });
|
|
68
|
-
return {
|
|
69
|
-
success: true,
|
|
70
|
-
content: parsed.display,
|
|
71
|
-
rawContent: parsed.raw,
|
|
72
|
-
lineCount: parsed.lineCount,
|
|
73
|
-
hasANSI: parsed.hasANSI,
|
|
74
|
-
session: sessionName
|
|
75
|
-
};
|
|
76
|
-
} catch (error) {
|
|
77
|
-
return { success: false, error: error.message };
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
/**
|
|
82
|
-
* Get session output
|
|
83
|
-
* @param {string} sessionName - Session name
|
|
84
|
-
* @returns {Object} Output result
|
|
85
|
-
*/
|
|
86
|
-
async function getSessionOutput(sessionName = DEFAULT_SESSION) {
|
|
87
|
-
const validation = validateSessionName(sessionName);
|
|
88
|
-
if (!validation.valid) {
|
|
89
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, validation.error) };
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
const exists = await tmuxSessionExists(sessionName);
|
|
93
|
-
if (!exists) {
|
|
94
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
const result = await captureOutput(sessionName, 500);
|
|
98
|
-
if (!result.success) {
|
|
99
|
-
return result;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
// Expose runtime state so clients can render Start/Stop actions correctly.
|
|
103
|
-
const running = isClaudeRunning(result.rawContent || result.content || '');
|
|
104
|
-
return {
|
|
105
|
-
...result,
|
|
106
|
-
isRunning: running
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
/**
|
|
111
|
-
* Get full session output with more history
|
|
112
|
-
* @param {string} sessionName - Session name
|
|
113
|
-
* @param {number} lines - Number of lines to capture
|
|
114
|
-
* @returns {Object} Output result
|
|
115
|
-
*/
|
|
116
|
-
async function getFullSessionOutput(sessionName = DEFAULT_SESSION, lines = 2000) {
|
|
117
|
-
const sessionValidation = validateSessionName(sessionName);
|
|
118
|
-
if (!sessionValidation.valid) {
|
|
119
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, sessionValidation.error) };
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
const linesValidation = validateLineCount(lines);
|
|
123
|
-
const safeLines = linesValidation.sanitized;
|
|
124
|
-
|
|
125
|
-
const exists = await tmuxSessionExists(sessionName);
|
|
126
|
-
if (!exists) {
|
|
127
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
return captureOutput(sessionName, safeLines);
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
/**
|
|
134
|
-
* List all tmux sessions
|
|
135
|
-
* @returns {Object} Sessions list result
|
|
136
|
-
*/
|
|
137
|
-
async function listSessions() {
|
|
138
|
-
try {
|
|
139
|
-
const output = await tmuxListSessions();
|
|
140
|
-
const sessions = output.split('\n')
|
|
141
|
-
.filter(line => line.trim())
|
|
142
|
-
.map(line => {
|
|
143
|
-
const [name, attached, sessionPath] = line.split(':');
|
|
144
|
-
return {
|
|
145
|
-
name,
|
|
146
|
-
attached: attached === '1',
|
|
147
|
-
path: sessionPath || os.homedir()
|
|
148
|
-
};
|
|
149
|
-
});
|
|
150
|
-
// Filter to only TacticRemote managed sessions
|
|
151
|
-
const managedSessions = [];
|
|
152
|
-
for (const s of sessions) {
|
|
153
|
-
if (await isSessionManaged(s.name)) {
|
|
154
|
-
managedSessions.push(s);
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
// Enrich each session with running status
|
|
158
|
-
for (const s of managedSessions) {
|
|
159
|
-
try {
|
|
160
|
-
const captured = await tmuxCapture(s.name, 20);
|
|
161
|
-
s.running = isClaudeRunning(captured);
|
|
162
|
-
} catch {
|
|
163
|
-
s.running = false;
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
return { success: true, sessions: managedSessions };
|
|
167
|
-
} catch (error) {
|
|
168
|
-
return { success: true, sessions: [] };
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
|
|
172
|
-
/**
|
|
173
|
-
* Create a new Claude tmux session
|
|
174
|
-
* @param {string} sessionName - Session name
|
|
175
|
-
* @param {string} workingDir - Working directory
|
|
176
|
-
* @param {string} claudeCommand - Command to start Claude
|
|
177
|
-
*/
|
|
178
|
-
async function createClaudeSession(sessionName, workingDir, claudeCommand = 'claude', cols, rows) {
|
|
179
|
-
await tmuxNewSession(sessionName, os.homedir(), cols, rows);
|
|
180
|
-
await markSessionManaged(sessionName);
|
|
181
|
-
await waitForShellReady(sessionName);
|
|
182
|
-
await tmuxSendKeys(sessionName, ['-l', `cd '${workingDir.replace(/'/g, "'\\''")}'`]);
|
|
183
|
-
await tmuxSendKeys(sessionName, ['C-m']);
|
|
184
|
-
await waitForShellReady(sessionName);
|
|
185
|
-
await tmuxSendKeys(sessionName, ['-l', claudeCommand]);
|
|
186
|
-
await tmuxSendKeys(sessionName, ['C-m']);
|
|
187
|
-
await sleep(2000);
|
|
188
|
-
console.log(`✅ Created tmux session: ${sessionName} with command: ${claudeCommand}`);
|
|
189
|
-
}
|
|
190
|
-
|
|
191
|
-
/**
|
|
192
|
-
* Create a new session at a specific path
|
|
193
|
-
* @param {string} name - Session name
|
|
194
|
-
* @param {string} sessionPath - Path for session
|
|
195
|
-
* @param {string} allowedBasePath - Base path restriction
|
|
196
|
-
* @param {string} currentPath - Current client path for resolving relative session paths
|
|
197
|
-
* @returns {Object} Result
|
|
198
|
-
*/
|
|
199
|
-
async function createSession(name, sessionPath, allowedBasePath, currentPath) {
|
|
200
|
-
console.log(`[DEBUG createSession] name=${name}, sessionPath=${sessionPath}, allowedBasePath=${allowedBasePath}, currentPath=${currentPath}`);
|
|
201
|
-
const nameValidation = validateSessionName(name);
|
|
202
|
-
if (!nameValidation.valid) {
|
|
203
|
-
console.log(`[DEBUG createSession] name validation failed: ${nameValidation.error}`);
|
|
204
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, nameValidation.error) };
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
const { validatePath } = require('./validators');
|
|
208
|
-
const pathValidation = validatePath(sessionPath, { allowedBasePath, currentPath });
|
|
209
|
-
console.log(`[DEBUG createSession] pathValidation: valid=${pathValidation.valid}, error=${pathValidation.error}, requiresAuth=${pathValidation.requiresAuth}, path=${pathValidation.path}`);
|
|
210
|
-
|
|
211
|
-
if (!pathValidation.valid) {
|
|
212
|
-
return { success: false, error: createError(ErrorCodes.PATH_INVALID, pathValidation.error) };
|
|
213
|
-
}
|
|
214
|
-
|
|
215
|
-
const fs = require('fs');
|
|
216
|
-
const pathExists = fs.existsSync(pathValidation.path);
|
|
217
|
-
|
|
218
|
-
if (!pathExists) {
|
|
219
|
-
return { success: false, error: createError(ErrorCodes.PATH_NOT_FOUND, `Path does not exist: ${sessionPath}`) };
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
try {
|
|
223
|
-
const exists = await tmuxSessionExists(name);
|
|
224
|
-
if (exists) {
|
|
225
|
-
if (await isSessionManaged(name)) {
|
|
226
|
-
console.log(`[DEBUG createSession] session "${name}" already managed, re-adopting`);
|
|
227
|
-
return { success: true, path: pathValidation.path };
|
|
228
|
-
}
|
|
229
|
-
console.log(`[DEBUG createSession] session "${name}" exists but NOT managed, refusing`);
|
|
230
|
-
return {
|
|
231
|
-
success: false,
|
|
232
|
-
error: createError(
|
|
233
|
-
ErrorCodes.SESSION_CREATE_FAILED,
|
|
234
|
-
`Session name "${name}" is already in use. Please choose a different name.`
|
|
235
|
-
)
|
|
236
|
-
};
|
|
237
|
-
}
|
|
238
|
-
await tmuxNewSession(name, os.homedir());
|
|
239
|
-
await markSessionManaged(name);
|
|
240
|
-
await waitForShellReady(name);
|
|
241
|
-
await tmuxSendKeys(name, ['-l', `cd '${pathValidation.path.replace(/'/g, "'\\''")}'`]);
|
|
242
|
-
await tmuxSendKeys(name, ['C-m']);
|
|
243
|
-
console.log(`✅ Created session: ${name} at ${pathValidation.path}`);
|
|
244
|
-
return { success: true, path: pathValidation.path };
|
|
245
|
-
} catch (error) {
|
|
246
|
-
console.log(`[DEBUG createSession] tmuxNewSession error: ${error.message}`);
|
|
247
|
-
return { success: false, error: createError(ErrorCodes.SESSION_CREATE_FAILED, error.message) };
|
|
248
|
-
}
|
|
249
|
-
}
|
|
250
|
-
|
|
251
|
-
/**
|
|
252
|
-
* Attach to an existing session
|
|
253
|
-
* @param {string} sessionName - Session to attach to
|
|
254
|
-
* @returns {Object} Attach result with session info
|
|
255
|
-
*/
|
|
256
|
-
async function attachSession(sessionName) {
|
|
257
|
-
const validation = validateSessionName(sessionName);
|
|
258
|
-
if (!validation.valid) {
|
|
259
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, validation.error) };
|
|
260
|
-
}
|
|
261
|
-
|
|
262
|
-
const exists = await tmuxSessionExists(sessionName);
|
|
263
|
-
if (!exists) {
|
|
264
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
if (!await isSessionManaged(sessionName)) {
|
|
268
|
-
return { success: false, error: createError(ErrorCodes.SESSION_NOT_FOUND, 'Session not managed by TacticRemote') };
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
try {
|
|
272
|
-
const sessionPath = await tmuxGetPanePath(sessionName);
|
|
273
|
-
const output = await tmuxCapture(sessionName, 50);
|
|
274
|
-
const running = isClaudeRunning(output);
|
|
275
|
-
const parsedOutput = await captureOutput(sessionName, 500);
|
|
276
|
-
|
|
277
|
-
return {
|
|
278
|
-
success: true,
|
|
279
|
-
path: sessionPath.trim(),
|
|
280
|
-
isRunning: running,
|
|
281
|
-
output: parsedOutput
|
|
282
|
-
};
|
|
283
|
-
} catch (error) {
|
|
284
|
-
return { success: false, error: error.message };
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
|
|
288
|
-
/**
|
|
289
|
-
* Delete a tmux session
|
|
290
|
-
* @param {string} sessionName - Session to delete
|
|
291
|
-
* @returns {Object} Delete result
|
|
292
|
-
*/
|
|
293
|
-
async function deleteSession(sessionName) {
|
|
294
|
-
const validation = validateSessionName(sessionName);
|
|
295
|
-
if (!validation.valid) {
|
|
296
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, validation.error) };
|
|
297
|
-
}
|
|
298
|
-
|
|
299
|
-
const exists = await tmuxSessionExists(sessionName);
|
|
300
|
-
if (!exists) {
|
|
301
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
302
|
-
}
|
|
303
|
-
|
|
304
|
-
try {
|
|
305
|
-
await tmuxKillSession(sessionName);
|
|
306
|
-
console.log(`🗑️ Deleted session: ${sessionName}`);
|
|
307
|
-
return { success: true };
|
|
308
|
-
} catch (error) {
|
|
309
|
-
return { success: false, error: error.message };
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
|
|
313
|
-
/**
|
|
314
|
-
* Kill a session (stop Claude and terminate)
|
|
315
|
-
* @param {string} sessionName - Session to kill
|
|
316
|
-
* @returns {Object} Kill result
|
|
317
|
-
*/
|
|
318
|
-
async function killSession(sessionName) {
|
|
319
|
-
const validation = validateSessionName(sessionName);
|
|
320
|
-
if (!validation.valid) {
|
|
321
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, validation.error) };
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
const exists = await tmuxSessionExists(sessionName);
|
|
325
|
-
if (!exists) {
|
|
326
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
try {
|
|
330
|
-
// Send Ctrl+C to stop any running process
|
|
331
|
-
await tmuxSendKeys(sessionName, ['C-c']);
|
|
332
|
-
await sleep(500);
|
|
333
|
-
// Send exit to close the shell
|
|
334
|
-
await tmuxSendKeys(sessionName, ['-l', 'exit']);
|
|
335
|
-
await tmuxSendKeys(sessionName, ['C-m']);
|
|
336
|
-
await sleep(500);
|
|
337
|
-
// Force kill the session
|
|
338
|
-
try {
|
|
339
|
-
await tmuxKillSession(sessionName);
|
|
340
|
-
} catch (e) {
|
|
341
|
-
// Ignore if already dead
|
|
342
|
-
}
|
|
343
|
-
console.log(`💀 Killed session: ${sessionName}`);
|
|
344
|
-
return { success: true };
|
|
345
|
-
} catch (error) {
|
|
346
|
-
return { success: false, error: error.message };
|
|
347
|
-
}
|
|
348
|
-
}
|
|
349
|
-
|
|
350
|
-
/**
|
|
351
|
-
* Send command to Claude
|
|
352
|
-
* @param {string} content - Command content
|
|
353
|
-
* @param {string} sessionName - Target session
|
|
354
|
-
* @param {string} currentPath - Current working path
|
|
355
|
-
* @returns {Object} Send result
|
|
356
|
-
*/
|
|
357
|
-
async function sendToClaude(content, sessionName = DEFAULT_SESSION, currentPath, cols, rows) {
|
|
358
|
-
const sessionValidation = validateSessionName(sessionName);
|
|
359
|
-
if (!sessionValidation.valid) {
|
|
360
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, sessionValidation.error) };
|
|
361
|
-
}
|
|
362
|
-
|
|
363
|
-
try {
|
|
364
|
-
const sessionExists = await tmuxSessionExists(sessionName);
|
|
365
|
-
if (!sessionExists) {
|
|
366
|
-
await createClaudeSession(sessionName, currentPath, 'claude', cols, rows);
|
|
367
|
-
await sleep(3000);
|
|
368
|
-
}
|
|
369
|
-
|
|
370
|
-
const escapedContent = escapeForTmux(content);
|
|
371
|
-
await tmuxSendKeys(sessionName, ['C-u']);
|
|
372
|
-
await sleep(200);
|
|
373
|
-
|
|
374
|
-
// Handle multi-line content: split by newlines and send each line
|
|
375
|
-
// with literal mode, pressing Enter between them.
|
|
376
|
-
const lines = escapedContent.split('\n');
|
|
377
|
-
for (let i = 0; i < lines.length; i++) {
|
|
378
|
-
if (lines[i].length > 0) {
|
|
379
|
-
await tmuxSendKeys(sessionName, ['-l', lines[i]]);
|
|
380
|
-
}
|
|
381
|
-
if (i < lines.length - 1) {
|
|
382
|
-
// Press Enter between lines (not after last line)
|
|
383
|
-
await tmuxSendKeys(sessionName, ['Enter']);
|
|
384
|
-
}
|
|
385
|
-
}
|
|
386
|
-
await sleep(200);
|
|
387
|
-
await tmuxSendKeys(sessionName, ['C-m']);
|
|
388
|
-
|
|
389
|
-
console.log(`📤 Sent to Claude [${sessionName}]: ${content.substring(0, 50)}...`);
|
|
390
|
-
return { success: true };
|
|
391
|
-
} catch (error) {
|
|
392
|
-
return { success: false, error: error.message };
|
|
393
|
-
}
|
|
394
|
-
}
|
|
395
|
-
|
|
396
|
-
/**
|
|
397
|
-
* Start Claude in a session
|
|
398
|
-
* @param {string} sessionName - Session name
|
|
399
|
-
* @param {string} claudeCommand - Claude command to run
|
|
400
|
-
* @param {string} currentPath - Current working path
|
|
401
|
-
* @returns {Object} Start result
|
|
402
|
-
*/
|
|
403
|
-
async function startClaude(sessionName = DEFAULT_SESSION, claudeCommand = 'claude', currentPath, cols, rows) {
|
|
404
|
-
console.log(`[DEBUG startClaude] sessionName=${sessionName}, claudeCommand=${claudeCommand}, currentPath=${currentPath}, cols=${cols}, rows=${rows}`);
|
|
405
|
-
const sessionValidation = validateSessionName(sessionName);
|
|
406
|
-
if (!sessionValidation.valid) {
|
|
407
|
-
console.log(`[DEBUG startClaude] session name validation failed: ${sessionValidation.error}`);
|
|
408
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, sessionValidation.error) };
|
|
409
|
-
}
|
|
410
|
-
|
|
411
|
-
const cmdValidation = validateClaudeCommand(claudeCommand);
|
|
412
|
-
if (!cmdValidation.valid) {
|
|
413
|
-
console.log(`[DEBUG startClaude] command validation failed: ${cmdValidation.error}`);
|
|
414
|
-
return { success: false, error: createError(ErrorCodes.COMMAND_INVALID, cmdValidation.error) };
|
|
415
|
-
}
|
|
416
|
-
const safeCommand = cmdValidation.sanitized;
|
|
417
|
-
console.log(`[DEBUG startClaude] safeCommand=${safeCommand}`);
|
|
418
|
-
|
|
419
|
-
try {
|
|
420
|
-
const sessionExists = await tmuxSessionExists(sessionName);
|
|
421
|
-
console.log(`[DEBUG startClaude] sessionExists=${sessionExists}`);
|
|
422
|
-
if (!sessionExists) {
|
|
423
|
-
await createClaudeSession(sessionName, currentPath, safeCommand, cols, rows);
|
|
424
|
-
console.log(`🚀 Started Claude in session: ${sessionName} with command: ${claudeCommand}`);
|
|
425
|
-
return { success: true, isRunning: true, alreadyRunning: false };
|
|
426
|
-
} else {
|
|
427
|
-
// Resize existing session before launching claude so it uses correct dimensions
|
|
428
|
-
if (cols && rows) {
|
|
429
|
-
try { await tmuxResizeWindow(sessionName, cols, rows); } catch (_e) { /* ignore */ }
|
|
430
|
-
}
|
|
431
|
-
const output = await tmuxCapture(sessionName, 120);
|
|
432
|
-
const running = isClaudeRunning(output);
|
|
433
|
-
console.log(`[DEBUG startClaude] isClaudeRunning=${running}, output last 200 chars: ${output.slice(-200)}`);
|
|
434
|
-
if (running) {
|
|
435
|
-
console.log(`ℹ️ Claude already running in session: ${sessionName}`);
|
|
436
|
-
return { success: true, isRunning: true, alreadyRunning: true };
|
|
437
|
-
}
|
|
438
|
-
// Wait for shell prompt to be ready before sending command.
|
|
439
|
-
// New sessions may still be loading shell config (.zshrc, .bashrc)
|
|
440
|
-
// which includes slow tools like pyenv, nvm, starship, etc.
|
|
441
|
-
console.log('[DEBUG startClaude] waiting for shell ready...');
|
|
442
|
-
await waitForShellReady(sessionName);
|
|
443
|
-
console.log(`[DEBUG startClaude] shell ready, sending command: ${safeCommand}`);
|
|
444
|
-
await tmuxSendKeys(sessionName, ['-l', safeCommand]);
|
|
445
|
-
await tmuxSendKeys(sessionName, ['C-m']);
|
|
446
|
-
}
|
|
447
|
-
console.log(`🚀 Started Claude in session: ${sessionName} with command: ${claudeCommand}`);
|
|
448
|
-
return { success: true, isRunning: true, alreadyRunning: false };
|
|
449
|
-
} catch (error) {
|
|
450
|
-
console.log(`[DEBUG startClaude] error: ${error.message}`);
|
|
451
|
-
return { success: false, error: error.message };
|
|
452
|
-
}
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
/**
|
|
456
|
-
* Wait for shell prompt to be ready by polling tmux output.
|
|
457
|
-
* Detects common prompt endings ($, %, >, #) or gives up after timeout.
|
|
458
|
-
*/
|
|
459
|
-
async function waitForShellReady(sessionName, timeoutMs = 8000) {
|
|
460
|
-
const startTime = Date.now();
|
|
461
|
-
const pollInterval = 300;
|
|
462
|
-
const promptPattern = /[$%>#→❯➜]\s*$/m;
|
|
463
|
-
|
|
464
|
-
console.log(`🔍 [waitForShellReady] START for session: ${sessionName}, timeout: ${timeoutMs}ms`);
|
|
465
|
-
while (Date.now() - startTime < timeoutMs) {
|
|
466
|
-
await sleep(pollInterval);
|
|
467
|
-
try {
|
|
468
|
-
const output = await tmuxCapture(sessionName, 5);
|
|
469
|
-
const trimmed = output.trim();
|
|
470
|
-
const lastLine = trimmed.split('\n').pop() || '';
|
|
471
|
-
const matches = promptPattern.test(trimmed);
|
|
472
|
-
console.log(`🔍 [waitForShellReady] ${Date.now() - startTime}ms | lastLine=${JSON.stringify(lastLine)} | matches=${matches}`);
|
|
473
|
-
if (trimmed.length > 0 && matches) {
|
|
474
|
-
console.log(`✅ [waitForShellReady] shell ready after ${Date.now() - startTime}ms`);
|
|
475
|
-
return;
|
|
476
|
-
}
|
|
477
|
-
} catch (e) {
|
|
478
|
-
console.log(`🔍 [waitForShellReady] capture error: ${e.message}`);
|
|
479
|
-
}
|
|
480
|
-
}
|
|
481
|
-
console.log(`⚠️ [waitForShellReady] TIMEOUT for session: ${sessionName} after ${timeoutMs}ms, proceeding anyway`);
|
|
482
|
-
}
|
|
483
|
-
|
|
484
|
-
/**
|
|
485
|
-
* Stop Claude in a session
|
|
486
|
-
* @param {string} sessionName - Session name
|
|
487
|
-
* @returns {Object} Stop result
|
|
488
|
-
*/
|
|
489
|
-
async function stopClaude(sessionName = DEFAULT_SESSION) {
|
|
490
|
-
const validation = validateSessionName(sessionName);
|
|
491
|
-
if (!validation.valid) {
|
|
492
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, validation.error) };
|
|
493
|
-
}
|
|
494
|
-
|
|
495
|
-
try {
|
|
496
|
-
await tmuxSendKeys(sessionName, ['C-c']);
|
|
497
|
-
await sleep(200);
|
|
498
|
-
await tmuxSendKeys(sessionName, ['C-c']);
|
|
499
|
-
await sleep(200);
|
|
500
|
-
await tmuxSendKeys(sessionName, ['-l', '/exit']);
|
|
501
|
-
await tmuxSendKeys(sessionName, ['C-m']);
|
|
502
|
-
console.log(`🛑 Stopped Claude in session: ${sessionName}`);
|
|
503
|
-
return { success: true };
|
|
504
|
-
} catch (error) {
|
|
505
|
-
return { success: false, error: error.message };
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
const TMUX_KEY_MAP = {
|
|
510
|
-
'Enter': 'Enter',
|
|
511
|
-
'Escape': 'Escape',
|
|
512
|
-
'Up': 'Up',
|
|
513
|
-
'Down': 'Down',
|
|
514
|
-
'Left': 'Left',
|
|
515
|
-
'Right': 'Right',
|
|
516
|
-
'Tab': 'Tab',
|
|
517
|
-
'S-Tab': 'BTab',
|
|
518
|
-
'Space': 'Space',
|
|
519
|
-
'C-c': 'C-c',
|
|
520
|
-
'C-d': 'C-d',
|
|
521
|
-
'C-u': 'C-u',
|
|
522
|
-
'C-z': 'C-z',
|
|
523
|
-
'C-a': 'C-a',
|
|
524
|
-
'C-b': 'C-b',
|
|
525
|
-
'C-e': 'C-e',
|
|
526
|
-
'C-k': 'C-k',
|
|
527
|
-
'C-l': 'C-l',
|
|
528
|
-
'C-r': 'C-r',
|
|
529
|
-
'C-w': 'C-w',
|
|
530
|
-
'Home': 'Home',
|
|
531
|
-
'End': 'End',
|
|
532
|
-
'PageUp': 'PPage',
|
|
533
|
-
'PageDown': 'NPage',
|
|
534
|
-
'PPage': 'PPage',
|
|
535
|
-
'NPage': 'NPage',
|
|
536
|
-
'F1': 'F1',
|
|
537
|
-
'F2': 'F2',
|
|
538
|
-
'F3': 'F3',
|
|
539
|
-
'F4': 'F4',
|
|
540
|
-
'F5': 'F5',
|
|
541
|
-
'F6': 'F6',
|
|
542
|
-
'y': 'y',
|
|
543
|
-
'n': 'n',
|
|
544
|
-
'1': '1',
|
|
545
|
-
'2': '2'
|
|
546
|
-
};
|
|
547
|
-
|
|
548
|
-
/**
|
|
549
|
-
* Send a special key to a session
|
|
550
|
-
* @param {string} key - Key to send
|
|
551
|
-
* @param {string} sessionName - Target session
|
|
552
|
-
* @returns {Object} Send result
|
|
553
|
-
*/
|
|
554
|
-
async function sendKeyToSession(key, sessionName = DEFAULT_SESSION) {
|
|
555
|
-
const sessionValidation = validateSessionName(sessionName);
|
|
556
|
-
if (!sessionValidation.valid) {
|
|
557
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, sessionValidation.error) };
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
const keyValidation = validateTmuxKey(key);
|
|
561
|
-
if (!keyValidation.valid) {
|
|
562
|
-
return { success: false, error: createError(ErrorCodes.COMMAND_INVALID, keyValidation.error) };
|
|
563
|
-
}
|
|
564
|
-
|
|
565
|
-
try {
|
|
566
|
-
const sessionExists = await tmuxSessionExists(sessionName);
|
|
567
|
-
if (!sessionExists) {
|
|
568
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
569
|
-
}
|
|
570
|
-
|
|
571
|
-
const HEX_KEY_MAP = { 'S-Tab': ['1b', '5b', '5a'] }; // ESC [ Z
|
|
572
|
-
if (HEX_KEY_MAP[key]) {
|
|
573
|
-
await tmuxSendKeys(sessionName, ['-H', ...HEX_KEY_MAP[key]]);
|
|
574
|
-
} else {
|
|
575
|
-
const tmuxKey = TMUX_KEY_MAP[key] || key;
|
|
576
|
-
await tmuxSendKeys(sessionName, [tmuxKey]);
|
|
577
|
-
}
|
|
578
|
-
console.log(`⌨️ Sent key [${sessionName}]: ${key}`);
|
|
579
|
-
return { success: true };
|
|
580
|
-
} catch (error) {
|
|
581
|
-
return { success: false, error: error.message };
|
|
582
|
-
}
|
|
583
|
-
}
|
|
584
|
-
|
|
585
|
-
async function sendKeySequence(sessionName, keys) {
|
|
586
|
-
const sessionValidation = validateSessionName(sessionName);
|
|
587
|
-
if (!sessionValidation.valid) {
|
|
588
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, sessionValidation.error) };
|
|
589
|
-
}
|
|
590
|
-
|
|
591
|
-
for (const key of keys) {
|
|
592
|
-
const keyValidation = validateTmuxKey(key);
|
|
593
|
-
if (!keyValidation.valid) {
|
|
594
|
-
return { success: false, error: createError(ErrorCodes.COMMAND_INVALID, keyValidation.error) };
|
|
595
|
-
}
|
|
596
|
-
}
|
|
597
|
-
|
|
598
|
-
try {
|
|
599
|
-
const sessionExists = await tmuxSessionExists(sessionName);
|
|
600
|
-
if (!sessionExists) {
|
|
601
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
602
|
-
}
|
|
603
|
-
|
|
604
|
-
const HEX_KEY_MAP = { 'S-Tab': ['1b', '5b', '5a'] };
|
|
605
|
-
for (const key of keys) {
|
|
606
|
-
if (HEX_KEY_MAP[key]) {
|
|
607
|
-
await tmuxSendKeys(sessionName, ['-H', ...HEX_KEY_MAP[key]]);
|
|
608
|
-
} else {
|
|
609
|
-
const tmuxKey = TMUX_KEY_MAP[key] || key;
|
|
610
|
-
await tmuxSendKeys(sessionName, [tmuxKey]);
|
|
611
|
-
}
|
|
612
|
-
await sleep(50);
|
|
613
|
-
}
|
|
614
|
-
console.log(`⌨️ Sent key sequence [${sessionName}]: ${keys.join(', ')}`);
|
|
615
|
-
return { success: true };
|
|
616
|
-
} catch (error) {
|
|
617
|
-
return { success: false, error: error.message };
|
|
618
|
-
}
|
|
619
|
-
}
|
|
620
|
-
|
|
621
|
-
/**
|
|
622
|
-
* Resize a tmux session window
|
|
623
|
-
* @param {string} sessionName - Session name
|
|
624
|
-
* @param {number} cols - Number of columns
|
|
625
|
-
* @param {number} rows - Number of rows
|
|
626
|
-
* @returns {Object} Result
|
|
627
|
-
*/
|
|
628
|
-
async function resizeSession(sessionName, cols, rows) {
|
|
629
|
-
const validation = validateSessionName(sessionName);
|
|
630
|
-
if (!validation.valid) {
|
|
631
|
-
return { success: false, error: createError(ErrorCodes.SESSION_INVALID_NAME, validation.error) };
|
|
632
|
-
}
|
|
633
|
-
|
|
634
|
-
const safeCols = Math.max(40, Math.min(500, parseInt(cols, 10) || 80));
|
|
635
|
-
const safeRows = Math.max(10, Math.min(200, parseInt(rows, 10) || 50));
|
|
636
|
-
|
|
637
|
-
const exists = await tmuxSessionExists(sessionName);
|
|
638
|
-
if (!exists) {
|
|
639
|
-
return { success: false, error: createSessionNotFoundError(sessionName) };
|
|
640
|
-
}
|
|
641
|
-
|
|
642
|
-
try {
|
|
643
|
-
await tmuxResizeWindow(sessionName, safeCols, safeRows);
|
|
644
|
-
console.log(`📐 Resized session ${sessionName} to ${safeCols}x${safeRows}`);
|
|
645
|
-
return { success: true, cols: safeCols, rows: safeRows };
|
|
646
|
-
} catch (error) {
|
|
647
|
-
return { success: false, error: error.message };
|
|
648
|
-
}
|
|
649
|
-
}
|
|
650
|
-
|
|
651
|
-
module.exports = {
|
|
652
|
-
DEFAULT_SESSION,
|
|
653
|
-
sleep,
|
|
654
|
-
captureOutput,
|
|
655
|
-
getSessionOutput,
|
|
656
|
-
getFullSessionOutput,
|
|
657
|
-
listSessions,
|
|
658
|
-
createClaudeSession,
|
|
659
|
-
createSession,
|
|
660
|
-
attachSession,
|
|
661
|
-
deleteSession,
|
|
662
|
-
killSession,
|
|
663
|
-
sendToClaude,
|
|
664
|
-
startClaude,
|
|
665
|
-
stopClaude,
|
|
666
|
-
sendKeyToSession,
|
|
667
|
-
sendKeySequence,
|
|
668
|
-
resizeSession,
|
|
669
|
-
isClaudeRunning,
|
|
670
|
-
isWaitingForInput
|
|
671
|
-
};
|
|
1
|
+
module.exports = require('../shared/server-core/tmuxManager');
|