@fefeding/aicmd 1.0.25 → 1.0.27

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 (77) hide show
  1. package/README.md +58 -5
  2. package/README.zh.md +64 -5
  3. package/dist/public/.vite/manifest.json +133 -13
  4. package/dist/public/ai-settings.css +1868 -0
  5. package/dist/public/ai-settings.js +7579 -0
  6. package/dist/public/bootstrap-icons.woff +0 -0
  7. package/dist/public/bootstrap-icons.woff2 +0 -0
  8. package/dist/public/bootstrap.css +1 -1
  9. package/dist/public/bootstrap.js +60 -119
  10. package/dist/public/connection-editor.css +5 -0
  11. package/dist/public/connection-editor.js +712 -0
  12. package/dist/public/connection.js +118 -0
  13. package/dist/public/index.css +0 -381
  14. package/dist/public/index.js +186 -5467
  15. package/dist/public/rdp_client_bg.wasm +0 -0
  16. package/dist/public/selection-copy.css +494 -0
  17. package/dist/public/selection-copy.js +5501 -0
  18. package/dist/public/src/term.html +17 -0
  19. package/dist/public/src/vscode-edit.html +21 -0
  20. package/dist/public/src/vscode-term.html +24 -0
  21. package/dist/public/term.css +14 -0
  22. package/dist/public/term.js +333 -0
  23. package/dist/public/views.css +111 -1515
  24. package/dist/public/views.js +233 -7476
  25. package/dist/public/vscode-clipboard.js +658 -0
  26. package/dist/public/vscode-edit.js +91 -0
  27. package/dist/public/vscode-term.js +116 -0
  28. package/dist/public/vue.js +360 -195
  29. package/dist/public/xterm.js +1647 -10
  30. package/dist/public/zmodem.js +2726 -0
  31. package/dist/server/index.d.ts +12 -2
  32. package/dist/server/index.d.ts.map +1 -1
  33. package/dist/server/index.js +14 -1
  34. package/dist/server/index.js.map +1 -1
  35. package/dist/server/index.ts +14 -1
  36. package/dist/server/model/connection.entity.d.ts +10 -2
  37. package/dist/server/model/connection.entity.d.ts.map +1 -1
  38. package/dist/server/model/connection.entity.js +9 -1
  39. package/dist/server/model/connection.entity.js.map +1 -1
  40. package/dist/server/model/connection.entity.ts +11 -2
  41. package/dist/server/service/ai.service.d.ts +15 -0
  42. package/dist/server/service/ai.service.d.ts.map +1 -1
  43. package/dist/server/service/ai.service.js +38 -6
  44. package/dist/server/service/ai.service.js.map +1 -1
  45. package/dist/server/service/ai.service.ts +43 -6
  46. package/dist/server/service/rdp-tunnel.service.d.ts +22 -0
  47. package/dist/server/service/rdp-tunnel.service.d.ts.map +1 -0
  48. package/dist/server/service/rdp-tunnel.service.js +464 -0
  49. package/dist/server/service/rdp-tunnel.service.js.map +1 -0
  50. package/dist/server/service/rdp-tunnel.service.ts +428 -0
  51. package/dist/server/service/rdp.service.d.ts +64 -0
  52. package/dist/server/service/rdp.service.d.ts.map +1 -0
  53. package/dist/server/service/rdp.service.js +324 -0
  54. package/dist/server/service/rdp.service.js.map +1 -0
  55. package/dist/server/service/rdp.service.ts +324 -0
  56. package/dist/server/service/ssh.service.d.ts +68 -2
  57. package/dist/server/service/ssh.service.d.ts.map +1 -1
  58. package/dist/server/service/ssh.service.js +551 -118
  59. package/dist/server/service/ssh.service.js.map +1 -1
  60. package/dist/server/service/ssh.service.ts +535 -116
  61. package/dist/server/utils/ansi.d.ts +20 -0
  62. package/dist/server/utils/ansi.d.ts.map +1 -0
  63. package/dist/server/utils/ansi.js +39 -0
  64. package/dist/server/utils/ansi.js.map +1 -0
  65. package/dist/server/utils/ansi.ts +34 -0
  66. package/dist/server/utils/rdp-ws.d.ts +15 -0
  67. package/dist/server/utils/rdp-ws.d.ts.map +1 -0
  68. package/dist/server/utils/rdp-ws.js +28 -0
  69. package/dist/server/utils/rdp-ws.js.map +1 -0
  70. package/dist/server/utils/rdp-ws.ts +32 -0
  71. package/dist/view/index.html +9 -7
  72. package/electron/main.js +118 -3
  73. package/electron/preload.js +4 -0
  74. package/package.json +32 -31
  75. package/public/aicmd.png +0 -0
  76. package/server.js +132 -12
  77. package/dist/public/rolldown-runtime.js +0 -41
@@ -43,6 +43,7 @@ const fs = __importStar(require("fs"));
43
43
  const path = __importStar(require("path"));
44
44
  const data_dir_1 = require("../utils/data-dir");
45
45
  const shell_1 = require("../utils/shell");
46
+ const ansi_1 = require("../utils/ansi");
46
47
  // 尝试加载 node-pty,如果可用则使用 PTY 模式
47
48
  let nodePty = null;
48
49
  try {
@@ -60,30 +61,43 @@ const CWD_CACHE_TTL = 120000;
60
61
  * cd 跟踪值的保护期:这段时间内后台探测结果不会覆盖它(见 refreshCwd)。
61
62
  */
62
63
  const CWD_TRACK_GRACE = 5000;
64
+ /**
65
+ * 后台 CWD 刷新的最小间隔:目录刚解析过就跳过,避免频繁 exec 占用 SSH channel。
66
+ */
67
+ const CWD_REFRESH_MIN_INTERVAL = 15000;
63
68
  /**
64
69
  * 远端进程探测脚本(通过独立 exec 通道执行,不会向交互式终端写入任何内容)。
65
70
  *
66
71
  * 输出格式(每行一条,可能 0~2 行):
67
72
  * SHELL:<pid>:<cwd> 本会话的交互式 shell
68
73
  * XFER:<pid>:<cwd> 本会话正在运行的 rz/sz 进程(rz 的 cwd 即文件将写入的目录)
74
+ * NOCWD:<kind>:<pid>:<pri>:<dep>
75
+ * 属于本会话、但 cwd 读不到(sudo su 后属主变了,需要 ptrace 权限)。
76
+ * 出现即表示本次探测结果不可信,必须换用交互式 shell 探测。
69
77
  *
70
78
  * 设计要点:
71
79
  * 1) 只认与本 exec 通道同源(祖先链命中同一个 sshd 会话进程)的候选,
72
80
  * 避免同一台机器开多个标签页时串台读到别的终端目录;
73
- * 2) 排除 exec 通道自身及其祖先,避免把 exec 自己的 shell(cwd 恒为 $HOME)
74
- * 误判成终端 —— 这正是"文件被传到家目录"的根因;
81
+ * 2) 排除 exec 通道自身、其祖先、以及**它的所有子孙进程**(见 is_exec_tree)——
82
+ * 命令替换 $(...)/管道 fork 出的子 shell 与父进程同名、深度更大、cwd 恒为 $HOME,
83
+ * 若不过滤就会被「最深优先」选中,这正是"文件被传到家目录"的根因;
75
84
  * 3) 不使用 exec 通道的 pwd 兜底,探测不到就返回空,宁可让用户手填。
76
85
  */
77
86
  const SESSION_PROBE_SCRIPT = [
87
+ 'self=$$',
78
88
  // 无 /proc 的远端(macOS / BSD):改用 lsof 读取 shell 的 cwd
79
89
  'if [ ! -d /proc ]; then',
80
- ' for pid in $(ps -eo pid=,comm= 2>/dev/null | awk \'$2 ~ /^(bash|zsh|sh|fish|dash|ksh|ksh93|mksh|tcsh|csh)$/ {print $1}\'); do',
90
+ ' for cand in $(ps -eo pid=,ppid=,comm= 2>/dev/null | awk \'$3 ~ /^(bash|zsh|sh|fish|dash|ksh|ksh93|mksh|tcsh|csh)$/ {print $1":"$2}\'); do',
91
+ ' pid=${cand%%:*}',
92
+ ' pp=${cand##*:}',
93
+ // 排除 exec 通道自身及其子进程:它们的 cwd 恒为 $HOME
94
+ ' [ "$pid" = "$self" ] && continue',
95
+ ' [ "$pp" = "$self" ] && continue',
81
96
  ' d=$(lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | sed -n "s/^n//p" | head -n 1)',
82
97
  ' case "$d" in /*) echo "SHELL:$pid:$d"; break;; esac',
83
98
  ' done',
84
99
  ' exit 0',
85
100
  'fi',
86
- 'self=$$',
87
101
  'ppid_of() { sed -n "s/^PPid:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
88
102
  'name_of() { sed -n "s/^Name:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
89
103
  'cwd_of() { readlink "/proc/$1/cwd" 2>/dev/null; }',
@@ -97,27 +111,44 @@ const SESSION_PROBE_SCRIPT = [
97
111
  ' self_chain="$self_chain$p "',
98
112
  ' i=$((i+1))',
99
113
  'done',
114
+ // 是否属于 exec 通道自己的进程树(self 及其子孙)。
115
+ // 只认 self 本身:self 的祖先(sshd 会话进程)是与交互式 shell 共享的,
116
+ // 拿它们做判定会把真正的交互式 shell 也一起排除掉。
117
+ 'is_exec_tree() {',
118
+ ' _et=$1',
119
+ ' [ "$_et" = "$self" ] && return 0',
120
+ ' _j=0',
121
+ ' while [ $_j -lt 12 ]; do',
122
+ ' _et=$(ppid_of "$_et")',
123
+ ' case "$_et" in ""|0|1) break;; esac',
124
+ ' [ "$_et" = "$self" ] && return 0',
125
+ ' _j=$((_j+1))',
126
+ ' done',
127
+ ' return 1',
128
+ '}',
100
129
  // 最近的 sshd 会话祖先:用于把候选限定在本 SSH 会话内
101
130
  'sshd_anc=""',
102
131
  'for q in $self_chain; do',
103
132
  ' n=$(name_of "$q")',
104
133
  ' case "$n" in sshd*) sshd_anc="$q"; break;; esac',
105
134
  'done',
106
- 'in_chain() { case "$self_chain" in *" $1 "*) return 0;; esac; return 1; }',
107
135
  // 返回值即优先级:2 = 与 sshd 会话同源(最准),1 = 仅 stdin 是 tty(tmux/su 等兜底),0 = 不匹配
136
+ // pri_src 记录判定依据:chain=进程链命中 / tty=stdin 是 tty / unknown=读不到(权限不足)
108
137
  'match_pri() {',
109
138
  ' pid=$1',
139
+ ' pri_src=""',
110
140
  ' if [ -n "$sshd_anc" ]; then',
111
141
  ' q=$pid; j=0',
112
142
  ' while [ $j -lt 12 ]; do',
113
143
  ' q=$(ppid_of "$q")',
114
144
  ' case "$q" in ""|0|1) break;; esac',
115
- ' [ "$q" = "$sshd_anc" ] && return 2',
145
+ ' [ "$q" = "$sshd_anc" ] && { pri_src=chain; return 2; }',
116
146
  ' j=$((j+1))',
117
147
  ' done',
118
148
  ' fi',
119
149
  ' tty=$(readlink "/proc/$pid/fd/0" 2>/dev/null)',
120
- ' case "$tty" in /dev/pts/*|/dev/tty*|/dev/console) return 1;; esac',
150
+ ' case "$tty" in /dev/pts/*|/dev/tty*|/dev/console) pri_src=tty; return 1;; esac',
151
+ ' pri_src=unknown',
121
152
  ' return 0',
122
153
  '}',
123
154
  // 进程深度(到 PID 1 的层数):多个候选时取最深的那个。
@@ -135,19 +166,26 @@ const SESSION_PROBE_SCRIPT = [
135
166
  'best_shell=""; best_shell_key=0',
136
167
  'best_xfer=""; best_xfer_key=0',
137
168
  'for pid in $(ls /proc 2>/dev/null | grep -E "^[0-9]+$"); do',
138
- ' in_chain "$pid" && continue',
139
169
  ' n=$(name_of "$pid")',
140
170
  ' case "$n" in',
141
171
  ' bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox) kind=shell;;',
142
172
  ' rz|sz|lrz|lsz|lrzsz) kind=xfer;;',
143
173
  ' *) continue;;',
144
174
  ' esac',
145
- ' c=$(cwd_of "$pid")',
146
- ' [ -n "$c" ] || continue',
175
+ // 先按名字过滤再判定,避免为每个进程都走一遍祖先链(省掉大量 fork)
176
+ ' is_exec_tree "$pid" && continue',
177
+ ' case "$self_chain" in *" $pid "*) continue;; esac',
147
178
  ' match_pri "$pid"',
148
179
  ' pri=$?',
180
+ // sshd 会话祖先未知时无法用进程链判定,fd/0 又因权限读不到的候选按「可能同源」处理,
181
+ // 否则 sudo su / su 之后会直接漏掉用户真正在用的那个 shell。
182
+ ' if [ "$pri" = 0 ] && [ -z "$sshd_anc" ] && [ "$pri_src" = unknown ]; then pri=1; fi',
149
183
  ' [ "$pri" = 0 ] && continue',
150
184
  ' dep=$(depth_of "$pid")',
185
+ ' c=$(cwd_of "$pid")',
186
+ // cwd 读不到:sudo su / su 到别的用户后,/proc/<pid>/cwd 需要 ptrace 权限。
187
+ // 必须上报而不是静默丢弃 —— 否则服务端会把唯一读得到的登录 shell 当成可信答案。
188
+ ' if [ -z "$c" ]; then echo "NOCWD:$kind:$pid:$pri:$dep"; continue; fi',
151
189
  ' key=$((pri * 100 + dep))',
152
190
  ' echo "CAND:$kind:$pid:$c:$pri:$dep"',
153
191
  ' if [ "$kind" = shell ]; then',
@@ -160,6 +198,22 @@ const SESSION_PROBE_SCRIPT = [
160
198
  '[ -n "$best_xfer" ] && echo "XFER:$best_xfer"',
161
199
  'exit 0',
162
200
  ].join('\n');
201
+ /**
202
+ * 判断一个路径是否为有效的绝对路径(跨平台)。
203
+ * - Unix:以 '/' 开头
204
+ * - Windows:盘符形式 `C:\...` / `C:/...`,或以 `\\` 开头的 UNC 路径
205
+ */
206
+ function isAbsolutePath(p) {
207
+ if (!p)
208
+ return false;
209
+ if (p.startsWith('/'))
210
+ return true;
211
+ if (/^[A-Za-z]:[\\/]/.test(p))
212
+ return true;
213
+ if (p.startsWith('\\\\'))
214
+ return true;
215
+ return false;
216
+ }
163
217
  /**
164
218
  * 终端会话管理服务
165
219
  * 支持 SSH 远程连接和本地 Shell
@@ -177,6 +231,8 @@ class SSHService {
177
231
  hasCreatedSession = false;
178
232
  /** 定时清理僵尸 session 的定时器 */
179
233
  cleanupTimer = null;
234
+ /** 正在建立中的 SFTP 连接(避免并发重复创建) */
235
+ sftpPromises = new Map();
180
236
  constructor(connectionService) {
181
237
  this.connectionService = connectionService;
182
238
  this.sessionsFilePath = (0, data_dir_1.getDataPath)('sessions.json');
@@ -293,6 +349,8 @@ class SSHService {
293
349
  pty: ptyProcess,
294
350
  createdAt: new Date(),
295
351
  cwd: homeDir,
352
+ os: isWindows ? 'windows' : 'unix',
353
+ osHint: isWindows ? 'windows' : 'linux',
296
354
  };
297
355
  this.sessions.set(sessionId, session);
298
356
  // Windows: 启动时执行 chcp 65001 设置 UTF-8 编码
@@ -373,23 +431,18 @@ class SSHService {
373
431
  if (connection.forwardAgent) {
374
432
  shellOpts.agentForward = true;
375
433
  }
376
- client.shell(shellOpts, (err, stream) => {
377
- if (err) {
378
- log(`打开 shell 失败: ${err.message}`);
379
- client.end();
380
- reject(err);
381
- return;
382
- }
383
- log(`Shell 会话已建立`);
384
- const session = {
385
- id: sessionId,
386
- connectionId,
387
- type: 'ssh',
388
- name: sessionName,
389
- client,
390
- stream,
391
- createdAt: new Date(),
392
- };
434
+ const session = {
435
+ id: sessionId,
436
+ connectionId,
437
+ type: 'ssh',
438
+ name: sessionName,
439
+ client,
440
+ createdAt: new Date(),
441
+ osHint: connection.platform,
442
+ };
443
+ this.openShell(client, shellOpts, connection, session).then((stream) => {
444
+ session.stream = stream;
445
+ log(`Shell 会话已建立${session.noPty ? '(无 PTY 降级模式)' : ''}`);
393
446
  this.sessions.set(sessionId, session);
394
447
  // 连接后后台探测初始 CWD(在 shell 初始化完成后),用于上传时定位当前目录
395
448
  setTimeout(() => {
@@ -419,6 +472,10 @@ class SSHService {
419
472
  }, 800);
420
473
  }
421
474
  resolve(session);
475
+ }).catch((err) => {
476
+ log(`打开 shell 失败: ${err.message}`);
477
+ client.end();
478
+ reject(err);
422
479
  });
423
480
  }).on('error', (err) => {
424
481
  clearTimeout(timeout);
@@ -427,6 +484,82 @@ class SSHService {
427
484
  }).connect(sshConfig);
428
485
  });
429
486
  }
487
+ /**
488
+ * 打开远端 shell,并在 PTY 不可用时优雅降级。
489
+ *
490
+ * 某些 Windows OpenSSH 配置 / 老旧版本对 pty-req 支持不完整,直接 `client.shell({term})`
491
+ * 会失败。这里依次尝试多个 term 类型,再尝试不带 term 的 shell;
492
+ * 全部失败则降级到「无 PTY 模式」(`client.exec` 启动默认 shell)——交互体验受限
493
+ * (无回显 / 行编辑),但命令仍可执行。降级时会在 session 上标记 noPty。
494
+ */
495
+ openShell(client, shellOpts, connection, session) {
496
+ return new Promise((resolve, reject) => {
497
+ const termCandidates = [shellOpts.term, 'xterm', 'vt100'];
498
+ let ti = 0;
499
+ const tryShell = () => {
500
+ const opts = { ...shellOpts, term: termCandidates[ti] };
501
+ if (!opts.term)
502
+ delete opts.term;
503
+ client.shell(opts, (err, stream) => {
504
+ if (!err)
505
+ return resolve(stream);
506
+ if (ti < termCandidates.length - 1) {
507
+ ti += 1;
508
+ return tryShell();
509
+ }
510
+ // 所有 term 候选都失败:尝试不带 term 的 shell 请求
511
+ client.shell({ ...shellOpts, term: undefined }, (e2, s2) => {
512
+ if (!e2 && s2)
513
+ return resolve(s2);
514
+ // 最终降级:以无 PTY 方式执行默认 shell(交互体验受限,但命令可执行)
515
+ const fallbackShell = connection.platform === 'windows'
516
+ ? 'powershell.exe -NoProfile -NonInteractive -NoLogo'
517
+ : (process.platform === 'win32' ? 'powershell.exe' : '/bin/bash -i');
518
+ client.exec(fallbackShell, (e3, s3) => {
519
+ if (!e3 && s3) {
520
+ if (session)
521
+ session.noPty = true;
522
+ console.warn('[SSH] PTY 不可用,已降级到无 PTY 模式(exec 默认 shell)');
523
+ return resolve(s3);
524
+ }
525
+ reject(err || e2 || e3 || new Error('无法打开远程 shell'));
526
+ });
527
+ });
528
+ });
529
+ };
530
+ tryShell();
531
+ });
532
+ }
533
+ /**
534
+ * 解析远端操作系统类型('unix' | 'windows'),结果缓存到 session。
535
+ * 优先使用连接配置中的 platform 提示;为 'auto' 时通过独立 exec 通道运行
536
+ * `uname -s` 探测(不污染交互式终端):能取到内核名即为类 Unix,否则视为 Windows。
537
+ */
538
+ async resolveSessionOs(sessionId) {
539
+ const session = this.sessions.get(sessionId);
540
+ if (!session)
541
+ return 'unix';
542
+ if (session.os)
543
+ return session.os;
544
+ const hint = session.osHint;
545
+ if (hint === 'windows') {
546
+ session.os = 'windows';
547
+ return 'windows';
548
+ }
549
+ if (hint === 'linux' || hint === 'macos') {
550
+ session.os = 'unix';
551
+ return 'unix';
552
+ }
553
+ try {
554
+ const out = await this.execRemote(sessionId, 'uname -s');
555
+ const s = (out || '').trim().toLowerCase();
556
+ session.os = /linux|darwin|freebsd|openbsd|netbsd|sunos/.test(s) ? 'unix' : 'windows';
557
+ }
558
+ catch {
559
+ session.os = 'unix'; // 探测失败时按类 Unix 处理(最常见的远端)
560
+ }
561
+ return session.os;
562
+ }
430
563
  /**
431
564
  * 获取默认 Shell
432
565
  */
@@ -682,8 +815,13 @@ class SSHService {
682
815
  * Sends a compact command to the remote terminal and captures the output
683
816
  */
684
817
  async activeCollectRemoteSystemInfo(sessionId) {
818
+ const os = await this.resolveSessionOs(sessionId);
685
819
  const marker = '__AICMD_SYS__';
686
- const cmd = `echo "${marker}:$(uname -s 2>/dev/null || echo unknown):$(uname -r 2>/dev/null || echo unknown):$(hostname 2>/dev/null || echo unknown):$(whoami 2>/dev/null || echo unknown):$SHELL:$(uname -m 2>/dev/null || echo unknown)"`;
820
+ // Windows(PowerShell)与类 Unix(bash/sh)使用不同的采集命令;
821
+ // 二者都通过同一个 __AICMD_SYS__ marker 回传,便于统一解析。
822
+ const cmd = os === 'windows'
823
+ ? `Write-Output "${marker}:Windows:$(Get-CimInstance Win32_OperatingSystem | Select-Object -ExpandProperty Version):$(hostname):$env:USERNAME:PowerShell:$(Get-CimInstance Win32_Processor | Select-Object -ExpandProperty Architecture)"`
824
+ : `echo "${marker}:$(uname -s 2>/dev/null || echo unknown):$(uname -r 2>/dev/null || echo unknown):$(hostname 2>/dev/null || echo unknown):$(whoami 2>/dev/null || echo unknown):$SHELL:$(uname -m 2>/dev/null || echo unknown)"`;
687
825
  try {
688
826
  // Start capture, then send the command
689
827
  // Use longer timeout (5s) to account for slow SSH connections and MOTD output
@@ -691,12 +829,13 @@ class SSHService {
691
829
  this.writeData(sessionId, cmd + '\r');
692
830
  const output = await outputPromise;
693
831
  // Clean ANSI escape codes for more reliable marker matching
694
- const cleaned = output.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '').replace(/\x1B\].*?\x07/g, '').replace(/\r/g, '');
832
+ const cleaned = (0, ansi_1.stripAnsiEscapes)(output).replace(/\r/g, '');
695
833
  // Extract our marker line
834
+ const echoPrefixes = ['echo', 'Write-Output'];
696
835
  for (const line of cleaned.split('\n')) {
697
836
  const trimmed = line.trim();
698
837
  // Handle possible command echo: skip lines that still contain the raw command prefix
699
- if (trimmed.includes(marker + ':') && !trimmed.startsWith('echo')) {
838
+ if (trimmed.includes(marker + ':') && !echoPrefixes.some(p => trimmed.startsWith(p))) {
700
839
  const markerIdx = trimmed.indexOf(marker + ':');
701
840
  const markerLine = trimmed.substring(markerIdx);
702
841
  const parts = markerLine.split(':');
@@ -762,6 +901,24 @@ class SSHService {
762
901
  if (genericWelcome)
763
902
  info['OS'] = genericWelcome[1].trim();
764
903
  }
904
+ // Windows(OpenSSH Server / cmd 横幅):"Microsoft Windows [Version 10.0.19041.1]"
905
+ if (!info['OS']) {
906
+ const winVer = motd.match(/Microsoft Windows.*?Version\s+([\d.]+)/i)
907
+ || motd.match(/\bWindows Server\b|\bWindows\b/i);
908
+ if (winVer) {
909
+ info['OS'] = winVer[1] ? `Windows ${winVer[1]}` : 'Windows';
910
+ const verMatch = motd.match(/Version\s+([\d.]+)/i);
911
+ if (verMatch)
912
+ info['Kernel'] = verMatch[1];
913
+ }
914
+ }
915
+ // macOS(部分系统登录横幅含 Darwin 内核信息)
916
+ if (!info['OS'] && /Darwin/i.test(motd)) {
917
+ info['OS'] = 'macOS (Darwin)';
918
+ const darwinMatch = motd.match(/Darwin[^\n]*?([\d.]+)/i);
919
+ if (darwinMatch)
920
+ info['Kernel'] = darwinMatch[1];
921
+ }
765
922
  // === 系统指标(Ubuntu landscape 格式,键值对可能在不同行) ===
766
923
  // System load
767
924
  const loadMatch = motd.match(/System load:\s*(\S+)/);
@@ -845,7 +1002,7 @@ class SSHService {
845
1002
  // === 最终兜底:如果只匹配到极少信息,保留原始 MOTD 作为上下文 ===
846
1003
  if (Object.keys(info).length === 0) {
847
1004
  // 完全没有匹配,返回清理后的原始文本(截取前 800 字符)
848
- const cleaned = motd.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '').replace(/\r/g, '').trim();
1005
+ const cleaned = (0, ansi_1.stripAnsiEscapes)(motd).replace(/\r/g, '').trim();
849
1006
  return cleaned.substring(0, 800);
850
1007
  }
851
1008
  const lines = ['System environment info:'];
@@ -1060,11 +1217,18 @@ Write-Output "__DOCKER__: $dockerVer"
1060
1217
  continue;
1061
1218
  }
1062
1219
  let next;
1063
- if (target.startsWith('/')) {
1064
- next = target;
1065
- }
1066
- else if (session.cwd && session.cwd.startsWith('/')) {
1067
- next = path.posix.resolve(session.cwd, target);
1220
+ const os = session.os ?? (session.osHint === 'windows' ? 'windows' : 'unix');
1221
+ if (target.startsWith('/') || /^[A-Za-z]:[\\/]/.test(target) || target.startsWith('\\\\')) {
1222
+ // 绝对路径(Unix 的 '/' 或 Windows 的盘符 / UNC)
1223
+ next = os === 'windows'
1224
+ ? target.replace(/\//g, '\\') // 统一为 Windows 反斜杠分隔符
1225
+ : target;
1226
+ }
1227
+ else if (isAbsolutePath(session.cwd)) {
1228
+ // 相对路径:基于当前目录拼接(跨平台使用对应 path 模块)
1229
+ next = os === 'windows'
1230
+ ? path.win32.resolve(session.cwd, target)
1231
+ : path.posix.resolve(session.cwd, target);
1068
1232
  }
1069
1233
  else {
1070
1234
  // 当前目录未知,无法拼接相对路径,重置为未知
@@ -1083,7 +1247,27 @@ Write-Output "__DOCKER__: $dockerVer"
1083
1247
  // 只探测 SSH 会话;本地会话的 cwd 由 cd 跟踪维护
1084
1248
  if (session.type !== 'ssh' || !session.client)
1085
1249
  return;
1086
- if (session.shellPid && session.cwd && session.cwd.startsWith('/'))
1250
+ const os = await this.resolveSessionOs(sessionId);
1251
+ if (os === 'windows') {
1252
+ // Windows 无 /proc,后台刷新无法获取 CWD;改用注入式探测拿到初始目录,
1253
+ // 以便后续 cd 跟踪能拼接相对路径。
1254
+ if (isAbsolutePath(session.cwd))
1255
+ return;
1256
+ try {
1257
+ const cwd = await this.probeCwdViaShell(sessionId);
1258
+ if (cwd) {
1259
+ session.cwd = cwd;
1260
+ session.cwdAt = Date.now();
1261
+ session.cwdReliable = true;
1262
+ console.log(`[SSH] seeded windows cwd for ${sessionId}: ${cwd}`);
1263
+ }
1264
+ }
1265
+ catch {
1266
+ // 忽略,上传时再探测
1267
+ }
1268
+ return;
1269
+ }
1270
+ if (session.shellPid && isAbsolutePath(session.cwd))
1087
1271
  return;
1088
1272
  try {
1089
1273
  await this.refreshCwd(sessionId);
@@ -1105,6 +1289,10 @@ Write-Output "__DOCKER__: $dockerVer"
1105
1289
  const session = this.sessions.get(sessionId);
1106
1290
  if (!session || session.type !== 'ssh' || !session.client)
1107
1291
  return;
1292
+ // 目录刚解析过就别再跑 exec 了:每次 exec 都要占用一个 channel,
1293
+ // 频繁调用会挤占 SFTP 的 channel 配额(MaxSessions)。
1294
+ if (session.cwdAt && (Date.now() - session.cwdAt) < CWD_REFRESH_MIN_INTERVAL)
1295
+ return;
1108
1296
  if (session.cwdRefreshTimer)
1109
1297
  clearTimeout(session.cwdRefreshTimer);
1110
1298
  session.cwdRefreshTimer = setTimeout(() => {
@@ -1140,7 +1328,7 @@ Write-Output "__DOCKER__: $dockerVer"
1140
1328
  session.shellPid = probe.shellPid;
1141
1329
  cwd = probe.shellCwd;
1142
1330
  }
1143
- if (cwd && cwd.startsWith('/')) {
1331
+ if (cwd && isAbsolutePath(cwd)) {
1144
1332
  // 用户刚刚敲过 cd(cd 跟踪值很新鲜)时,不覆盖它:
1145
1333
  // cd 是用户的显式意图,比推断出的进程目录更可信,
1146
1334
  // 也能避免探测到错误进程时把正确目录改回成家目录。
@@ -1153,10 +1341,10 @@ Write-Output "__DOCKER__: $dockerVer"
1153
1341
  session.cwdAt = Date.now();
1154
1342
  }
1155
1343
  }
1156
- return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
1344
+ return session.cwd && isAbsolutePath(session.cwd) ? session.cwd : '';
1157
1345
  }
1158
1346
  catch {
1159
- return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
1347
+ return session.cwd && isAbsolutePath(session.cwd) ? session.cwd : '';
1160
1348
  }
1161
1349
  finally {
1162
1350
  session.cwdRefreshing = false;
@@ -1170,16 +1358,21 @@ Write-Output "__DOCKER__: $dockerVer"
1170
1358
  async readPidCwd(sessionId, pid) {
1171
1359
  if (!Number.isInteger(pid) || pid <= 0)
1172
1360
  return '';
1173
- const out = await this.execRemote(sessionId, `cat /proc/${pid}/comm 2>/dev/null; readlink /proc/${pid}/cwd 2>/dev/null`, 4000);
1361
+ const out = await this.execRemote(sessionId, `cat /proc/${pid}/comm 2>/dev/null; readlink /proc/${pid}/cwd 2>/dev/null; readlink /proc/${pid}/fd/0 2>/dev/null`, 4000);
1174
1362
  const lines = out.split('\n').map(l => l.trim()).filter(Boolean);
1175
- if (lines.length < 2)
1363
+ if (lines.length < 3)
1176
1364
  return '';
1177
1365
  const comm = lines[0];
1178
- const cwd = lines[lines.length - 1];
1179
- if (!cwd.startsWith('/'))
1366
+ const cwd = lines[1];
1367
+ const stdin = lines[2];
1368
+ if (!isAbsolutePath(cwd))
1180
1369
  return '';
1181
1370
  if (!/^(bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox|rz|sz|lrz|lsz)$/.test(comm))
1182
1371
  return '';
1372
+ // 交互式 shell / rz 的 stdin 一定是 tty;exec 通道(及其子 shell)是 pipe/socket,
1373
+ // 这里再校验一次,避免 PID 复用时读到无关进程的目录(通常是 $HOME)。
1374
+ if (!/^\/dev\/(pts|tty|console)/.test(stdin))
1375
+ return '';
1183
1376
  return cwd;
1184
1377
  }
1185
1378
  /**
@@ -1192,6 +1385,8 @@ Write-Output "__DOCKER__: $dockerVer"
1192
1385
  shellCwd: '',
1193
1386
  xferCwd: '',
1194
1387
  candidates: [],
1388
+ unreadable: [],
1389
+ reliable: true,
1195
1390
  };
1196
1391
  const out = await this.execRemote(sessionId, SESSION_PROBE_SCRIPT, 5000);
1197
1392
  for (const raw of out.split('\n')) {
@@ -1203,6 +1398,11 @@ Write-Output "__DOCKER__: $dockerVer"
1203
1398
  result.candidates.push(line.substring(5));
1204
1399
  continue;
1205
1400
  }
1401
+ if (line.startsWith('NOCWD:')) {
1402
+ // 诊断 + 可信度:kind:pid:pri:depth(cwd 因权限读不到)
1403
+ result.unreadable.push(line.substring(6));
1404
+ continue;
1405
+ }
1206
1406
  const m = line.match(/^(SHELL|XFER):(\d+):(\/.*)$/);
1207
1407
  if (!m)
1208
1408
  continue;
@@ -1216,8 +1416,13 @@ Write-Output "__DOCKER__: $dockerVer"
1216
1416
  result.xferCwd = cwd;
1217
1417
  }
1218
1418
  }
1419
+ // 只要还有读不到的同源候选,本次结果就只能算「推断」:
1420
+ // 用户真正在用的 shell 很可能就是那个读不到的(sudo su 后的 root shell)。
1421
+ if (result.unreadable.length)
1422
+ result.reliable = false;
1219
1423
  console.log(`[SSH] probeSessionProcess: shell=${result.shellPid || '-'}:${result.shellCwd || '-'} ` +
1220
- `xfer=${result.xferCwd || '-'} cands=[${result.candidates.join(' | ')}]`);
1424
+ `xfer=${result.xferCwd || '-'} reliable=${result.reliable} ` +
1425
+ `cands=[${result.candidates.join(' | ')}] nocwd=[${result.unreadable.join(' | ')}]`);
1221
1426
  return result;
1222
1427
  }
1223
1428
  /**
@@ -1233,11 +1438,18 @@ Write-Output "__DOCKER__: $dockerVer"
1233
1438
  }
1234
1439
  let stdout = '';
1235
1440
  let settled = false;
1441
+ let streamRef = null;
1236
1442
  const finish = () => {
1237
1443
  if (settled)
1238
1444
  return;
1239
1445
  settled = true;
1240
1446
  clearTimeout(timer);
1447
+ // 必须显式关闭 channel:OpenSSH 默认 MaxSessions=10,
1448
+ // 泄漏的 channel 累积后会导致后续 SFTP channel 打开失败(上传时好时坏)。
1449
+ try {
1450
+ streamRef?.end();
1451
+ }
1452
+ catch { /* ignore */ }
1241
1453
  resolve(stdout);
1242
1454
  };
1243
1455
  const timer = setTimeout(finish, timeoutMs);
@@ -1248,6 +1460,7 @@ Write-Output "__DOCKER__: $dockerVer"
1248
1460
  finish();
1249
1461
  return;
1250
1462
  }
1463
+ streamRef = stream;
1251
1464
  stream.on('data', (data) => { stdout += data.toString('utf-8'); });
1252
1465
  stream.stderr.on('data', () => { });
1253
1466
  stream.on('close', finish);
@@ -1276,6 +1489,15 @@ Write-Output "__DOCKER__: $dockerVer"
1276
1489
  * 通知输出监听器(由 WebSocket 处理器在收到终端输出时调用)
1277
1490
  */
1278
1491
  notifyOutput(sessionId, data) {
1492
+ // 累积到会话输出缓冲(供 Agent 的 read_terminal / shell.read 读取)
1493
+ const session = this.sessions.get(sessionId);
1494
+ if (session) {
1495
+ let buf = (session.outputBuffer || '') + data;
1496
+ // 限制缓冲上限,避免长会话无限增长(保留尾部约 32KB)
1497
+ if (buf.length > 32768)
1498
+ buf = buf.slice(-32768);
1499
+ session.outputBuffer = buf;
1500
+ }
1279
1501
  const listener = this.outputListeners.get(sessionId);
1280
1502
  if (listener) {
1281
1503
  try {
@@ -1286,6 +1508,81 @@ Write-Output "__DOCKER__: $dockerVer"
1286
1508
  }
1287
1509
  }
1288
1510
  }
1511
+ /**
1512
+ * 读取会话累积的输出缓冲(当前屏幕/历史内容),不依赖「调用后新到达」的采集窗口。
1513
+ * @param maxLines 最多返回末尾行数,默认 200
1514
+ */
1515
+ getOutputBuffer(sessionId, maxLines = 200) {
1516
+ const session = this.sessions.get(sessionId);
1517
+ if (!session || !session.outputBuffer)
1518
+ return '';
1519
+ const cleaned = (0, ansi_1.stripAnsiEscapes)(session.outputBuffer);
1520
+ const lines = cleaned.split('\n');
1521
+ return lines.slice(-maxLines).join('\n');
1522
+ }
1523
+ /**
1524
+ * 采集输出并「空闲即停」:新数据停止到达超过 idleMs 后认为本次输出结束,
1525
+ * 最长不超过 maxMs。相比固定时间窗口,能完整拿到慢命令的输出,
1526
+ * 又不会像定长等待那样白白浪费时间。
1527
+ * @param sessionId 会话 ID
1528
+ * @param idleMs 判定输出结束的静默时长,默认 700ms
1529
+ * @param maxMs 最长等待(兜底),默认 10000ms
1530
+ * @returns 已去除 ANSI 转义序列的输出文本
1531
+ */
1532
+ captureOutputIdle(sessionId, idleMs = 700, maxMs = 10000) {
1533
+ return new Promise((resolve) => {
1534
+ const clean = (s) => (0, ansi_1.stripAnsiEscapes)(s);
1535
+ const session = this.sessions.get(sessionId);
1536
+ let raw = '';
1537
+ let settled = false;
1538
+ let lastLen = 0;
1539
+ let lastChangeAt = Date.now();
1540
+ let streamHandler = null;
1541
+ let listener = null;
1542
+ let idleTimer = null;
1543
+ let maxTimer = null;
1544
+ const finish = () => {
1545
+ if (settled)
1546
+ return;
1547
+ settled = true;
1548
+ if (idleTimer)
1549
+ clearInterval(idleTimer);
1550
+ if (maxTimer)
1551
+ clearTimeout(maxTimer);
1552
+ if (streamHandler && session?.stream) {
1553
+ session.stream.removeListener('data', streamHandler);
1554
+ }
1555
+ else if (listener) {
1556
+ this.removeOutputListener(sessionId);
1557
+ }
1558
+ resolve(clean(raw));
1559
+ };
1560
+ idleTimer = setInterval(() => {
1561
+ if (settled)
1562
+ return;
1563
+ const now = Date.now();
1564
+ if (raw.length !== lastLen) {
1565
+ lastLen = raw.length;
1566
+ lastChangeAt = now;
1567
+ return;
1568
+ }
1569
+ // 已有数据且静默超过 idleMs,判定本次输出结束
1570
+ if (raw.length > 0 && now - lastChangeAt >= idleMs)
1571
+ finish();
1572
+ }, 100);
1573
+ maxTimer = setTimeout(finish, maxMs);
1574
+ const onData = (text) => { raw += text; };
1575
+ if (session?.stream) {
1576
+ streamHandler = (chunk) => onData(chunk.toString('utf-8'));
1577
+ session.stream.on('data', streamHandler);
1578
+ }
1579
+ else {
1580
+ // 本地 shell fallback:通过 notifyOutput 机制
1581
+ listener = onData;
1582
+ this.addOutputListener(sessionId, listener);
1583
+ }
1584
+ });
1585
+ }
1289
1586
  /**
1290
1587
  * 捕获会话在指定时间内的输出
1291
1588
  * @param sessionId 会话 ID
@@ -1311,10 +1608,7 @@ Write-Output "__DOCKER__: $dockerVer"
1311
1608
  else if (listener) {
1312
1609
  this.removeOutputListener(sessionId);
1313
1610
  }
1314
- resolve(output
1315
- .replace(/\x1B\][^\x07]*\x07/g, '')
1316
- .replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '')
1317
- .replace(/\x1B[^\x1B]*[a-zA-Z]/g, ''));
1611
+ resolve((0, ansi_1.stripAnsiEscapes)(output));
1318
1612
  };
1319
1613
  const timer = setTimeout(finish, timeoutMs);
1320
1614
  const onData = (text) => {
@@ -1365,6 +1659,9 @@ Write-Output "__DOCKER__: $dockerVer"
1365
1659
  clearTimeout(session.cwdRefreshTimer);
1366
1660
  session.cwdRefreshTimer = undefined;
1367
1661
  }
1662
+ // 关闭复用的 SFTP channel,避免连接关闭后仍占用资源
1663
+ this.invalidateSftp(sessionId);
1664
+ this.sftpPromises.delete(sessionId);
1368
1665
  try {
1369
1666
  if (session.pty) {
1370
1667
  session.pty.kill();
@@ -1411,25 +1708,68 @@ Write-Output "__DOCKER__: $dockerVer"
1411
1708
  * 也不能把陈旧的(很可能是家目录的)路径当成当前目录 —— 那会导致文件传错位置。
1412
1709
  */
1413
1710
  async getSessionCwd(sessionId, opts = {}) {
1711
+ return (await this.getSessionCwdDetailed(sessionId, opts)).cwd;
1712
+ }
1713
+ /**
1714
+ * 同 getSessionCwd,但额外返回可信度。
1715
+ *
1716
+ * reliable=false 的典型场景:`sudo su` / `su` 之后,用户真正在用的 shell 属于 root,
1717
+ * 而 exec 通道跑在登录用户下,/proc/<pid>/cwd 需要 ptrace 权限、读不到,
1718
+ * 探测结果退化成「唯一读得到的那个进程」(往往是登录 shell = 家目录)。
1719
+ * 调用方必须据此改向交互式 shell 询问或让用户确认,不能直接拿它当结论。
1720
+ */
1721
+ async getSessionCwdDetailed(sessionId, opts = {}) {
1414
1722
  const allowShellProbe = opts.allowShellProbe !== false;
1415
1723
  const session = this.sessions.get(sessionId);
1416
1724
  if (!session)
1417
- return '';
1418
- const cached = session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
1725
+ return { cwd: '', reliable: false };
1726
+ const cached = session.cwd && isAbsolutePath(session.cwd) ? session.cwd : '';
1419
1727
  const cacheFresh = !!cached && !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_CACHE_TTL;
1420
- // 0) 强制刷新 + 允许注入探测:直接向 shell 询问,这是最权威的手段。
1421
- // 调用方(上传前兜底、用户点"重新检测")已确保终端处于可打断状态,
1422
- // 否则只靠 exec 探测,一旦 shellPid 指错进程就会一直拿到错误的目录。
1423
- if (opts.force && allowShellProbe) {
1424
- let probed = await this.probeCwdViaShell(sessionId);
1425
- if (!probed)
1426
- probed = await this.probeCwdViaShell(sessionId);
1427
- if (probed && probed.startsWith('/')) {
1428
- session.cwd = probed;
1429
- session.cwdAt = Date.now();
1430
- console.log(`[SSH] getSessionCwd (forced shell probe): '${probed}'`);
1431
- return probed;
1432
- }
1728
+ const commit = (cwd, reliable) => {
1729
+ session.cwd = cwd;
1730
+ session.cwdAt = Date.now();
1731
+ session.cwdReliable = reliable;
1732
+ console.log(`[SSH] getSessionCwd: '${cwd}' reliable=${reliable}`);
1733
+ return { cwd, reliable };
1734
+ };
1735
+ // 0) 强制刷新:按可信度从高到低依次尝试,拿到结果立即返回;
1736
+ // 全部失败时只在缓存仍然新鲜的情况下才用缓存兜底,绝不把不可信的猜测当当前目录。
1737
+ if (opts.force) {
1738
+ let probed = '';
1739
+ // 0.1) 向 shell 询问(最权威)。调用方(上传前兜底、用户点"重新检测")已确保
1740
+ // 终端处于可打断状态;rz 把终端设为 raw 模式时 Ctrl+C 只是普通字节,
1741
+ // 探测会失败并落到 0.2,不会污染结果。
1742
+ if (allowShellProbe) {
1743
+ let probed = await this.probeCwdViaShell(sessionId);
1744
+ if (!probed)
1745
+ probed = await this.probeCwdViaShell(sessionId);
1746
+ if (isAbsolutePath(probed))
1747
+ return commit(probed, true);
1748
+ }
1749
+ // 0.2) 进程探测:rz/sz 自己的 cwd 最权威(它就是文件要写入的目录)。
1750
+ if (session.type === 'ssh' && session.client) {
1751
+ const probe = await this.probeSessionProcess(sessionId);
1752
+ if (probe.shellPid)
1753
+ session.shellPid = probe.shellPid;
1754
+ if (isAbsolutePath(probe.xferCwd))
1755
+ return commit(probe.xferCwd, true);
1756
+ // 可信的 shell 进程目录(能读到所有同源进程):直接用,无需再麻烦用户。
1757
+ if (isAbsolutePath(probe.shellCwd) && probe.reliable) {
1758
+ return commit(probe.shellCwd, true);
1759
+ }
1760
+ // 不可信(sudo su 等只读到部分进程):优先用「用户刚敲的 cd」跟踪值,
1761
+ // 它最贴近真实意图;最后才退回不可信的进程推断,绝不能把登录 shell 家目录
1762
+ // 当成当前目录(那会让文件传到错误的位置)。
1763
+ const trackedFresh = !!cached && !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_TRACK_GRACE;
1764
+ if (trackedFresh)
1765
+ return commit(cached, true);
1766
+ if (isAbsolutePath(probe.shellCwd))
1767
+ return commit(probe.shellCwd, probe.reliable);
1768
+ }
1769
+ const forcedFallback = cacheFresh ? cached : '';
1770
+ console.log(`[SSH] getSessionCwd: forced probe failed for ${sessionId} ` +
1771
+ `(allowShellProbe=${allowShellProbe}, staleCache=${cached || '-'}, returning='${forcedFallback}')`);
1772
+ return { cwd: forcedFallback, reliable: false };
1433
1773
  }
1434
1774
  // 0.5) rz/sz 正在等待传输:直接取 rz 进程自身的 cwd。
1435
1775
  // 这是最权威的来源 —— rz 由用户所在的 shell 启动,其 cwd 就是文件要写入的目录,
@@ -1439,25 +1779,24 @@ Write-Output "__DOCKER__: $dockerVer"
1439
1779
  if (probe.shellPid)
1440
1780
  session.shellPid = probe.shellPid;
1441
1781
  const cwd = probe.xferCwd || probe.shellCwd;
1442
- if (cwd) {
1443
- session.cwd = cwd;
1444
- session.cwdAt = Date.now();
1445
- return cwd;
1446
- }
1782
+ if (cwd)
1783
+ return commit(cwd, probe.reliable);
1447
1784
  }
1448
1785
  // 1) 缓存命中(且未过期、未强制刷新)
1449
- if (cached && cacheFresh && !opts.force) {
1450
- return cached;
1786
+ // 注意:缓存值本身不可信时必须重新探测,不能直接用 ——
1787
+ // 那正是"sudo su 后上次探测只拿到登录 shell 家目录"的情况,
1788
+ // 若在这里直接返回,错误目录会被一直沿用,警告也就永远消不掉。
1789
+ if (cached && cacheFresh && session.cwdReliable !== false) {
1790
+ return { cwd: cached, reliable: true };
1451
1791
  }
1452
1792
  // 2) 已知 shell PID:直接读 /proc
1793
+ // inferredCwd:进程探测得到的推断值,可信则立即采用,不可信时留作最后兜底
1794
+ let inferredCwd = '';
1453
1795
  if (session.type === 'ssh' && session.client) {
1454
1796
  if (session.shellPid) {
1455
1797
  const cwd = await this.readPidCwd(sessionId, session.shellPid);
1456
- if (cwd) {
1457
- session.cwd = cwd;
1458
- session.cwdAt = Date.now();
1459
- return cwd;
1460
- }
1798
+ if (cwd)
1799
+ return commit(cwd, true);
1461
1800
  session.shellPid = undefined;
1462
1801
  }
1463
1802
  // 3) 完整进程探测(默认 shell 优先,rz 场景下优先 rz 进程自身的 cwd)
@@ -1467,36 +1806,45 @@ Write-Output "__DOCKER__: $dockerVer"
1467
1806
  const cwd = (opts.preferTransferProcess && probe.xferCwd)
1468
1807
  ? probe.xferCwd
1469
1808
  : (probe.shellCwd || probe.xferCwd);
1470
- if (cwd) {
1471
- session.cwd = cwd;
1472
- session.cwdAt = Date.now();
1473
- return cwd;
1474
- }
1809
+ // 只有结果可信才直接采用。不可信(sudo su 后只能读到登录 shell)时必须继续
1810
+ // 走第 4 步向交互式 shell 询问 —— 否则会把登录 shell 的家目录当成当前目录,
1811
+ // 文件就传到错误的位置了(这正是"老是传到 /home/ubuntu"的根因)。
1812
+ if (cwd && probe.reliable)
1813
+ return commit(cwd, true);
1814
+ // 不允许注入式探测(rz 正在等待接收):只能用这个推断值,如实标记不可信,
1815
+ // 由前端提示用户核对或改走 ZMODEM 直发。
1816
+ if (cwd && !allowShellProbe)
1817
+ return commit(cwd, false);
1818
+ inferredCwd = cwd || '';
1475
1819
  }
1476
1820
  // 4) 注入式探测(会打断前台进程)
1477
1821
  if (allowShellProbe) {
1478
1822
  let cwd = await this.probeCwdViaShell(sessionId);
1479
1823
  if (!cwd)
1480
1824
  cwd = await this.probeCwdViaShell(sessionId);
1481
- if (cwd && cwd.startsWith('/')) {
1482
- session.cwd = cwd;
1483
- session.cwdAt = Date.now();
1484
- return cwd;
1485
- }
1825
+ if (isAbsolutePath(cwd))
1826
+ return commit(cwd, true);
1486
1827
  }
1828
+ // 注入式探测也失败:退回进程推断值(有总比没有强,前端会提示用户核对)
1829
+ if (inferredCwd)
1830
+ return commit(inferredCwd, false);
1487
1831
  // 全部失败:缓存已过期时返回空(让前端提示手填),避免把陈旧目录当当前目录使用
1488
1832
  const fallback = cacheFresh ? cached : '';
1489
1833
  console.log(`[SSH] getSessionCwd: probes failed for ${sessionId} ` +
1490
- `(allowShellProbe=${allowShellProbe}, force=${!!opts.force}, staleCache=${cached || '-'}, returning='${fallback || ''}')`);
1491
- return fallback;
1834
+ `(allowShellProbe=${allowShellProbe}, staleCache=${cached || '-'}, returning='${fallback}')`);
1835
+ return { cwd: fallback, reliable: false };
1492
1836
  }
1493
- /** 向交互式 shell 注入 printf $PWD 探测 CWD(会先 Ctrl+C 打断前台进程) */
1837
+ /** 向交互式 shell 注入命令探测 CWD(会先 Ctrl+C 打断前台进程) */
1494
1838
  async probeCwdViaShell(sessionId) {
1839
+ const os = await this.resolveSessionOs(sessionId);
1495
1840
  const marker = `__AICmd_CWD_${Date.now()}__`;
1496
1841
  // 先发送 Ctrl+C 中断可能正在运行的前台进程(如 rz、vim、top 等),
1497
- // 否则 printf 命令会被前台进程吞掉,shell 不会执行
1842
+ // 否则命令会被前台进程吞掉,shell 不会执行
1498
1843
  this.writeData(sessionId, '\x03');
1499
1844
  await new Promise(r => setTimeout(r, 200));
1845
+ // Ctrl+U 清空当前输入行:若行内还有残留字符,注入的命令会被拼接成无效命令而拿不到结果
1846
+ this.writeData(sessionId, '\x15');
1847
+ await new Promise(r => setTimeout(r, 150));
1500
1848
  // 启动捕获后发送命令(marker 行输出完整就立即返回,通常几百毫秒)
1501
1849
  const stopWhen = (text) => {
1502
1850
  const i = text.indexOf(marker);
@@ -1506,21 +1854,24 @@ Write-Output "__DOCKER__: $dockerVer"
1506
1854
  return after.includes('\n') || after.length > 80;
1507
1855
  };
1508
1856
  const outputPromise = this.captureOutput(sessionId, 3000, stopWhen);
1509
- this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\r`);
1857
+ // 类 Unix:printf 输出 $PWD(绝对路径以 '/' 开头)
1858
+ // Windows(PowerShell):$PWD 自动变量即当前位置,字符串化为盘符路径(如 C:\Users\me)
1859
+ if (os === 'windows') {
1860
+ this.writeData(sessionId, ` Write-Output "${marker}:$PWD"\r`);
1861
+ }
1862
+ else {
1863
+ this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\r`);
1864
+ }
1510
1865
  const output = await outputPromise;
1511
- console.log(`[SSH] probeCwdViaShell: raw output: ${JSON.stringify(output.substring(0, 500))}`);
1512
- // 更彻底的 ANSI 清理:包括 OSC 序列、CSI 序列、以及各种控制字符
1513
- const cleaned = output
1514
- .replace(/\x1B\][^\x07]*\x07/g, '') // OSC 序列
1515
- .replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '') // CSI 序列
1516
- .replace(/\x1B[^\x1B]*[a-zA-Z]/g, '') // 其他转义序列
1517
- .replace(/\r/g, '');
1866
+ // 更彻底的 ANSI 清理:OSC / CSI / 其它有界转义(不得使用会吞正文的贪婪兜底)
1867
+ const cleaned = (0, ansi_1.stripAnsiEscapes)(output).replace(/\r/g, '');
1518
1868
  const isCommandEcho = (text) => (text.includes('printf') ||
1869
+ text.includes('Write-Output') ||
1519
1870
  text.includes('$PWD') ||
1520
1871
  text.includes('%s') ||
1521
1872
  text.includes('echo') ||
1522
1873
  text.includes('$(pwd)'));
1523
- const isValidCwd = (cwd) => cwd.startsWith('/') && !isCommandEcho(cwd);
1874
+ const isValidCwd = (cwd) => isAbsolutePath(cwd) && !isCommandEcho(cwd);
1524
1875
  for (const line of cleaned.split('\n')) {
1525
1876
  const trimmed = line.trim();
1526
1877
  if (!trimmed || isCommandEcho(trimmed))
@@ -1576,14 +1927,34 @@ Write-Output "__DOCKER__: $dockerVer"
1576
1927
  // 解析相对路径:必须通过交互式 shell 获取当前 CWD。
1577
1928
  // 注意:不能 fallback 到 SFTP realpath('.'),它通常是登录 home 目录,会导致文件传错位置。
1578
1929
  let fullPath = remotePath;
1579
- if (!remotePath.startsWith('/')) {
1580
- console.log(`[SSH] Getting shell CWD...`);
1581
- const cwd = await this.getSessionCwd(sessionId);
1582
- console.log(`[SSH] Shell CWD: '${cwd}'`);
1583
- if (!cwd || !cwd.startsWith('/')) {
1584
- throw new Error('无法获取当前终端目录,请确认终端处于正常 Shell 提示符状态后重试');
1930
+ const uploadOs = await this.resolveSessionOs(sessionId);
1931
+ if (uploadOs === 'windows') {
1932
+ // Win32-OpenSSH 的 SFTP 子系统以正斜杠 + 盘符形式表示路径(如 C:/Users/name/file),
1933
+ // 与 PowerShell $PWD 返回的反斜杠路径不同,需统一转换为正斜杠。
1934
+ const norm = (p) => p.replace(/\\/g, '/');
1935
+ if (/^[A-Za-z]:[\\/]/.test(remotePath) || remotePath.startsWith('\\\\')) {
1936
+ fullPath = norm(remotePath);
1937
+ }
1938
+ else {
1939
+ console.log(`[SSH] Getting shell CWD (windows)...`);
1940
+ const cwd = await this.getSessionCwd(sessionId);
1941
+ console.log(`[SSH] Shell CWD: '${cwd}'`);
1942
+ if (!isAbsolutePath(cwd)) {
1943
+ throw new Error('无法获取当前终端目录,请确认终端处于正常 Shell 提示符状态后重试');
1944
+ }
1945
+ fullPath = `${norm(cwd).replace(/\/$/, '')}/${norm(remotePath)}`;
1946
+ }
1947
+ }
1948
+ else {
1949
+ if (!remotePath.startsWith('/')) {
1950
+ console.log(`[SSH] Getting shell CWD...`);
1951
+ const cwd = await this.getSessionCwd(sessionId);
1952
+ console.log(`[SSH] Shell CWD: '${cwd}'`);
1953
+ if (!cwd || !cwd.startsWith('/')) {
1954
+ throw new Error('无法获取当前终端目录,请确认终端处于正常 Shell 提示符状态后重试');
1955
+ }
1956
+ fullPath = `${cwd.replace(/\/$/, '')}/${remotePath}`;
1585
1957
  }
1586
- fullPath = `${cwd.replace(/\/$/, '')}/${remotePath}`;
1587
1958
  }
1588
1959
  console.log(`[SSH] SFTP upload path: ${remotePath} -> ${fullPath}`);
1589
1960
  // 使用 Promise + 超时包装(120秒,大文件需要更多时间)
@@ -1606,21 +1977,25 @@ Write-Output "__DOCKER__: $dockerVer"
1606
1977
  else
1607
1978
  resolve(bytes);
1608
1979
  };
1609
- const doSftpWrite = (targetPath, callback) => {
1610
- console.log(`[SSH] SFTP opening subsystem...`);
1611
- session.client.sftp((sftpErr, sftp) => {
1980
+ const doSftpWrite = (targetPath, callback, isRetry = false) => {
1981
+ console.log(`[SSH] SFTP getting subsystem (reuse=${!!session.sftp})...`);
1982
+ this.getSftp(sessionId).then((sftp) => {
1612
1983
  if (done)
1613
1984
  return;
1614
- if (sftpErr) {
1615
- callback(new Error('SFTP init failed: ' + sftpErr.message));
1616
- return;
1617
- }
1618
1985
  console.log(`[SSH] SFTP writing ${fileBuffer.length} bytes to ${targetPath}...`);
1619
1986
  sftp.open(targetPath, 'w', (openErr, fd) => {
1620
1987
  if (done)
1621
1988
  return;
1622
1989
  if (openErr) {
1623
1990
  console.error(`[SSH] SFTP open error: ${openErr.message}`);
1991
+ // channel 类故障(达到 MaxSessions 上限 / channel 已失效):重建实例后重试一次
1992
+ if (!isRetry && /channel|not open|closed|failure/i.test(openErr.message)) {
1993
+ console.log('[SSH] SFTP channel broken, recreating subsystem and retrying once');
1994
+ this.invalidateSftp(sessionId);
1995
+ setTimeout(() => { if (!done)
1996
+ doSftpWrite(targetPath, callback, true); }, 300);
1997
+ return;
1998
+ }
1624
1999
  callback(new Error('SFTP open failed: ' + openErr.message));
1625
2000
  return;
1626
2001
  }
@@ -1644,6 +2019,18 @@ Write-Output "__DOCKER__: $dockerVer"
1644
2019
  });
1645
2020
  });
1646
2021
  });
2022
+ }).catch((initErr) => {
2023
+ if (done)
2024
+ return;
2025
+ // 建立 subsystem 就可能 "Channel open failure"(MaxSessions 上限):重建后重试一次
2026
+ if (!isRetry && /channel|failure|closed|not open/i.test(initErr?.message || '')) {
2027
+ console.log('[SSH] SFTP init failed, recreating subsystem and retrying once');
2028
+ this.invalidateSftp(sessionId);
2029
+ setTimeout(() => { if (!done)
2030
+ doSftpWrite(targetPath, callback, true); }, 300);
2031
+ return;
2032
+ }
2033
+ callback(new Error(initErr?.message || 'SFTP init failed'));
1647
2034
  });
1648
2035
  };
1649
2036
  // 先尝试直接写入目标路径
@@ -1653,8 +2040,12 @@ Write-Output "__DOCKER__: $dockerVer"
1653
2040
  if (!err) {
1654
2041
  // 直接写入成功,验证文件
1655
2042
  console.log(`[SSH] SFTP direct write succeeded, verifying...`);
1656
- session.client.sftp((_, sftp) => {
2043
+ this.getSftp(sessionId).then((sftp) => {
2044
+ if (done)
2045
+ return;
1657
2046
  sftp.stat(fullPath, (statErr, stats) => {
2047
+ if (done)
2048
+ return;
1658
2049
  if (statErr || stats.size !== fileBuffer.length) {
1659
2050
  finish(new Error('SFTP verify failed'));
1660
2051
  }
@@ -1663,6 +2054,10 @@ Write-Output "__DOCKER__: $dockerVer"
1663
2054
  finish(null, fileBuffer.length);
1664
2055
  }
1665
2056
  });
2057
+ }).catch((statInitErr) => {
2058
+ if (done)
2059
+ return;
2060
+ finish(new Error(statInitErr?.message || 'SFTP verify init failed'));
1666
2061
  });
1667
2062
  return;
1668
2063
  }
@@ -1787,20 +2182,58 @@ Write-Output "__DOCKER__: $dockerVer"
1787
2182
  }
1788
2183
  // ========== 文件管理(SFTP / 本地 fs) ==========
1789
2184
  /**
1790
- * 获取 SFTP 客户端(ssh2 的 sftp 子系统)
2185
+ * 获取(并复用)SFTP 客户端(ssh2 的 sftp 子系统)
2186
+ *
2187
+ * 必须复用:OpenSSH 默认 MaxSessions=10,而每次 client.sftp() 都会新开一个
2188
+ * subsystem channel。若每次调用都新建且不关闭,几次之后就会
2189
+ * "Channel open failure: open failed",表现为上传时好时坏、重连后又正常。
1791
2190
  */
1792
2191
  getSftp(sessionId) {
1793
2192
  const session = this.sessions.get(sessionId);
1794
2193
  if (!session || !session.client) {
1795
2194
  return Promise.reject(new Error('SFTP is only available for SSH sessions'));
1796
2195
  }
1797
- return new Promise((resolve, reject) => {
2196
+ if (session.sftp)
2197
+ return Promise.resolve(session.sftp);
2198
+ const pending = this.sftpPromises.get(sessionId);
2199
+ if (pending)
2200
+ return pending;
2201
+ const p = new Promise((resolve, reject) => {
1798
2202
  session.client.sftp((err, sftp) => {
1799
- if (err)
1800
- return reject(err);
2203
+ this.sftpPromises.delete(sessionId);
2204
+ if (err || !sftp) {
2205
+ reject(new Error('SFTP init failed: ' + (err?.message || 'unknown')));
2206
+ return;
2207
+ }
2208
+ session.sftp = sftp;
2209
+ // 实例出错/关闭后丢弃,下次自动重建
2210
+ const drop = () => {
2211
+ if (session.sftp === sftp)
2212
+ session.sftp = undefined;
2213
+ };
2214
+ try {
2215
+ sftp.on('error', drop);
2216
+ sftp.on('close', drop);
2217
+ }
2218
+ catch { /* ignore */ }
1801
2219
  resolve(sftp);
1802
2220
  });
1803
2221
  });
2222
+ this.sftpPromises.set(sessionId, p);
2223
+ return p;
2224
+ }
2225
+ /** 丢弃并关闭失效的 SFTP 实例(下次使用时重建) */
2226
+ invalidateSftp(sessionId) {
2227
+ const session = this.sessions.get(sessionId);
2228
+ const sftp = session?.sftp;
2229
+ if (!sftp)
2230
+ return;
2231
+ session.sftp = undefined;
2232
+ this.sftpPromises.delete(sessionId);
2233
+ try {
2234
+ sftp.end();
2235
+ }
2236
+ catch { /* ignore */ }
1804
2237
  }
1805
2238
  /**
1806
2239
  * 列出远程(或本地)目录内容