@pyrokine/mcp-ssh 1.1.2 → 1.2.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.
Files changed (43) hide show
  1. package/README.md +3 -1
  2. package/README_zh.md +3 -1
  3. package/dist/file-ops.d.ts +7 -10
  4. package/dist/file-ops.js +74 -172
  5. package/dist/forward-manager.d.ts +33 -0
  6. package/dist/forward-manager.js +185 -0
  7. package/dist/index.js +8 -953
  8. package/dist/pty-manager.d.ts +37 -0
  9. package/dist/pty-manager.js +169 -0
  10. package/dist/session-manager.d.ts +28 -86
  11. package/dist/session-manager.js +131 -441
  12. package/dist/ssh-config.d.ts +0 -4
  13. package/dist/ssh-config.js +1 -8
  14. package/dist/tools/connection.d.ts +7 -0
  15. package/dist/tools/connection.js +215 -0
  16. package/dist/tools/exec.d.ts +8 -0
  17. package/dist/tools/exec.js +221 -0
  18. package/dist/tools/file.d.ts +8 -0
  19. package/dist/tools/file.js +192 -0
  20. package/dist/tools/forward.d.ts +7 -0
  21. package/dist/tools/forward.js +116 -0
  22. package/dist/tools/index.d.ts +8 -0
  23. package/dist/tools/index.js +8 -0
  24. package/dist/tools/pty.d.ts +7 -0
  25. package/dist/tools/pty.js +178 -0
  26. package/dist/tools/utils.d.ts +22 -0
  27. package/dist/tools/utils.js +21 -0
  28. package/dist/types.d.ts +0 -7
  29. package/package.json +3 -2
  30. package/src/file-ops.ts +117 -212
  31. package/src/forward-manager.ts +257 -0
  32. package/src/index.ts +17 -1099
  33. package/src/pty-manager.ts +220 -0
  34. package/src/session-manager.ts +166 -532
  35. package/src/ssh-config.ts +1 -8
  36. package/src/tools/connection.ts +240 -0
  37. package/src/tools/exec.ts +260 -0
  38. package/src/tools/file.ts +219 -0
  39. package/src/tools/forward.ts +141 -0
  40. package/src/tools/index.ts +9 -0
  41. package/src/tools/pty.ts +203 -0
  42. package/src/tools/utils.ts +23 -0
  43. package/src/types.ts +0 -9
@@ -0,0 +1,37 @@
1
+ /**
2
+ * PTY 会话管理器
3
+ *
4
+ * 负责 PTY 会话的完整生命周期:创建、读写、调整大小、关闭
5
+ */
6
+ import type { ClientChannel } from 'ssh2';
7
+ import type { PtyOptions, PtySessionInfo } from './types.js';
8
+ /** PTY 创建所需的外部依赖 */
9
+ export interface PtyDependencies {
10
+ /** 通过 alias 获取 SSH client 并执行命令 */
11
+ execPty(alias: string, command: string, options: PtyOptions): Promise<ClientChannel>;
12
+ }
13
+ export declare class PtyManager {
14
+ private sessions;
15
+ private idCounter;
16
+ private readonly defaultBufferSize;
17
+ start(deps: PtyDependencies, alias: string, command: string, options?: PtyOptions): Promise<string>;
18
+ write(ptyId: string, data: string): boolean;
19
+ read(ptyId: string, options?: {
20
+ mode?: 'screen' | 'raw';
21
+ clear?: boolean;
22
+ }): {
23
+ data: string;
24
+ active: boolean;
25
+ rows: number;
26
+ cols: number;
27
+ };
28
+ resize(ptyId: string, rows: number, cols: number): boolean;
29
+ close(ptyId: string): boolean;
30
+ /** 关闭指定 alias 的所有 PTY 会话 */
31
+ closeByAlias(alias: string): void;
32
+ list(): PtySessionInfo[];
33
+ private getSession;
34
+ private generateId;
35
+ /** 从终端仿真器获取当前屏幕内容 */
36
+ private getScreenContent;
37
+ }
@@ -0,0 +1,169 @@
1
+ /**
2
+ * PTY 会话管理器
3
+ *
4
+ * 负责 PTY 会话的完整生命周期:创建、读写、调整大小、关闭
5
+ */
6
+ import xterm from '@xterm/headless';
7
+ const Terminal = xterm.Terminal;
8
+ export class PtyManager {
9
+ sessions = new Map();
10
+ idCounter = 0;
11
+ defaultBufferSize = 1024 * 1024; // 1MB
12
+ async start(deps, alias, command, options = {}) {
13
+ const ptyId = this.generateId();
14
+ const rows = options.rows || 24;
15
+ const cols = options.cols || 80;
16
+ const maxBufferSize = options.bufferSize || this.defaultBufferSize;
17
+ const stream = await deps.execPty(alias, command, options);
18
+ // 创建 xterm headless 终端仿真器
19
+ const terminal = new Terminal({ rows, cols, allowProposedApi: true });
20
+ const ptySession = {
21
+ id: ptyId,
22
+ alias,
23
+ command,
24
+ stream,
25
+ terminal,
26
+ rows,
27
+ cols,
28
+ createdAt: Date.now(),
29
+ lastReadAt: Date.now(),
30
+ rawBuffer: '',
31
+ maxBufferSize,
32
+ active: true,
33
+ };
34
+ // 监听输出数据
35
+ stream.on('data', (data) => {
36
+ if (!ptySession.active) {
37
+ return;
38
+ }
39
+ const chunk = data.toString('utf-8');
40
+ // 写入终端仿真器(解析 ANSI 序列)
41
+ terminal.write(chunk);
42
+ // 同时保留原始流(用于 raw 模式)
43
+ ptySession.rawBuffer += chunk;
44
+ if (ptySession.rawBuffer.length > maxBufferSize) {
45
+ ptySession.rawBuffer = ptySession.rawBuffer.slice(-maxBufferSize);
46
+ }
47
+ });
48
+ stream.on('close', () => {
49
+ ptySession.active = false;
50
+ });
51
+ stream.on('error', (err) => {
52
+ ptySession.active = false;
53
+ terminal.write(`\n[PTY Error: ${err.message}]`);
54
+ });
55
+ this.sessions.set(ptyId, ptySession);
56
+ return ptyId;
57
+ }
58
+ write(ptyId, data) {
59
+ const session = this.getSession(ptyId);
60
+ if (!session.active) {
61
+ throw new Error(`PTY session '${ptyId}' is closed`);
62
+ }
63
+ return session.stream.write(data);
64
+ }
65
+ read(ptyId, options = {}) {
66
+ const session = this.getSession(ptyId);
67
+ const mode = options.mode || 'screen';
68
+ const clear = options.clear !== false;
69
+ let data;
70
+ if (mode === 'screen') {
71
+ data = this.getScreenContent(session.terminal);
72
+ }
73
+ else {
74
+ data = session.rawBuffer;
75
+ if (clear) {
76
+ session.rawBuffer = '';
77
+ }
78
+ }
79
+ session.lastReadAt = Date.now();
80
+ return {
81
+ data,
82
+ active: session.active,
83
+ rows: session.rows,
84
+ cols: session.cols,
85
+ };
86
+ }
87
+ resize(ptyId, rows, cols) {
88
+ const session = this.getSession(ptyId);
89
+ if (!session.active) {
90
+ throw new Error(`PTY session '${ptyId}' is closed`);
91
+ }
92
+ session.stream.setWindow(rows, cols, 0, 0);
93
+ session.terminal.resize(cols, rows);
94
+ session.rows = rows;
95
+ session.cols = cols;
96
+ return true;
97
+ }
98
+ close(ptyId) {
99
+ const session = this.sessions.get(ptyId);
100
+ if (!session) {
101
+ return false;
102
+ }
103
+ try {
104
+ session.stream.close();
105
+ }
106
+ catch (e) {
107
+ console.warn(`PTY ${ptyId} stream close failed:`, e.message);
108
+ }
109
+ try {
110
+ session.terminal.dispose();
111
+ }
112
+ catch (e) {
113
+ console.warn(`PTY ${ptyId} terminal dispose failed:`, e.message);
114
+ }
115
+ session.active = false;
116
+ this.sessions.delete(ptyId);
117
+ return true;
118
+ }
119
+ /** 关闭指定 alias 的所有 PTY 会话 */
120
+ closeByAlias(alias) {
121
+ for (const [id, session] of this.sessions) {
122
+ if (session.alias === alias) {
123
+ this.close(id);
124
+ }
125
+ }
126
+ }
127
+ list() {
128
+ const result = [];
129
+ for (const [id, pty] of this.sessions) {
130
+ result.push({
131
+ id,
132
+ alias: pty.alias,
133
+ command: pty.command,
134
+ rows: pty.rows,
135
+ cols: pty.cols,
136
+ createdAt: pty.createdAt,
137
+ lastReadAt: pty.lastReadAt,
138
+ bufferSize: pty.rawBuffer.length,
139
+ active: pty.active,
140
+ });
141
+ }
142
+ return result;
143
+ }
144
+ getSession(ptyId) {
145
+ const session = this.sessions.get(ptyId);
146
+ if (!session) {
147
+ throw new Error(`PTY session '${ptyId}' not found`);
148
+ }
149
+ return session;
150
+ }
151
+ generateId() {
152
+ return `pty_${++this.idCounter}_${Date.now()}`;
153
+ }
154
+ /** 从终端仿真器获取当前屏幕内容 */
155
+ getScreenContent(terminal) {
156
+ const buffer = terminal.buffer.active;
157
+ const lines = [];
158
+ for (let i = 0; i < terminal.rows; i++) {
159
+ const line = buffer.getLine(i);
160
+ if (line) {
161
+ lines.push(line.translateToString(true));
162
+ }
163
+ }
164
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
165
+ lines.pop();
166
+ }
167
+ return lines.join('\n');
168
+ }
169
+ }
@@ -7,8 +7,8 @@
7
7
  * - 自动重连
8
8
  * - 会话持久化
9
9
  */
10
- import { Client, ClientChannel, SFTPWrapper } from 'ssh2';
11
- import { ExecOptions, ExecResult, PersistedSession, PortForwardInfo, PtyOptions, PtySessionInfo, SSHConnectionConfig, SSHSessionInfo } from './types.js';
10
+ import { Client, SFTPWrapper } from 'ssh2';
11
+ import { ExecOptions, ExecResult, PortForwardInfo, PtyOptions, PtySessionInfo, SSHConnectionConfig, SSHSessionInfo } from './types.js';
12
12
  interface SSHSession {
13
13
  client: Client;
14
14
  config: SSHConnectionConfig;
@@ -16,26 +16,19 @@ interface SSHSession {
16
16
  lastUsedAt: number;
17
17
  reconnectAttempts: number;
18
18
  connected: boolean;
19
- tcpDispatcher?: TcpConnectionHandler;
19
+ manualClose: boolean;
20
20
  }
21
- type TcpConnectionHandler = (info: {
22
- destIP: string;
23
- destPort: number;
24
- srcIP: string;
25
- srcPort: number;
26
- }, accept: () => ClientChannel, reject: () => void) => void;
27
21
  export declare class SessionManager {
28
22
  private sessions;
29
- private ptySessions;
30
- private forwardSessions;
31
- private ptyIdCounter;
32
- private forwardIdCounter;
33
- private persistPath;
23
+ private readonly ptyManager;
24
+ private readonly forwardManager;
25
+ private readonly persistPath;
34
26
  private defaultKeepaliveInterval;
35
27
  private defaultKeepaliveCountMax;
36
28
  private defaultTimeout;
37
29
  private maxReconnectAttempts;
38
- private defaultPtyBufferSize;
30
+ private defaultMaxOutputSize;
31
+ private reconnectDelay;
39
32
  constructor(persistPath?: string);
40
33
  /**
41
34
  * 建立 SSH 连接
@@ -49,10 +42,6 @@ export declare class SessionManager {
49
42
  * 断开连接
50
43
  */
51
44
  disconnect(alias: string): boolean;
52
- /**
53
- * 断开所有连接
54
- */
55
- disconnectAll(): void;
56
45
  /**
57
46
  * 获取会话
58
47
  */
@@ -67,10 +56,11 @@ export declare class SessionManager {
67
56
  exec(alias: string, command: string, options?: ExecOptions): Promise<ExecResult>;
68
57
  /**
69
58
  * 以其他用户身份执行命令
70
- * @param loadProfile 是否加载用户的 shell 配置(默认 true)。
71
- * su -c 创建非交互式 shell,不会自动执行 rc 文件,
72
- * 但大多数用户的环境变量设置在 rc 文件中,因此默认加载。
73
- * 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
59
+ *
60
+ * options.loadProfile 控制是否加载用户的 shell 配置(默认 true)。
61
+ * su -c 创建非交互式 shell,不会自动执行 rc 文件,
62
+ * 但大多数用户的环境变量设置在 rc 文件中,因此默认加载。
63
+ * 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
74
64
  */
75
65
  execAsUser(alias: string, command: string, targetUser: string, options?: ExecOptions & {
76
66
  loadProfile?: boolean;
@@ -83,22 +73,8 @@ export declare class SessionManager {
83
73
  * 获取 SFTP 客户端
84
74
  */
85
75
  getSftp(alias: string): Promise<SFTPWrapper>;
86
- /**
87
- * 加载持久化的会话信息(仅用于显示,不自动重连)
88
- */
89
- loadPersistedSessions(): PersistedSession[];
90
- /**
91
- * 启动持久化 PTY 会话
92
- */
93
76
  ptyStart(alias: string, command: string, options?: PtyOptions): Promise<string>;
94
- /**
95
- * 向 PTY 写入数据
96
- */
97
77
  ptyWrite(ptyId: string, data: string): boolean;
98
- /**
99
- * 读取 PTY 输出
100
- * @param mode 'screen' 返回当前屏幕内容,'raw' 返回原始 ANSI 流
101
- */
102
78
  ptyRead(ptyId: string, options?: {
103
79
  mode?: 'screen' | 'raw';
104
80
  clear?: boolean;
@@ -108,40 +84,17 @@ export declare class SessionManager {
108
84
  rows: number;
109
85
  cols: number;
110
86
  };
111
- /**
112
- * 调整 PTY 窗口大小
113
- */
114
87
  ptyResize(ptyId: string, rows: number, cols: number): boolean;
115
- /**
116
- * 关闭 PTY 会话
117
- */
118
88
  ptyClose(ptyId: string): boolean;
119
- /**
120
- * 列出所有 PTY 会话
121
- */
122
89
  ptyList(): PtySessionInfo[];
123
- /**
124
- * 关闭所有 PTY 会话
125
- */
126
- ptyCloseAll(): number;
127
- /**
128
- * 创建本地端口转发
129
- * 本地监听 localHost:localPort,转发到远程 remoteHost:remotePort
130
- */
131
90
  forwardLocal(alias: string, localPort: number, remoteHost: string, remotePort: number, localHost?: string): Promise<string>;
132
- /**
133
- * 创建远程端口转发
134
- * 远程监听 remoteHost:remotePort,转发到本地 localHost:localPort
135
- */
136
91
  forwardRemote(alias: string, remotePort: number, localHost: string, localPort: number, remoteHost?: string): Promise<string>;
137
- /**
138
- * 关闭端口转发
139
- */
140
92
  forwardClose(forwardId: string): boolean;
93
+ forwardList(): PortForwardInfo[];
141
94
  /**
142
- * 列出所有端口转发
95
+ * 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
143
96
  */
144
- forwardList(): PortForwardInfo[];
97
+ private execPtyStream;
145
98
  private ensurePersistDir;
146
99
  /**
147
100
  * 生成连接别名
@@ -155,6 +108,14 @@ export declare class SessionManager {
155
108
  * 检查连接是否存活
156
109
  */
157
110
  private isAlive;
111
+ /**
112
+ * 调度自动重连(支持多次重试)
113
+ */
114
+ private scheduleReconnect;
115
+ /**
116
+ * 根据错误类型生成排查建议
117
+ */
118
+ private diagnoseConnectionError;
158
119
  /**
159
120
  * 转义 shell 参数(使用单引号方式)
160
121
  */
@@ -167,6 +128,10 @@ export declare class SessionManager {
167
128
  * 校验环境变量名(只允许字母、数字、下划线,不能以数字开头)
168
129
  */
169
130
  private isValidEnvKey;
131
+ /**
132
+ * 构建完整命令:注入环境变量 + 切换工作目录
133
+ */
134
+ private buildCommand;
170
135
  /**
171
136
  * 根据用户 shell 类型生成加载配置文件的命令
172
137
  * bash → .bashrc, zsh → .zshrc, 其他 → .profile
@@ -176,29 +141,6 @@ export declare class SessionManager {
176
141
  * 持久化会话信息
177
142
  */
178
143
  private persistSessions;
179
- /**
180
- * 生成 PTY 会话 ID
181
- */
182
- private generatePtyId;
183
- /**
184
- * 从终端仿真器获取当前屏幕内容
185
- */
186
- private getScreenContent;
187
- /**
188
- * 生成端口转发 ID
189
- */
190
- private generateForwardId;
191
- /**
192
- * 确保 SSH session 有共享的 tcp connection dispatcher
193
- * 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
194
- * @param alias - session 的 map key
195
- */
196
- private ensureTcpDispatcher;
197
- /**
198
- * 移除 SSH session 的 tcp dispatcher(当没有 remote forward 时)
199
- * @param alias - session 的 map key
200
- */
201
- private removeTcpDispatcherIfEmpty;
202
144
  }
203
145
  export declare const sessionManager: SessionManager;
204
146
  export {};