@fefeding/aicmd 1.0.26 → 1.0.28
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.
- package/README.md +60 -5
- package/README.zh.md +66 -5
- package/dist/public/.vite/manifest.json +133 -13
- package/dist/public/ai-settings.css +1868 -0
- package/dist/public/ai-settings.js +7579 -0
- package/dist/public/bootstrap-icons.woff +0 -0
- package/dist/public/bootstrap-icons.woff2 +0 -0
- package/dist/public/bootstrap.css +1 -1
- package/dist/public/bootstrap.js +60 -119
- package/dist/public/connection-editor.css +5 -0
- package/dist/public/connection-editor.js +831 -0
- package/dist/public/connection.js +118 -0
- package/dist/public/index.css +0 -381
- package/dist/public/index.js +186 -5467
- package/dist/public/rdp_client_bg.wasm +0 -0
- package/dist/public/selection-copy.css +494 -0
- package/dist/public/selection-copy.js +5540 -0
- package/dist/public/src/term.html +17 -0
- package/dist/public/src/vscode-edit.html +21 -0
- package/dist/public/src/vscode-term.html +24 -0
- package/dist/public/term.css +14 -0
- package/dist/public/term.js +333 -0
- package/dist/public/views.css +111 -1515
- package/dist/public/views.js +233 -7476
- package/dist/public/vscode-clipboard.js +658 -0
- package/dist/public/vscode-edit.js +91 -0
- package/dist/public/vscode-term.js +116 -0
- package/dist/public/vue.js +360 -195
- package/dist/public/xterm.js +1647 -10
- package/dist/public/zmodem.js +2726 -0
- package/dist/server/index.d.ts +12 -2
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +14 -1
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.ts +14 -1
- package/dist/server/model/connection.entity.d.ts +27 -2
- package/dist/server/model/connection.entity.d.ts.map +1 -1
- package/dist/server/model/connection.entity.js +11 -1
- package/dist/server/model/connection.entity.js.map +1 -1
- package/dist/server/model/connection.entity.ts +30 -2
- package/dist/server/service/ai.service.d.ts +15 -0
- package/dist/server/service/ai.service.d.ts.map +1 -1
- package/dist/server/service/ai.service.js +38 -6
- package/dist/server/service/ai.service.js.map +1 -1
- package/dist/server/service/ai.service.ts +43 -6
- package/dist/server/service/connection.service.d.ts +1 -1
- package/dist/server/service/connection.service.d.ts.map +1 -1
- package/dist/server/service/connection.service.js +32 -3
- package/dist/server/service/connection.service.js.map +1 -1
- package/dist/server/service/connection.service.ts +30 -3
- package/dist/server/service/monitor.service.d.ts.map +1 -1
- package/dist/server/service/monitor.service.js +8 -1
- package/dist/server/service/monitor.service.js.map +1 -1
- package/dist/server/service/monitor.service.ts +8 -1
- package/dist/server/service/rdp-tunnel.service.d.ts +22 -0
- package/dist/server/service/rdp-tunnel.service.d.ts.map +1 -0
- package/dist/server/service/rdp-tunnel.service.js +474 -0
- package/dist/server/service/rdp-tunnel.service.js.map +1 -0
- package/dist/server/service/rdp-tunnel.service.ts +439 -0
- package/dist/server/service/rdp.service.d.ts +64 -0
- package/dist/server/service/rdp.service.d.ts.map +1 -0
- package/dist/server/service/rdp.service.js +324 -0
- package/dist/server/service/rdp.service.js.map +1 -0
- package/dist/server/service/rdp.service.ts +324 -0
- package/dist/server/service/ssh.service.d.ts +57 -1
- package/dist/server/service/ssh.service.d.ts.map +1 -1
- package/dist/server/service/ssh.service.js +460 -109
- package/dist/server/service/ssh.service.js.map +1 -1
- package/dist/server/service/ssh.service.ts +455 -107
- package/dist/server/utils/ansi.d.ts +20 -0
- package/dist/server/utils/ansi.d.ts.map +1 -0
- package/dist/server/utils/ansi.js +39 -0
- package/dist/server/utils/ansi.js.map +1 -0
- package/dist/server/utils/ansi.ts +34 -0
- package/dist/server/utils/proxy.d.ts +28 -0
- package/dist/server/utils/proxy.d.ts.map +1 -0
- package/dist/server/utils/proxy.js +596 -0
- package/dist/server/utils/proxy.js.map +1 -0
- package/dist/server/utils/proxy.ts +556 -0
- package/dist/server/utils/rdp-ws.d.ts +15 -0
- package/dist/server/utils/rdp-ws.d.ts.map +1 -0
- package/dist/server/utils/rdp-ws.js +28 -0
- package/dist/server/utils/rdp-ws.js.map +1 -0
- package/dist/server/utils/rdp-ws.ts +32 -0
- package/dist/view/index.html +9 -7
- package/electron/main.js +118 -3
- package/electron/preload.js +4 -0
- package/package.json +32 -31
- package/public/aicmd.png +0 -0
- package/server.js +132 -12
- 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 {
|
|
@@ -70,24 +71,33 @@ const CWD_REFRESH_MIN_INTERVAL = 15000;
|
|
|
70
71
|
* 输出格式(每行一条,可能 0~2 行):
|
|
71
72
|
* SHELL:<pid>:<cwd> 本会话的交互式 shell
|
|
72
73
|
* XFER:<pid>:<cwd> 本会话正在运行的 rz/sz 进程(rz 的 cwd 即文件将写入的目录)
|
|
74
|
+
* NOCWD:<kind>:<pid>:<pri>:<dep>
|
|
75
|
+
* 属于本会话、但 cwd 读不到(sudo su 后属主变了,需要 ptrace 权限)。
|
|
76
|
+
* 出现即表示本次探测结果不可信,必须换用交互式 shell 探测。
|
|
73
77
|
*
|
|
74
78
|
* 设计要点:
|
|
75
79
|
* 1) 只认与本 exec 通道同源(祖先链命中同一个 sshd 会话进程)的候选,
|
|
76
80
|
* 避免同一台机器开多个标签页时串台读到别的终端目录;
|
|
77
|
-
* 2) 排除 exec
|
|
78
|
-
*
|
|
81
|
+
* 2) 排除 exec 通道自身、其祖先、以及**它的所有子孙进程**(见 is_exec_tree)——
|
|
82
|
+
* 命令替换 $(...)/管道 fork 出的子 shell 与父进程同名、深度更大、cwd 恒为 $HOME,
|
|
83
|
+
* 若不过滤就会被「最深优先」选中,这正是"文件被传到家目录"的根因;
|
|
79
84
|
* 3) 不使用 exec 通道的 pwd 兜底,探测不到就返回空,宁可让用户手填。
|
|
80
85
|
*/
|
|
81
86
|
const SESSION_PROBE_SCRIPT = [
|
|
87
|
+
'self=$$',
|
|
82
88
|
// 无 /proc 的远端(macOS / BSD):改用 lsof 读取 shell 的 cwd
|
|
83
89
|
'if [ ! -d /proc ]; then',
|
|
84
|
-
' for
|
|
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',
|
|
85
96
|
' d=$(lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | sed -n "s/^n//p" | head -n 1)',
|
|
86
97
|
' case "$d" in /*) echo "SHELL:$pid:$d"; break;; esac',
|
|
87
98
|
' done',
|
|
88
99
|
' exit 0',
|
|
89
100
|
'fi',
|
|
90
|
-
'self=$$',
|
|
91
101
|
'ppid_of() { sed -n "s/^PPid:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
|
|
92
102
|
'name_of() { sed -n "s/^Name:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
|
|
93
103
|
'cwd_of() { readlink "/proc/$1/cwd" 2>/dev/null; }',
|
|
@@ -101,27 +111,44 @@ const SESSION_PROBE_SCRIPT = [
|
|
|
101
111
|
' self_chain="$self_chain$p "',
|
|
102
112
|
' i=$((i+1))',
|
|
103
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
|
+
'}',
|
|
104
129
|
// 最近的 sshd 会话祖先:用于把候选限定在本 SSH 会话内
|
|
105
130
|
'sshd_anc=""',
|
|
106
131
|
'for q in $self_chain; do',
|
|
107
132
|
' n=$(name_of "$q")',
|
|
108
133
|
' case "$n" in sshd*) sshd_anc="$q"; break;; esac',
|
|
109
134
|
'done',
|
|
110
|
-
'in_chain() { case "$self_chain" in *" $1 "*) return 0;; esac; return 1; }',
|
|
111
135
|
// 返回值即优先级:2 = 与 sshd 会话同源(最准),1 = 仅 stdin 是 tty(tmux/su 等兜底),0 = 不匹配
|
|
136
|
+
// pri_src 记录判定依据:chain=进程链命中 / tty=stdin 是 tty / unknown=读不到(权限不足)
|
|
112
137
|
'match_pri() {',
|
|
113
138
|
' pid=$1',
|
|
139
|
+
' pri_src=""',
|
|
114
140
|
' if [ -n "$sshd_anc" ]; then',
|
|
115
141
|
' q=$pid; j=0',
|
|
116
142
|
' while [ $j -lt 12 ]; do',
|
|
117
143
|
' q=$(ppid_of "$q")',
|
|
118
144
|
' case "$q" in ""|0|1) break;; esac',
|
|
119
|
-
' [ "$q" = "$sshd_anc" ] && return 2',
|
|
145
|
+
' [ "$q" = "$sshd_anc" ] && { pri_src=chain; return 2; }',
|
|
120
146
|
' j=$((j+1))',
|
|
121
147
|
' done',
|
|
122
148
|
' fi',
|
|
123
149
|
' tty=$(readlink "/proc/$pid/fd/0" 2>/dev/null)',
|
|
124
|
-
' 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',
|
|
125
152
|
' return 0',
|
|
126
153
|
'}',
|
|
127
154
|
// 进程深度(到 PID 1 的层数):多个候选时取最深的那个。
|
|
@@ -139,19 +166,26 @@ const SESSION_PROBE_SCRIPT = [
|
|
|
139
166
|
'best_shell=""; best_shell_key=0',
|
|
140
167
|
'best_xfer=""; best_xfer_key=0',
|
|
141
168
|
'for pid in $(ls /proc 2>/dev/null | grep -E "^[0-9]+$"); do',
|
|
142
|
-
' in_chain "$pid" && continue',
|
|
143
169
|
' n=$(name_of "$pid")',
|
|
144
170
|
' case "$n" in',
|
|
145
171
|
' bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox) kind=shell;;',
|
|
146
172
|
' rz|sz|lrz|lsz|lrzsz) kind=xfer;;',
|
|
147
173
|
' *) continue;;',
|
|
148
174
|
' esac',
|
|
149
|
-
|
|
150
|
-
'
|
|
175
|
+
// 先按名字过滤再判定,避免为每个进程都走一遍祖先链(省掉大量 fork)
|
|
176
|
+
' is_exec_tree "$pid" && continue',
|
|
177
|
+
' case "$self_chain" in *" $pid "*) continue;; esac',
|
|
151
178
|
' match_pri "$pid"',
|
|
152
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',
|
|
153
183
|
' [ "$pri" = 0 ] && continue',
|
|
154
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',
|
|
155
189
|
' key=$((pri * 100 + dep))',
|
|
156
190
|
' echo "CAND:$kind:$pid:$c:$pri:$dep"',
|
|
157
191
|
' if [ "$kind" = shell ]; then',
|
|
@@ -164,6 +198,22 @@ const SESSION_PROBE_SCRIPT = [
|
|
|
164
198
|
'[ -n "$best_xfer" ] && echo "XFER:$best_xfer"',
|
|
165
199
|
'exit 0',
|
|
166
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
|
+
}
|
|
167
217
|
/**
|
|
168
218
|
* 终端会话管理服务
|
|
169
219
|
* 支持 SSH 远程连接和本地 Shell
|
|
@@ -299,6 +349,8 @@ class SSHService {
|
|
|
299
349
|
pty: ptyProcess,
|
|
300
350
|
createdAt: new Date(),
|
|
301
351
|
cwd: homeDir,
|
|
352
|
+
os: isWindows ? 'windows' : 'unix',
|
|
353
|
+
osHint: isWindows ? 'windows' : 'linux',
|
|
302
354
|
};
|
|
303
355
|
this.sessions.set(sessionId, session);
|
|
304
356
|
// Windows: 启动时执行 chcp 65001 设置 UTF-8 编码
|
|
@@ -355,10 +407,11 @@ class SSHService {
|
|
|
355
407
|
/**
|
|
356
408
|
* 创建 SSH 会话
|
|
357
409
|
*/
|
|
358
|
-
createSSHSession(sessionId, connectionId, connection, cols, rows, name, onLog) {
|
|
410
|
+
async createSSHSession(sessionId, connectionId, connection, cols, rows, name, onLog) {
|
|
359
411
|
const log = (msg) => { console.log(`[SSH] ${msg}`); onLog?.(msg); };
|
|
412
|
+
// 代理握手是异步的,需在创建 ssh2 Client 前完成
|
|
413
|
+
const sshConfig = await this.connectionService.getSSHConfig(connection, onLog);
|
|
360
414
|
return new Promise((resolve, reject) => {
|
|
361
|
-
const sshConfig = this.connectionService.getSSHConfig(connection, onLog);
|
|
362
415
|
const client = new ssh2_1.Client();
|
|
363
416
|
const sessionName = name || connection.name || 'SSH';
|
|
364
417
|
log(`正在连接到 ${connection.host}:${connection.port || 22} (用户: ${connection.username})`);
|
|
@@ -379,23 +432,18 @@ class SSHService {
|
|
|
379
432
|
if (connection.forwardAgent) {
|
|
380
433
|
shellOpts.agentForward = true;
|
|
381
434
|
}
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
name: sessionName,
|
|
395
|
-
client,
|
|
396
|
-
stream,
|
|
397
|
-
createdAt: new Date(),
|
|
398
|
-
};
|
|
435
|
+
const session = {
|
|
436
|
+
id: sessionId,
|
|
437
|
+
connectionId,
|
|
438
|
+
type: 'ssh',
|
|
439
|
+
name: sessionName,
|
|
440
|
+
client,
|
|
441
|
+
createdAt: new Date(),
|
|
442
|
+
osHint: connection.platform,
|
|
443
|
+
};
|
|
444
|
+
this.openShell(client, shellOpts, connection, session).then((stream) => {
|
|
445
|
+
session.stream = stream;
|
|
446
|
+
log(`Shell 会话已建立${session.noPty ? '(无 PTY 降级模式)' : ''}`);
|
|
399
447
|
this.sessions.set(sessionId, session);
|
|
400
448
|
// 连接后后台探测初始 CWD(在 shell 初始化完成后),用于上传时定位当前目录
|
|
401
449
|
setTimeout(() => {
|
|
@@ -425,6 +473,10 @@ class SSHService {
|
|
|
425
473
|
}, 800);
|
|
426
474
|
}
|
|
427
475
|
resolve(session);
|
|
476
|
+
}).catch((err) => {
|
|
477
|
+
log(`打开 shell 失败: ${err.message}`);
|
|
478
|
+
client.end();
|
|
479
|
+
reject(err);
|
|
428
480
|
});
|
|
429
481
|
}).on('error', (err) => {
|
|
430
482
|
clearTimeout(timeout);
|
|
@@ -433,6 +485,82 @@ class SSHService {
|
|
|
433
485
|
}).connect(sshConfig);
|
|
434
486
|
});
|
|
435
487
|
}
|
|
488
|
+
/**
|
|
489
|
+
* 打开远端 shell,并在 PTY 不可用时优雅降级。
|
|
490
|
+
*
|
|
491
|
+
* 某些 Windows OpenSSH 配置 / 老旧版本对 pty-req 支持不完整,直接 `client.shell({term})`
|
|
492
|
+
* 会失败。这里依次尝试多个 term 类型,再尝试不带 term 的 shell;
|
|
493
|
+
* 全部失败则降级到「无 PTY 模式」(`client.exec` 启动默认 shell)——交互体验受限
|
|
494
|
+
* (无回显 / 行编辑),但命令仍可执行。降级时会在 session 上标记 noPty。
|
|
495
|
+
*/
|
|
496
|
+
openShell(client, shellOpts, connection, session) {
|
|
497
|
+
return new Promise((resolve, reject) => {
|
|
498
|
+
const termCandidates = [shellOpts.term, 'xterm', 'vt100'];
|
|
499
|
+
let ti = 0;
|
|
500
|
+
const tryShell = () => {
|
|
501
|
+
const opts = { ...shellOpts, term: termCandidates[ti] };
|
|
502
|
+
if (!opts.term)
|
|
503
|
+
delete opts.term;
|
|
504
|
+
client.shell(opts, (err, stream) => {
|
|
505
|
+
if (!err)
|
|
506
|
+
return resolve(stream);
|
|
507
|
+
if (ti < termCandidates.length - 1) {
|
|
508
|
+
ti += 1;
|
|
509
|
+
return tryShell();
|
|
510
|
+
}
|
|
511
|
+
// 所有 term 候选都失败:尝试不带 term 的 shell 请求
|
|
512
|
+
client.shell({ ...shellOpts, term: undefined }, (e2, s2) => {
|
|
513
|
+
if (!e2 && s2)
|
|
514
|
+
return resolve(s2);
|
|
515
|
+
// 最终降级:以无 PTY 方式执行默认 shell(交互体验受限,但命令可执行)
|
|
516
|
+
const fallbackShell = connection.platform === 'windows'
|
|
517
|
+
? 'powershell.exe -NoProfile -NonInteractive -NoLogo'
|
|
518
|
+
: (process.platform === 'win32' ? 'powershell.exe' : '/bin/bash -i');
|
|
519
|
+
client.exec(fallbackShell, (e3, s3) => {
|
|
520
|
+
if (!e3 && s3) {
|
|
521
|
+
if (session)
|
|
522
|
+
session.noPty = true;
|
|
523
|
+
console.warn('[SSH] PTY 不可用,已降级到无 PTY 模式(exec 默认 shell)');
|
|
524
|
+
return resolve(s3);
|
|
525
|
+
}
|
|
526
|
+
reject(err || e2 || e3 || new Error('无法打开远程 shell'));
|
|
527
|
+
});
|
|
528
|
+
});
|
|
529
|
+
});
|
|
530
|
+
};
|
|
531
|
+
tryShell();
|
|
532
|
+
});
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* 解析远端操作系统类型('unix' | 'windows'),结果缓存到 session。
|
|
536
|
+
* 优先使用连接配置中的 platform 提示;为 'auto' 时通过独立 exec 通道运行
|
|
537
|
+
* `uname -s` 探测(不污染交互式终端):能取到内核名即为类 Unix,否则视为 Windows。
|
|
538
|
+
*/
|
|
539
|
+
async resolveSessionOs(sessionId) {
|
|
540
|
+
const session = this.sessions.get(sessionId);
|
|
541
|
+
if (!session)
|
|
542
|
+
return 'unix';
|
|
543
|
+
if (session.os)
|
|
544
|
+
return session.os;
|
|
545
|
+
const hint = session.osHint;
|
|
546
|
+
if (hint === 'windows') {
|
|
547
|
+
session.os = 'windows';
|
|
548
|
+
return 'windows';
|
|
549
|
+
}
|
|
550
|
+
if (hint === 'linux' || hint === 'macos') {
|
|
551
|
+
session.os = 'unix';
|
|
552
|
+
return 'unix';
|
|
553
|
+
}
|
|
554
|
+
try {
|
|
555
|
+
const out = await this.execRemote(sessionId, 'uname -s');
|
|
556
|
+
const s = (out || '').trim().toLowerCase();
|
|
557
|
+
session.os = /linux|darwin|freebsd|openbsd|netbsd|sunos/.test(s) ? 'unix' : 'windows';
|
|
558
|
+
}
|
|
559
|
+
catch {
|
|
560
|
+
session.os = 'unix'; // 探测失败时按类 Unix 处理(最常见的远端)
|
|
561
|
+
}
|
|
562
|
+
return session.os;
|
|
563
|
+
}
|
|
436
564
|
/**
|
|
437
565
|
* 获取默认 Shell
|
|
438
566
|
*/
|
|
@@ -688,8 +816,13 @@ class SSHService {
|
|
|
688
816
|
* Sends a compact command to the remote terminal and captures the output
|
|
689
817
|
*/
|
|
690
818
|
async activeCollectRemoteSystemInfo(sessionId) {
|
|
819
|
+
const os = await this.resolveSessionOs(sessionId);
|
|
691
820
|
const marker = '__AICMD_SYS__';
|
|
692
|
-
|
|
821
|
+
// Windows(PowerShell)与类 Unix(bash/sh)使用不同的采集命令;
|
|
822
|
+
// 二者都通过同一个 __AICMD_SYS__ marker 回传,便于统一解析。
|
|
823
|
+
const cmd = os === 'windows'
|
|
824
|
+
? `Write-Output "${marker}:Windows:$(Get-CimInstance Win32_OperatingSystem | Select-Object -ExpandProperty Version):$(hostname):$env:USERNAME:PowerShell:$(Get-CimInstance Win32_Processor | Select-Object -ExpandProperty Architecture)"`
|
|
825
|
+
: `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)"`;
|
|
693
826
|
try {
|
|
694
827
|
// Start capture, then send the command
|
|
695
828
|
// Use longer timeout (5s) to account for slow SSH connections and MOTD output
|
|
@@ -697,12 +830,13 @@ class SSHService {
|
|
|
697
830
|
this.writeData(sessionId, cmd + '\r');
|
|
698
831
|
const output = await outputPromise;
|
|
699
832
|
// Clean ANSI escape codes for more reliable marker matching
|
|
700
|
-
const cleaned =
|
|
833
|
+
const cleaned = (0, ansi_1.stripAnsiEscapes)(output).replace(/\r/g, '');
|
|
701
834
|
// Extract our marker line
|
|
835
|
+
const echoPrefixes = ['echo', 'Write-Output'];
|
|
702
836
|
for (const line of cleaned.split('\n')) {
|
|
703
837
|
const trimmed = line.trim();
|
|
704
838
|
// Handle possible command echo: skip lines that still contain the raw command prefix
|
|
705
|
-
if (trimmed.includes(marker + ':') && !trimmed.startsWith(
|
|
839
|
+
if (trimmed.includes(marker + ':') && !echoPrefixes.some(p => trimmed.startsWith(p))) {
|
|
706
840
|
const markerIdx = trimmed.indexOf(marker + ':');
|
|
707
841
|
const markerLine = trimmed.substring(markerIdx);
|
|
708
842
|
const parts = markerLine.split(':');
|
|
@@ -768,6 +902,24 @@ class SSHService {
|
|
|
768
902
|
if (genericWelcome)
|
|
769
903
|
info['OS'] = genericWelcome[1].trim();
|
|
770
904
|
}
|
|
905
|
+
// Windows(OpenSSH Server / cmd 横幅):"Microsoft Windows [Version 10.0.19041.1]"
|
|
906
|
+
if (!info['OS']) {
|
|
907
|
+
const winVer = motd.match(/Microsoft Windows.*?Version\s+([\d.]+)/i)
|
|
908
|
+
|| motd.match(/\bWindows Server\b|\bWindows\b/i);
|
|
909
|
+
if (winVer) {
|
|
910
|
+
info['OS'] = winVer[1] ? `Windows ${winVer[1]}` : 'Windows';
|
|
911
|
+
const verMatch = motd.match(/Version\s+([\d.]+)/i);
|
|
912
|
+
if (verMatch)
|
|
913
|
+
info['Kernel'] = verMatch[1];
|
|
914
|
+
}
|
|
915
|
+
}
|
|
916
|
+
// macOS(部分系统登录横幅含 Darwin 内核信息)
|
|
917
|
+
if (!info['OS'] && /Darwin/i.test(motd)) {
|
|
918
|
+
info['OS'] = 'macOS (Darwin)';
|
|
919
|
+
const darwinMatch = motd.match(/Darwin[^\n]*?([\d.]+)/i);
|
|
920
|
+
if (darwinMatch)
|
|
921
|
+
info['Kernel'] = darwinMatch[1];
|
|
922
|
+
}
|
|
771
923
|
// === 系统指标(Ubuntu landscape 格式,键值对可能在不同行) ===
|
|
772
924
|
// System load
|
|
773
925
|
const loadMatch = motd.match(/System load:\s*(\S+)/);
|
|
@@ -851,7 +1003,7 @@ class SSHService {
|
|
|
851
1003
|
// === 最终兜底:如果只匹配到极少信息,保留原始 MOTD 作为上下文 ===
|
|
852
1004
|
if (Object.keys(info).length === 0) {
|
|
853
1005
|
// 完全没有匹配,返回清理后的原始文本(截取前 800 字符)
|
|
854
|
-
const cleaned =
|
|
1006
|
+
const cleaned = (0, ansi_1.stripAnsiEscapes)(motd).replace(/\r/g, '').trim();
|
|
855
1007
|
return cleaned.substring(0, 800);
|
|
856
1008
|
}
|
|
857
1009
|
const lines = ['System environment info:'];
|
|
@@ -1066,11 +1218,18 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1066
1218
|
continue;
|
|
1067
1219
|
}
|
|
1068
1220
|
let next;
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1221
|
+
const os = session.os ?? (session.osHint === 'windows' ? 'windows' : 'unix');
|
|
1222
|
+
if (target.startsWith('/') || /^[A-Za-z]:[\\/]/.test(target) || target.startsWith('\\\\')) {
|
|
1223
|
+
// 绝对路径(Unix 的 '/' 或 Windows 的盘符 / UNC)
|
|
1224
|
+
next = os === 'windows'
|
|
1225
|
+
? target.replace(/\//g, '\\') // 统一为 Windows 反斜杠分隔符
|
|
1226
|
+
: target;
|
|
1227
|
+
}
|
|
1228
|
+
else if (isAbsolutePath(session.cwd)) {
|
|
1229
|
+
// 相对路径:基于当前目录拼接(跨平台使用对应 path 模块)
|
|
1230
|
+
next = os === 'windows'
|
|
1231
|
+
? path.win32.resolve(session.cwd, target)
|
|
1232
|
+
: path.posix.resolve(session.cwd, target);
|
|
1074
1233
|
}
|
|
1075
1234
|
else {
|
|
1076
1235
|
// 当前目录未知,无法拼接相对路径,重置为未知
|
|
@@ -1089,7 +1248,27 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1089
1248
|
// 只探测 SSH 会话;本地会话的 cwd 由 cd 跟踪维护
|
|
1090
1249
|
if (session.type !== 'ssh' || !session.client)
|
|
1091
1250
|
return;
|
|
1092
|
-
|
|
1251
|
+
const os = await this.resolveSessionOs(sessionId);
|
|
1252
|
+
if (os === 'windows') {
|
|
1253
|
+
// Windows 无 /proc,后台刷新无法获取 CWD;改用注入式探测拿到初始目录,
|
|
1254
|
+
// 以便后续 cd 跟踪能拼接相对路径。
|
|
1255
|
+
if (isAbsolutePath(session.cwd))
|
|
1256
|
+
return;
|
|
1257
|
+
try {
|
|
1258
|
+
const cwd = await this.probeCwdViaShell(sessionId);
|
|
1259
|
+
if (cwd) {
|
|
1260
|
+
session.cwd = cwd;
|
|
1261
|
+
session.cwdAt = Date.now();
|
|
1262
|
+
session.cwdReliable = true;
|
|
1263
|
+
console.log(`[SSH] seeded windows cwd for ${sessionId}: ${cwd}`);
|
|
1264
|
+
}
|
|
1265
|
+
}
|
|
1266
|
+
catch {
|
|
1267
|
+
// 忽略,上传时再探测
|
|
1268
|
+
}
|
|
1269
|
+
return;
|
|
1270
|
+
}
|
|
1271
|
+
if (session.shellPid && isAbsolutePath(session.cwd))
|
|
1093
1272
|
return;
|
|
1094
1273
|
try {
|
|
1095
1274
|
await this.refreshCwd(sessionId);
|
|
@@ -1150,7 +1329,7 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1150
1329
|
session.shellPid = probe.shellPid;
|
|
1151
1330
|
cwd = probe.shellCwd;
|
|
1152
1331
|
}
|
|
1153
|
-
if (cwd && cwd
|
|
1332
|
+
if (cwd && isAbsolutePath(cwd)) {
|
|
1154
1333
|
// 用户刚刚敲过 cd(cd 跟踪值很新鲜)时,不覆盖它:
|
|
1155
1334
|
// cd 是用户的显式意图,比推断出的进程目录更可信,
|
|
1156
1335
|
// 也能避免探测到错误进程时把正确目录改回成家目录。
|
|
@@ -1163,10 +1342,10 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1163
1342
|
session.cwdAt = Date.now();
|
|
1164
1343
|
}
|
|
1165
1344
|
}
|
|
1166
|
-
return session.cwd && session.cwd
|
|
1345
|
+
return session.cwd && isAbsolutePath(session.cwd) ? session.cwd : '';
|
|
1167
1346
|
}
|
|
1168
1347
|
catch {
|
|
1169
|
-
return session.cwd && session.cwd
|
|
1348
|
+
return session.cwd && isAbsolutePath(session.cwd) ? session.cwd : '';
|
|
1170
1349
|
}
|
|
1171
1350
|
finally {
|
|
1172
1351
|
session.cwdRefreshing = false;
|
|
@@ -1180,16 +1359,21 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1180
1359
|
async readPidCwd(sessionId, pid) {
|
|
1181
1360
|
if (!Number.isInteger(pid) || pid <= 0)
|
|
1182
1361
|
return '';
|
|
1183
|
-
const out = await this.execRemote(sessionId, `cat /proc/${pid}/comm 2>/dev/null; readlink /proc/${pid}/cwd 2>/dev/null`, 4000);
|
|
1362
|
+
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);
|
|
1184
1363
|
const lines = out.split('\n').map(l => l.trim()).filter(Boolean);
|
|
1185
|
-
if (lines.length <
|
|
1364
|
+
if (lines.length < 3)
|
|
1186
1365
|
return '';
|
|
1187
1366
|
const comm = lines[0];
|
|
1188
|
-
const cwd = lines[
|
|
1189
|
-
|
|
1367
|
+
const cwd = lines[1];
|
|
1368
|
+
const stdin = lines[2];
|
|
1369
|
+
if (!isAbsolutePath(cwd))
|
|
1190
1370
|
return '';
|
|
1191
1371
|
if (!/^(bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox|rz|sz|lrz|lsz)$/.test(comm))
|
|
1192
1372
|
return '';
|
|
1373
|
+
// 交互式 shell / rz 的 stdin 一定是 tty;exec 通道(及其子 shell)是 pipe/socket,
|
|
1374
|
+
// 这里再校验一次,避免 PID 复用时读到无关进程的目录(通常是 $HOME)。
|
|
1375
|
+
if (!/^\/dev\/(pts|tty|console)/.test(stdin))
|
|
1376
|
+
return '';
|
|
1193
1377
|
return cwd;
|
|
1194
1378
|
}
|
|
1195
1379
|
/**
|
|
@@ -1202,6 +1386,8 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1202
1386
|
shellCwd: '',
|
|
1203
1387
|
xferCwd: '',
|
|
1204
1388
|
candidates: [],
|
|
1389
|
+
unreadable: [],
|
|
1390
|
+
reliable: true,
|
|
1205
1391
|
};
|
|
1206
1392
|
const out = await this.execRemote(sessionId, SESSION_PROBE_SCRIPT, 5000);
|
|
1207
1393
|
for (const raw of out.split('\n')) {
|
|
@@ -1213,6 +1399,11 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1213
1399
|
result.candidates.push(line.substring(5));
|
|
1214
1400
|
continue;
|
|
1215
1401
|
}
|
|
1402
|
+
if (line.startsWith('NOCWD:')) {
|
|
1403
|
+
// 诊断 + 可信度:kind:pid:pri:depth(cwd 因权限读不到)
|
|
1404
|
+
result.unreadable.push(line.substring(6));
|
|
1405
|
+
continue;
|
|
1406
|
+
}
|
|
1216
1407
|
const m = line.match(/^(SHELL|XFER):(\d+):(\/.*)$/);
|
|
1217
1408
|
if (!m)
|
|
1218
1409
|
continue;
|
|
@@ -1226,8 +1417,13 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1226
1417
|
result.xferCwd = cwd;
|
|
1227
1418
|
}
|
|
1228
1419
|
}
|
|
1420
|
+
// 只要还有读不到的同源候选,本次结果就只能算「推断」:
|
|
1421
|
+
// 用户真正在用的 shell 很可能就是那个读不到的(sudo su 后的 root shell)。
|
|
1422
|
+
if (result.unreadable.length)
|
|
1423
|
+
result.reliable = false;
|
|
1229
1424
|
console.log(`[SSH] probeSessionProcess: shell=${result.shellPid || '-'}:${result.shellCwd || '-'} ` +
|
|
1230
|
-
`xfer=${result.xferCwd || '-'}
|
|
1425
|
+
`xfer=${result.xferCwd || '-'} reliable=${result.reliable} ` +
|
|
1426
|
+
`cands=[${result.candidates.join(' | ')}] nocwd=[${result.unreadable.join(' | ')}]`);
|
|
1231
1427
|
return result;
|
|
1232
1428
|
}
|
|
1233
1429
|
/**
|
|
@@ -1294,6 +1490,15 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1294
1490
|
* 通知输出监听器(由 WebSocket 处理器在收到终端输出时调用)
|
|
1295
1491
|
*/
|
|
1296
1492
|
notifyOutput(sessionId, data) {
|
|
1493
|
+
// 累积到会话输出缓冲(供 Agent 的 read_terminal / shell.read 读取)
|
|
1494
|
+
const session = this.sessions.get(sessionId);
|
|
1495
|
+
if (session) {
|
|
1496
|
+
let buf = (session.outputBuffer || '') + data;
|
|
1497
|
+
// 限制缓冲上限,避免长会话无限增长(保留尾部约 32KB)
|
|
1498
|
+
if (buf.length > 32768)
|
|
1499
|
+
buf = buf.slice(-32768);
|
|
1500
|
+
session.outputBuffer = buf;
|
|
1501
|
+
}
|
|
1297
1502
|
const listener = this.outputListeners.get(sessionId);
|
|
1298
1503
|
if (listener) {
|
|
1299
1504
|
try {
|
|
@@ -1304,6 +1509,81 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1304
1509
|
}
|
|
1305
1510
|
}
|
|
1306
1511
|
}
|
|
1512
|
+
/**
|
|
1513
|
+
* 读取会话累积的输出缓冲(当前屏幕/历史内容),不依赖「调用后新到达」的采集窗口。
|
|
1514
|
+
* @param maxLines 最多返回末尾行数,默认 200
|
|
1515
|
+
*/
|
|
1516
|
+
getOutputBuffer(sessionId, maxLines = 200) {
|
|
1517
|
+
const session = this.sessions.get(sessionId);
|
|
1518
|
+
if (!session || !session.outputBuffer)
|
|
1519
|
+
return '';
|
|
1520
|
+
const cleaned = (0, ansi_1.stripAnsiEscapes)(session.outputBuffer);
|
|
1521
|
+
const lines = cleaned.split('\n');
|
|
1522
|
+
return lines.slice(-maxLines).join('\n');
|
|
1523
|
+
}
|
|
1524
|
+
/**
|
|
1525
|
+
* 采集输出并「空闲即停」:新数据停止到达超过 idleMs 后认为本次输出结束,
|
|
1526
|
+
* 最长不超过 maxMs。相比固定时间窗口,能完整拿到慢命令的输出,
|
|
1527
|
+
* 又不会像定长等待那样白白浪费时间。
|
|
1528
|
+
* @param sessionId 会话 ID
|
|
1529
|
+
* @param idleMs 判定输出结束的静默时长,默认 700ms
|
|
1530
|
+
* @param maxMs 最长等待(兜底),默认 10000ms
|
|
1531
|
+
* @returns 已去除 ANSI 转义序列的输出文本
|
|
1532
|
+
*/
|
|
1533
|
+
captureOutputIdle(sessionId, idleMs = 700, maxMs = 10000) {
|
|
1534
|
+
return new Promise((resolve) => {
|
|
1535
|
+
const clean = (s) => (0, ansi_1.stripAnsiEscapes)(s);
|
|
1536
|
+
const session = this.sessions.get(sessionId);
|
|
1537
|
+
let raw = '';
|
|
1538
|
+
let settled = false;
|
|
1539
|
+
let lastLen = 0;
|
|
1540
|
+
let lastChangeAt = Date.now();
|
|
1541
|
+
let streamHandler = null;
|
|
1542
|
+
let listener = null;
|
|
1543
|
+
let idleTimer = null;
|
|
1544
|
+
let maxTimer = null;
|
|
1545
|
+
const finish = () => {
|
|
1546
|
+
if (settled)
|
|
1547
|
+
return;
|
|
1548
|
+
settled = true;
|
|
1549
|
+
if (idleTimer)
|
|
1550
|
+
clearInterval(idleTimer);
|
|
1551
|
+
if (maxTimer)
|
|
1552
|
+
clearTimeout(maxTimer);
|
|
1553
|
+
if (streamHandler && session?.stream) {
|
|
1554
|
+
session.stream.removeListener('data', streamHandler);
|
|
1555
|
+
}
|
|
1556
|
+
else if (listener) {
|
|
1557
|
+
this.removeOutputListener(sessionId);
|
|
1558
|
+
}
|
|
1559
|
+
resolve(clean(raw));
|
|
1560
|
+
};
|
|
1561
|
+
idleTimer = setInterval(() => {
|
|
1562
|
+
if (settled)
|
|
1563
|
+
return;
|
|
1564
|
+
const now = Date.now();
|
|
1565
|
+
if (raw.length !== lastLen) {
|
|
1566
|
+
lastLen = raw.length;
|
|
1567
|
+
lastChangeAt = now;
|
|
1568
|
+
return;
|
|
1569
|
+
}
|
|
1570
|
+
// 已有数据且静默超过 idleMs,判定本次输出结束
|
|
1571
|
+
if (raw.length > 0 && now - lastChangeAt >= idleMs)
|
|
1572
|
+
finish();
|
|
1573
|
+
}, 100);
|
|
1574
|
+
maxTimer = setTimeout(finish, maxMs);
|
|
1575
|
+
const onData = (text) => { raw += text; };
|
|
1576
|
+
if (session?.stream) {
|
|
1577
|
+
streamHandler = (chunk) => onData(chunk.toString('utf-8'));
|
|
1578
|
+
session.stream.on('data', streamHandler);
|
|
1579
|
+
}
|
|
1580
|
+
else {
|
|
1581
|
+
// 本地 shell fallback:通过 notifyOutput 机制
|
|
1582
|
+
listener = onData;
|
|
1583
|
+
this.addOutputListener(sessionId, listener);
|
|
1584
|
+
}
|
|
1585
|
+
});
|
|
1586
|
+
}
|
|
1307
1587
|
/**
|
|
1308
1588
|
* 捕获会话在指定时间内的输出
|
|
1309
1589
|
* @param sessionId 会话 ID
|
|
@@ -1329,10 +1609,7 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1329
1609
|
else if (listener) {
|
|
1330
1610
|
this.removeOutputListener(sessionId);
|
|
1331
1611
|
}
|
|
1332
|
-
resolve(output
|
|
1333
|
-
.replace(/\x1B\][^\x07]*\x07/g, '')
|
|
1334
|
-
.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '')
|
|
1335
|
-
.replace(/\x1B[^\x1B]*[a-zA-Z]/g, ''));
|
|
1612
|
+
resolve((0, ansi_1.stripAnsiEscapes)(output));
|
|
1336
1613
|
};
|
|
1337
1614
|
const timer = setTimeout(finish, timeoutMs);
|
|
1338
1615
|
const onData = (text) => {
|
|
@@ -1432,25 +1709,68 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1432
1709
|
* 也不能把陈旧的(很可能是家目录的)路径当成当前目录 —— 那会导致文件传错位置。
|
|
1433
1710
|
*/
|
|
1434
1711
|
async getSessionCwd(sessionId, opts = {}) {
|
|
1712
|
+
return (await this.getSessionCwdDetailed(sessionId, opts)).cwd;
|
|
1713
|
+
}
|
|
1714
|
+
/**
|
|
1715
|
+
* 同 getSessionCwd,但额外返回可信度。
|
|
1716
|
+
*
|
|
1717
|
+
* reliable=false 的典型场景:`sudo su` / `su` 之后,用户真正在用的 shell 属于 root,
|
|
1718
|
+
* 而 exec 通道跑在登录用户下,/proc/<pid>/cwd 需要 ptrace 权限、读不到,
|
|
1719
|
+
* 探测结果退化成「唯一读得到的那个进程」(往往是登录 shell = 家目录)。
|
|
1720
|
+
* 调用方必须据此改向交互式 shell 询问或让用户确认,不能直接拿它当结论。
|
|
1721
|
+
*/
|
|
1722
|
+
async getSessionCwdDetailed(sessionId, opts = {}) {
|
|
1435
1723
|
const allowShellProbe = opts.allowShellProbe !== false;
|
|
1436
1724
|
const session = this.sessions.get(sessionId);
|
|
1437
1725
|
if (!session)
|
|
1438
|
-
return '';
|
|
1439
|
-
const cached = session.cwd && session.cwd
|
|
1726
|
+
return { cwd: '', reliable: false };
|
|
1727
|
+
const cached = session.cwd && isAbsolutePath(session.cwd) ? session.cwd : '';
|
|
1440
1728
|
const cacheFresh = !!cached && !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_CACHE_TTL;
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1729
|
+
const commit = (cwd, reliable) => {
|
|
1730
|
+
session.cwd = cwd;
|
|
1731
|
+
session.cwdAt = Date.now();
|
|
1732
|
+
session.cwdReliable = reliable;
|
|
1733
|
+
console.log(`[SSH] getSessionCwd: '${cwd}' reliable=${reliable}`);
|
|
1734
|
+
return { cwd, reliable };
|
|
1735
|
+
};
|
|
1736
|
+
// 0) 强制刷新:按可信度从高到低依次尝试,拿到结果立即返回;
|
|
1737
|
+
// 全部失败时只在缓存仍然新鲜的情况下才用缓存兜底,绝不把不可信的猜测当当前目录。
|
|
1738
|
+
if (opts.force) {
|
|
1739
|
+
let probed = '';
|
|
1740
|
+
// 0.1) 向 shell 询问(最权威)。调用方(上传前兜底、用户点"重新检测")已确保
|
|
1741
|
+
// 终端处于可打断状态;rz 把终端设为 raw 模式时 Ctrl+C 只是普通字节,
|
|
1742
|
+
// 探测会失败并落到 0.2,不会污染结果。
|
|
1743
|
+
if (allowShellProbe) {
|
|
1744
|
+
let probed = await this.probeCwdViaShell(sessionId);
|
|
1745
|
+
if (!probed)
|
|
1746
|
+
probed = await this.probeCwdViaShell(sessionId);
|
|
1747
|
+
if (isAbsolutePath(probed))
|
|
1748
|
+
return commit(probed, true);
|
|
1749
|
+
}
|
|
1750
|
+
// 0.2) 进程探测:rz/sz 自己的 cwd 最权威(它就是文件要写入的目录)。
|
|
1751
|
+
if (session.type === 'ssh' && session.client) {
|
|
1752
|
+
const probe = await this.probeSessionProcess(sessionId);
|
|
1753
|
+
if (probe.shellPid)
|
|
1754
|
+
session.shellPid = probe.shellPid;
|
|
1755
|
+
if (isAbsolutePath(probe.xferCwd))
|
|
1756
|
+
return commit(probe.xferCwd, true);
|
|
1757
|
+
// 可信的 shell 进程目录(能读到所有同源进程):直接用,无需再麻烦用户。
|
|
1758
|
+
if (isAbsolutePath(probe.shellCwd) && probe.reliable) {
|
|
1759
|
+
return commit(probe.shellCwd, true);
|
|
1760
|
+
}
|
|
1761
|
+
// 不可信(sudo su 等只读到部分进程):优先用「用户刚敲的 cd」跟踪值,
|
|
1762
|
+
// 它最贴近真实意图;最后才退回不可信的进程推断,绝不能把登录 shell 家目录
|
|
1763
|
+
// 当成当前目录(那会让文件传到错误的位置)。
|
|
1764
|
+
const trackedFresh = !!cached && !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_TRACK_GRACE;
|
|
1765
|
+
if (trackedFresh)
|
|
1766
|
+
return commit(cached, true);
|
|
1767
|
+
if (isAbsolutePath(probe.shellCwd))
|
|
1768
|
+
return commit(probe.shellCwd, probe.reliable);
|
|
1769
|
+
}
|
|
1770
|
+
const forcedFallback = cacheFresh ? cached : '';
|
|
1771
|
+
console.log(`[SSH] getSessionCwd: forced probe failed for ${sessionId} ` +
|
|
1772
|
+
`(allowShellProbe=${allowShellProbe}, staleCache=${cached || '-'}, returning='${forcedFallback}')`);
|
|
1773
|
+
return { cwd: forcedFallback, reliable: false };
|
|
1454
1774
|
}
|
|
1455
1775
|
// 0.5) rz/sz 正在等待传输:直接取 rz 进程自身的 cwd。
|
|
1456
1776
|
// 这是最权威的来源 —— rz 由用户所在的 shell 启动,其 cwd 就是文件要写入的目录,
|
|
@@ -1460,25 +1780,24 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1460
1780
|
if (probe.shellPid)
|
|
1461
1781
|
session.shellPid = probe.shellPid;
|
|
1462
1782
|
const cwd = probe.xferCwd || probe.shellCwd;
|
|
1463
|
-
if (cwd)
|
|
1464
|
-
|
|
1465
|
-
session.cwdAt = Date.now();
|
|
1466
|
-
return cwd;
|
|
1467
|
-
}
|
|
1783
|
+
if (cwd)
|
|
1784
|
+
return commit(cwd, probe.reliable);
|
|
1468
1785
|
}
|
|
1469
1786
|
// 1) 缓存命中(且未过期、未强制刷新)
|
|
1470
|
-
|
|
1471
|
-
|
|
1787
|
+
// 注意:缓存值本身不可信时必须重新探测,不能直接用 ——
|
|
1788
|
+
// 那正是"sudo su 后上次探测只拿到登录 shell 家目录"的情况,
|
|
1789
|
+
// 若在这里直接返回,错误目录会被一直沿用,警告也就永远消不掉。
|
|
1790
|
+
if (cached && cacheFresh && session.cwdReliable !== false) {
|
|
1791
|
+
return { cwd: cached, reliable: true };
|
|
1472
1792
|
}
|
|
1473
1793
|
// 2) 已知 shell PID:直接读 /proc
|
|
1794
|
+
// inferredCwd:进程探测得到的推断值,可信则立即采用,不可信时留作最后兜底
|
|
1795
|
+
let inferredCwd = '';
|
|
1474
1796
|
if (session.type === 'ssh' && session.client) {
|
|
1475
1797
|
if (session.shellPid) {
|
|
1476
1798
|
const cwd = await this.readPidCwd(sessionId, session.shellPid);
|
|
1477
|
-
if (cwd)
|
|
1478
|
-
|
|
1479
|
-
session.cwdAt = Date.now();
|
|
1480
|
-
return cwd;
|
|
1481
|
-
}
|
|
1799
|
+
if (cwd)
|
|
1800
|
+
return commit(cwd, true);
|
|
1482
1801
|
session.shellPid = undefined;
|
|
1483
1802
|
}
|
|
1484
1803
|
// 3) 完整进程探测(默认 shell 优先,rz 场景下优先 rz 进程自身的 cwd)
|
|
@@ -1488,36 +1807,45 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1488
1807
|
const cwd = (opts.preferTransferProcess && probe.xferCwd)
|
|
1489
1808
|
? probe.xferCwd
|
|
1490
1809
|
: (probe.shellCwd || probe.xferCwd);
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1810
|
+
// 只有结果可信才直接采用。不可信(sudo su 后只能读到登录 shell)时必须继续
|
|
1811
|
+
// 走第 4 步向交互式 shell 询问 —— 否则会把登录 shell 的家目录当成当前目录,
|
|
1812
|
+
// 文件就传到错误的位置了(这正是"老是传到 /home/ubuntu"的根因)。
|
|
1813
|
+
if (cwd && probe.reliable)
|
|
1814
|
+
return commit(cwd, true);
|
|
1815
|
+
// 不允许注入式探测(rz 正在等待接收):只能用这个推断值,如实标记不可信,
|
|
1816
|
+
// 由前端提示用户核对或改走 ZMODEM 直发。
|
|
1817
|
+
if (cwd && !allowShellProbe)
|
|
1818
|
+
return commit(cwd, false);
|
|
1819
|
+
inferredCwd = cwd || '';
|
|
1496
1820
|
}
|
|
1497
1821
|
// 4) 注入式探测(会打断前台进程)
|
|
1498
1822
|
if (allowShellProbe) {
|
|
1499
1823
|
let cwd = await this.probeCwdViaShell(sessionId);
|
|
1500
1824
|
if (!cwd)
|
|
1501
1825
|
cwd = await this.probeCwdViaShell(sessionId);
|
|
1502
|
-
if (cwd
|
|
1503
|
-
|
|
1504
|
-
session.cwdAt = Date.now();
|
|
1505
|
-
return cwd;
|
|
1506
|
-
}
|
|
1826
|
+
if (isAbsolutePath(cwd))
|
|
1827
|
+
return commit(cwd, true);
|
|
1507
1828
|
}
|
|
1829
|
+
// 注入式探测也失败:退回进程推断值(有总比没有强,前端会提示用户核对)
|
|
1830
|
+
if (inferredCwd)
|
|
1831
|
+
return commit(inferredCwd, false);
|
|
1508
1832
|
// 全部失败:缓存已过期时返回空(让前端提示手填),避免把陈旧目录当当前目录使用
|
|
1509
1833
|
const fallback = cacheFresh ? cached : '';
|
|
1510
1834
|
console.log(`[SSH] getSessionCwd: probes failed for ${sessionId} ` +
|
|
1511
|
-
`(allowShellProbe=${allowShellProbe},
|
|
1512
|
-
return fallback;
|
|
1835
|
+
`(allowShellProbe=${allowShellProbe}, staleCache=${cached || '-'}, returning='${fallback}')`);
|
|
1836
|
+
return { cwd: fallback, reliable: false };
|
|
1513
1837
|
}
|
|
1514
|
-
/** 向交互式 shell
|
|
1838
|
+
/** 向交互式 shell 注入命令探测 CWD(会先 Ctrl+C 打断前台进程) */
|
|
1515
1839
|
async probeCwdViaShell(sessionId) {
|
|
1840
|
+
const os = await this.resolveSessionOs(sessionId);
|
|
1516
1841
|
const marker = `__AICmd_CWD_${Date.now()}__`;
|
|
1517
1842
|
// 先发送 Ctrl+C 中断可能正在运行的前台进程(如 rz、vim、top 等),
|
|
1518
|
-
//
|
|
1843
|
+
// 否则命令会被前台进程吞掉,shell 不会执行
|
|
1519
1844
|
this.writeData(sessionId, '\x03');
|
|
1520
1845
|
await new Promise(r => setTimeout(r, 200));
|
|
1846
|
+
// Ctrl+U 清空当前输入行:若行内还有残留字符,注入的命令会被拼接成无效命令而拿不到结果
|
|
1847
|
+
this.writeData(sessionId, '\x15');
|
|
1848
|
+
await new Promise(r => setTimeout(r, 150));
|
|
1521
1849
|
// 启动捕获后发送命令(marker 行输出完整就立即返回,通常几百毫秒)
|
|
1522
1850
|
const stopWhen = (text) => {
|
|
1523
1851
|
const i = text.indexOf(marker);
|
|
@@ -1527,21 +1855,24 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1527
1855
|
return after.includes('\n') || after.length > 80;
|
|
1528
1856
|
};
|
|
1529
1857
|
const outputPromise = this.captureOutput(sessionId, 3000, stopWhen);
|
|
1530
|
-
|
|
1858
|
+
// 类 Unix:printf 输出 $PWD(绝对路径以 '/' 开头)
|
|
1859
|
+
// Windows(PowerShell):$PWD 自动变量即当前位置,字符串化为盘符路径(如 C:\Users\me)
|
|
1860
|
+
if (os === 'windows') {
|
|
1861
|
+
this.writeData(sessionId, ` Write-Output "${marker}:$PWD"\r`);
|
|
1862
|
+
}
|
|
1863
|
+
else {
|
|
1864
|
+
this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\r`);
|
|
1865
|
+
}
|
|
1531
1866
|
const output = await outputPromise;
|
|
1532
|
-
|
|
1533
|
-
|
|
1534
|
-
const cleaned = output
|
|
1535
|
-
.replace(/\x1B\][^\x07]*\x07/g, '') // OSC 序列
|
|
1536
|
-
.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '') // CSI 序列
|
|
1537
|
-
.replace(/\x1B[^\x1B]*[a-zA-Z]/g, '') // 其他转义序列
|
|
1538
|
-
.replace(/\r/g, '');
|
|
1867
|
+
// 更彻底的 ANSI 清理:OSC / CSI / 其它有界转义(不得使用会吞正文的贪婪兜底)
|
|
1868
|
+
const cleaned = (0, ansi_1.stripAnsiEscapes)(output).replace(/\r/g, '');
|
|
1539
1869
|
const isCommandEcho = (text) => (text.includes('printf') ||
|
|
1870
|
+
text.includes('Write-Output') ||
|
|
1540
1871
|
text.includes('$PWD') ||
|
|
1541
1872
|
text.includes('%s') ||
|
|
1542
1873
|
text.includes('echo') ||
|
|
1543
1874
|
text.includes('$(pwd)'));
|
|
1544
|
-
const isValidCwd = (cwd) => cwd
|
|
1875
|
+
const isValidCwd = (cwd) => isAbsolutePath(cwd) && !isCommandEcho(cwd);
|
|
1545
1876
|
for (const line of cleaned.split('\n')) {
|
|
1546
1877
|
const trimmed = line.trim();
|
|
1547
1878
|
if (!trimmed || isCommandEcho(trimmed))
|
|
@@ -1597,14 +1928,34 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1597
1928
|
// 解析相对路径:必须通过交互式 shell 获取当前 CWD。
|
|
1598
1929
|
// 注意:不能 fallback 到 SFTP realpath('.'),它通常是登录 home 目录,会导致文件传错位置。
|
|
1599
1930
|
let fullPath = remotePath;
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1605
|
-
|
|
1606
|
-
|
|
1607
|
-
|
|
1931
|
+
const uploadOs = await this.resolveSessionOs(sessionId);
|
|
1932
|
+
if (uploadOs === 'windows') {
|
|
1933
|
+
// Win32-OpenSSH 的 SFTP 子系统以正斜杠 + 盘符形式表示路径(如 C:/Users/name/file),
|
|
1934
|
+
// 与 PowerShell $PWD 返回的反斜杠路径不同,需统一转换为正斜杠。
|
|
1935
|
+
const norm = (p) => p.replace(/\\/g, '/');
|
|
1936
|
+
if (/^[A-Za-z]:[\\/]/.test(remotePath) || remotePath.startsWith('\\\\')) {
|
|
1937
|
+
fullPath = norm(remotePath);
|
|
1938
|
+
}
|
|
1939
|
+
else {
|
|
1940
|
+
console.log(`[SSH] Getting shell CWD (windows)...`);
|
|
1941
|
+
const cwd = await this.getSessionCwd(sessionId);
|
|
1942
|
+
console.log(`[SSH] Shell CWD: '${cwd}'`);
|
|
1943
|
+
if (!isAbsolutePath(cwd)) {
|
|
1944
|
+
throw new Error('无法获取当前终端目录,请确认终端处于正常 Shell 提示符状态后重试');
|
|
1945
|
+
}
|
|
1946
|
+
fullPath = `${norm(cwd).replace(/\/$/, '')}/${norm(remotePath)}`;
|
|
1947
|
+
}
|
|
1948
|
+
}
|
|
1949
|
+
else {
|
|
1950
|
+
if (!remotePath.startsWith('/')) {
|
|
1951
|
+
console.log(`[SSH] Getting shell CWD...`);
|
|
1952
|
+
const cwd = await this.getSessionCwd(sessionId);
|
|
1953
|
+
console.log(`[SSH] Shell CWD: '${cwd}'`);
|
|
1954
|
+
if (!cwd || !cwd.startsWith('/')) {
|
|
1955
|
+
throw new Error('无法获取当前终端目录,请确认终端处于正常 Shell 提示符状态后重试');
|
|
1956
|
+
}
|
|
1957
|
+
fullPath = `${cwd.replace(/\/$/, '')}/${remotePath}`;
|
|
1958
|
+
}
|
|
1608
1959
|
}
|
|
1609
1960
|
console.log(`[SSH] SFTP upload path: ${remotePath} -> ${fullPath}`);
|
|
1610
1961
|
// 使用 Promise + 超时包装(120秒,大文件需要更多时间)
|