@fefeding/aicmd 1.0.26 → 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 +57 -1
  57. package/dist/server/service/ssh.service.d.ts.map +1 -1
  58. package/dist/server/service/ssh.service.js +457 -107
  59. package/dist/server/service/ssh.service.js.map +1 -1
  60. package/dist/server/service/ssh.service.ts +452 -105
  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,8 +38,12 @@ 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;
44
49
  /** 复用的 SFTP 实例(每个会话只建一次,避免 channel 泄漏) */
@@ -49,6 +54,12 @@ interface TerminalSession {
49
54
  lastCwdRefreshAt?: number;
50
55
  /** 是否正在刷新 CWD(避免并发 exec) */
51
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;
52
63
  }
53
64
 
54
65
  /**
@@ -73,24 +84,33 @@ const CWD_REFRESH_MIN_INTERVAL = 15000;
73
84
  * 输出格式(每行一条,可能 0~2 行):
74
85
  * SHELL:<pid>:<cwd> 本会话的交互式 shell
75
86
  * XFER:<pid>:<cwd> 本会话正在运行的 rz/sz 进程(rz 的 cwd 即文件将写入的目录)
87
+ * NOCWD:<kind>:<pid>:<pri>:<dep>
88
+ * 属于本会话、但 cwd 读不到(sudo su 后属主变了,需要 ptrace 权限)。
89
+ * 出现即表示本次探测结果不可信,必须换用交互式 shell 探测。
76
90
  *
77
91
  * 设计要点:
78
92
  * 1) 只认与本 exec 通道同源(祖先链命中同一个 sshd 会话进程)的候选,
79
93
  * 避免同一台机器开多个标签页时串台读到别的终端目录;
80
- * 2) 排除 exec 通道自身及其祖先,避免把 exec 自己的 shell(cwd 恒为 $HOME)
81
- * 误判成终端 —— 这正是"文件被传到家目录"的根因;
94
+ * 2) 排除 exec 通道自身、其祖先、以及**它的所有子孙进程**(见 is_exec_tree)——
95
+ * 命令替换 $(...)/管道 fork 出的子 shell 与父进程同名、深度更大、cwd 恒为 $HOME,
96
+ * 若不过滤就会被「最深优先」选中,这正是"文件被传到家目录"的根因;
82
97
  * 3) 不使用 exec 通道的 pwd 兜底,探测不到就返回空,宁可让用户手填。
83
98
  */
84
99
  const SESSION_PROBE_SCRIPT = [
100
+ 'self=$$',
85
101
  // 无 /proc 的远端(macOS / BSD):改用 lsof 读取 shell 的 cwd
86
102
  'if [ ! -d /proc ]; then',
87
- ' 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',
88
109
  ' d=$(lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | sed -n "s/^n//p" | head -n 1)',
89
110
  ' case "$d" in /*) echo "SHELL:$pid:$d"; break;; esac',
90
111
  ' done',
91
112
  ' exit 0',
92
113
  'fi',
93
- 'self=$$',
94
114
  'ppid_of() { sed -n "s/^PPid:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
95
115
  'name_of() { sed -n "s/^Name:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
96
116
  'cwd_of() { readlink "/proc/$1/cwd" 2>/dev/null; }',
@@ -104,27 +124,44 @@ const SESSION_PROBE_SCRIPT = [
104
124
  ' self_chain="$self_chain$p "',
105
125
  ' i=$((i+1))',
106
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
+ '}',
107
142
  // 最近的 sshd 会话祖先:用于把候选限定在本 SSH 会话内
108
143
  'sshd_anc=""',
109
144
  'for q in $self_chain; do',
110
145
  ' n=$(name_of "$q")',
111
146
  ' case "$n" in sshd*) sshd_anc="$q"; break;; esac',
112
147
  'done',
113
- 'in_chain() { case "$self_chain" in *" $1 "*) return 0;; esac; return 1; }',
114
148
  // 返回值即优先级:2 = 与 sshd 会话同源(最准),1 = 仅 stdin 是 tty(tmux/su 等兜底),0 = 不匹配
149
+ // pri_src 记录判定依据:chain=进程链命中 / tty=stdin 是 tty / unknown=读不到(权限不足)
115
150
  'match_pri() {',
116
151
  ' pid=$1',
152
+ ' pri_src=""',
117
153
  ' if [ -n "$sshd_anc" ]; then',
118
154
  ' q=$pid; j=0',
119
155
  ' while [ $j -lt 12 ]; do',
120
156
  ' q=$(ppid_of "$q")',
121
157
  ' case "$q" in ""|0|1) break;; esac',
122
- ' [ "$q" = "$sshd_anc" ] && return 2',
158
+ ' [ "$q" = "$sshd_anc" ] && { pri_src=chain; return 2; }',
123
159
  ' j=$((j+1))',
124
160
  ' done',
125
161
  ' fi',
126
162
  ' tty=$(readlink "/proc/$pid/fd/0" 2>/dev/null)',
127
- ' 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',
128
165
  ' return 0',
129
166
  '}',
130
167
  // 进程深度(到 PID 1 的层数):多个候选时取最深的那个。
@@ -142,19 +179,26 @@ const SESSION_PROBE_SCRIPT = [
142
179
  'best_shell=""; best_shell_key=0',
143
180
  'best_xfer=""; best_xfer_key=0',
144
181
  'for pid in $(ls /proc 2>/dev/null | grep -E "^[0-9]+$"); do',
145
- ' in_chain "$pid" && continue',
146
182
  ' n=$(name_of "$pid")',
147
183
  ' case "$n" in',
148
184
  ' bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox) kind=shell;;',
149
185
  ' rz|sz|lrz|lsz|lrzsz) kind=xfer;;',
150
186
  ' *) continue;;',
151
187
  ' esac',
152
- ' c=$(cwd_of "$pid")',
153
- ' [ -n "$c" ] || continue',
188
+ // 先按名字过滤再判定,避免为每个进程都走一遍祖先链(省掉大量 fork)
189
+ ' is_exec_tree "$pid" && continue',
190
+ ' case "$self_chain" in *" $pid "*) continue;; esac',
154
191
  ' match_pri "$pid"',
155
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',
156
196
  ' [ "$pri" = 0 ] && continue',
157
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',
158
202
  ' key=$((pri * 100 + dep))',
159
203
  ' echo "CAND:$kind:$pid:$c:$pri:$dep"',
160
204
  ' if [ "$kind" = shell ]; then',
@@ -168,6 +212,19 @@ const SESSION_PROBE_SCRIPT = [
168
212
  'exit 0',
169
213
  ].join('\n');
170
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
+
171
228
  /** Session 元数据(用于在 server 端持久化 tab 信息) */
172
229
  interface SessionMetadata {
173
230
  sessionId: string;
@@ -357,6 +414,8 @@ export class SSHService {
357
414
  pty: ptyProcess,
358
415
  createdAt: new Date(),
359
416
  cwd: homeDir,
417
+ os: isWindows ? 'windows' : 'unix',
418
+ osHint: isWindows ? 'windows' : 'linux',
360
419
  };
361
420
 
362
421
  this.sessions.set(sessionId, session);
@@ -451,25 +510,20 @@ export class SSHService {
451
510
  shellOpts.agentForward = true;
452
511
  }
453
512
 
454
- client.shell(shellOpts, (err: Error | undefined, stream: ClientChannel) => {
455
- if (err) {
456
- log(`打开 shell 失败: ${err.message}`);
457
- client.end();
458
- reject(err);
459
- return;
460
- }
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
+ };
461
522
 
462
- log(`Shell 会话已建立`);
523
+ this.openShell(client, shellOpts, connection, session).then((stream) => {
524
+ session.stream = stream;
463
525
 
464
- const session: TerminalSession = {
465
- id: sessionId,
466
- connectionId,
467
- type: 'ssh',
468
- name: sessionName,
469
- client,
470
- stream,
471
- createdAt: new Date(),
472
- };
526
+ log(`Shell 会话已建立${session.noPty ? '(无 PTY 降级模式)' : ''}`);
473
527
 
474
528
  this.sessions.set(sessionId, session);
475
529
 
@@ -503,6 +557,10 @@ export class SSHService {
503
557
  }
504
558
 
505
559
  resolve(session);
560
+ }).catch((err: Error) => {
561
+ log(`打开 shell 失败: ${err.message}`);
562
+ client.end();
563
+ reject(err);
506
564
  });
507
565
  }).on('error', (err: Error) => {
508
566
  clearTimeout(timeout);
@@ -512,6 +570,76 @@ export class SSHService {
512
570
  });
513
571
  }
514
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
+
515
643
  /**
516
644
  * 获取默认 Shell
517
645
  */
@@ -779,8 +907,13 @@ export class SSHService {
779
907
  * Sends a compact command to the remote terminal and captures the output
780
908
  */
781
909
  private async activeCollectRemoteSystemInfo(sessionId: string): Promise<string> {
910
+ const os = await this.resolveSessionOs(sessionId);
782
911
  const marker = '__AICMD_SYS__';
783
- 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)"`;
784
917
  try {
785
918
  // Start capture, then send the command
786
919
  // Use longer timeout (5s) to account for slow SSH connections and MOTD output
@@ -788,12 +921,13 @@ export class SSHService {
788
921
  this.writeData(sessionId, cmd + '\r');
789
922
  const output = await outputPromise;
790
923
  // Clean ANSI escape codes for more reliable marker matching
791
- 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, '');
792
925
  // Extract our marker line
926
+ const echoPrefixes = ['echo', 'Write-Output'];
793
927
  for (const line of cleaned.split('\n')) {
794
928
  const trimmed = line.trim();
795
929
  // Handle possible command echo: skip lines that still contain the raw command prefix
796
- if (trimmed.includes(marker + ':') && !trimmed.startsWith('echo')) {
930
+ if (trimmed.includes(marker + ':') && !echoPrefixes.some(p => trimmed.startsWith(p))) {
797
931
  const markerIdx = trimmed.indexOf(marker + ':');
798
932
  const markerLine = trimmed.substring(markerIdx);
799
933
  const parts = markerLine.split(':');
@@ -857,6 +991,22 @@ export class SSHService {
857
991
  const genericWelcome = motd.match(/Welcome to (.+?)(?:\s*[\(\n])/);
858
992
  if (genericWelcome) info['OS'] = genericWelcome[1].trim();
859
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
+ }
860
1010
 
861
1011
  // === 系统指标(Ubuntu landscape 格式,键值对可能在不同行) ===
862
1012
  // System load
@@ -939,7 +1089,7 @@ export class SSHService {
939
1089
  // === 最终兜底:如果只匹配到极少信息,保留原始 MOTD 作为上下文 ===
940
1090
  if (Object.keys(info).length === 0) {
941
1091
  // 完全没有匹配,返回清理后的原始文本(截取前 800 字符)
942
- const cleaned = motd.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '').replace(/\r/g, '').trim();
1092
+ const cleaned = stripAnsiEscapes(motd).replace(/\r/g, '').trim();
943
1093
  return cleaned.substring(0, 800);
944
1094
  }
945
1095
 
@@ -1157,10 +1307,17 @@ Write-Output "__DOCKER__: $dockerVer"
1157
1307
  continue;
1158
1308
  }
1159
1309
  let next: string | undefined;
1160
- if (target.startsWith('/')) {
1161
- next = target;
1162
- } else if (session.cwd && session.cwd.startsWith('/')) {
1163
- 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);
1164
1321
  } else {
1165
1322
  // 当前目录未知,无法拼接相对路径,重置为未知
1166
1323
  next = undefined;
@@ -1177,7 +1334,25 @@ Write-Output "__DOCKER__: $dockerVer"
1177
1334
  if (!session) return;
1178
1335
  // 只探测 SSH 会话;本地会话的 cwd 由 cd 跟踪维护
1179
1336
  if (session.type !== 'ssh' || !session.client) return;
1180
- 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;
1181
1356
  try {
1182
1357
  await this.refreshCwd(sessionId);
1183
1358
  if (session.cwd) console.log(`[SSH] seeded cwd for ${sessionId}: ${session.cwd} (pid=${session.shellPid || '-'})`);
@@ -1229,7 +1404,7 @@ Write-Output "__DOCKER__: $dockerVer"
1229
1404
  if (probe.shellPid) session.shellPid = probe.shellPid;
1230
1405
  cwd = probe.shellCwd;
1231
1406
  }
1232
- if (cwd && cwd.startsWith('/')) {
1407
+ if (cwd && isAbsolutePath(cwd)) {
1233
1408
  // 用户刚刚敲过 cd(cd 跟踪值很新鲜)时,不覆盖它:
1234
1409
  // cd 是用户的显式意图,比推断出的进程目录更可信,
1235
1410
  // 也能避免探测到错误进程时把正确目录改回成家目录。
@@ -1241,9 +1416,9 @@ Write-Output "__DOCKER__: $dockerVer"
1241
1416
  session.cwdAt = Date.now();
1242
1417
  }
1243
1418
  }
1244
- return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
1419
+ return session.cwd && isAbsolutePath(session.cwd) ? session.cwd : '';
1245
1420
  } catch {
1246
- return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
1421
+ return session.cwd && isAbsolutePath(session.cwd) ? session.cwd : '';
1247
1422
  } finally {
1248
1423
  session.cwdRefreshing = false;
1249
1424
  session.lastCwdRefreshAt = Date.now();
@@ -1258,15 +1433,19 @@ Write-Output "__DOCKER__: $dockerVer"
1258
1433
  if (!Number.isInteger(pid) || pid <= 0) return '';
1259
1434
  const out = await this.execRemote(
1260
1435
  sessionId,
1261
- `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`,
1262
1437
  4000,
1263
1438
  );
1264
1439
  const lines = out.split('\n').map(l => l.trim()).filter(Boolean);
1265
- if (lines.length < 2) return '';
1440
+ if (lines.length < 3) return '';
1266
1441
  const comm = lines[0];
1267
- const cwd = lines[lines.length - 1];
1268
- if (!cwd.startsWith('/')) return '';
1442
+ const cwd = lines[1];
1443
+ const stdin = lines[2];
1444
+ if (!isAbsolutePath(cwd)) return '';
1269
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 '';
1270
1449
  return cwd;
1271
1450
  }
1272
1451
 
@@ -1276,12 +1455,22 @@ Write-Output "__DOCKER__: $dockerVer"
1276
1455
  */
1277
1456
  private async probeSessionProcess(
1278
1457
  sessionId: string,
1279
- ): 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
+ }> {
1280
1467
  const result = {
1281
1468
  shellPid: undefined as number | undefined,
1282
1469
  shellCwd: '',
1283
1470
  xferCwd: '',
1284
1471
  candidates: [] as string[],
1472
+ unreadable: [] as string[],
1473
+ reliable: true,
1285
1474
  };
1286
1475
  const out = await this.execRemote(sessionId, SESSION_PROBE_SCRIPT, 5000);
1287
1476
  for (const raw of out.split('\n')) {
@@ -1292,6 +1481,11 @@ Write-Output "__DOCKER__: $dockerVer"
1292
1481
  result.candidates.push(line.substring(5));
1293
1482
  continue;
1294
1483
  }
1484
+ if (line.startsWith('NOCWD:')) {
1485
+ // 诊断 + 可信度:kind:pid:pri:depth(cwd 因权限读不到)
1486
+ result.unreadable.push(line.substring(6));
1487
+ continue;
1488
+ }
1295
1489
  const m = line.match(/^(SHELL|XFER):(\d+):(\/.*)$/);
1296
1490
  if (!m) continue;
1297
1491
  const pid = Number(m[2]);
@@ -1303,9 +1497,13 @@ Write-Output "__DOCKER__: $dockerVer"
1303
1497
  result.xferCwd = cwd;
1304
1498
  }
1305
1499
  }
1500
+ // 只要还有读不到的同源候选,本次结果就只能算「推断」:
1501
+ // 用户真正在用的 shell 很可能就是那个读不到的(sudo su 后的 root shell)。
1502
+ if (result.unreadable.length) result.reliable = false;
1306
1503
  console.log(
1307
1504
  `[SSH] probeSessionProcess: shell=${result.shellPid || '-'}:${result.shellCwd || '-'} ` +
1308
- `xfer=${result.xferCwd || '-'} cands=[${result.candidates.join(' | ')}]`,
1505
+ `xfer=${result.xferCwd || '-'} reliable=${result.reliable} ` +
1506
+ `cands=[${result.candidates.join(' | ')}] nocwd=[${result.unreadable.join(' | ')}]`,
1309
1507
  );
1310
1508
  return result;
1311
1509
  }
@@ -1372,6 +1570,14 @@ Write-Output "__DOCKER__: $dockerVer"
1372
1570
  * 通知输出监听器(由 WebSocket 处理器在收到终端输出时调用)
1373
1571
  */
1374
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
+ }
1375
1581
  const listener = this.outputListeners.get(sessionId);
1376
1582
  if (listener) {
1377
1583
  try {
@@ -1382,6 +1588,79 @@ Write-Output "__DOCKER__: $dockerVer"
1382
1588
  }
1383
1589
  }
1384
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
+
1385
1664
  /**
1386
1665
  * 捕获会话在指定时间内的输出
1387
1666
  * @param sessionId 会话 ID
@@ -1410,11 +1689,7 @@ Write-Output "__DOCKER__: $dockerVer"
1410
1689
  } else if (listener) {
1411
1690
  this.removeOutputListener(sessionId);
1412
1691
  }
1413
- resolve(output
1414
- .replace(/\x1B\][^\x07]*\x07/g, '')
1415
- .replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '')
1416
- .replace(/\x1B[^\x1B]*[a-zA-Z]/g, '')
1417
- );
1692
+ resolve(stripAnsiEscapes(output));
1418
1693
  };
1419
1694
 
1420
1695
  const timer = setTimeout(finish, timeoutMs);
@@ -1516,25 +1791,74 @@ Write-Output "__DOCKER__: $dockerVer"
1516
1791
  sessionId: string,
1517
1792
  opts: { allowShellProbe?: boolean; preferTransferProcess?: boolean; force?: boolean } = {},
1518
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 }> {
1519
1809
  const allowShellProbe = opts.allowShellProbe !== false;
1520
1810
  const session = this.sessions.get(sessionId);
1521
- if (!session) return '';
1811
+ if (!session) return { cwd: '', reliable: false };
1522
1812
 
1523
- const cached = session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
1813
+ const cached = session.cwd && isAbsolutePath(session.cwd) ? session.cwd : '';
1524
1814
  const cacheFresh = !!cached && !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_CACHE_TTL;
1525
1815
 
1526
- // 0) 强制刷新 + 允许注入探测:直接向 shell 询问,这是最权威的手段。
1527
- // 调用方(上传前兜底、用户点"重新检测")已确保终端处于可打断状态,
1528
- // 否则只靠 exec 探测,一旦 shellPid 指错进程就会一直拿到错误的目录。
1529
- if (opts.force && allowShellProbe) {
1530
- let probed = await this.probeCwdViaShell(sessionId);
1531
- if (!probed) probed = await this.probeCwdViaShell(sessionId);
1532
- if (probed && probed.startsWith('/')) {
1533
- session.cwd = probed;
1534
- session.cwdAt = Date.now();
1535
- console.log(`[SSH] getSessionCwd (forced shell probe): '${probed}'`);
1536
- 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);
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);
1537
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 };
1538
1862
  }
1539
1863
 
1540
1864
  // 0.5) rz/sz 正在等待传输:直接取 rz 进程自身的 cwd。
@@ -1544,27 +1868,24 @@ Write-Output "__DOCKER__: $dockerVer"
1544
1868
  const probe = await this.probeSessionProcess(sessionId);
1545
1869
  if (probe.shellPid) session.shellPid = probe.shellPid;
1546
1870
  const cwd = probe.xferCwd || probe.shellCwd;
1547
- if (cwd) {
1548
- session.cwd = cwd;
1549
- session.cwdAt = Date.now();
1550
- return cwd;
1551
- }
1871
+ if (cwd) return commit(cwd, probe.reliable);
1552
1872
  }
1553
1873
 
1554
1874
  // 1) 缓存命中(且未过期、未强制刷新)
1555
- if (cached && cacheFresh && !opts.force) {
1556
- return cached;
1875
+ // 注意:缓存值本身不可信时必须重新探测,不能直接用 ——
1876
+ // 那正是"sudo su 后上次探测只拿到登录 shell 家目录"的情况,
1877
+ // 若在这里直接返回,错误目录会被一直沿用,警告也就永远消不掉。
1878
+ if (cached && cacheFresh && session.cwdReliable !== false) {
1879
+ return { cwd: cached, reliable: true };
1557
1880
  }
1558
1881
 
1559
1882
  // 2) 已知 shell PID:直接读 /proc
1883
+ // inferredCwd:进程探测得到的推断值,可信则立即采用,不可信时留作最后兜底
1884
+ let inferredCwd = '';
1560
1885
  if (session.type === 'ssh' && session.client) {
1561
1886
  if (session.shellPid) {
1562
1887
  const cwd = await this.readPidCwd(sessionId, session.shellPid);
1563
- if (cwd) {
1564
- session.cwd = cwd;
1565
- session.cwdAt = Date.now();
1566
- return cwd;
1567
- }
1888
+ if (cwd) return commit(cwd, true);
1568
1889
  session.shellPid = undefined;
1569
1890
  }
1570
1891
 
@@ -1574,40 +1895,46 @@ Write-Output "__DOCKER__: $dockerVer"
1574
1895
  const cwd = (opts.preferTransferProcess && probe.xferCwd)
1575
1896
  ? probe.xferCwd
1576
1897
  : (probe.shellCwd || probe.xferCwd);
1577
- if (cwd) {
1578
- session.cwd = cwd;
1579
- session.cwdAt = Date.now();
1580
- return cwd;
1581
- }
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 || '';
1582
1906
  }
1583
1907
 
1584
1908
  // 4) 注入式探测(会打断前台进程)
1585
1909
  if (allowShellProbe) {
1586
1910
  let cwd = await this.probeCwdViaShell(sessionId);
1587
1911
  if (!cwd) cwd = await this.probeCwdViaShell(sessionId);
1588
- if (cwd && cwd.startsWith('/')) {
1589
- session.cwd = cwd;
1590
- session.cwdAt = Date.now();
1591
- return cwd;
1592
- }
1912
+ if (isAbsolutePath(cwd)) return commit(cwd, true);
1593
1913
  }
1594
1914
 
1915
+ // 注入式探测也失败:退回进程推断值(有总比没有强,前端会提示用户核对)
1916
+ if (inferredCwd) return commit(inferredCwd, false);
1917
+
1595
1918
  // 全部失败:缓存已过期时返回空(让前端提示手填),避免把陈旧目录当当前目录使用
1596
1919
  const fallback = cacheFresh ? cached : '';
1597
1920
  console.log(
1598
1921
  `[SSH] getSessionCwd: probes failed for ${sessionId} ` +
1599
- `(allowShellProbe=${allowShellProbe}, force=${!!opts.force}, staleCache=${cached || '-'}, returning='${fallback || ''}')`,
1922
+ `(allowShellProbe=${allowShellProbe}, staleCache=${cached || '-'}, returning='${fallback}')`,
1600
1923
  );
1601
- return fallback;
1924
+ return { cwd: fallback, reliable: false };
1602
1925
  }
1603
1926
 
1604
- /** 向交互式 shell 注入 printf $PWD 探测 CWD(会先 Ctrl+C 打断前台进程) */
1927
+ /** 向交互式 shell 注入命令探测 CWD(会先 Ctrl+C 打断前台进程) */
1605
1928
  private async probeCwdViaShell(sessionId: string): Promise<string> {
1929
+ const os = await this.resolveSessionOs(sessionId);
1606
1930
  const marker = `__AICmd_CWD_${Date.now()}__`;
1607
1931
  // 先发送 Ctrl+C 中断可能正在运行的前台进程(如 rz、vim、top 等),
1608
- // 否则 printf 命令会被前台进程吞掉,shell 不会执行
1932
+ // 否则命令会被前台进程吞掉,shell 不会执行
1609
1933
  this.writeData(sessionId, '\x03');
1610
1934
  await new Promise(r => setTimeout(r, 200));
1935
+ // Ctrl+U 清空当前输入行:若行内还有残留字符,注入的命令会被拼接成无效命令而拿不到结果
1936
+ this.writeData(sessionId, '\x15');
1937
+ await new Promise(r => setTimeout(r, 150));
1611
1938
 
1612
1939
  // 启动捕获后发送命令(marker 行输出完整就立即返回,通常几百毫秒)
1613
1940
  const stopWhen = (text: string) => {
@@ -1617,23 +1944,25 @@ Write-Output "__DOCKER__: $dockerVer"
1617
1944
  return after.includes('\n') || after.length > 80;
1618
1945
  };
1619
1946
  const outputPromise = this.captureOutput(sessionId, 3000, stopWhen);
1620
- 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
+ }
1621
1954
  const output = await outputPromise;
1622
- console.log(`[SSH] probeCwdViaShell: raw output: ${JSON.stringify(output.substring(0, 500))}`);
1623
- // 更彻底的 ANSI 清理:包括 OSC 序列、CSI 序列、以及各种控制字符
1624
- const cleaned = output
1625
- .replace(/\x1B\][^\x07]*\x07/g, '') // OSC 序列
1626
- .replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '') // CSI 序列
1627
- .replace(/\x1B[^\x1B]*[a-zA-Z]/g, '') // 其他转义序列
1628
- .replace(/\r/g, '');
1955
+ // 更彻底的 ANSI 清理:OSC / CSI / 其它有界转义(不得使用会吞正文的贪婪兜底)
1956
+ const cleaned = stripAnsiEscapes(output).replace(/\r/g, '');
1629
1957
  const isCommandEcho = (text: string) => (
1630
1958
  text.includes('printf') ||
1959
+ text.includes('Write-Output') ||
1631
1960
  text.includes('$PWD') ||
1632
1961
  text.includes('%s') ||
1633
1962
  text.includes('echo') ||
1634
1963
  text.includes('$(pwd)')
1635
1964
  );
1636
- const isValidCwd = (cwd: string) => cwd.startsWith('/') && !isCommandEcho(cwd);
1965
+ const isValidCwd = (cwd: string) => isAbsolutePath(cwd) && !isCommandEcho(cwd);
1637
1966
 
1638
1967
  for (const line of cleaned.split('\n')) {
1639
1968
  const trimmed = line.trim();
@@ -1694,14 +2023,32 @@ Write-Output "__DOCKER__: $dockerVer"
1694
2023
  // 解析相对路径:必须通过交互式 shell 获取当前 CWD。
1695
2024
  // 注意:不能 fallback 到 SFTP realpath('.'),它通常是登录 home 目录,会导致文件传错位置。
1696
2025
  let fullPath = remotePath;
1697
- if (!remotePath.startsWith('/')) {
1698
- console.log(`[SSH] Getting shell CWD...`);
1699
- const cwd = await this.getSessionCwd(sessionId);
1700
- console.log(`[SSH] Shell CWD: '${cwd}'`);
1701
- if (!cwd || !cwd.startsWith('/')) {
1702
- 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}`;
1703
2051
  }
1704
- fullPath = `${cwd.replace(/\/$/, '')}/${remotePath}`;
1705
2052
  }
1706
2053
  console.log(`[SSH] SFTP upload path: ${remotePath} -> ${fullPath}`);
1707
2054