@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
@@ -8,6 +8,7 @@ import * as fs from 'fs';
8
8
  import * as path from 'path';
9
9
  import { getDataPath } from '../utils/data-dir';
10
10
  import { shellQuote } from '../utils/shell';
11
+ import { stripAnsiEscapes } from '../utils/ansi';
11
12
 
12
13
  // 尝试加载 node-pty,如果可用则使用 PTY 模式
13
14
  let nodePty: any = null;
@@ -37,16 +38,28 @@ interface TerminalSession {
37
38
  cwd?: string;
38
39
  /** cwd 最后一次被成功解析的时间戳(用于判断缓存是否过期) */
39
40
  cwdAt?: number;
41
+ /** 缓存的 cwd 是否可信(false = 只是「唯一读得到的进程」推断值,如 sudo su 后的登录 shell) */
42
+ cwdReliable?: boolean;
40
43
  /** 未提交的输入行缓冲(xterm 逐字符发送,需累积成完整命令行才能解析 cd) */
41
44
  inputBuffer?: string;
45
+ /** 累积的终端输出缓冲(供 Agent 的 read_terminal / shell.read 读取当前屏幕内容,避免空闲时抓不到输出) */
46
+ outputBuffer?: string;
42
47
  /** 远端交互式 shell 的 PID(用于 /proc/<pid>/cwd 精确读取当前目录,不影响终端) */
43
48
  shellPid?: number;
49
+ /** 复用的 SFTP 实例(每个会话只建一次,避免 channel 泄漏) */
50
+ sftp?: any;
44
51
  /** 后台刷新 CWD 的防抖定时器 */
45
52
  cwdRefreshTimer?: NodeJS.Timeout;
46
53
  /** 上次后台刷新 CWD 的时间戳 */
47
54
  lastCwdRefreshAt?: number;
48
55
  /** 是否正在刷新 CWD(避免并发 exec) */
49
56
  cwdRefreshing?: boolean;
57
+ /** 用户配置的目标平台提示(来自 connection.platform) */
58
+ osHint?: 'auto' | 'linux' | 'macos' | 'windows';
59
+ /** 探测/推断出的远端操作系统:'unix'(Linux/macOS/BSD)或 'windows' */
60
+ os?: 'unix' | 'windows';
61
+ /** 是否以无 PTY 降级模式运行(Windows 某些 OpenSSH 配置下 PTY 不可用时) */
62
+ noPty?: boolean;
50
63
  }
51
64
 
52
65
  /**
@@ -60,30 +73,44 @@ const CWD_CACHE_TTL = 120000;
60
73
  */
61
74
  const CWD_TRACK_GRACE = 5000;
62
75
 
76
+ /**
77
+ * 后台 CWD 刷新的最小间隔:目录刚解析过就跳过,避免频繁 exec 占用 SSH channel。
78
+ */
79
+ const CWD_REFRESH_MIN_INTERVAL = 15000;
80
+
63
81
  /**
64
82
  * 远端进程探测脚本(通过独立 exec 通道执行,不会向交互式终端写入任何内容)。
65
83
  *
66
84
  * 输出格式(每行一条,可能 0~2 行):
67
85
  * SHELL:<pid>:<cwd> 本会话的交互式 shell
68
86
  * XFER:<pid>:<cwd> 本会话正在运行的 rz/sz 进程(rz 的 cwd 即文件将写入的目录)
87
+ * NOCWD:<kind>:<pid>:<pri>:<dep>
88
+ * 属于本会话、但 cwd 读不到(sudo su 后属主变了,需要 ptrace 权限)。
89
+ * 出现即表示本次探测结果不可信,必须换用交互式 shell 探测。
69
90
  *
70
91
  * 设计要点:
71
92
  * 1) 只认与本 exec 通道同源(祖先链命中同一个 sshd 会话进程)的候选,
72
93
  * 避免同一台机器开多个标签页时串台读到别的终端目录;
73
- * 2) 排除 exec 通道自身及其祖先,避免把 exec 自己的 shell(cwd 恒为 $HOME)
74
- * 误判成终端 —— 这正是"文件被传到家目录"的根因;
94
+ * 2) 排除 exec 通道自身、其祖先、以及**它的所有子孙进程**(见 is_exec_tree)——
95
+ * 命令替换 $(...)/管道 fork 出的子 shell 与父进程同名、深度更大、cwd 恒为 $HOME,
96
+ * 若不过滤就会被「最深优先」选中,这正是"文件被传到家目录"的根因;
75
97
  * 3) 不使用 exec 通道的 pwd 兜底,探测不到就返回空,宁可让用户手填。
76
98
  */
77
99
  const SESSION_PROBE_SCRIPT = [
100
+ 'self=$$',
78
101
  // 无 /proc 的远端(macOS / BSD):改用 lsof 读取 shell 的 cwd
79
102
  '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',
103
+ ' 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',
104
+ ' pid=${cand%%:*}',
105
+ ' pp=${cand##*:}',
106
+ // 排除 exec 通道自身及其子进程:它们的 cwd 恒为 $HOME
107
+ ' [ "$pid" = "$self" ] && continue',
108
+ ' [ "$pp" = "$self" ] && continue',
81
109
  ' d=$(lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | sed -n "s/^n//p" | head -n 1)',
82
110
  ' case "$d" in /*) echo "SHELL:$pid:$d"; break;; esac',
83
111
  ' done',
84
112
  ' exit 0',
85
113
  'fi',
86
- 'self=$$',
87
114
  'ppid_of() { sed -n "s/^PPid:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
88
115
  'name_of() { sed -n "s/^Name:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
89
116
  'cwd_of() { readlink "/proc/$1/cwd" 2>/dev/null; }',
@@ -97,27 +124,44 @@ const SESSION_PROBE_SCRIPT = [
97
124
  ' self_chain="$self_chain$p "',
98
125
  ' i=$((i+1))',
99
126
  'done',
127
+ // 是否属于 exec 通道自己的进程树(self 及其子孙)。
128
+ // 只认 self 本身:self 的祖先(sshd 会话进程)是与交互式 shell 共享的,
129
+ // 拿它们做判定会把真正的交互式 shell 也一起排除掉。
130
+ 'is_exec_tree() {',
131
+ ' _et=$1',
132
+ ' [ "$_et" = "$self" ] && return 0',
133
+ ' _j=0',
134
+ ' while [ $_j -lt 12 ]; do',
135
+ ' _et=$(ppid_of "$_et")',
136
+ ' case "$_et" in ""|0|1) break;; esac',
137
+ ' [ "$_et" = "$self" ] && return 0',
138
+ ' _j=$((_j+1))',
139
+ ' done',
140
+ ' return 1',
141
+ '}',
100
142
  // 最近的 sshd 会话祖先:用于把候选限定在本 SSH 会话内
101
143
  'sshd_anc=""',
102
144
  'for q in $self_chain; do',
103
145
  ' n=$(name_of "$q")',
104
146
  ' case "$n" in sshd*) sshd_anc="$q"; break;; esac',
105
147
  'done',
106
- 'in_chain() { case "$self_chain" in *" $1 "*) return 0;; esac; return 1; }',
107
148
  // 返回值即优先级:2 = 与 sshd 会话同源(最准),1 = 仅 stdin 是 tty(tmux/su 等兜底),0 = 不匹配
149
+ // pri_src 记录判定依据:chain=进程链命中 / tty=stdin 是 tty / unknown=读不到(权限不足)
108
150
  'match_pri() {',
109
151
  ' pid=$1',
152
+ ' pri_src=""',
110
153
  ' if [ -n "$sshd_anc" ]; then',
111
154
  ' q=$pid; j=0',
112
155
  ' while [ $j -lt 12 ]; do',
113
156
  ' q=$(ppid_of "$q")',
114
157
  ' case "$q" in ""|0|1) break;; esac',
115
- ' [ "$q" = "$sshd_anc" ] && return 2',
158
+ ' [ "$q" = "$sshd_anc" ] && { pri_src=chain; return 2; }',
116
159
  ' j=$((j+1))',
117
160
  ' done',
118
161
  ' fi',
119
162
  ' tty=$(readlink "/proc/$pid/fd/0" 2>/dev/null)',
120
- ' case "$tty" in /dev/pts/*|/dev/tty*|/dev/console) return 1;; esac',
163
+ ' case "$tty" in /dev/pts/*|/dev/tty*|/dev/console) pri_src=tty; return 1;; esac',
164
+ ' pri_src=unknown',
121
165
  ' return 0',
122
166
  '}',
123
167
  // 进程深度(到 PID 1 的层数):多个候选时取最深的那个。
@@ -135,19 +179,26 @@ const SESSION_PROBE_SCRIPT = [
135
179
  'best_shell=""; best_shell_key=0',
136
180
  'best_xfer=""; best_xfer_key=0',
137
181
  'for pid in $(ls /proc 2>/dev/null | grep -E "^[0-9]+$"); do',
138
- ' in_chain "$pid" && continue',
139
182
  ' n=$(name_of "$pid")',
140
183
  ' case "$n" in',
141
184
  ' bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox) kind=shell;;',
142
185
  ' rz|sz|lrz|lsz|lrzsz) kind=xfer;;',
143
186
  ' *) continue;;',
144
187
  ' esac',
145
- ' c=$(cwd_of "$pid")',
146
- ' [ -n "$c" ] || continue',
188
+ // 先按名字过滤再判定,避免为每个进程都走一遍祖先链(省掉大量 fork)
189
+ ' is_exec_tree "$pid" && continue',
190
+ ' case "$self_chain" in *" $pid "*) continue;; esac',
147
191
  ' match_pri "$pid"',
148
192
  ' pri=$?',
193
+ // sshd 会话祖先未知时无法用进程链判定,fd/0 又因权限读不到的候选按「可能同源」处理,
194
+ // 否则 sudo su / su 之后会直接漏掉用户真正在用的那个 shell。
195
+ ' if [ "$pri" = 0 ] && [ -z "$sshd_anc" ] && [ "$pri_src" = unknown ]; then pri=1; fi',
149
196
  ' [ "$pri" = 0 ] && continue',
150
197
  ' dep=$(depth_of "$pid")',
198
+ ' c=$(cwd_of "$pid")',
199
+ // cwd 读不到:sudo su / su 到别的用户后,/proc/<pid>/cwd 需要 ptrace 权限。
200
+ // 必须上报而不是静默丢弃 —— 否则服务端会把唯一读得到的登录 shell 当成可信答案。
201
+ ' if [ -z "$c" ]; then echo "NOCWD:$kind:$pid:$pri:$dep"; continue; fi',
151
202
  ' key=$((pri * 100 + dep))',
152
203
  ' echo "CAND:$kind:$pid:$c:$pri:$dep"',
153
204
  ' if [ "$kind" = shell ]; then',
@@ -161,6 +212,19 @@ const SESSION_PROBE_SCRIPT = [
161
212
  'exit 0',
162
213
  ].join('\n');
163
214
 
215
+ /**
216
+ * 判断一个路径是否为有效的绝对路径(跨平台)。
217
+ * - Unix:以 '/' 开头
218
+ * - Windows:盘符形式 `C:\...` / `C:/...`,或以 `\\` 开头的 UNC 路径
219
+ */
220
+ function isAbsolutePath(p?: string): boolean {
221
+ if (!p) return false;
222
+ if (p.startsWith('/')) return true;
223
+ if (/^[A-Za-z]:[\\/]/.test(p)) return true;
224
+ if (p.startsWith('\\\\')) return true;
225
+ return false;
226
+ }
227
+
164
228
  /** Session 元数据(用于在 server 端持久化 tab 信息) */
165
229
  interface SessionMetadata {
166
230
  sessionId: string;
@@ -218,6 +282,8 @@ export class SSHService {
218
282
  private hasCreatedSession: boolean = false;
219
283
  /** 定时清理僵尸 session 的定时器 */
220
284
  private cleanupTimer: ReturnType<typeof setInterval> | null = null;
285
+ /** 正在建立中的 SFTP 连接(避免并发重复创建) */
286
+ private sftpPromises: Map<string, Promise<any>> = new Map();
221
287
 
222
288
  constructor(connectionService: ConnectionService) {
223
289
  this.connectionService = connectionService;
@@ -348,6 +414,8 @@ export class SSHService {
348
414
  pty: ptyProcess,
349
415
  createdAt: new Date(),
350
416
  cwd: homeDir,
417
+ os: isWindows ? 'windows' : 'unix',
418
+ osHint: isWindows ? 'windows' : 'linux',
351
419
  };
352
420
 
353
421
  this.sessions.set(sessionId, session);
@@ -442,25 +510,20 @@ export class SSHService {
442
510
  shellOpts.agentForward = true;
443
511
  }
444
512
 
445
- client.shell(shellOpts, (err: Error | undefined, stream: ClientChannel) => {
446
- if (err) {
447
- log(`打开 shell 失败: ${err.message}`);
448
- client.end();
449
- reject(err);
450
- return;
451
- }
513
+ const session: TerminalSession = {
514
+ id: sessionId,
515
+ connectionId,
516
+ type: 'ssh',
517
+ name: sessionName,
518
+ client,
519
+ createdAt: new Date(),
520
+ osHint: connection.platform,
521
+ };
452
522
 
453
- log(`Shell 会话已建立`);
523
+ this.openShell(client, shellOpts, connection, session).then((stream) => {
524
+ session.stream = stream;
454
525
 
455
- const session: TerminalSession = {
456
- id: sessionId,
457
- connectionId,
458
- type: 'ssh',
459
- name: sessionName,
460
- client,
461
- stream,
462
- createdAt: new Date(),
463
- };
526
+ log(`Shell 会话已建立${session.noPty ? '(无 PTY 降级模式)' : ''}`);
464
527
 
465
528
  this.sessions.set(sessionId, session);
466
529
 
@@ -494,6 +557,10 @@ export class SSHService {
494
557
  }
495
558
 
496
559
  resolve(session);
560
+ }).catch((err: Error) => {
561
+ log(`打开 shell 失败: ${err.message}`);
562
+ client.end();
563
+ reject(err);
497
564
  });
498
565
  }).on('error', (err: Error) => {
499
566
  clearTimeout(timeout);
@@ -503,6 +570,76 @@ export class SSHService {
503
570
  });
504
571
  }
505
572
 
573
+ /**
574
+ * 打开远端 shell,并在 PTY 不可用时优雅降级。
575
+ *
576
+ * 某些 Windows OpenSSH 配置 / 老旧版本对 pty-req 支持不完整,直接 `client.shell({term})`
577
+ * 会失败。这里依次尝试多个 term 类型,再尝试不带 term 的 shell;
578
+ * 全部失败则降级到「无 PTY 模式」(`client.exec` 启动默认 shell)——交互体验受限
579
+ * (无回显 / 行编辑),但命令仍可执行。降级时会在 session 上标记 noPty。
580
+ */
581
+ private openShell(
582
+ client: Client,
583
+ shellOpts: any,
584
+ connection: ConnectionEntity,
585
+ session?: TerminalSession,
586
+ ): Promise<ClientChannel> {
587
+ return new Promise<ClientChannel>((resolve, reject) => {
588
+ const termCandidates = [shellOpts.term, 'xterm', 'vt100'];
589
+ let ti = 0;
590
+ const tryShell = () => {
591
+ const opts = { ...shellOpts, term: termCandidates[ti] } as any;
592
+ if (!opts.term) delete opts.term;
593
+ client.shell(opts, (err: Error | undefined, stream: ClientChannel) => {
594
+ if (!err) return resolve(stream);
595
+ if (ti < termCandidates.length - 1) {
596
+ ti += 1;
597
+ return tryShell();
598
+ }
599
+ // 所有 term 候选都失败:尝试不带 term 的 shell 请求
600
+ client.shell({ ...shellOpts, term: undefined } as any, (e2, s2) => {
601
+ if (!e2 && s2) return resolve(s2);
602
+ // 最终降级:以无 PTY 方式执行默认 shell(交互体验受限,但命令可执行)
603
+ const fallbackShell = connection.platform === 'windows'
604
+ ? 'powershell.exe -NoProfile -NonInteractive -NoLogo'
605
+ : (process.platform === 'win32' ? 'powershell.exe' : '/bin/bash -i');
606
+ client.exec(fallbackShell, (e3, s3) => {
607
+ if (!e3 && s3) {
608
+ if (session) session.noPty = true;
609
+ console.warn('[SSH] PTY 不可用,已降级到无 PTY 模式(exec 默认 shell)');
610
+ return resolve(s3);
611
+ }
612
+ reject(err || e2 || e3 || new Error('无法打开远程 shell'));
613
+ });
614
+ });
615
+ });
616
+ };
617
+ tryShell();
618
+ });
619
+ }
620
+
621
+ /**
622
+ * 解析远端操作系统类型('unix' | 'windows'),结果缓存到 session。
623
+ * 优先使用连接配置中的 platform 提示;为 'auto' 时通过独立 exec 通道运行
624
+ * `uname -s` 探测(不污染交互式终端):能取到内核名即为类 Unix,否则视为 Windows。
625
+ */
626
+ private async resolveSessionOs(sessionId: string): Promise<'unix' | 'windows'> {
627
+ const session = this.sessions.get(sessionId);
628
+ if (!session) return 'unix';
629
+ if (session.os) return session.os;
630
+ const hint = session.osHint;
631
+ if (hint === 'windows') { session.os = 'windows'; return 'windows'; }
632
+ if (hint === 'linux' || hint === 'macos') { session.os = 'unix'; return 'unix'; }
633
+ try {
634
+ const out = await this.execRemote(sessionId, 'uname -s');
635
+ const s = (out || '').trim().toLowerCase();
636
+ session.os = /linux|darwin|freebsd|openbsd|netbsd|sunos/.test(s) ? 'unix' : 'windows';
637
+ } catch {
638
+ session.os = 'unix'; // 探测失败时按类 Unix 处理(最常见的远端)
639
+ }
640
+ return session.os;
641
+ }
642
+
506
643
  /**
507
644
  * 获取默认 Shell
508
645
  */
@@ -770,8 +907,13 @@ export class SSHService {
770
907
  * Sends a compact command to the remote terminal and captures the output
771
908
  */
772
909
  private async activeCollectRemoteSystemInfo(sessionId: string): Promise<string> {
910
+ const os = await this.resolveSessionOs(sessionId);
773
911
  const marker = '__AICMD_SYS__';
774
- 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)"`;
912
+ // Windows(PowerShell)与类 Unix(bash/sh)使用不同的采集命令;
913
+ // 二者都通过同一个 __AICMD_SYS__ marker 回传,便于统一解析。
914
+ const cmd = os === 'windows'
915
+ ? `Write-Output "${marker}:Windows:$(Get-CimInstance Win32_OperatingSystem | Select-Object -ExpandProperty Version):$(hostname):$env:USERNAME:PowerShell:$(Get-CimInstance Win32_Processor | Select-Object -ExpandProperty Architecture)"`
916
+ : `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)"`;
775
917
  try {
776
918
  // Start capture, then send the command
777
919
  // Use longer timeout (5s) to account for slow SSH connections and MOTD output
@@ -779,12 +921,13 @@ export class SSHService {
779
921
  this.writeData(sessionId, cmd + '\r');
780
922
  const output = await outputPromise;
781
923
  // Clean ANSI escape codes for more reliable marker matching
782
- const cleaned = output.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '').replace(/\x1B\].*?\x07/g, '').replace(/\r/g, '');
924
+ const cleaned = stripAnsiEscapes(output).replace(/\r/g, '');
783
925
  // Extract our marker line
926
+ const echoPrefixes = ['echo', 'Write-Output'];
784
927
  for (const line of cleaned.split('\n')) {
785
928
  const trimmed = line.trim();
786
929
  // Handle possible command echo: skip lines that still contain the raw command prefix
787
- if (trimmed.includes(marker + ':') && !trimmed.startsWith('echo')) {
930
+ if (trimmed.includes(marker + ':') && !echoPrefixes.some(p => trimmed.startsWith(p))) {
788
931
  const markerIdx = trimmed.indexOf(marker + ':');
789
932
  const markerLine = trimmed.substring(markerIdx);
790
933
  const parts = markerLine.split(':');
@@ -848,6 +991,22 @@ export class SSHService {
848
991
  const genericWelcome = motd.match(/Welcome to (.+?)(?:\s*[\(\n])/);
849
992
  if (genericWelcome) info['OS'] = genericWelcome[1].trim();
850
993
  }
994
+ // Windows(OpenSSH Server / cmd 横幅):"Microsoft Windows [Version 10.0.19041.1]"
995
+ if (!info['OS']) {
996
+ const winVer = motd.match(/Microsoft Windows.*?Version\s+([\d.]+)/i)
997
+ || motd.match(/\bWindows Server\b|\bWindows\b/i);
998
+ if (winVer) {
999
+ info['OS'] = winVer[1] ? `Windows ${winVer[1]}` : 'Windows';
1000
+ const verMatch = motd.match(/Version\s+([\d.]+)/i);
1001
+ if (verMatch) info['Kernel'] = verMatch[1];
1002
+ }
1003
+ }
1004
+ // macOS(部分系统登录横幅含 Darwin 内核信息)
1005
+ if (!info['OS'] && /Darwin/i.test(motd)) {
1006
+ info['OS'] = 'macOS (Darwin)';
1007
+ const darwinMatch = motd.match(/Darwin[^\n]*?([\d.]+)/i);
1008
+ if (darwinMatch) info['Kernel'] = darwinMatch[1];
1009
+ }
851
1010
 
852
1011
  // === 系统指标(Ubuntu landscape 格式,键值对可能在不同行) ===
853
1012
  // System load
@@ -930,7 +1089,7 @@ export class SSHService {
930
1089
  // === 最终兜底:如果只匹配到极少信息,保留原始 MOTD 作为上下文 ===
931
1090
  if (Object.keys(info).length === 0) {
932
1091
  // 完全没有匹配,返回清理后的原始文本(截取前 800 字符)
933
- const cleaned = motd.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '').replace(/\r/g, '').trim();
1092
+ const cleaned = stripAnsiEscapes(motd).replace(/\r/g, '').trim();
934
1093
  return cleaned.substring(0, 800);
935
1094
  }
936
1095
 
@@ -1148,10 +1307,17 @@ Write-Output "__DOCKER__: $dockerVer"
1148
1307
  continue;
1149
1308
  }
1150
1309
  let next: string | undefined;
1151
- if (target.startsWith('/')) {
1152
- next = target;
1153
- } else if (session.cwd && session.cwd.startsWith('/')) {
1154
- next = path.posix.resolve(session.cwd, target);
1310
+ const os = session.os ?? (session.osHint === 'windows' ? 'windows' : 'unix');
1311
+ if (target.startsWith('/') || /^[A-Za-z]:[\\/]/.test(target) || target.startsWith('\\\\')) {
1312
+ // 绝对路径(Unix 的 '/' 或 Windows 的盘符 / UNC)
1313
+ next = os === 'windows'
1314
+ ? target.replace(/\//g, '\\') // 统一为 Windows 反斜杠分隔符
1315
+ : target;
1316
+ } else if (isAbsolutePath(session.cwd)) {
1317
+ // 相对路径:基于当前目录拼接(跨平台使用对应 path 模块)
1318
+ next = os === 'windows'
1319
+ ? path.win32.resolve(session.cwd, target)
1320
+ : path.posix.resolve(session.cwd, target);
1155
1321
  } else {
1156
1322
  // 当前目录未知,无法拼接相对路径,重置为未知
1157
1323
  next = undefined;
@@ -1168,7 +1334,25 @@ Write-Output "__DOCKER__: $dockerVer"
1168
1334
  if (!session) return;
1169
1335
  // 只探测 SSH 会话;本地会话的 cwd 由 cd 跟踪维护
1170
1336
  if (session.type !== 'ssh' || !session.client) return;
1171
- if (session.shellPid && session.cwd && session.cwd.startsWith('/')) return;
1337
+ const os = await this.resolveSessionOs(sessionId);
1338
+ if (os === 'windows') {
1339
+ // Windows 无 /proc,后台刷新无法获取 CWD;改用注入式探测拿到初始目录,
1340
+ // 以便后续 cd 跟踪能拼接相对路径。
1341
+ if (isAbsolutePath(session.cwd)) return;
1342
+ try {
1343
+ const cwd = await this.probeCwdViaShell(sessionId);
1344
+ if (cwd) {
1345
+ session.cwd = cwd;
1346
+ session.cwdAt = Date.now();
1347
+ session.cwdReliable = true;
1348
+ console.log(`[SSH] seeded windows cwd for ${sessionId}: ${cwd}`);
1349
+ }
1350
+ } catch {
1351
+ // 忽略,上传时再探测
1352
+ }
1353
+ return;
1354
+ }
1355
+ if (session.shellPid && isAbsolutePath(session.cwd)) return;
1172
1356
  try {
1173
1357
  await this.refreshCwd(sessionId);
1174
1358
  if (session.cwd) console.log(`[SSH] seeded cwd for ${sessionId}: ${session.cwd} (pid=${session.shellPid || '-'})`);
@@ -1187,6 +1371,9 @@ Write-Output "__DOCKER__: $dockerVer"
1187
1371
  private scheduleCwdRefresh(sessionId: string): void {
1188
1372
  const session = this.sessions.get(sessionId);
1189
1373
  if (!session || session.type !== 'ssh' || !session.client) return;
1374
+ // 目录刚解析过就别再跑 exec 了:每次 exec 都要占用一个 channel,
1375
+ // 频繁调用会挤占 SFTP 的 channel 配额(MaxSessions)。
1376
+ if (session.cwdAt && (Date.now() - session.cwdAt) < CWD_REFRESH_MIN_INTERVAL) return;
1190
1377
  if (session.cwdRefreshTimer) clearTimeout(session.cwdRefreshTimer);
1191
1378
  session.cwdRefreshTimer = setTimeout(() => {
1192
1379
  session.cwdRefreshTimer = undefined;
@@ -1217,7 +1404,7 @@ Write-Output "__DOCKER__: $dockerVer"
1217
1404
  if (probe.shellPid) session.shellPid = probe.shellPid;
1218
1405
  cwd = probe.shellCwd;
1219
1406
  }
1220
- if (cwd && cwd.startsWith('/')) {
1407
+ if (cwd && isAbsolutePath(cwd)) {
1221
1408
  // 用户刚刚敲过 cd(cd 跟踪值很新鲜)时,不覆盖它:
1222
1409
  // cd 是用户的显式意图,比推断出的进程目录更可信,
1223
1410
  // 也能避免探测到错误进程时把正确目录改回成家目录。
@@ -1229,9 +1416,9 @@ Write-Output "__DOCKER__: $dockerVer"
1229
1416
  session.cwdAt = Date.now();
1230
1417
  }
1231
1418
  }
1232
- return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
1419
+ return session.cwd && isAbsolutePath(session.cwd) ? session.cwd : '';
1233
1420
  } catch {
1234
- return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
1421
+ return session.cwd && isAbsolutePath(session.cwd) ? session.cwd : '';
1235
1422
  } finally {
1236
1423
  session.cwdRefreshing = false;
1237
1424
  session.lastCwdRefreshAt = Date.now();
@@ -1246,15 +1433,19 @@ Write-Output "__DOCKER__: $dockerVer"
1246
1433
  if (!Number.isInteger(pid) || pid <= 0) return '';
1247
1434
  const out = await this.execRemote(
1248
1435
  sessionId,
1249
- `cat /proc/${pid}/comm 2>/dev/null; readlink /proc/${pid}/cwd 2>/dev/null`,
1436
+ `cat /proc/${pid}/comm 2>/dev/null; readlink /proc/${pid}/cwd 2>/dev/null; readlink /proc/${pid}/fd/0 2>/dev/null`,
1250
1437
  4000,
1251
1438
  );
1252
1439
  const lines = out.split('\n').map(l => l.trim()).filter(Boolean);
1253
- if (lines.length < 2) return '';
1440
+ if (lines.length < 3) return '';
1254
1441
  const comm = lines[0];
1255
- const cwd = lines[lines.length - 1];
1256
- if (!cwd.startsWith('/')) return '';
1442
+ const cwd = lines[1];
1443
+ const stdin = lines[2];
1444
+ if (!isAbsolutePath(cwd)) return '';
1257
1445
  if (!/^(bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox|rz|sz|lrz|lsz)$/.test(comm)) return '';
1446
+ // 交互式 shell / rz 的 stdin 一定是 tty;exec 通道(及其子 shell)是 pipe/socket,
1447
+ // 这里再校验一次,避免 PID 复用时读到无关进程的目录(通常是 $HOME)。
1448
+ if (!/^\/dev\/(pts|tty|console)/.test(stdin)) return '';
1258
1449
  return cwd;
1259
1450
  }
1260
1451
 
@@ -1264,12 +1455,22 @@ Write-Output "__DOCKER__: $dockerVer"
1264
1455
  */
1265
1456
  private async probeSessionProcess(
1266
1457
  sessionId: string,
1267
- ): Promise<{ shellPid?: number; shellCwd: string; xferCwd: string; candidates: string[] }> {
1458
+ ): Promise<{
1459
+ shellPid?: number;
1460
+ shellCwd: string;
1461
+ xferCwd: string;
1462
+ candidates: string[];
1463
+ /** 存在读不到 cwd 的同源进程(sudo su 等)时为 true:结果只是「唯一读得到的那个」,不可信 */
1464
+ unreadable: string[];
1465
+ reliable: boolean;
1466
+ }> {
1268
1467
  const result = {
1269
1468
  shellPid: undefined as number | undefined,
1270
1469
  shellCwd: '',
1271
1470
  xferCwd: '',
1272
1471
  candidates: [] as string[],
1472
+ unreadable: [] as string[],
1473
+ reliable: true,
1273
1474
  };
1274
1475
  const out = await this.execRemote(sessionId, SESSION_PROBE_SCRIPT, 5000);
1275
1476
  for (const raw of out.split('\n')) {
@@ -1280,6 +1481,11 @@ Write-Output "__DOCKER__: $dockerVer"
1280
1481
  result.candidates.push(line.substring(5));
1281
1482
  continue;
1282
1483
  }
1484
+ if (line.startsWith('NOCWD:')) {
1485
+ // 诊断 + 可信度:kind:pid:pri:depth(cwd 因权限读不到)
1486
+ result.unreadable.push(line.substring(6));
1487
+ continue;
1488
+ }
1283
1489
  const m = line.match(/^(SHELL|XFER):(\d+):(\/.*)$/);
1284
1490
  if (!m) continue;
1285
1491
  const pid = Number(m[2]);
@@ -1291,9 +1497,13 @@ Write-Output "__DOCKER__: $dockerVer"
1291
1497
  result.xferCwd = cwd;
1292
1498
  }
1293
1499
  }
1500
+ // 只要还有读不到的同源候选,本次结果就只能算「推断」:
1501
+ // 用户真正在用的 shell 很可能就是那个读不到的(sudo su 后的 root shell)。
1502
+ if (result.unreadable.length) result.reliable = false;
1294
1503
  console.log(
1295
1504
  `[SSH] probeSessionProcess: shell=${result.shellPid || '-'}:${result.shellCwd || '-'} ` +
1296
- `xfer=${result.xferCwd || '-'} cands=[${result.candidates.join(' | ')}]`,
1505
+ `xfer=${result.xferCwd || '-'} reliable=${result.reliable} ` +
1506
+ `cands=[${result.candidates.join(' | ')}] nocwd=[${result.unreadable.join(' | ')}]`,
1297
1507
  );
1298
1508
  return result;
1299
1509
  }
@@ -1311,10 +1521,14 @@ Write-Output "__DOCKER__: $dockerVer"
1311
1521
  }
1312
1522
  let stdout = '';
1313
1523
  let settled = false;
1524
+ let streamRef: ClientChannel | null = null;
1314
1525
  const finish = () => {
1315
1526
  if (settled) return;
1316
1527
  settled = true;
1317
1528
  clearTimeout(timer);
1529
+ // 必须显式关闭 channel:OpenSSH 默认 MaxSessions=10,
1530
+ // 泄漏的 channel 累积后会导致后续 SFTP channel 打开失败(上传时好时坏)。
1531
+ try { streamRef?.end(); } catch { /* ignore */ }
1318
1532
  resolve(stdout);
1319
1533
  };
1320
1534
  const timer = setTimeout(finish, timeoutMs);
@@ -1325,6 +1539,7 @@ Write-Output "__DOCKER__: $dockerVer"
1325
1539
  finish();
1326
1540
  return;
1327
1541
  }
1542
+ streamRef = stream;
1328
1543
  stream.on('data', (data: Buffer) => { stdout += data.toString('utf-8'); });
1329
1544
  stream.stderr.on('data', () => {});
1330
1545
  stream.on('close', finish);
@@ -1355,6 +1570,14 @@ Write-Output "__DOCKER__: $dockerVer"
1355
1570
  * 通知输出监听器(由 WebSocket 处理器在收到终端输出时调用)
1356
1571
  */
1357
1572
  notifyOutput(sessionId: string, data: string): void {
1573
+ // 累积到会话输出缓冲(供 Agent 的 read_terminal / shell.read 读取)
1574
+ const session = this.sessions.get(sessionId);
1575
+ if (session) {
1576
+ let buf = (session.outputBuffer || '') + data;
1577
+ // 限制缓冲上限,避免长会话无限增长(保留尾部约 32KB)
1578
+ if (buf.length > 32768) buf = buf.slice(-32768);
1579
+ session.outputBuffer = buf;
1580
+ }
1358
1581
  const listener = this.outputListeners.get(sessionId);
1359
1582
  if (listener) {
1360
1583
  try {
@@ -1365,6 +1588,79 @@ Write-Output "__DOCKER__: $dockerVer"
1365
1588
  }
1366
1589
  }
1367
1590
 
1591
+ /**
1592
+ * 读取会话累积的输出缓冲(当前屏幕/历史内容),不依赖「调用后新到达」的采集窗口。
1593
+ * @param maxLines 最多返回末尾行数,默认 200
1594
+ */
1595
+ getOutputBuffer(sessionId: string, maxLines = 200): string {
1596
+ const session = this.sessions.get(sessionId);
1597
+ if (!session || !session.outputBuffer) return '';
1598
+ const cleaned = stripAnsiEscapes(session.outputBuffer);
1599
+ const lines = cleaned.split('\n');
1600
+ return lines.slice(-maxLines).join('\n');
1601
+ }
1602
+
1603
+ /**
1604
+ * 采集输出并「空闲即停」:新数据停止到达超过 idleMs 后认为本次输出结束,
1605
+ * 最长不超过 maxMs。相比固定时间窗口,能完整拿到慢命令的输出,
1606
+ * 又不会像定长等待那样白白浪费时间。
1607
+ * @param sessionId 会话 ID
1608
+ * @param idleMs 判定输出结束的静默时长,默认 700ms
1609
+ * @param maxMs 最长等待(兜底),默认 10000ms
1610
+ * @returns 已去除 ANSI 转义序列的输出文本
1611
+ */
1612
+ captureOutputIdle(sessionId: string, idleMs = 700, maxMs = 10000): Promise<string> {
1613
+ return new Promise((resolve) => {
1614
+ const clean = (s: string) => stripAnsiEscapes(s);
1615
+
1616
+ const session = this.sessions.get(sessionId);
1617
+ let raw = '';
1618
+ let settled = false;
1619
+ let lastLen = 0;
1620
+ let lastChangeAt = Date.now();
1621
+ let streamHandler: ((chunk: Buffer) => void) | null = null;
1622
+ let listener: ((data: string) => void) | null = null;
1623
+ let idleTimer: ReturnType<typeof setInterval> | null = null;
1624
+ let maxTimer: ReturnType<typeof setTimeout> | null = null;
1625
+
1626
+ const finish = () => {
1627
+ if (settled) return;
1628
+ settled = true;
1629
+ if (idleTimer) clearInterval(idleTimer);
1630
+ if (maxTimer) clearTimeout(maxTimer);
1631
+ if (streamHandler && session?.stream) {
1632
+ session.stream.removeListener('data', streamHandler);
1633
+ } else if (listener) {
1634
+ this.removeOutputListener(sessionId);
1635
+ }
1636
+ resolve(clean(raw));
1637
+ };
1638
+
1639
+ idleTimer = setInterval(() => {
1640
+ if (settled) return;
1641
+ const now = Date.now();
1642
+ if (raw.length !== lastLen) {
1643
+ lastLen = raw.length;
1644
+ lastChangeAt = now;
1645
+ return;
1646
+ }
1647
+ // 已有数据且静默超过 idleMs,判定本次输出结束
1648
+ if (raw.length > 0 && now - lastChangeAt >= idleMs) finish();
1649
+ }, 100);
1650
+ maxTimer = setTimeout(finish, maxMs);
1651
+
1652
+ const onData = (text: string) => { raw += text; };
1653
+ if (session?.stream) {
1654
+ streamHandler = (chunk: Buffer) => onData(chunk.toString('utf-8'));
1655
+ session.stream.on('data', streamHandler);
1656
+ } else {
1657
+ // 本地 shell fallback:通过 notifyOutput 机制
1658
+ listener = onData;
1659
+ this.addOutputListener(sessionId, listener);
1660
+ }
1661
+ });
1662
+ }
1663
+
1368
1664
  /**
1369
1665
  * 捕获会话在指定时间内的输出
1370
1666
  * @param sessionId 会话 ID
@@ -1393,11 +1689,7 @@ Write-Output "__DOCKER__: $dockerVer"
1393
1689
  } else if (listener) {
1394
1690
  this.removeOutputListener(sessionId);
1395
1691
  }
1396
- resolve(output
1397
- .replace(/\x1B\][^\x07]*\x07/g, '')
1398
- .replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '')
1399
- .replace(/\x1B[^\x1B]*[a-zA-Z]/g, '')
1400
- );
1692
+ resolve(stripAnsiEscapes(output));
1401
1693
  };
1402
1694
 
1403
1695
  const timer = setTimeout(finish, timeoutMs);
@@ -1448,6 +1740,9 @@ Write-Output "__DOCKER__: $dockerVer"
1448
1740
  clearTimeout(session.cwdRefreshTimer);
1449
1741
  session.cwdRefreshTimer = undefined;
1450
1742
  }
1743
+ // 关闭复用的 SFTP channel,避免连接关闭后仍占用资源
1744
+ this.invalidateSftp(sessionId);
1745
+ this.sftpPromises.delete(sessionId);
1451
1746
  try {
1452
1747
  if (session.pty) {
1453
1748
  session.pty.kill();
@@ -1496,25 +1791,74 @@ Write-Output "__DOCKER__: $dockerVer"
1496
1791
  sessionId: string,
1497
1792
  opts: { allowShellProbe?: boolean; preferTransferProcess?: boolean; force?: boolean } = {},
1498
1793
  ): Promise<string> {
1794
+ return (await this.getSessionCwdDetailed(sessionId, opts)).cwd;
1795
+ }
1796
+
1797
+ /**
1798
+ * 同 getSessionCwd,但额外返回可信度。
1799
+ *
1800
+ * reliable=false 的典型场景:`sudo su` / `su` 之后,用户真正在用的 shell 属于 root,
1801
+ * 而 exec 通道跑在登录用户下,/proc/<pid>/cwd 需要 ptrace 权限、读不到,
1802
+ * 探测结果退化成「唯一读得到的那个进程」(往往是登录 shell = 家目录)。
1803
+ * 调用方必须据此改向交互式 shell 询问或让用户确认,不能直接拿它当结论。
1804
+ */
1805
+ async getSessionCwdDetailed(
1806
+ sessionId: string,
1807
+ opts: { allowShellProbe?: boolean; preferTransferProcess?: boolean; force?: boolean } = {},
1808
+ ): Promise<{ cwd: string; reliable: boolean }> {
1499
1809
  const allowShellProbe = opts.allowShellProbe !== false;
1500
1810
  const session = this.sessions.get(sessionId);
1501
- if (!session) return '';
1811
+ if (!session) return { cwd: '', reliable: false };
1502
1812
 
1503
- const cached = session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
1813
+ const cached = session.cwd && isAbsolutePath(session.cwd) ? session.cwd : '';
1504
1814
  const cacheFresh = !!cached && !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_CACHE_TTL;
1505
1815
 
1506
- // 0) 强制刷新 + 允许注入探测:直接向 shell 询问,这是最权威的手段。
1507
- // 调用方(上传前兜底、用户点"重新检测")已确保终端处于可打断状态,
1508
- // 否则只靠 exec 探测,一旦 shellPid 指错进程就会一直拿到错误的目录。
1509
- if (opts.force && allowShellProbe) {
1510
- let probed = await this.probeCwdViaShell(sessionId);
1511
- if (!probed) probed = await this.probeCwdViaShell(sessionId);
1512
- if (probed && probed.startsWith('/')) {
1513
- session.cwd = probed;
1514
- session.cwdAt = Date.now();
1515
- console.log(`[SSH] getSessionCwd (forced shell probe): '${probed}'`);
1516
- return probed;
1816
+ const commit = (cwd: string, reliable: boolean) => {
1817
+ session.cwd = cwd;
1818
+ session.cwdAt = Date.now();
1819
+ session.cwdReliable = reliable;
1820
+ console.log(`[SSH] getSessionCwd: '${cwd}' reliable=${reliable}`);
1821
+ return { cwd, reliable };
1822
+ };
1823
+
1824
+ // 0) 强制刷新:按可信度从高到低依次尝试,拿到结果立即返回;
1825
+ // 全部失败时只在缓存仍然新鲜的情况下才用缓存兜底,绝不把不可信的猜测当当前目录。
1826
+ if (opts.force) {
1827
+ let probed = '';
1828
+
1829
+ // 0.1) 向 shell 询问(最权威)。调用方(上传前兜底、用户点"重新检测")已确保
1830
+ // 终端处于可打断状态;rz 把终端设为 raw 模式时 Ctrl+C 只是普通字节,
1831
+ // 探测会失败并落到 0.2,不会污染结果。
1832
+ if (allowShellProbe) {
1833
+ let probed = await this.probeCwdViaShell(sessionId);
1834
+ if (!probed) probed = await this.probeCwdViaShell(sessionId);
1835
+ if (isAbsolutePath(probed)) return commit(probed, true);
1517
1836
  }
1837
+
1838
+ // 0.2) 进程探测:rz/sz 自己的 cwd 最权威(它就是文件要写入的目录)。
1839
+ if (session.type === 'ssh' && session.client) {
1840
+ const probe = await this.probeSessionProcess(sessionId);
1841
+ if (probe.shellPid) session.shellPid = probe.shellPid;
1842
+ if (isAbsolutePath(probe.xferCwd)) return commit(probe.xferCwd, true);
1843
+
1844
+ // 可信的 shell 进程目录(能读到所有同源进程):直接用,无需再麻烦用户。
1845
+ if (isAbsolutePath(probe.shellCwd) && probe.reliable) {
1846
+ return commit(probe.shellCwd, true);
1847
+ }
1848
+ // 不可信(sudo su 等只读到部分进程):优先用「用户刚敲的 cd」跟踪值,
1849
+ // 它最贴近真实意图;最后才退回不可信的进程推断,绝不能把登录 shell 家目录
1850
+ // 当成当前目录(那会让文件传到错误的位置)。
1851
+ const trackedFresh = !!cached && !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_TRACK_GRACE;
1852
+ if (trackedFresh) return commit(cached, true);
1853
+ if (isAbsolutePath(probe.shellCwd)) return commit(probe.shellCwd, probe.reliable);
1854
+ }
1855
+
1856
+ const forcedFallback = cacheFresh ? cached : '';
1857
+ console.log(
1858
+ `[SSH] getSessionCwd: forced probe failed for ${sessionId} ` +
1859
+ `(allowShellProbe=${allowShellProbe}, staleCache=${cached || '-'}, returning='${forcedFallback}')`,
1860
+ );
1861
+ return { cwd: forcedFallback, reliable: false };
1518
1862
  }
1519
1863
 
1520
1864
  // 0.5) rz/sz 正在等待传输:直接取 rz 进程自身的 cwd。
@@ -1524,27 +1868,24 @@ Write-Output "__DOCKER__: $dockerVer"
1524
1868
  const probe = await this.probeSessionProcess(sessionId);
1525
1869
  if (probe.shellPid) session.shellPid = probe.shellPid;
1526
1870
  const cwd = probe.xferCwd || probe.shellCwd;
1527
- if (cwd) {
1528
- session.cwd = cwd;
1529
- session.cwdAt = Date.now();
1530
- return cwd;
1531
- }
1871
+ if (cwd) return commit(cwd, probe.reliable);
1532
1872
  }
1533
1873
 
1534
1874
  // 1) 缓存命中(且未过期、未强制刷新)
1535
- if (cached && cacheFresh && !opts.force) {
1536
- return cached;
1875
+ // 注意:缓存值本身不可信时必须重新探测,不能直接用 ——
1876
+ // 那正是"sudo su 后上次探测只拿到登录 shell 家目录"的情况,
1877
+ // 若在这里直接返回,错误目录会被一直沿用,警告也就永远消不掉。
1878
+ if (cached && cacheFresh && session.cwdReliable !== false) {
1879
+ return { cwd: cached, reliable: true };
1537
1880
  }
1538
1881
 
1539
1882
  // 2) 已知 shell PID:直接读 /proc
1883
+ // inferredCwd:进程探测得到的推断值,可信则立即采用,不可信时留作最后兜底
1884
+ let inferredCwd = '';
1540
1885
  if (session.type === 'ssh' && session.client) {
1541
1886
  if (session.shellPid) {
1542
1887
  const cwd = await this.readPidCwd(sessionId, session.shellPid);
1543
- if (cwd) {
1544
- session.cwd = cwd;
1545
- session.cwdAt = Date.now();
1546
- return cwd;
1547
- }
1888
+ if (cwd) return commit(cwd, true);
1548
1889
  session.shellPid = undefined;
1549
1890
  }
1550
1891
 
@@ -1554,40 +1895,46 @@ Write-Output "__DOCKER__: $dockerVer"
1554
1895
  const cwd = (opts.preferTransferProcess && probe.xferCwd)
1555
1896
  ? probe.xferCwd
1556
1897
  : (probe.shellCwd || probe.xferCwd);
1557
- if (cwd) {
1558
- session.cwd = cwd;
1559
- session.cwdAt = Date.now();
1560
- return cwd;
1561
- }
1898
+ // 只有结果可信才直接采用。不可信(sudo su 后只能读到登录 shell)时必须继续
1899
+ // 走第 4 步向交互式 shell 询问 —— 否则会把登录 shell 的家目录当成当前目录,
1900
+ // 文件就传到错误的位置了(这正是"老是传到 /home/ubuntu"的根因)。
1901
+ if (cwd && probe.reliable) return commit(cwd, true);
1902
+ // 不允许注入式探测(rz 正在等待接收):只能用这个推断值,如实标记不可信,
1903
+ // 由前端提示用户核对或改走 ZMODEM 直发。
1904
+ if (cwd && !allowShellProbe) return commit(cwd, false);
1905
+ inferredCwd = cwd || '';
1562
1906
  }
1563
1907
 
1564
1908
  // 4) 注入式探测(会打断前台进程)
1565
1909
  if (allowShellProbe) {
1566
1910
  let cwd = await this.probeCwdViaShell(sessionId);
1567
1911
  if (!cwd) cwd = await this.probeCwdViaShell(sessionId);
1568
- if (cwd && cwd.startsWith('/')) {
1569
- session.cwd = cwd;
1570
- session.cwdAt = Date.now();
1571
- return cwd;
1572
- }
1912
+ if (isAbsolutePath(cwd)) return commit(cwd, true);
1573
1913
  }
1574
1914
 
1915
+ // 注入式探测也失败:退回进程推断值(有总比没有强,前端会提示用户核对)
1916
+ if (inferredCwd) return commit(inferredCwd, false);
1917
+
1575
1918
  // 全部失败:缓存已过期时返回空(让前端提示手填),避免把陈旧目录当当前目录使用
1576
1919
  const fallback = cacheFresh ? cached : '';
1577
1920
  console.log(
1578
1921
  `[SSH] getSessionCwd: probes failed for ${sessionId} ` +
1579
- `(allowShellProbe=${allowShellProbe}, force=${!!opts.force}, staleCache=${cached || '-'}, returning='${fallback || ''}')`,
1922
+ `(allowShellProbe=${allowShellProbe}, staleCache=${cached || '-'}, returning='${fallback}')`,
1580
1923
  );
1581
- return fallback;
1924
+ return { cwd: fallback, reliable: false };
1582
1925
  }
1583
1926
 
1584
- /** 向交互式 shell 注入 printf $PWD 探测 CWD(会先 Ctrl+C 打断前台进程) */
1927
+ /** 向交互式 shell 注入命令探测 CWD(会先 Ctrl+C 打断前台进程) */
1585
1928
  private async probeCwdViaShell(sessionId: string): Promise<string> {
1929
+ const os = await this.resolveSessionOs(sessionId);
1586
1930
  const marker = `__AICmd_CWD_${Date.now()}__`;
1587
1931
  // 先发送 Ctrl+C 中断可能正在运行的前台进程(如 rz、vim、top 等),
1588
- // 否则 printf 命令会被前台进程吞掉,shell 不会执行
1932
+ // 否则命令会被前台进程吞掉,shell 不会执行
1589
1933
  this.writeData(sessionId, '\x03');
1590
1934
  await new Promise(r => setTimeout(r, 200));
1935
+ // Ctrl+U 清空当前输入行:若行内还有残留字符,注入的命令会被拼接成无效命令而拿不到结果
1936
+ this.writeData(sessionId, '\x15');
1937
+ await new Promise(r => setTimeout(r, 150));
1591
1938
 
1592
1939
  // 启动捕获后发送命令(marker 行输出完整就立即返回,通常几百毫秒)
1593
1940
  const stopWhen = (text: string) => {
@@ -1597,23 +1944,25 @@ Write-Output "__DOCKER__: $dockerVer"
1597
1944
  return after.includes('\n') || after.length > 80;
1598
1945
  };
1599
1946
  const outputPromise = this.captureOutput(sessionId, 3000, stopWhen);
1600
- this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\r`);
1947
+ // 类 Unix:printf 输出 $PWD(绝对路径以 '/' 开头)
1948
+ // Windows(PowerShell):$PWD 自动变量即当前位置,字符串化为盘符路径(如 C:\Users\me)
1949
+ if (os === 'windows') {
1950
+ this.writeData(sessionId, ` Write-Output "${marker}:$PWD"\r`);
1951
+ } else {
1952
+ this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\r`);
1953
+ }
1601
1954
  const output = await outputPromise;
1602
- console.log(`[SSH] probeCwdViaShell: raw output: ${JSON.stringify(output.substring(0, 500))}`);
1603
- // 更彻底的 ANSI 清理:包括 OSC 序列、CSI 序列、以及各种控制字符
1604
- const cleaned = output
1605
- .replace(/\x1B\][^\x07]*\x07/g, '') // OSC 序列
1606
- .replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '') // CSI 序列
1607
- .replace(/\x1B[^\x1B]*[a-zA-Z]/g, '') // 其他转义序列
1608
- .replace(/\r/g, '');
1955
+ // 更彻底的 ANSI 清理:OSC / CSI / 其它有界转义(不得使用会吞正文的贪婪兜底)
1956
+ const cleaned = stripAnsiEscapes(output).replace(/\r/g, '');
1609
1957
  const isCommandEcho = (text: string) => (
1610
1958
  text.includes('printf') ||
1959
+ text.includes('Write-Output') ||
1611
1960
  text.includes('$PWD') ||
1612
1961
  text.includes('%s') ||
1613
1962
  text.includes('echo') ||
1614
1963
  text.includes('$(pwd)')
1615
1964
  );
1616
- const isValidCwd = (cwd: string) => cwd.startsWith('/') && !isCommandEcho(cwd);
1965
+ const isValidCwd = (cwd: string) => isAbsolutePath(cwd) && !isCommandEcho(cwd);
1617
1966
 
1618
1967
  for (const line of cleaned.split('\n')) {
1619
1968
  const trimmed = line.trim();
@@ -1674,14 +2023,32 @@ Write-Output "__DOCKER__: $dockerVer"
1674
2023
  // 解析相对路径:必须通过交互式 shell 获取当前 CWD。
1675
2024
  // 注意:不能 fallback 到 SFTP realpath('.'),它通常是登录 home 目录,会导致文件传错位置。
1676
2025
  let fullPath = remotePath;
1677
- if (!remotePath.startsWith('/')) {
1678
- console.log(`[SSH] Getting shell CWD...`);
1679
- const cwd = await this.getSessionCwd(sessionId);
1680
- console.log(`[SSH] Shell CWD: '${cwd}'`);
1681
- if (!cwd || !cwd.startsWith('/')) {
1682
- throw new Error('无法获取当前终端目录,请确认终端处于正常 Shell 提示符状态后重试');
2026
+ const uploadOs = await this.resolveSessionOs(sessionId);
2027
+ if (uploadOs === 'windows') {
2028
+ // Win32-OpenSSH 的 SFTP 子系统以正斜杠 + 盘符形式表示路径(如 C:/Users/name/file),
2029
+ // 与 PowerShell $PWD 返回的反斜杠路径不同,需统一转换为正斜杠。
2030
+ const norm = (p: string) => p.replace(/\\/g, '/');
2031
+ if (/^[A-Za-z]:[\\/]/.test(remotePath) || remotePath.startsWith('\\\\')) {
2032
+ fullPath = norm(remotePath);
2033
+ } else {
2034
+ console.log(`[SSH] Getting shell CWD (windows)...`);
2035
+ const cwd = await this.getSessionCwd(sessionId);
2036
+ console.log(`[SSH] Shell CWD: '${cwd}'`);
2037
+ if (!isAbsolutePath(cwd)) {
2038
+ throw new Error('无法获取当前终端目录,请确认终端处于正常 Shell 提示符状态后重试');
2039
+ }
2040
+ fullPath = `${norm(cwd).replace(/\/$/, '')}/${norm(remotePath)}`;
2041
+ }
2042
+ } else {
2043
+ if (!remotePath.startsWith('/')) {
2044
+ console.log(`[SSH] Getting shell CWD...`);
2045
+ const cwd = await this.getSessionCwd(sessionId);
2046
+ console.log(`[SSH] Shell CWD: '${cwd}'`);
2047
+ if (!cwd || !cwd.startsWith('/')) {
2048
+ throw new Error('无法获取当前终端目录,请确认终端处于正常 Shell 提示符状态后重试');
2049
+ }
2050
+ fullPath = `${cwd.replace(/\/$/, '')}/${remotePath}`;
1683
2051
  }
1684
- fullPath = `${cwd.replace(/\/$/, '')}/${remotePath}`;
1685
2052
  }
1686
2053
  console.log(`[SSH] SFTP upload path: ${remotePath} -> ${fullPath}`);
1687
2054
 
@@ -1700,20 +2067,23 @@ Write-Output "__DOCKER__: $dockerVer"
1700
2067
  if (err) reject(err); else resolve(bytes!);
1701
2068
  };
1702
2069
 
1703
- const doSftpWrite = (targetPath: string, callback: (err: Error | null) => void) => {
1704
- console.log(`[SSH] SFTP opening subsystem...`);
1705
- session.client!.sftp((sftpErr: Error | undefined, sftp: any) => {
2070
+ const doSftpWrite = (targetPath: string, callback: (err: Error | null) => void, isRetry = false) => {
2071
+ console.log(`[SSH] SFTP getting subsystem (reuse=${!!session.sftp})...`);
2072
+ this.getSftp(sessionId).then((sftp) => {
1706
2073
  if (done) return;
1707
- if (sftpErr) {
1708
- callback(new Error('SFTP init failed: ' + sftpErr.message));
1709
- return;
1710
- }
1711
2074
  console.log(`[SSH] SFTP writing ${fileBuffer.length} bytes to ${targetPath}...`);
1712
2075
 
1713
2076
  sftp.open(targetPath, 'w', (openErr: Error | undefined, fd: number) => {
1714
2077
  if (done) return;
1715
2078
  if (openErr) {
1716
2079
  console.error(`[SSH] SFTP open error: ${openErr.message}`);
2080
+ // channel 类故障(达到 MaxSessions 上限 / channel 已失效):重建实例后重试一次
2081
+ if (!isRetry && /channel|not open|closed|failure/i.test(openErr.message)) {
2082
+ console.log('[SSH] SFTP channel broken, recreating subsystem and retrying once');
2083
+ this.invalidateSftp(sessionId);
2084
+ setTimeout(() => { if (!done) doSftpWrite(targetPath, callback, true); }, 300);
2085
+ return;
2086
+ }
1717
2087
  callback(new Error('SFTP open failed: ' + openErr.message));
1718
2088
  return;
1719
2089
  }
@@ -1737,6 +2107,16 @@ Write-Output "__DOCKER__: $dockerVer"
1737
2107
  });
1738
2108
  });
1739
2109
  });
2110
+ }).catch((initErr: any) => {
2111
+ if (done) return;
2112
+ // 建立 subsystem 就可能 "Channel open failure"(MaxSessions 上限):重建后重试一次
2113
+ if (!isRetry && /channel|failure|closed|not open/i.test(initErr?.message || '')) {
2114
+ console.log('[SSH] SFTP init failed, recreating subsystem and retrying once');
2115
+ this.invalidateSftp(sessionId);
2116
+ setTimeout(() => { if (!done) doSftpWrite(targetPath, callback, true); }, 300);
2117
+ return;
2118
+ }
2119
+ callback(new Error(initErr?.message || 'SFTP init failed'));
1740
2120
  });
1741
2121
  };
1742
2122
 
@@ -1746,8 +2126,10 @@ Write-Output "__DOCKER__: $dockerVer"
1746
2126
  if (!err) {
1747
2127
  // 直接写入成功,验证文件
1748
2128
  console.log(`[SSH] SFTP direct write succeeded, verifying...`);
1749
- session.client!.sftp((_, sftp) => {
2129
+ this.getSftp(sessionId).then((sftp) => {
2130
+ if (done) return;
1750
2131
  sftp.stat(fullPath, (statErr: Error | undefined, stats: any) => {
2132
+ if (done) return;
1751
2133
  if (statErr || stats.size !== fileBuffer.length) {
1752
2134
  finish(new Error('SFTP verify failed'));
1753
2135
  } else {
@@ -1755,6 +2137,9 @@ Write-Output "__DOCKER__: $dockerVer"
1755
2137
  finish(null, fileBuffer.length);
1756
2138
  }
1757
2139
  });
2140
+ }).catch((statInitErr: any) => {
2141
+ if (done) return;
2142
+ finish(new Error(statInitErr?.message || 'SFTP verify init failed'));
1758
2143
  });
1759
2144
  return;
1760
2145
  }
@@ -1890,19 +2275,53 @@ Write-Output "__DOCKER__: $dockerVer"
1890
2275
  // ========== 文件管理(SFTP / 本地 fs) ==========
1891
2276
 
1892
2277
  /**
1893
- * 获取 SFTP 客户端(ssh2 的 sftp 子系统)
2278
+ * 获取(并复用)SFTP 客户端(ssh2 的 sftp 子系统)
2279
+ *
2280
+ * 必须复用:OpenSSH 默认 MaxSessions=10,而每次 client.sftp() 都会新开一个
2281
+ * subsystem channel。若每次调用都新建且不关闭,几次之后就会
2282
+ * "Channel open failure: open failed",表现为上传时好时坏、重连后又正常。
1894
2283
  */
1895
2284
  private getSftp(sessionId: string): Promise<any> {
1896
2285
  const session = this.sessions.get(sessionId);
1897
2286
  if (!session || !session.client) {
1898
2287
  return Promise.reject(new Error('SFTP is only available for SSH sessions'));
1899
2288
  }
1900
- return new Promise((resolve, reject) => {
2289
+ if (session.sftp) return Promise.resolve(session.sftp);
2290
+
2291
+ const pending = this.sftpPromises.get(sessionId);
2292
+ if (pending) return pending;
2293
+
2294
+ const p = new Promise<any>((resolve, reject) => {
1901
2295
  session.client!.sftp((err: Error | undefined, sftp: any) => {
1902
- if (err) return reject(err);
2296
+ this.sftpPromises.delete(sessionId);
2297
+ if (err || !sftp) {
2298
+ reject(new Error('SFTP init failed: ' + (err?.message || 'unknown')));
2299
+ return;
2300
+ }
2301
+ session.sftp = sftp;
2302
+ // 实例出错/关闭后丢弃,下次自动重建
2303
+ const drop = () => {
2304
+ if (session.sftp === sftp) session.sftp = undefined;
2305
+ };
2306
+ try {
2307
+ sftp.on('error', drop);
2308
+ sftp.on('close', drop);
2309
+ } catch { /* ignore */ }
1903
2310
  resolve(sftp);
1904
2311
  });
1905
2312
  });
2313
+ this.sftpPromises.set(sessionId, p);
2314
+ return p;
2315
+ }
2316
+
2317
+ /** 丢弃并关闭失效的 SFTP 实例(下次使用时重建) */
2318
+ private invalidateSftp(sessionId: string): void {
2319
+ const session = this.sessions.get(sessionId);
2320
+ const sftp = session?.sftp;
2321
+ if (!sftp) return;
2322
+ session!.sftp = undefined;
2323
+ this.sftpPromises.delete(sessionId);
2324
+ try { sftp.end(); } catch { /* ignore */ }
1906
2325
  }
1907
2326
 
1908
2327
  /**