mcp-ssh-manager 4.4.0 → 4.4.2

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,28 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [4.4.2] - 2026-11-28
11
+
12
+ **A session starts again on CentOS 7.** 4.4.1 broke it there; found, traced and fixed by @nethinwei (#163, #180). Nothing else changes.
13
+
14
+ ### Fixed
15
+
16
+ - **A session could not start on CentOS 7, nor when the shell took more than five seconds to answer (4.4.1, #163).** A new session sends a few set-up lines (stop the echo, drop the prompt, turn line editing off), then a readiness marker, and gave the shell five seconds to print it. On bash 4.2 (CentOS 7) the lines sent after `set +o emacs` in the same write never run, so the marker never came; line editing seems to take the lines it had read ahead with it. Behind a bastion, or with a heavy rc file, the shell can also take more than five seconds to answer. The set-up lines now go on one line, and the session waits up to thirty seconds.
17
+
18
+ ## [4.4.1] - 2026-11-27
19
+
20
+ **Sessions: four fixes, reported and traced to the line by @nethinwei (#163).**
21
+ They concern the session tools (start a session, send a command) and the Live page; `ssh_execute` is unchanged.
22
+ The first was seen on a bastion that ignores the request to turn echo off; the other three
23
+ show on any server.
24
+
25
+ ### Fixed
26
+
27
+ - **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.
28
+ - **`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`.
29
+ - **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.
30
+ - **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.
31
+
10
32
  ## [4.4.0] - 2026-11-26
11
33
 
12
34
  **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.1.tgz"
17
+ sha256 "7b699c25345a95f5ef3388344c149a456fa8dd3b5b23388aa7e7b0374e496bc8"
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.2-c04500?style=flat-square)](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.4.2)
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.2`):** 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.2):
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.2,
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,10 @@ 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.2](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.4.2) — a session starts again on CentOS 7, and on a host that takes seconds to answer.** 4.4.1 sent a new session's set-up in a way bash 4.2 drops, so no session started on CentOS 7, and it gave the shell only five seconds to answer, too short behind a bastion. The set-up now goes on one line and the session waits up to thirty seconds. Found, traced and fixed by @nethinwei (#163, #180).
726
+
727
+ **[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).
728
+
725
729
  **[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
730
 
727
731
  **[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.2",
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.2",
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.2",
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.2 ([release](https://github.com/bvisible/mcp-ssh-manager/releases/tag/v4.4.2)).
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.2",
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.2",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "mcp-ssh-manager",
14
- "version": "4.4.0",
14
+ "version": "4.4.2",
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,72 @@ 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
+ // How long a new session waits for its shell to answer. A bastion can take
72
+ // more than five seconds to reach the host.
73
+ const READY_TIMEOUT = 30000;
74
+
75
+ // Commands after which the working directory or the environment may differ.
76
+ const CONTEXT_COMMAND = /^\s*(?:cd|pushd|popd|export|unset|source|\.)(?:\s|$)/;
77
+
16
78
  // Session states
17
79
  const SESSION_STATES = {
18
80
  INITIALIZING: 'initializing',
@@ -39,6 +101,10 @@ class SSHSession {
39
101
  this.shell = null;
40
102
  this.outputBuffer = '';
41
103
  this.errorBuffer = '';
104
+ // The prompt a server keeps printing when it will not stop (see initialize).
105
+ this.prompt = '';
106
+ /** @type {(() => void)|null} Called whenever the shell prints something */
107
+ this.onShellData = null;
42
108
  }
43
109
 
44
110
  /**
@@ -64,6 +130,7 @@ class SSHSession {
64
130
  this.shell.on('data', (data) => {
65
131
  this.outputBuffer += data.toString();
66
132
  this.lastActivity = new Date();
133
+ this.onShellData?.();
67
134
 
68
135
  // Log output in verbose mode
69
136
  if (logger.verbose) {
@@ -86,11 +153,37 @@ class SSHSession {
86
153
  });
87
154
  });
88
155
 
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);
156
+ // The ECHO mode above is only a request, and a server may ignore it; a
157
+ // prompt also comes back after every line, and bash's line editing prints
158
+ // a newline and bracketed-paste codes around each line it reads. Ask the
159
+ // shell itself to stop all of it, and wait for an explicit readiness
160
+ // marker rather than a prompt. A shell that is not a shell (a bastion
161
+ // menu) answers none of it, and reading the output no longer depends on it.
162
+ //
163
+ // All of it goes on one line. On bash 4.2 (CentOS 7) the lines sent
164
+ // after `set +o emacs` in the same write never run, so the marker never
165
+ // came; line editing seems to take what it had read ahead with it. On
166
+ // one line, the marker is read before editing goes off.
167
+ const readyId = generateId();
168
+ this.shell.write([
169
+ 'stty -echo 2>/dev/null',
170
+ 'PS1=\'\'; PS2=\'\'; PROMPT_COMMAND=\'\'',
171
+ '[ -n "$ZSH_VERSION" ] && unsetopt zle',
172
+ 'set +o emacs +o vi 2>/dev/null',
173
+ `printf '\\n%s%s\\n' ready_ ${readyId}`
174
+ ].join('; ') + '\n');
175
+ await this.waitUntil(
176
+ () => findMarkerLine(plainText(this.outputBuffer), `ready_${readyId}`),
177
+ READY_TIMEOUT,
178
+ `ready_${readyId}`
179
+ );
180
+
181
+ // What is left after the marker is the shell's prompt, when it still
182
+ // prints one. A fixed prompt is removed from the lines of every command's
183
+ // output; one that changes (the directory in it) cannot be, so a shell
184
+ // that ignores PS1 keeps its prompt in the output.
185
+ await new Promise(resolve => setTimeout(resolve, 150));
186
+ this.prompt = this.learnPrompt(readyId);
94
187
 
95
188
  // Allow context queries through standard execute flow
96
189
  this.state = SESSION_STATES.READY;
@@ -112,42 +205,165 @@ class SSHSession {
112
205
  }
113
206
  }
114
207
 
208
+ /**
209
+ * The prompt the shell printed after the readiness marker, if any.
210
+ * @param {string} readyId - Id of the readiness marker
211
+ * @returns {string} The prompt, or an empty string
212
+ */
213
+ learnPrompt(readyId) {
214
+ const text = plainText(this.outputBuffer);
215
+ const marker = findMarkerLine(text, `ready_${readyId}`);
216
+ if (!marker) return '';
217
+ const after = text.slice(marker.index + marker.length).replace(/^\n/, '');
218
+ // A prompt is one unfinished line; anything longer is output we do not know.
219
+ return after.includes('\n') ? '' : after;
220
+ }
221
+
222
+ /**
223
+ * Wait until `find` returns something, as the shell prints.
224
+ * @param {() => any} find - Returns a truthy value once what is awaited has arrived
225
+ * @param {number} timeout - Milliseconds to wait
226
+ * @param {string} label - What is awaited, for the error
227
+ * @returns {Promise<any>} Whatever `find` returned
228
+ */
229
+ waitUntil(find, timeout, label) {
230
+ return new Promise((resolve, reject) => {
231
+ const done = () => { clearTimeout(timer); this.onShellData = null; };
232
+ const timer = setTimeout(() => {
233
+ done();
234
+ reject(new Error(`Timeout waiting for marker: ${label}`));
235
+ }, timeout);
236
+ const check = () => {
237
+ const found = find();
238
+ if (!found) return;
239
+ done();
240
+ resolve(found);
241
+ };
242
+ this.onShellData = check;
243
+ check();
244
+ });
245
+ }
246
+
115
247
  /**
116
248
  * Wait for a marker in shell output
117
249
  */
118
250
  async waitForMarker(marker, timeout = 5000) {
119
- const startTime = Date.now();
251
+ await this.waitUntil(() => findMarkerLine(plainText(this.outputBuffer), marker), timeout, marker);
252
+ return true;
253
+ }
120
254
 
121
- while (Date.now() - startTime < timeout) {
122
- if (this.outputBuffer.includes(marker)) {
123
- return true;
124
- }
255
+ /**
256
+ * What a command printed so far, and how it ended.
257
+ *
258
+ * The text between the command's start marker and its end marker, without
259
+ * the terminal's escape sequences and without the prompt. Before the end
260
+ * marker has arrived, only complete lines count.
261
+ *
262
+ * @param {string} id - The command's id
263
+ * @returns {{text: string, done: boolean, exitCode: number|null}|null} Null until the start marker has arrived
264
+ */
265
+ readCommand(id) {
266
+ const text = plainText(this.outputBuffer);
267
+ const start = findMarkerLine(text, `start_${id}`);
268
+ if (!start) return null;
269
+ const from = start.index + start.length + (text[start.index + start.length] === '\n' ? 1 : 0);
270
+ const rest = text.slice(from);
271
+ const end = findMarkerLine(rest, `cmd_${id}`);
272
+ let body;
273
+ if (end) {
274
+ body = rest.slice(0, end.index);
275
+ } else {
276
+ body = rest.slice(0, rest.lastIndexOf('\n') + 1);
277
+ }
278
+ if (this.prompt) {
279
+ // The shell prints its prompt before reading each line it is sent, so
280
+ // several can pile up in front of the text that follows them.
281
+ const withoutPrompts = line => {
282
+ let rest = line;
283
+ while (rest.startsWith(this.prompt)) rest = rest.slice(this.prompt.length);
284
+ return rest;
285
+ };
286
+ body = body.split('\n').map(withoutPrompts).join('\n');
287
+ }
288
+ return { text: body, done: Boolean(end), exitCode: end ? end.status : null };
289
+ }
125
290
 
126
- // Wait a bit
127
- await new Promise(resolve => setTimeout(resolve, 100));
291
+ /**
292
+ * Send a command wrapped in markers and wait for it to finish.
293
+ * Does not touch the session state: callers do.
294
+ *
295
+ * @param {string} command - The command line
296
+ * @param {{timeout?: number, onOutput?: (text: string) => void}} [options] - `onOutput` receives the output as it arrives
297
+ * @returns {Promise<{output: string, exitCode: number|null}>} The output, and the status the shell reported
298
+ */
299
+ async run(command, options = {}) {
300
+ // Clear buffers
301
+ this.outputBuffer = '';
302
+ this.errorBuffer = '';
303
+
304
+ const id = generateId();
305
+
306
+ // Both markers are spelled as separate printf arguments (see findMarkerLine).
307
+ this.shell.write(
308
+ `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`
309
+ );
310
+
311
+ // Forward what the command prints while it runs. Only whole lines, and
312
+ // never the trailing blank lines: the next chunk may continue them.
313
+ let forwarded = '';
314
+ const forward = (text) => {
315
+ if (!options.onOutput) return;
316
+ const shown = text.replace(/\n+$/, '');
317
+ if (shown.length <= forwarded.length || !shown.startsWith(forwarded)) return;
318
+ options.onOutput(shown.slice(forwarded.length));
319
+ forwarded = shown;
320
+ };
321
+
322
+ const finished = await this.waitUntil(() => {
323
+ const seen = this.readCommand(id);
324
+ if (seen && !seen.done) forward(seen.text);
325
+ return seen?.done ? seen : null;
326
+ }, options.timeout || 30000, `cmd_${id}`);
327
+
328
+ const output = finished.text.replace(/\n+$/, '');
329
+ forward(output);
330
+ return { output, exitCode: finished.exitCode };
331
+ }
332
+
333
+ /**
334
+ * Read the working directory and a few variables back from the shell.
335
+ * Does not touch the session state: callers do.
336
+ */
337
+ async refreshContext() {
338
+ const pwdResult = await this.run('pwd');
339
+ if (pwdResult.exitCode === 0) {
340
+ this.context.cwd = pwdResult.output.trim();
128
341
  }
129
342
 
130
- throw new Error(`Timeout waiting for marker: ${marker}`);
343
+ // One value per line: PATH holds colons, so they cannot separate the three.
344
+ const envResult = await this.run('printf \'%s\\n%s\\n%s\\n\' "$PATH" "$USER" "$HOME"');
345
+ if (envResult.exitCode === 0) {
346
+ const [PATH, USER, HOME] = envResult.output.split('\n');
347
+ this.context.env = { PATH, USER, HOME };
348
+ }
131
349
  }
132
350
 
133
351
  /**
134
352
  * Update session context (pwd, env)
135
353
  */
136
354
  async updateContext() {
355
+ if (this.state !== SESSION_STATES.READY) {
356
+ logger.warn(`Failed to update context for session ${this.id}`, {
357
+ error: `Session ${this.id} is not ready (state: ${this.state})`
358
+ });
359
+ return;
360
+ }
361
+ this.state = SESSION_STATES.BUSY;
137
362
  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
- }
363
+ await this.refreshContext();
364
+ this.state = SESSION_STATES.READY;
150
365
  } catch (error) {
366
+ this.state = SESSION_STATES.ERROR;
151
367
  logger.warn(`Failed to update context for session ${this.id}`, {
152
368
  error: error.message
153
369
  });
@@ -156,6 +372,9 @@ class SSHSession {
156
372
 
157
373
  /**
158
374
  * Execute a command in the session
375
+ *
376
+ * @param {string} command - The command line
377
+ * @param {{timeout?: number, silent?: boolean, onOutput?: (text: string) => void}} [options] - `onOutput` receives the output as it arrives
159
378
  */
160
379
  async execute(command, options = {}) {
161
380
  if (this.state !== SESSION_STATES.READY) {
@@ -166,10 +385,6 @@ class SSHSession {
166
385
  this.lastActivity = new Date();
167
386
 
168
387
  try {
169
- // Clear buffers
170
- this.outputBuffer = '';
171
- this.errorBuffer = '';
172
-
173
388
  // Add to history unless silent
174
389
  if (!options.silent) {
175
390
  this.context.history.push({
@@ -184,33 +399,26 @@ class SSHSession {
184
399
  });
185
400
  }
186
401
 
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();
402
+ const { output, exitCode } = await this.run(command, options);
403
+
404
+ // Update context if command might have changed it. The session is still
405
+ // busy here, so this reads the shell directly: going through execute()
406
+ // was refused ("not ready") and the context stayed as it was.
407
+ if (CONTEXT_COMMAND.test(command)) {
408
+ try {
409
+ await this.refreshContext();
410
+ } catch (error) {
411
+ logger.warn(`Failed to update context for session ${this.id}`, {
412
+ error: error.message
413
+ });
414
+ }
208
415
  }
209
416
 
210
417
  this.state = SESSION_STATES.READY;
211
418
 
212
419
  return {
213
- success,
420
+ success: exitCode === 0,
421
+ exitCode,
214
422
  output,
215
423
  error: this.errorBuffer,
216
424
  session: this.id
@@ -226,6 +434,14 @@ class SSHSession {
226
434
  }
227
435
  }
228
436
 
437
+ /**
438
+ * Can a command be sent now?
439
+ * @returns {boolean} True when the session is ready
440
+ */
441
+ isReady() {
442
+ return this.state === SESSION_STATES.READY;
443
+ }
444
+
229
445
  /**
230
446
  * Set session variable
231
447
  */