mcp-ssh-manager 4.4.0 → 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 CHANGED
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [4.4.1] - 2026-11-27
11
+
12
+ **Sessions: four fixes, reported and traced to the line by @nethinwei (#163).**
13
+ They concern the session tools (start a session, send a command) and the Live page; `ssh_execute` is unchanged.
14
+ The first was seen on a bastion that ignores the request to turn echo off; the other three
15
+ show on any server.
16
+
17
+ ### Fixed
18
+
19
+ - **Every command in a session came back as failed on a server that echoes its input.** The engine finds the end of a command by a marker it makes the shell print, and looked for it anywhere in the text: the echoed copy of the line that prints it was found first, so the exit status was unknown (`null`), the command was reported as failed and its output stopped at that line. The marker is now written as separate arguments, so no echo can contain it, and is read only as a whole line. A session also waits for the shell's own answer before it starts, not for the echo of the question, and asks the shell to stop echoing and to drop its prompt.
20
+ - **`cd` and `export` did not update the session's context.** The engine read the working directory while the session was still busy, was refused ("not ready") and kept the old one. It now reads it before the session is ready again, and also after `pushd`, `popd`, `unset` and `source`.
21
+ - **Prompts and terminal escape sequences were in the output, the working directory and the environment**, and `Working Directory` could stay `null`. The environment was also wrong on every server: `PATH`, `USER` and `HOME` were read by splitting on colons, which `PATH` contains. The output of a session command no longer carries colour codes, window titles, carriage returns or a fixed prompt the shell keeps printing. A prompt that changes with the directory, on a shell that ignores `PS1`, cannot be told from output and stays.
22
+ - **A command sent into a session did not show on the Live page or in the history.** Only `ssh_execute` opened the stream the control plane mirrors, so a session command ran, was checked by the policy and audited, and could not be seen. The tool that sends a command into a session now opens it too: the command appears while it runs, its output as it is printed, and its exit status when it ends. With no control plane running, nothing changes.
23
+
10
24
  ## [4.4.0] - 2026-11-26
11
25
 
12
26
  **A feature release with two interface fixes.** Nothing changes unless you turn the new
@@ -13,8 +13,8 @@
13
13
  class SshManager < Formula
14
14
  desc "SSH server management for AI agents, with approval and audit"
15
15
  homepage "https://github.com/bvisible/mcp-ssh-manager"
16
- url "https://registry.npmjs.org/mcp-ssh-manager/-/mcp-ssh-manager-4.3.6.tgz"
17
- sha256 "2ab2076b2c06fbdccfdeba4f4fc9737ecd7a7838d6fd281687ee979fda2122d2"
16
+ url "https://registry.npmjs.org/mcp-ssh-manager/-/mcp-ssh-manager-4.4.0.tgz"
17
+ sha256 "c9d84858818f0a829ef216ce94d04127a704d1ca6c30de6894c96fe87ce7838c"
18
18
  license "MIT"
19
19
 
20
20
  depends_on "node"
package/README.md CHANGED
@@ -25,7 +25,7 @@
25
25
  [![Desktop app downloads](https://img.shields.io/endpoint?url=https%3A%2F%2Fraw.githubusercontent.com%2Fbvisible%2Fmcp-ssh-manager%2Fstats%2Fdesktop.json&style=flat-square)](https://github.com/bvisible/mcp-ssh-manager/releases/latest)
26
26
  [![GitHub stars](https://img.shields.io/github/stars/bvisible/mcp-ssh-manager?style=flat-square&color=c04500)](https://github.com/bvisible/mcp-ssh-manager/stargazers)
27
27
  [![MCP Toplist](https://mcptoplist.com/badge/io.github.bvisible%2Fmcp-ssh-manager.svg)](https://mcptoplist.com/server/io.github.bvisible%2Fmcp-ssh-manager)
28
- [![Version](https://img.shields.io/badge/release-4.4.0-c04500?style=flat-square)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.4.0)
28
+ [![Version](https://img.shields.io/badge/release-4.4.1-c04500?style=flat-square)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.4.1)
29
29
  [![Claude Code](https://img.shields.io/badge/Claude_Code-Compatible-5A67D8?style=flat-square&logo=anthropic)](https://claude.ai/code)
30
30
  [![OpenAI Codex](https://img.shields.io/badge/OpenAI_Codex-Compatible-00A67E?style=flat-square&logo=openai)](https://openai.com/codex)
31
31
  [![MCP](https://img.shields.io/badge/MCP-Server-orange?style=flat-square)](https://modelcontextprotocol.io)
@@ -58,9 +58,9 @@ An MCP SSH server is the most dangerous tool you can hand an agent: a shell on m
58
58
 
59
59
  ## Choose your workspace
60
60
 
61
- **Desktop application (`4.4.0`):** one installation with its own runtime,
61
+ **Desktop application (`4.4.1`):** one installation with its own runtime,
62
62
  terminal, file browser and server settings. No separate Node.js or npm
63
- installation. [Download it](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.4.0):
63
+ installation. [Download it](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.4.1):
64
64
 
65
65
  | Platform | File | Signature |
66
66
  |---|---|---|
@@ -68,7 +68,7 @@ installation. [Download it](https://github.com/bvisible/mcp-ssh-manager/releases
68
68
  | Windows x64 / arm64 | `…-setup.exe` | **Not code-signed yet.** Windows shows *"Windows protected your PC"*: *More info → Run anyway*. Check the file against the SHA-256 in `release-manifest-win32.json` on the release (`ssh-manager app` does it for you). Signing comes in a later release. |
69
69
  | Linux x64 | `.deb`, `.AppImage` | Unsigned, as Linux packages usually are |
70
70
 
71
- **Already using npm / the CLI?** `npm update -g mcp-ssh-manager` brings 4.4.0,
71
+ **Already using npm / the CLI?** `npm update -g mcp-ssh-manager` brings 4.4.1,
72
72
  and the V4 engine runs without an interface, from your existing `.env`, TOML or
73
73
  process variables — no automatic import, no forced wizard, no approval prompt
74
74
  unless you enable one per server. The one behaviour that tightens is **SSH
@@ -722,6 +722,8 @@ The hero animation ships twice, light and dark, swapped by `<picture>` on `prefe
722
722
 
723
723
  ## What's new
724
724
 
725
+ **[4.4.1](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.4.1) — sessions read what the shell answers, and a session command shows on the Live page.** Sending a command into a session reported it as failed on a server that echoes its input (a bastion that ignores the request to turn echo off), kept the old working directory after `cd` and `export`, and returned prompts and escape codes in the output. It now reads the shell's own answer, and the commands you send into a session appear on the Live page and in the history as `ssh_execute` ones do. Reported and traced to the line by @nethinwei (#163).
726
+
725
727
  **[4.4.0](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.4.0) — keep the desktop app running when you close its window, readable dropdowns in dark mode, and `vim` works in the terminal.** *Options → Appearance* has a new, opt-in switch: with it on, closing the window leaves SSH Manager in the system tray (Windows, Linux) or the menu bar (macOS), so approval requests still reach you; nothing changes until you turn it on. Native `<select>` menus are no longer light text on a white menu in dark mode on Windows and Linux, and vim no longer freezes the interface's terminal on its first screen. From @AnA-0823 (#173, #174) and @congzhou09 (#175). See the [CHANGELOG](CHANGELOG.md#440---2026-11-26).
726
728
 
727
729
  **[4.3.6](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.3.6) — a security fix: a project folder's `.env` could run a command on your machine.** The `.env` of the folder an MCP client was started in could define a server whose `PROXYCOMMAND` ran when a tool connected to it, before any SSH login and whatever the server's mode. That `.env` is no longer read unless you placed it (`~/.ssh-manager/.env`, your home's, the install folder's) or set `SSH_MANAGER_TRUST_PROJECT_ENV=1` in the environment of the engine; the engine says which file it left unread. If your servers were in a `.env` next to the project, move it to `~/.ssh-manager/.env` or name it with `SSH_ENV_PATH`. Reported by @Pythame (GHSA-wxcj-q5hp-wjrw). See the [CHANGELOG](CHANGELOG.md#436---2026-11-25).
@@ -1,12 +1,12 @@
1
1
  {
2
2
  "name": "ssh-manager-desktop",
3
- "version": "4.4.0",
3
+ "version": "4.4.1",
4
4
  "lockfileVersion": 3,
5
5
  "requires": true,
6
6
  "packages": {
7
7
  "": {
8
8
  "name": "ssh-manager-desktop",
9
- "version": "4.4.0",
9
+ "version": "4.4.1",
10
10
  "license": "MIT",
11
11
  "dependencies": {
12
12
  "electron-updater": "^6.8.9",
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "ssh-manager-desktop",
3
3
  "productName": "SSH Manager",
4
- "version": "4.4.0",
4
+ "version": "4.4.1",
5
5
  "private": true,
6
6
  "description": "The SSH Manager control plane as a desktop application",
7
7
  "main": "main.js",
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.4.0 ([release](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.4.0)).
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.4.0",
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: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",
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",
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.4.0",
9
+ "version": "4.4.1",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "mcp-ssh-manager",
14
- "version": "4.4.0",
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
- const result = await session.execute(command, { timeout });
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 }, {
@@ -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 generateMarker(prefix) {
13
- return `${prefix}_${randomUUID().replace(/-/g, '')}`;
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
- // Wait for an explicit readiness marker instead of a shell prompt
90
- const readyMarker = generateMarker('ready');
91
- const readyCommand = `printf '\\n${readyMarker}\\n'`;
92
- this.shell.write(`${readyCommand}\n`);
93
- await this.waitForMarker(readyMarker);
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
- const startTime = Date.now();
242
+ await this.waitUntil(() => findMarkerLine(plainText(this.outputBuffer), marker), timeout, marker);
243
+ return true;
244
+ }
120
245
 
121
- while (Date.now() - startTime < timeout) {
122
- if (this.outputBuffer.includes(marker)) {
123
- return true;
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
- // Wait a bit
127
- await new Promise(resolve => setTimeout(resolve, 100));
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
- throw new Error(`Timeout waiting for marker: ${marker}`);
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
- // Get current directory
139
- const pwdResult = await this.execute('pwd', { silent: true });
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 endMarker = generateMarker('cmd');
188
-
189
- // Send command wrapped in an explicit completion marker
190
- this.shell.write(`set +e\n${command}\n__mcp_status=$?\nprintf '\\n${endMarker}:%s\\n' "$__mcp_status"\n`);
191
-
192
- // Wait for command completion marker
193
- await this.waitForMarker(endMarker, options.timeout || 30000);
194
-
195
- const markerIndex = this.outputBuffer.indexOf(endMarker);
196
- if (markerIndex < 0) {
197
- throw new Error(`Command marker not found: ${endMarker}`);
198
- }
199
- const markerLine = this.outputBuffer.slice(markerIndex).split(/\r?\n/, 1)[0];
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
  */