mcp-ssh-manager 4.3.6 → 4.4.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/CHANGELOG.md +37 -0
- package/Formula/ssh-manager.rb +2 -2
- package/README.md +9 -5
- package/desktop/electron/electron-builder.yml +1 -0
- package/desktop/electron/main.js +21 -14
- package/desktop/electron/package-lock.json +2 -2
- package/desktop/electron/package.json +1 -1
- package/desktop/electron/window-close.mjs +35 -0
- package/dist/ui/app.css +1 -1
- package/dist/ui/app.js +123 -123
- package/docs/MIGRATION.md +1 -1
- package/package.json +5 -2
- package/server.json +2 -2
- package/src/index.js +15 -1
- package/src/session-manager.js +260 -53
package/docs/MIGRATION.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Upgrading from 3.8 to 4.0
|
|
2
2
|
|
|
3
|
-
**4.0 is released, on npm and as a desktop application**; the latest is 4.
|
|
3
|
+
**4.0 is released, on npm and as a desktop application**; the latest is 4.4.1 ([release](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.4.1)).
|
|
4
4
|
The last 3.8 release is 3.8.7, for anyone who pins the 3.8 line.
|
|
5
5
|
|
|
6
6
|
The upgrade path preserves headless npm/CLI use. The application, vault import
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "mcp-ssh-manager",
|
|
3
|
-
"version": "4.
|
|
3
|
+
"version": "4.4.1",
|
|
4
4
|
"mcpName": "io.github.bvisible/mcp-ssh-manager",
|
|
5
5
|
"description": "MCP server for SSH: let AI agents (Claude Code, Codex, any MCP client) run commands, transfer files and manage servers over SSH, with human approval, an encrypted vault and a live audit trail.",
|
|
6
6
|
"main": "src/index.js",
|
|
@@ -14,13 +14,15 @@
|
|
|
14
14
|
"setup": "npm install && pip install -r tools/requirements.txt",
|
|
15
15
|
"configure": "python tools/server-manager.py",
|
|
16
16
|
"test-connection": "python tools/test-connection.py",
|
|
17
|
-
"test": "npm run test:lockfile && npm run test:sudostdin && npm run test:vault && npm run test:recovery && npm run test:upgrade && npm run test:notify && npm run test:commands && npm run test:commandlog && npm run test:portability && npm run test:approval && npm run test:controlplane && npm run test:terminal && npm run test:files && npm run test:livestream && npm run test:livefailure && npm run test:transferpaths && npm run test:skills && npm run test:redaction && npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:shellsegments && npm run test:policynames && npm run test:auditsuccess && npm run test:ping && npm run test:config && npm run test:fieldnames && npm run test:groups && npm run test:agentforward && npm run test:agentkey && npm run test:certpath && npm run test:agentannounce && npm run test:autherrors && npm run test:envchoice && npm run test:projectenv && npm run test:lifecycle && npm run test:tunnel && npm run test:sync && npm run test:sync-path && npm run test:dbquoting && npm run test:dbinjection && npm run test:quoteprops && npm run test:backupinjection && npm run test:dbrowcount && npm run test:dbclientcmds && npm run test:migration && npm run test:security && npm run test:hostkeys && npm run test:proxy && npm run test:working-directory && npm run test:groups-persistence && npm run test:release && npm run test:cli-experience && npm run test:desktop-install && npm run test:agent-clients && npm run test:appupdate && npm run test:preview && npm run test:desktop-smoke && npm run test:local-shell && npm run test:cli-edit && npm run test:timeoutwrap && npm run test:downloadstats && npm run test:remotetunnel && npm run test:connsharing && npm run test:auditcoverage && npm run test:background && npm run test:quietstderr && npm run test:sshguard && npm run test:locale && npm run test:langtool && npm run test:healthdisks && npm run test:backupintegrity && npm run test:clienvlines && npm run test:clicodex",
|
|
17
|
+
"test": "npm run test:lockfile && npm run test:sudostdin && npm run test:vault && npm run test:recovery && npm run test:upgrade && npm run test:notify && npm run test:commands && npm run test:commandlog && npm run test:portability && npm run test:approval && npm run test:controlplane && npm run test:terminal && npm run test:files && npm run test:livestream && npm run test:livefailure && npm run test:sessionshell && npm run test:sessionlive && npm run test:transferpaths && npm run test:skills && npm run test:redaction && npm run test:profiles && npm run test:aliases && npm run test:hooks && npm run test:tools && npm run test:policy && npm run test:shellsegments && npm run test:policynames && npm run test:auditsuccess && npm run test:ping && npm run test:config && npm run test:fieldnames && npm run test:groups && npm run test:agentforward && npm run test:agentkey && npm run test:certpath && npm run test:agentannounce && npm run test:autherrors && npm run test:envchoice && npm run test:projectenv && npm run test:lifecycle && npm run test:tunnel && npm run test:sync && npm run test:sync-path && npm run test:dbquoting && npm run test:dbinjection && npm run test:quoteprops && npm run test:backupinjection && npm run test:dbrowcount && npm run test:dbclientcmds && npm run test:migration && npm run test:security && npm run test:hostkeys && npm run test:proxy && npm run test:working-directory && npm run test:groups-persistence && npm run test:release && npm run test:cli-experience && npm run test:desktop-install && npm run test:agent-clients && npm run test:appupdate && npm run test:preview && npm run test:desktop-smoke && npm run test:local-shell && npm run test:windowclose && npm run test:cli-edit && npm run test:timeoutwrap && npm run test:downloadstats && npm run test:remotetunnel && npm run test:connsharing && npm run test:auditcoverage && npm run test:background && npm run test:quietstderr && npm run test:sshguard && npm run test:locale && npm run test:langtool && npm run test:healthdisks && npm run test:backupintegrity && npm run test:clienvlines && npm run test:clicodex",
|
|
18
18
|
"test:lockfile": "node tests/test-lockfile.js",
|
|
19
19
|
"test:sudostdin": "node tests/test-sudo-stdin.js",
|
|
20
20
|
"test:vault": "node tests/test-secret-store.js",
|
|
21
21
|
"test:approval": "node tests/test-approval.js",
|
|
22
22
|
"test:controlplane": "node tests/test-control-plane.js",
|
|
23
23
|
"test:livestream": "node tests/test-live-stream.js",
|
|
24
|
+
"test:sessionshell": "node tests/test-session-shell.js",
|
|
25
|
+
"test:sessionlive": "node tests/test-session-live.js",
|
|
24
26
|
"test:livefailure": "node tests/test-live-stream-failure.js",
|
|
25
27
|
"test:transferpaths": "node tests/test-transfer-paths.js",
|
|
26
28
|
"test:skills": "node tests/test-skills.js",
|
|
@@ -94,6 +96,7 @@
|
|
|
94
96
|
"test:preview": "node tests/test-preview-candidate.js",
|
|
95
97
|
"test:desktop-smoke": "node tests/test-desktop-smoke.js",
|
|
96
98
|
"test:local-shell": "node tests/test-local-shell.js",
|
|
99
|
+
"test:windowclose": "node tests/test-window-close.js",
|
|
97
100
|
"test:policynames": "node tests/test-policy-name-resolution.js",
|
|
98
101
|
"test:locale": "node tests/test-locale.js",
|
|
99
102
|
"test:langtool": "node tests/test-language-tool.js",
|
package/server.json
CHANGED
|
@@ -6,12 +6,12 @@
|
|
|
6
6
|
"url": "https://github.com/bvisible/mcp-ssh-manager",
|
|
7
7
|
"source": "github"
|
|
8
8
|
},
|
|
9
|
-
"version": "4.
|
|
9
|
+
"version": "4.4.1",
|
|
10
10
|
"packages": [
|
|
11
11
|
{
|
|
12
12
|
"registryType": "npm",
|
|
13
13
|
"identifier": "mcp-ssh-manager",
|
|
14
|
-
"version": "4.
|
|
14
|
+
"version": "4.4.1",
|
|
15
15
|
"transport": {
|
|
16
16
|
"type": "stdio"
|
|
17
17
|
},
|
package/src/index.js
CHANGED
|
@@ -1871,7 +1871,21 @@ registerToolConditional(
|
|
|
1871
1871
|
auditServer = session.serverName;
|
|
1872
1872
|
|
|
1873
1873
|
const startTime = Date.now();
|
|
1874
|
-
|
|
1874
|
+
// Mirror the command to the control plane while it runs, as ssh_execute
|
|
1875
|
+
// does, so it shows on the Live page and in the history. Opened only for
|
|
1876
|
+
// a command that will run: a busy or closed session refuses it first.
|
|
1877
|
+
const live = session.isReady() ? openStream(session.serverName, command) : null;
|
|
1878
|
+
let result;
|
|
1879
|
+
try {
|
|
1880
|
+
result = await session.execute(command, {
|
|
1881
|
+
timeout,
|
|
1882
|
+
onOutput: live ? text => live.write('stdout', text) : undefined
|
|
1883
|
+
});
|
|
1884
|
+
} finally {
|
|
1885
|
+
// However the attempt ends the window is told; no result means no exit
|
|
1886
|
+
// code, and end() then reports -1, as for ssh_execute.
|
|
1887
|
+
live?.end(result?.exitCode);
|
|
1888
|
+
}
|
|
1875
1889
|
const duration = Date.now() - startTime;
|
|
1876
1890
|
|
|
1877
1891
|
await auditOk(session.serverName, 'ssh_session_send', { session: sessionId, command }, {
|
package/src/session-manager.js
CHANGED
|
@@ -9,10 +9,68 @@ import { logger } from './logger.js';
|
|
|
9
9
|
// Map to store active sessions
|
|
10
10
|
const sessions = new Map();
|
|
11
11
|
|
|
12
|
-
function
|
|
13
|
-
return
|
|
12
|
+
function generateId() {
|
|
13
|
+
return randomUUID().replace(/-/g, '');
|
|
14
14
|
}
|
|
15
15
|
|
|
16
|
+
// Terminal escape sequences a pty shell may print around its output: colours,
|
|
17
|
+
// cursor moves, bracketed-paste switches (CSI), window titles (OSC) and the
|
|
18
|
+
// two-character forms. Built from strings so the source holds no raw control
|
|
19
|
+
// character.
|
|
20
|
+
const ESC = String.fromCharCode(27);
|
|
21
|
+
const BEL = String.fromCharCode(7);
|
|
22
|
+
const ANSI_PATTERN = new RegExp(
|
|
23
|
+
[
|
|
24
|
+
`${ESC}\\[[0-?]*[ -/]*[@-~]`,
|
|
25
|
+
`${ESC}\\][^${BEL}${ESC}]*(?:${BEL}|${ESC}\\\\)`,
|
|
26
|
+
`${ESC}[()][A-Za-z0-9]`,
|
|
27
|
+
`${ESC}[=>78DEHMNOZ\\\\^_c]`
|
|
28
|
+
].join('|'),
|
|
29
|
+
'g'
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* What the shell printed, without the terminal's decoration: no escape
|
|
34
|
+
* sequences, LF line ends (a pty turns each LF into CRLF), and a carriage
|
|
35
|
+
* return keeps what a terminal would still show, the text after the last one.
|
|
36
|
+
* @param {string} text - Raw shell output
|
|
37
|
+
* @returns {string} Plain text
|
|
38
|
+
*/
|
|
39
|
+
function plainText(text) {
|
|
40
|
+
return text
|
|
41
|
+
.replace(ANSI_PATTERN, '')
|
|
42
|
+
.replace(/\r\n/g, '\n')
|
|
43
|
+
.split('\n')
|
|
44
|
+
.map(line => (line.includes('\r') ? line.split('\r').filter(Boolean).pop() ?? '' : line))
|
|
45
|
+
.join('\n');
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* Find a marker that stands alone on a line.
|
|
50
|
+
*
|
|
51
|
+
* The marker is never written whole. The command line that prints it spells
|
|
52
|
+
* it as separate printf arguments, so a server that echoes what it is sent
|
|
53
|
+
* (it may ignore the request to turn echo off) gives back a line that does not
|
|
54
|
+
* contain the marker. Only the shell's real answer matches. Matching anywhere
|
|
55
|
+
* in the text, as this used to, found the echoed line first.
|
|
56
|
+
*
|
|
57
|
+
* @param {string} text - Plain text to search
|
|
58
|
+
* @param {string} marker - The marker, for example `cmd_<id>`
|
|
59
|
+
* @returns {{index: number, length: number, status: number|null}|null} Where the line is, and the status it carries
|
|
60
|
+
*/
|
|
61
|
+
function findMarkerLine(text, marker) {
|
|
62
|
+
const found = new RegExp(`^${marker}(?::(\\d+))?[ \\t]*$`, 'm').exec(text);
|
|
63
|
+
if (!found) return null;
|
|
64
|
+
return {
|
|
65
|
+
index: found.index,
|
|
66
|
+
length: found[0].length,
|
|
67
|
+
status: found[1] === undefined ? null : Number.parseInt(found[1], 10)
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Commands after which the working directory or the environment may differ.
|
|
72
|
+
const CONTEXT_COMMAND = /^\s*(?:cd|pushd|popd|export|unset|source|\.)(?:\s|$)/;
|
|
73
|
+
|
|
16
74
|
// Session states
|
|
17
75
|
const SESSION_STATES = {
|
|
18
76
|
INITIALIZING: 'initializing',
|
|
@@ -39,6 +97,10 @@ class SSHSession {
|
|
|
39
97
|
this.shell = null;
|
|
40
98
|
this.outputBuffer = '';
|
|
41
99
|
this.errorBuffer = '';
|
|
100
|
+
// The prompt a server keeps printing when it will not stop (see initialize).
|
|
101
|
+
this.prompt = '';
|
|
102
|
+
/** @type {(() => void)|null} Called whenever the shell prints something */
|
|
103
|
+
this.onShellData = null;
|
|
42
104
|
}
|
|
43
105
|
|
|
44
106
|
/**
|
|
@@ -64,6 +126,7 @@ class SSHSession {
|
|
|
64
126
|
this.shell.on('data', (data) => {
|
|
65
127
|
this.outputBuffer += data.toString();
|
|
66
128
|
this.lastActivity = new Date();
|
|
129
|
+
this.onShellData?.();
|
|
67
130
|
|
|
68
131
|
// Log output in verbose mode
|
|
69
132
|
if (logger.verbose) {
|
|
@@ -86,11 +149,32 @@ class SSHSession {
|
|
|
86
149
|
});
|
|
87
150
|
});
|
|
88
151
|
|
|
89
|
-
//
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
152
|
+
// The ECHO mode above is only a request, and a server may ignore it; a
|
|
153
|
+
// prompt also comes back after every line, and bash's line editing prints
|
|
154
|
+
// a newline and bracketed-paste codes around each line it reads. Ask the
|
|
155
|
+
// shell itself to stop all of it, and wait for an explicit readiness
|
|
156
|
+
// marker rather than a prompt. A shell that is not a shell (a bastion
|
|
157
|
+
// menu) answers none of it, and reading the output no longer depends on it.
|
|
158
|
+
const readyId = generateId();
|
|
159
|
+
this.shell.write([
|
|
160
|
+
'stty -echo 2>/dev/null',
|
|
161
|
+
'PS1=\'\'; PS2=\'\'; PROMPT_COMMAND=\'\'',
|
|
162
|
+
'[ -n "$ZSH_VERSION" ] && unsetopt zle',
|
|
163
|
+
'set +o emacs +o vi 2>/dev/null',
|
|
164
|
+
`printf '\\n%s%s\\n' ready_ ${readyId}`
|
|
165
|
+
].join('\n') + '\n');
|
|
166
|
+
await this.waitUntil(
|
|
167
|
+
() => findMarkerLine(plainText(this.outputBuffer), `ready_${readyId}`),
|
|
168
|
+
5000,
|
|
169
|
+
`ready_${readyId}`
|
|
170
|
+
);
|
|
171
|
+
|
|
172
|
+
// What is left after the marker is the shell's prompt, when it still
|
|
173
|
+
// prints one. A fixed prompt is removed from the lines of every command's
|
|
174
|
+
// output; one that changes (the directory in it) cannot be, so a shell
|
|
175
|
+
// that ignores PS1 keeps its prompt in the output.
|
|
176
|
+
await new Promise(resolve => setTimeout(resolve, 150));
|
|
177
|
+
this.prompt = this.learnPrompt(readyId);
|
|
94
178
|
|
|
95
179
|
// Allow context queries through standard execute flow
|
|
96
180
|
this.state = SESSION_STATES.READY;
|
|
@@ -112,42 +196,165 @@ class SSHSession {
|
|
|
112
196
|
}
|
|
113
197
|
}
|
|
114
198
|
|
|
199
|
+
/**
|
|
200
|
+
* The prompt the shell printed after the readiness marker, if any.
|
|
201
|
+
* @param {string} readyId - Id of the readiness marker
|
|
202
|
+
* @returns {string} The prompt, or an empty string
|
|
203
|
+
*/
|
|
204
|
+
learnPrompt(readyId) {
|
|
205
|
+
const text = plainText(this.outputBuffer);
|
|
206
|
+
const marker = findMarkerLine(text, `ready_${readyId}`);
|
|
207
|
+
if (!marker) return '';
|
|
208
|
+
const after = text.slice(marker.index + marker.length).replace(/^\n/, '');
|
|
209
|
+
// A prompt is one unfinished line; anything longer is output we do not know.
|
|
210
|
+
return after.includes('\n') ? '' : after;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/**
|
|
214
|
+
* Wait until `find` returns something, as the shell prints.
|
|
215
|
+
* @param {() => any} find - Returns a truthy value once what is awaited has arrived
|
|
216
|
+
* @param {number} timeout - Milliseconds to wait
|
|
217
|
+
* @param {string} label - What is awaited, for the error
|
|
218
|
+
* @returns {Promise<any>} Whatever `find` returned
|
|
219
|
+
*/
|
|
220
|
+
waitUntil(find, timeout, label) {
|
|
221
|
+
return new Promise((resolve, reject) => {
|
|
222
|
+
const done = () => { clearTimeout(timer); this.onShellData = null; };
|
|
223
|
+
const timer = setTimeout(() => {
|
|
224
|
+
done();
|
|
225
|
+
reject(new Error(`Timeout waiting for marker: ${label}`));
|
|
226
|
+
}, timeout);
|
|
227
|
+
const check = () => {
|
|
228
|
+
const found = find();
|
|
229
|
+
if (!found) return;
|
|
230
|
+
done();
|
|
231
|
+
resolve(found);
|
|
232
|
+
};
|
|
233
|
+
this.onShellData = check;
|
|
234
|
+
check();
|
|
235
|
+
});
|
|
236
|
+
}
|
|
237
|
+
|
|
115
238
|
/**
|
|
116
239
|
* Wait for a marker in shell output
|
|
117
240
|
*/
|
|
118
241
|
async waitForMarker(marker, timeout = 5000) {
|
|
119
|
-
|
|
242
|
+
await this.waitUntil(() => findMarkerLine(plainText(this.outputBuffer), marker), timeout, marker);
|
|
243
|
+
return true;
|
|
244
|
+
}
|
|
120
245
|
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
246
|
+
/**
|
|
247
|
+
* What a command printed so far, and how it ended.
|
|
248
|
+
*
|
|
249
|
+
* The text between the command's start marker and its end marker, without
|
|
250
|
+
* the terminal's escape sequences and without the prompt. Before the end
|
|
251
|
+
* marker has arrived, only complete lines count.
|
|
252
|
+
*
|
|
253
|
+
* @param {string} id - The command's id
|
|
254
|
+
* @returns {{text: string, done: boolean, exitCode: number|null}|null} Null until the start marker has arrived
|
|
255
|
+
*/
|
|
256
|
+
readCommand(id) {
|
|
257
|
+
const text = plainText(this.outputBuffer);
|
|
258
|
+
const start = findMarkerLine(text, `start_${id}`);
|
|
259
|
+
if (!start) return null;
|
|
260
|
+
const from = start.index + start.length + (text[start.index + start.length] === '\n' ? 1 : 0);
|
|
261
|
+
const rest = text.slice(from);
|
|
262
|
+
const end = findMarkerLine(rest, `cmd_${id}`);
|
|
263
|
+
let body;
|
|
264
|
+
if (end) {
|
|
265
|
+
body = rest.slice(0, end.index);
|
|
266
|
+
} else {
|
|
267
|
+
body = rest.slice(0, rest.lastIndexOf('\n') + 1);
|
|
268
|
+
}
|
|
269
|
+
if (this.prompt) {
|
|
270
|
+
// The shell prints its prompt before reading each line it is sent, so
|
|
271
|
+
// several can pile up in front of the text that follows them.
|
|
272
|
+
const withoutPrompts = line => {
|
|
273
|
+
let rest = line;
|
|
274
|
+
while (rest.startsWith(this.prompt)) rest = rest.slice(this.prompt.length);
|
|
275
|
+
return rest;
|
|
276
|
+
};
|
|
277
|
+
body = body.split('\n').map(withoutPrompts).join('\n');
|
|
278
|
+
}
|
|
279
|
+
return { text: body, done: Boolean(end), exitCode: end ? end.status : null };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/**
|
|
283
|
+
* Send a command wrapped in markers and wait for it to finish.
|
|
284
|
+
* Does not touch the session state: callers do.
|
|
285
|
+
*
|
|
286
|
+
* @param {string} command - The command line
|
|
287
|
+
* @param {{timeout?: number, onOutput?: (text: string) => void}} [options] - `onOutput` receives the output as it arrives
|
|
288
|
+
* @returns {Promise<{output: string, exitCode: number|null}>} The output, and the status the shell reported
|
|
289
|
+
*/
|
|
290
|
+
async run(command, options = {}) {
|
|
291
|
+
// Clear buffers
|
|
292
|
+
this.outputBuffer = '';
|
|
293
|
+
this.errorBuffer = '';
|
|
294
|
+
|
|
295
|
+
const id = generateId();
|
|
296
|
+
|
|
297
|
+
// Both markers are spelled as separate printf arguments (see findMarkerLine).
|
|
298
|
+
this.shell.write(
|
|
299
|
+
`set +e\nprintf '\\n%s%s\\n' start_ ${id}\n${command}\n__mcp_status=$?\nprintf '\\n%s%s:%s\\n' cmd_ ${id} "$__mcp_status"\n`
|
|
300
|
+
);
|
|
301
|
+
|
|
302
|
+
// Forward what the command prints while it runs. Only whole lines, and
|
|
303
|
+
// never the trailing blank lines: the next chunk may continue them.
|
|
304
|
+
let forwarded = '';
|
|
305
|
+
const forward = (text) => {
|
|
306
|
+
if (!options.onOutput) return;
|
|
307
|
+
const shown = text.replace(/\n+$/, '');
|
|
308
|
+
if (shown.length <= forwarded.length || !shown.startsWith(forwarded)) return;
|
|
309
|
+
options.onOutput(shown.slice(forwarded.length));
|
|
310
|
+
forwarded = shown;
|
|
311
|
+
};
|
|
125
312
|
|
|
126
|
-
|
|
127
|
-
|
|
313
|
+
const finished = await this.waitUntil(() => {
|
|
314
|
+
const seen = this.readCommand(id);
|
|
315
|
+
if (seen && !seen.done) forward(seen.text);
|
|
316
|
+
return seen?.done ? seen : null;
|
|
317
|
+
}, options.timeout || 30000, `cmd_${id}`);
|
|
318
|
+
|
|
319
|
+
const output = finished.text.replace(/\n+$/, '');
|
|
320
|
+
forward(output);
|
|
321
|
+
return { output, exitCode: finished.exitCode };
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Read the working directory and a few variables back from the shell.
|
|
326
|
+
* Does not touch the session state: callers do.
|
|
327
|
+
*/
|
|
328
|
+
async refreshContext() {
|
|
329
|
+
const pwdResult = await this.run('pwd');
|
|
330
|
+
if (pwdResult.exitCode === 0) {
|
|
331
|
+
this.context.cwd = pwdResult.output.trim();
|
|
128
332
|
}
|
|
129
333
|
|
|
130
|
-
|
|
334
|
+
// One value per line: PATH holds colons, so they cannot separate the three.
|
|
335
|
+
const envResult = await this.run('printf \'%s\\n%s\\n%s\\n\' "$PATH" "$USER" "$HOME"');
|
|
336
|
+
if (envResult.exitCode === 0) {
|
|
337
|
+
const [PATH, USER, HOME] = envResult.output.split('\n');
|
|
338
|
+
this.context.env = { PATH, USER, HOME };
|
|
339
|
+
}
|
|
131
340
|
}
|
|
132
341
|
|
|
133
342
|
/**
|
|
134
343
|
* Update session context (pwd, env)
|
|
135
344
|
*/
|
|
136
345
|
async updateContext() {
|
|
346
|
+
if (this.state !== SESSION_STATES.READY) {
|
|
347
|
+
logger.warn(`Failed to update context for session ${this.id}`, {
|
|
348
|
+
error: `Session ${this.id} is not ready (state: ${this.state})`
|
|
349
|
+
});
|
|
350
|
+
return;
|
|
351
|
+
}
|
|
352
|
+
this.state = SESSION_STATES.BUSY;
|
|
137
353
|
try {
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
if (pwdResult.success) {
|
|
141
|
-
this.context.cwd = pwdResult.output.trim();
|
|
142
|
-
}
|
|
143
|
-
|
|
144
|
-
// Get environment variables (selective)
|
|
145
|
-
const envResult = await this.execute('echo $PATH:$USER:$HOME', { silent: true });
|
|
146
|
-
if (envResult.success) {
|
|
147
|
-
const [path, user, home] = envResult.output.trim().split(':');
|
|
148
|
-
this.context.env = { PATH: path, USER: user, HOME: home };
|
|
149
|
-
}
|
|
354
|
+
await this.refreshContext();
|
|
355
|
+
this.state = SESSION_STATES.READY;
|
|
150
356
|
} catch (error) {
|
|
357
|
+
this.state = SESSION_STATES.ERROR;
|
|
151
358
|
logger.warn(`Failed to update context for session ${this.id}`, {
|
|
152
359
|
error: error.message
|
|
153
360
|
});
|
|
@@ -156,6 +363,9 @@ class SSHSession {
|
|
|
156
363
|
|
|
157
364
|
/**
|
|
158
365
|
* Execute a command in the session
|
|
366
|
+
*
|
|
367
|
+
* @param {string} command - The command line
|
|
368
|
+
* @param {{timeout?: number, silent?: boolean, onOutput?: (text: string) => void}} [options] - `onOutput` receives the output as it arrives
|
|
159
369
|
*/
|
|
160
370
|
async execute(command, options = {}) {
|
|
161
371
|
if (this.state !== SESSION_STATES.READY) {
|
|
@@ -166,10 +376,6 @@ class SSHSession {
|
|
|
166
376
|
this.lastActivity = new Date();
|
|
167
377
|
|
|
168
378
|
try {
|
|
169
|
-
// Clear buffers
|
|
170
|
-
this.outputBuffer = '';
|
|
171
|
-
this.errorBuffer = '';
|
|
172
|
-
|
|
173
379
|
// Add to history unless silent
|
|
174
380
|
if (!options.silent) {
|
|
175
381
|
this.context.history.push({
|
|
@@ -184,33 +390,26 @@ class SSHSession {
|
|
|
184
390
|
});
|
|
185
391
|
}
|
|
186
392
|
|
|
187
|
-
const
|
|
188
|
-
|
|
189
|
-
//
|
|
190
|
-
this
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
const statusMatch = markerLine.match(/:(\d+)$/);
|
|
201
|
-
const exitCode = statusMatch ? Number.parseInt(statusMatch[1], 10) : null;
|
|
202
|
-
const output = this.outputBuffer.slice(0, markerIndex).replace(/\r?\n+$/, '');
|
|
203
|
-
const success = exitCode === 0;
|
|
204
|
-
|
|
205
|
-
// Update context if command might have changed it
|
|
206
|
-
if (command.startsWith('cd ') || command.startsWith('export ')) {
|
|
207
|
-
await this.updateContext();
|
|
393
|
+
const { output, exitCode } = await this.run(command, options);
|
|
394
|
+
|
|
395
|
+
// Update context if command might have changed it. The session is still
|
|
396
|
+
// busy here, so this reads the shell directly: going through execute()
|
|
397
|
+
// was refused ("not ready") and the context stayed as it was.
|
|
398
|
+
if (CONTEXT_COMMAND.test(command)) {
|
|
399
|
+
try {
|
|
400
|
+
await this.refreshContext();
|
|
401
|
+
} catch (error) {
|
|
402
|
+
logger.warn(`Failed to update context for session ${this.id}`, {
|
|
403
|
+
error: error.message
|
|
404
|
+
});
|
|
405
|
+
}
|
|
208
406
|
}
|
|
209
407
|
|
|
210
408
|
this.state = SESSION_STATES.READY;
|
|
211
409
|
|
|
212
410
|
return {
|
|
213
|
-
success,
|
|
411
|
+
success: exitCode === 0,
|
|
412
|
+
exitCode,
|
|
214
413
|
output,
|
|
215
414
|
error: this.errorBuffer,
|
|
216
415
|
session: this.id
|
|
@@ -226,6 +425,14 @@ class SSHSession {
|
|
|
226
425
|
}
|
|
227
426
|
}
|
|
228
427
|
|
|
428
|
+
/**
|
|
429
|
+
* Can a command be sent now?
|
|
430
|
+
* @returns {boolean} True when the session is ready
|
|
431
|
+
*/
|
|
432
|
+
isReady() {
|
|
433
|
+
return this.state === SESSION_STATES.READY;
|
|
434
|
+
}
|
|
435
|
+
|
|
229
436
|
/**
|
|
230
437
|
* Set session variable
|
|
231
438
|
*/
|