@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
@@ -8,11 +8,11 @@
8
8
  * - 会话持久化
9
9
  */
10
10
 
11
- import xterm from '@xterm/headless'
12
11
  import * as fs from 'fs'
13
- import * as net from 'net'
14
12
  import * as path from 'path'
15
13
  import {Client, ClientChannel, ConnectConfig, SFTPWrapper} from 'ssh2'
14
+ import {ForwardManager} from './forward-manager.js'
15
+ import {PtyManager} from './pty-manager.js'
16
16
  import {
17
17
  ExecOptions,
18
18
  ExecResult,
@@ -24,66 +24,27 @@ import {
24
24
  SSHSessionInfo,
25
25
  } from './types.js'
26
26
 
27
- const Terminal = xterm.Terminal as typeof import('@xterm/headless').Terminal
28
- type TerminalType = import('@xterm/headless').Terminal;
29
-
30
27
  interface SSHSession {
31
28
  client: Client;
32
29
  config: SSHConnectionConfig;
33
30
  connectedAt: number;
34
31
  lastUsedAt: number;
35
32
  reconnectAttempts: number;
36
- connected: boolean; // 通过事件监听维护的连接状态
37
- tcpDispatcher?: TcpConnectionHandler; // remote forward 共享的 dispatcher
38
- }
39
-
40
- interface PtySession {
41
- id: string;
42
- alias: string;
43
- command: string;
44
- stream: ClientChannel;
45
- terminal: TerminalType; // xterm headless 终端仿真器
46
- rows: number;
47
- cols: number;
48
- createdAt: number;
49
- lastReadAt: number;
50
- rawBuffer: string; // 原始 ANSI 流
51
- maxBufferSize: number;
52
- active: boolean;
53
- }
54
-
55
- // tcp connection 事件处理函数类型
56
- type TcpConnectionHandler = (
57
- info: { destIP: string; destPort: number; srcIP: string; srcPort: number },
58
- accept: () => ClientChannel,
59
- reject: () => void,
60
- ) => void;
61
-
62
- interface ForwardSession {
63
- id: string;
64
- alias: string;
65
- type: 'local' | 'remote';
66
- localHost: string;
67
- localPort: number;
68
- remoteHost: string;
69
- remotePort: number;
70
- server?: net.Server; // 本地转发的 TCP 服务器
71
- createdAt: number;
72
- active: boolean;
33
+ connected: boolean; // 通过事件监听维护的连接状态
34
+ manualClose: boolean; // 标记主动关闭,阻止 close 事件触发自动重连
73
35
  }
74
36
 
75
37
  export class SessionManager {
76
- private sessions: Map<string, SSHSession> = new Map()
77
- private ptySessions: Map<string, PtySession> = new Map()
78
- private forwardSessions: Map<string, ForwardSession> = new Map()
79
- private ptyIdCounter = 0
80
- private forwardIdCounter = 0
81
- private persistPath: string
82
- private defaultKeepaliveInterval = 30000 // 30秒
83
- private defaultKeepaliveCountMax = 3
84
- private defaultTimeout = 30000 // 30秒
85
- private maxReconnectAttempts = 3
86
- private defaultPtyBufferSize = 1024 * 1024 // 1MB
38
+ private sessions: Map<string, SSHSession> = new Map()
39
+ private readonly ptyManager = new PtyManager()
40
+ private readonly forwardManager = new ForwardManager()
41
+ private readonly persistPath: string
42
+ private defaultKeepaliveInterval = 30000 // 30秒
43
+ private defaultKeepaliveCountMax = 3
44
+ private defaultTimeout = 30000 // 30秒
45
+ private maxReconnectAttempts = 3
46
+ private defaultMaxOutputSize = 10 * 1024 * 1024 // 10MB
47
+ private reconnectDelay = 5000 // 5秒
87
48
 
88
49
  constructor(persistPath?: string) {
89
50
  this.persistPath = persistPath || path.join(
@@ -139,12 +100,11 @@ export class SessionManager {
139
100
  const jumpSession = this.sessions.get(jumpAlias)
140
101
  if (jumpSession) {
141
102
  // 通过跳板机建立连接
142
- const stream = await this.forwardConnection(
103
+ connectConfig.sock = await this.forwardConnection(
143
104
  jumpSession.client,
144
105
  config.host,
145
106
  config.port || 22,
146
107
  )
147
- connectConfig.sock = stream
148
108
  }
149
109
  }
150
110
 
@@ -157,6 +117,7 @@ export class SessionManager {
157
117
  lastUsedAt: Date.now(),
158
118
  reconnectAttempts: 0,
159
119
  connected: true,
120
+ manualClose: false,
160
121
  }
161
122
  this.sessions.set(alias, session)
162
123
  this.persistSessions()
@@ -165,23 +126,22 @@ export class SessionManager {
165
126
 
166
127
  client.on('error', (err) => {
167
128
  const session = this.sessions.get(alias)
168
- if (session) {
129
+ if (session && session.client === client) {
169
130
  session.connected = false
170
131
  }
171
- reject(new Error(`SSH connection failed: ${err.message}`))
132
+ const target = `${connectConfig.username}@${connectConfig.host}:${connectConfig.port}`
133
+ const suggestion = this.diagnoseConnectionError(err)
134
+ reject(new Error(`SSH connection to ${target} failed: ${err.message}${suggestion ?
135
+ ` (${suggestion})` :
136
+ ''}`))
172
137
  })
173
138
 
174
139
  client.on('close', () => {
175
140
  const session = this.sessions.get(alias)
176
- if (session) {
141
+ if (session && session.client === client) {
177
142
  session.connected = false
178
- // 自动重连逻辑
179
- if (session.reconnectAttempts < this.maxReconnectAttempts) {
180
- session.reconnectAttempts++
181
- setTimeout(() => {
182
- this.reconnect(alias).catch(() => {
183
- })
184
- }, 5000) // 5 秒后重连
143
+ if (!session.manualClose) {
144
+ this.scheduleReconnect(alias)
185
145
  }
186
146
  }
187
147
  })
@@ -199,9 +159,12 @@ export class SessionManager {
199
159
  throw new Error(`Session ${alias} not found`)
200
160
  }
201
161
 
162
+ session.manualClose = true
163
+ session.connected = false
164
+
202
165
  try {
203
166
  session.client.end()
204
- } catch {
167
+ } catch { /* 忽略已关闭的连接 */
205
168
  }
206
169
 
207
170
  await this.connect(session.config)
@@ -213,9 +176,13 @@ export class SessionManager {
213
176
  disconnect(alias: string): boolean {
214
177
  const session = this.sessions.get(alias)
215
178
  if (session) {
179
+ session.manualClose = true
180
+ // 清理关联的 PTY 和 forward 资源
181
+ this.ptyManager.closeByAlias(alias)
182
+ this.forwardManager.closeByAlias(alias)
216
183
  try {
217
184
  session.client.end()
218
- } catch {
185
+ } catch { /* 忽略已关闭的连接 */
219
186
  }
220
187
  this.sessions.delete(alias)
221
188
  this.persistSessions()
@@ -224,15 +191,6 @@ export class SessionManager {
224
191
  return false
225
192
  }
226
193
 
227
- /**
228
- * 断开所有连接
229
- */
230
- disconnectAll(): void {
231
- for (const alias of this.sessions.keys()) {
232
- this.disconnect(alias)
233
- }
234
- }
235
-
236
194
  /**
237
195
  * 获取会话
238
196
  */
@@ -278,32 +236,8 @@ export class SessionManager {
278
236
  ): Promise<ExecResult> {
279
237
  const session = this.getSession(alias)
280
238
  const startTime = Date.now()
281
- const maxOutputSize = options.maxOutputSize || 10 * 1024 * 1024 // 默认 10MB
282
-
283
- // 构建完整命令(包含环境变量)
284
- let fullCommand = command
285
- const env = {...session.config.env, ...options.env}
286
-
287
- if (Object.keys(env).length > 0) {
288
- // 校验并过滤环境变量名
289
- const validEnvEntries = Object.entries(env).filter(([k]) => {
290
- if (!this.isValidEnvKey(k)) {
291
- // 静默忽略非法环境变量名
292
- return false
293
- }
294
- return true
295
- })
296
- if (validEnvEntries.length > 0) {
297
- const envStr = validEnvEntries
298
- .map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
299
- .join('; ')
300
- fullCommand = `${envStr}; ${command}`
301
- }
302
- }
303
-
304
- if (options.cwd) {
305
- fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`
306
- }
239
+ const maxOutputSize = options.maxOutputSize || this.defaultMaxOutputSize
240
+ const fullCommand = this.buildCommand(command, session, options)
307
241
 
308
242
  return new Promise((resolve, reject) => {
309
243
  const timeout = options.timeout || this.defaultTimeout
@@ -378,10 +312,11 @@ export class SessionManager {
378
312
 
379
313
  /**
380
314
  * 以其他用户身份执行命令
381
- * @param loadProfile 是否加载用户的 shell 配置(默认 true)。
382
- * su -c 创建非交互式 shell,不会自动执行 rc 文件,
383
- * 但大多数用户的环境变量设置在 rc 文件中,因此默认加载。
384
- * 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
315
+ *
316
+ * options.loadProfile 控制是否加载用户的 shell 配置(默认 true)。
317
+ * su -c 创建非交互式 shell,不会自动执行 rc 文件,
318
+ * 但大多数用户的环境变量设置在 rc 文件中,因此默认加载。
319
+ * 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)。
385
320
  */
386
321
  async execAsUser(
387
322
  alias: string,
@@ -439,245 +374,39 @@ export class SessionManager {
439
374
  })
440
375
  }
441
376
 
442
- /**
443
- * 加载持久化的会话信息(仅用于显示,不自动重连)
444
- */
445
- loadPersistedSessions(): PersistedSession[] {
446
- try {
447
- if (fs.existsSync(this.persistPath)) {
448
- return JSON.parse(fs.readFileSync(this.persistPath, 'utf-8'))
449
- }
450
- } catch {
451
- }
452
- return []
453
- }
454
-
455
- /**
456
- * 启动持久化 PTY 会话
457
- */
458
- async ptyStart(
459
- alias: string,
460
- command: string,
461
- options: PtyOptions = {},
462
- ): Promise<string> {
463
- const session = this.getSession(alias)
464
- const ptyId = this.generatePtyId()
465
-
466
- const rows = options.rows || 24
467
- const cols = options.cols || 80
468
- const term = options.term || 'xterm-256color'
469
- const maxBufferSize = options.bufferSize || this.defaultPtyBufferSize
470
-
471
- // 构建完整命令
472
- let fullCommand = command
473
- const env = {...session.config.env, ...options.env}
474
-
475
- if (Object.keys(env).length > 0) {
476
- const envStr = Object.entries(env)
477
- .map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
478
- .join('; ')
479
- fullCommand = `${envStr}; ${command}`
480
- }
481
-
482
- if (options.cwd) {
483
- fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`
484
- }
485
-
486
- return new Promise((resolve, reject) => {
487
- session.client.exec(
488
- fullCommand,
489
- {
490
- pty: {rows, cols, term},
491
- },
492
- (err, stream) => {
493
- if (err) {
494
- reject(new Error(`PTY start failed: ${err.message}`))
495
- return
496
- }
497
-
498
- // 创建 xterm headless 终端仿真器
499
- const terminal = new Terminal({
500
- rows,
501
- cols,
502
- allowProposedApi: true,
503
- })
504
-
505
- const ptySession: PtySession = {
506
- id: ptyId,
507
- alias,
508
- command,
509
- stream,
510
- terminal,
511
- rows,
512
- cols,
513
- createdAt: Date.now(),
514
- lastReadAt: Date.now(),
515
- rawBuffer: '',
516
- maxBufferSize,
517
- active: true,
518
- }
377
+ // ===== PTY 委托 =====
519
378
 
520
- // 监听输出数据
521
- stream.on('data', (data: Buffer) => {
522
- if (!ptySession.active) {
523
- return
524
- }
525
- const chunk = data.toString('utf-8')
526
- // 写入终端仿真器(解析 ANSI 序列)
527
- terminal.write(chunk)
528
- // 同时保留原始流(用于 raw 模式)
529
- ptySession.rawBuffer += chunk
530
- if (ptySession.rawBuffer.length > maxBufferSize) {
531
- ptySession.rawBuffer = ptySession.rawBuffer.slice(-maxBufferSize)
532
- }
533
- })
534
-
535
- stream.on('close', () => {
536
- ptySession.active = false
537
- })
538
-
539
- stream.on('error', (err: Error) => {
540
- ptySession.active = false
541
- terminal.write(`\n[PTY Error: ${err.message}]`)
542
- })
543
-
544
- this.ptySessions.set(ptyId, ptySession)
545
- resolve(ptyId)
546
- },
547
- )
548
- })
379
+ async ptyStart(alias: string, command: string, options: PtyOptions = {}): Promise<string> {
380
+ return this.ptyManager.start({
381
+ execPty: (a, cmd, opts) => this.execPtyStream(a, cmd, opts),
382
+ }, alias, command, options)
549
383
  }
550
384
 
551
- /**
552
- * 向 PTY 写入数据
553
- */
554
385
  ptyWrite(ptyId: string, data: string): boolean {
555
- const ptySession = this.ptySessions.get(ptyId)
556
- if (!ptySession) {
557
- throw new Error(`PTY session '${ptyId}' not found`)
558
- }
559
- if (!ptySession.active) {
560
- throw new Error(`PTY session '${ptyId}' is closed`)
561
- }
562
- return ptySession.stream.write(data)
386
+ return this.ptyManager.write(ptyId, data)
563
387
  }
564
388
 
565
- /**
566
- * 读取 PTY 输出
567
- * @param mode 'screen' 返回当前屏幕内容,'raw' 返回原始 ANSI 流
568
- */
569
389
  ptyRead(
570
390
  ptyId: string,
571
391
  options: { mode?: 'screen' | 'raw'; clear?: boolean } = {},
572
392
  ): { data: string; active: boolean; rows: number; cols: number } {
573
- const ptySession = this.ptySessions.get(ptyId)
574
- if (!ptySession) {
575
- throw new Error(`PTY session '${ptyId}' not found`)
576
- }
577
-
578
- const mode = options.mode || 'screen'
579
- const clear = options.clear !== false
580
-
581
- let data: string
582
- if (mode === 'screen') {
583
- // 返回当前屏幕内容(解析后的纯文本)
584
- data = this.getScreenContent(ptySession.terminal)
585
- } else {
586
- // 返回原始 ANSI 流
587
- data = ptySession.rawBuffer
588
- if (clear) {
589
- ptySession.rawBuffer = ''
590
- }
591
- }
592
-
593
- ptySession.lastReadAt = Date.now()
594
- return {
595
- data,
596
- active: ptySession.active,
597
- rows: ptySession.rows,
598
- cols: ptySession.cols,
599
- }
393
+ return this.ptyManager.read(ptyId, options)
600
394
  }
601
395
 
602
- /**
603
- * 调整 PTY 窗口大小
604
- */
605
396
  ptyResize(ptyId: string, rows: number, cols: number): boolean {
606
- const ptySession = this.ptySessions.get(ptyId)
607
- if (!ptySession) {
608
- throw new Error(`PTY session '${ptyId}' not found`)
609
- }
610
- if (!ptySession.active) {
611
- throw new Error(`PTY session '${ptyId}' is closed`)
612
- }
613
- // 调整远程 PTY 窗口
614
- ptySession.stream.setWindow(rows, cols, 0, 0)
615
- // 调整本地终端仿真器
616
- ptySession.terminal.resize(cols, rows)
617
- ptySession.rows = rows
618
- ptySession.cols = cols
619
- return true
397
+ return this.ptyManager.resize(ptyId, rows, cols)
620
398
  }
621
399
 
622
- /**
623
- * 关闭 PTY 会话
624
- */
625
400
  ptyClose(ptyId: string): boolean {
626
- const ptySession = this.ptySessions.get(ptyId)
627
- if (!ptySession) {
628
- return false
629
- }
630
- try {
631
- ptySession.stream.close()
632
- } catch {
633
- }
634
- try {
635
- ptySession.terminal.dispose()
636
- } catch {
637
- }
638
- ptySession.active = false
639
- this.ptySessions.delete(ptyId)
640
- return true
401
+ return this.ptyManager.close(ptyId)
641
402
  }
642
403
 
643
- /**
644
- * 列出所有 PTY 会话
645
- */
646
404
  ptyList(): PtySessionInfo[] {
647
- const result: PtySessionInfo[] = []
648
- for (const [id, pty] of this.ptySessions) {
649
- result.push({
650
- id,
651
- alias: pty.alias,
652
- command: pty.command,
653
- rows: pty.rows,
654
- cols: pty.cols,
655
- createdAt: pty.createdAt,
656
- lastReadAt: pty.lastReadAt,
657
- bufferSize: pty.rawBuffer.length,
658
- active: pty.active,
659
- })
660
- }
661
- return result
405
+ return this.ptyManager.list()
662
406
  }
663
407
 
664
- /**
665
- * 关闭所有 PTY 会话
666
- */
667
- ptyCloseAll(): number {
668
- let count = 0
669
- for (const ptyId of this.ptySessions.keys()) {
670
- if (this.ptyClose(ptyId)) {
671
- count++
672
- }
673
- }
674
- return count
675
- }
408
+ // ===== Forward 委托 =====
676
409
 
677
- /**
678
- * 创建本地端口转发
679
- * 本地监听 localHost:localPort,转发到远程 remoteHost:remotePort
680
- */
681
410
  async forwardLocal(
682
411
  alias: string,
683
412
  localPort: number,
@@ -685,53 +414,12 @@ export class SessionManager {
685
414
  remotePort: number,
686
415
  localHost: string = '127.0.0.1',
687
416
  ): Promise<string> {
688
- const session = this.getSession(alias)
689
- const forwardId = this.generateForwardId()
690
-
691
- return new Promise((resolve, reject) => {
692
- const server = net.createServer((socket) => {
693
- session.client.forwardOut(
694
- socket.remoteAddress || '127.0.0.1',
695
- socket.remotePort || 0,
696
- remoteHost,
697
- remotePort,
698
- (err, stream) => {
699
- if (err) {
700
- socket.end()
701
- return
702
- }
703
- socket.pipe(stream).pipe(socket)
704
- },
705
- )
706
- })
707
-
708
- server.on('error', (err) => {
709
- reject(new Error(`Local forward failed: ${err.message}`))
710
- })
711
-
712
- server.listen(localPort, localHost, () => {
713
- const fwdSession: ForwardSession = {
714
- id: forwardId,
715
- alias,
716
- type: 'local',
717
- localHost,
718
- localPort,
719
- remoteHost,
720
- remotePort,
721
- server,
722
- createdAt: Date.now(),
723
- active: true,
724
- }
725
- this.forwardSessions.set(forwardId, fwdSession)
726
- resolve(forwardId)
727
- })
728
- })
417
+ return this.forwardManager.forwardLocal(
418
+ {getClient: (a) => this.getSession(a).client},
419
+ alias, localPort, remoteHost, remotePort, localHost,
420
+ )
729
421
  }
730
422
 
731
- /**
732
- * 创建远程端口转发
733
- * 远程监听 remoteHost:remotePort,转发到本地 localHost:localPort
734
- */
735
423
  async forwardRemote(
736
424
  alias: string,
737
425
  remotePort: number,
@@ -739,90 +427,48 @@ export class SessionManager {
739
427
  localPort: number,
740
428
  remoteHost: string = '127.0.0.1',
741
429
  ): Promise<string> {
742
- const session = this.getSession(alias)
743
- const forwardId = this.generateForwardId()
744
-
745
- return new Promise((resolve, reject) => {
746
- session.client.forwardIn(remoteHost, remotePort, (err) => {
747
- if (err) {
748
- reject(new Error(`Remote forward failed: ${err.message}`))
749
- return
750
- }
751
-
752
- const fwdSession: ForwardSession = {
753
- id: forwardId,
754
- alias,
755
- type: 'remote',
756
- localHost,
757
- localPort,
758
- remoteHost,
759
- remotePort,
760
- createdAt: Date.now(),
761
- active: true,
762
- }
763
- this.forwardSessions.set(forwardId, fwdSession)
764
-
765
- // 确保该 session 有共享的 tcp dispatcher
766
- this.ensureTcpDispatcher(session, alias)
430
+ return this.forwardManager.forwardRemote(
431
+ {getClient: (a) => this.getSession(a).client},
432
+ alias, remotePort, localHost, localPort, remoteHost,
433
+ )
434
+ }
767
435
 
768
- resolve(forwardId)
769
- })
436
+ forwardClose(forwardId: string): boolean {
437
+ return this.forwardManager.close(forwardId, {
438
+ getClient: (a) => this.getSession(a).client,
770
439
  })
771
440
  }
772
441
 
773
- // ========== PTY 会话管理 ==========
442
+ forwardList(): PortForwardInfo[] {
443
+ return this.forwardManager.list()
444
+ }
774
445
 
775
446
  /**
776
- * 关闭端口转发
447
+ * 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
777
448
  */
778
- forwardClose(forwardId: string): boolean {
779
- const fwdSession = this.forwardSessions.get(forwardId)
780
- if (!fwdSession) {
781
- return false
782
- }
783
-
784
- fwdSession.active = false
449
+ private execPtyStream(
450
+ alias: string,
451
+ command: string,
452
+ options: PtyOptions,
453
+ ): Promise<ClientChannel> {
454
+ const session = this.getSession(alias)
455
+ const fullCommand = this.buildCommand(command, session, {env: options.env, cwd: options.cwd})
785
456
 
786
- if (fwdSession.type === 'local' && fwdSession.server) {
787
- try {
788
- fwdSession.server.close()
789
- } catch {
790
- }
791
- } else if (fwdSession.type === 'remote') {
792
- const session = this.sessions.get(fwdSession.alias)
793
- if (session) {
794
- try {
795
- session.client.unforwardIn(fwdSession.remoteHost, fwdSession.remotePort)
796
- } catch {
457
+ return new Promise((resolve, reject) => {
458
+ session.client.exec(fullCommand, {
459
+ pty: {
460
+ rows: options.rows || 24,
461
+ cols: options.cols || 80,
462
+ term: options.term || 'xterm-256color',
463
+ },
464
+ }, (err, stream) => {
465
+ if (err) {
466
+ reject(new Error(`PTY exec failed: ${err.message}`))
467
+ } else {
468
+ resolve(stream)
797
469
  }
798
- // 检查是否需要移除共享 dispatcher
799
- this.removeTcpDispatcherIfEmpty(session, fwdSession.alias)
800
- }
801
- }
802
-
803
- this.forwardSessions.delete(forwardId)
804
- return true
805
- }
806
-
807
- /**
808
- * 列出所有端口转发
809
- */
810
- forwardList(): PortForwardInfo[] {
811
- const result: PortForwardInfo[] = []
812
- for (const [id, fwd] of this.forwardSessions) {
813
- result.push({
814
- id,
815
- alias: fwd.alias,
816
- type: fwd.type,
817
- localHost: fwd.localHost,
818
- localPort: fwd.localPort,
819
- remoteHost: fwd.remoteHost,
820
- remotePort: fwd.remotePort,
821
- createdAt: fwd.createdAt,
822
- active: fwd.active,
823
- })
824
- }
825
- return result
470
+ })
471
+ })
826
472
  }
827
473
 
828
474
  private ensurePersistDir(): void {
@@ -871,6 +517,57 @@ export class SessionManager {
871
517
  return session.connected
872
518
  }
873
519
 
520
+ /**
521
+ * 调度自动重连(支持多次重试)
522
+ */
523
+ private scheduleReconnect(alias: string): void {
524
+ const session = this.sessions.get(alias)
525
+ if (!session || session.reconnectAttempts >= this.maxReconnectAttempts) {
526
+ return
527
+ }
528
+
529
+ session.reconnectAttempts++
530
+ const attempt = session.reconnectAttempts
531
+
532
+ setTimeout(async () => {
533
+ try {
534
+ await this.reconnect(alias)
535
+ } catch (err) {
536
+ console.error(
537
+ `Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}):`,
538
+ (err as Error).message,
539
+ )
540
+ // reconnect 失败后继续调度下一次尝试
541
+ this.scheduleReconnect(alias)
542
+ }
543
+ }, this.reconnectDelay)
544
+ }
545
+
546
+ /**
547
+ * 根据错误类型生成排查建议
548
+ */
549
+ private diagnoseConnectionError(err: Error & { code?: string }): string {
550
+ const msg = err.message || ''
551
+ const code = err.code || ''
552
+
553
+ if (code === 'ECONNREFUSED' || msg.includes('ECONNREFUSED')) {
554
+ return 'check if SSH service is running on the target host'
555
+ }
556
+ if (code === 'ETIMEDOUT' || msg.includes('ETIMEDOUT') || msg.includes('Timed out')) {
557
+ return 'check host reachability, firewall rules, or try a jump host'
558
+ }
559
+ if (code === 'ENOTFOUND' || msg.includes('ENOTFOUND') || msg.includes('getaddrinfo')) {
560
+ return 'hostname cannot be resolved, check DNS or use IP address'
561
+ }
562
+ if (msg.includes('All configured authentication methods failed')) {
563
+ return 'check password, key path, or key permissions (chmod 600)'
564
+ }
565
+ if (msg.includes('ECONNRESET') || msg.includes('Connection reset')) {
566
+ return 'connection was reset by the remote host'
567
+ }
568
+ return ''
569
+ }
570
+
874
571
  /**
875
572
  * 转义 shell 参数(使用单引号方式)
876
573
  */
@@ -892,7 +589,32 @@ export class SessionManager {
892
589
  return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(key)
893
590
  }
894
591
 
895
- // ========== 端口转发 ==========
592
+ /**
593
+ * 构建完整命令:注入环境变量 + 切换工作目录
594
+ */
595
+ private buildCommand(
596
+ command: string,
597
+ session: SSHSession,
598
+ options: { env?: Record<string, string>; cwd?: string },
599
+ ): string {
600
+ let fullCommand = command
601
+ const env = {...session.config.env, ...options.env}
602
+
603
+ if (Object.keys(env).length > 0) {
604
+ const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k))
605
+ if (validEntries.length > 0) {
606
+ const envStr = validEntries
607
+ .map(([k, v]) => `export ${k}=${this.escapeShellArg(v)}`)
608
+ .join('; ')
609
+ fullCommand = `${envStr}; ${command}`
610
+ }
611
+ }
612
+
613
+ if (options.cwd) {
614
+ fullCommand = `cd ${this.escapeShellArg(options.cwd)} && ${fullCommand}`
615
+ }
616
+ return fullCommand
617
+ }
896
618
 
897
619
  /**
898
620
  * 根据用户 shell 类型生成加载配置文件的命令
@@ -929,94 +651,6 @@ export class SessionManager {
929
651
  }
930
652
  }
931
653
 
932
- /**
933
- * 生成 PTY 会话 ID
934
- */
935
- private generatePtyId(): string {
936
- return `pty_${++this.ptyIdCounter}_${Date.now()}`
937
- }
938
-
939
- /**
940
- * 从终端仿真器获取当前屏幕内容
941
- */
942
- private getScreenContent(terminal: TerminalType): string {
943
- const buffer = terminal.buffer.active
944
- const lines: string[] = []
945
- for (let i = 0; i < terminal.rows; i++) {
946
- const line = buffer.getLine(i)
947
- if (line) {
948
- lines.push(line.translateToString(true))
949
- }
950
- }
951
- // 移除尾部空行
952
- while (lines.length > 0 && lines[lines.length - 1].trim() === '') {
953
- lines.pop()
954
- }
955
- return lines.join('\n')
956
- }
957
-
958
- /**
959
- * 生成端口转发 ID
960
- */
961
- private generateForwardId(): string {
962
- return `fwd_${++this.forwardIdCounter}_${Date.now()}`
963
- }
964
-
965
- /**
966
- * 确保 SSH session 有共享的 tcp connection dispatcher
967
- * 所有 remote forward 共用一个 dispatcher,根据 destIP/destPort 路由
968
- * @param alias - session 的 map key
969
- */
970
- private ensureTcpDispatcher(session: SSHSession, alias: string): void {
971
- if (session.tcpDispatcher) {
972
- return // 已存在
973
- }
974
-
975
- const dispatcher: TcpConnectionHandler = (info, accept, rejectConn) => {
976
- // 查找匹配的 remote forward
977
- for (const fwd of this.forwardSessions.values()) {
978
- if (fwd.type === 'remote' &&
979
- fwd.active &&
980
- fwd.alias === alias &&
981
- fwd.remoteHost === info.destIP &&
982
- fwd.remotePort === info.destPort) {
983
- // 找到匹配的 forward,建立连接
984
- const stream = accept()
985
- const socket = net.createConnection(fwd.localPort, fwd.localHost)
986
- socket.pipe(stream).pipe(socket)
987
- socket.on('error', () => stream.close())
988
- stream.on('error', () => socket.destroy())
989
- return
990
- }
991
- }
992
- // 没有匹配的 forward,拒绝连接
993
- rejectConn()
994
- }
995
-
996
- session.tcpDispatcher = dispatcher
997
- session.client.on('tcp connection', dispatcher)
998
- }
999
-
1000
- /**
1001
- * 移除 SSH session 的 tcp dispatcher(当没有 remote forward 时)
1002
- * @param alias - session 的 map key
1003
- */
1004
- private removeTcpDispatcherIfEmpty(session: SSHSession, alias: string): void {
1005
- if (!session.tcpDispatcher) {
1006
- return
1007
- }
1008
-
1009
- // 检查是否还有该 session 的 remote forward
1010
- for (const fwd of this.forwardSessions.values()) {
1011
- if (fwd.type === 'remote' && fwd.alias === alias && fwd.active) {
1012
- return // 还有活跃的 remote forward
1013
- }
1014
- }
1015
-
1016
- // 没有了,移除 dispatcher
1017
- session.client.removeListener('tcp connection', session.tcpDispatcher)
1018
- session.tcpDispatcher = undefined
1019
- }
1020
654
  }
1021
655
 
1022
656
  // 全局单例