@fefeding/aicmd 1.0.23 → 1.0.25
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/dist/public/index.js +321 -144
- package/dist/public/views.css +32 -32
- package/dist/public/views.js +131 -105
- package/dist/public/vue.js +76 -36
- package/dist/server/service/ssh.service.d.ts +70 -15
- package/dist/server/service/ssh.service.d.ts.map +1 -1
- package/dist/server/service/ssh.service.js +455 -121
- package/dist/server/service/ssh.service.js.map +1 -1
- package/dist/server/service/ssh.service.ts +475 -119
- package/electron/main.js +8 -2
- package/electron/preload.js +2 -2
- package/package.json +9 -9
- package/server.js +9 -1
|
@@ -51,6 +51,115 @@ try {
|
|
|
51
51
|
catch (e) {
|
|
52
52
|
console.warn('[SSH] node-pty 不可用,本地 Shell 将使用降级模式(无 PTY)');
|
|
53
53
|
}
|
|
54
|
+
/**
|
|
55
|
+
* CWD 缓存有效期:超过该时长没能再次成功解析目录,缓存即视为不可信。
|
|
56
|
+
* 后台刷新在终端静默 700ms 后就会跑,正常情况下 cwd 时间戳远新于此值。
|
|
57
|
+
*/
|
|
58
|
+
const CWD_CACHE_TTL = 120000;
|
|
59
|
+
/**
|
|
60
|
+
* cd 跟踪值的保护期:这段时间内后台探测结果不会覆盖它(见 refreshCwd)。
|
|
61
|
+
*/
|
|
62
|
+
const CWD_TRACK_GRACE = 5000;
|
|
63
|
+
/**
|
|
64
|
+
* 远端进程探测脚本(通过独立 exec 通道执行,不会向交互式终端写入任何内容)。
|
|
65
|
+
*
|
|
66
|
+
* 输出格式(每行一条,可能 0~2 行):
|
|
67
|
+
* SHELL:<pid>:<cwd> 本会话的交互式 shell
|
|
68
|
+
* XFER:<pid>:<cwd> 本会话正在运行的 rz/sz 进程(rz 的 cwd 即文件将写入的目录)
|
|
69
|
+
*
|
|
70
|
+
* 设计要点:
|
|
71
|
+
* 1) 只认与本 exec 通道同源(祖先链命中同一个 sshd 会话进程)的候选,
|
|
72
|
+
* 避免同一台机器开多个标签页时串台读到别的终端目录;
|
|
73
|
+
* 2) 排除 exec 通道自身及其祖先,避免把 exec 自己的 shell(cwd 恒为 $HOME)
|
|
74
|
+
* 误判成终端 —— 这正是"文件被传到家目录"的根因;
|
|
75
|
+
* 3) 不使用 exec 通道的 pwd 兜底,探测不到就返回空,宁可让用户手填。
|
|
76
|
+
*/
|
|
77
|
+
const SESSION_PROBE_SCRIPT = [
|
|
78
|
+
// 无 /proc 的远端(macOS / BSD):改用 lsof 读取 shell 的 cwd
|
|
79
|
+
'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',
|
|
81
|
+
' d=$(lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | sed -n "s/^n//p" | head -n 1)',
|
|
82
|
+
' case "$d" in /*) echo "SHELL:$pid:$d"; break;; esac',
|
|
83
|
+
' done',
|
|
84
|
+
' exit 0',
|
|
85
|
+
'fi',
|
|
86
|
+
'self=$$',
|
|
87
|
+
'ppid_of() { sed -n "s/^PPid:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
|
|
88
|
+
'name_of() { sed -n "s/^Name:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
|
|
89
|
+
'cwd_of() { readlink "/proc/$1/cwd" 2>/dev/null; }',
|
|
90
|
+
// 收集 exec 通道自身的进程链(self + 祖先),这些必须排除
|
|
91
|
+
'self_chain=" $self "',
|
|
92
|
+
'p=$self',
|
|
93
|
+
'i=0',
|
|
94
|
+
'while [ $i -lt 12 ]; do',
|
|
95
|
+
' p=$(ppid_of "$p")',
|
|
96
|
+
' case "$p" in ""|0|1) break;; esac',
|
|
97
|
+
' self_chain="$self_chain$p "',
|
|
98
|
+
' i=$((i+1))',
|
|
99
|
+
'done',
|
|
100
|
+
// 最近的 sshd 会话祖先:用于把候选限定在本 SSH 会话内
|
|
101
|
+
'sshd_anc=""',
|
|
102
|
+
'for q in $self_chain; do',
|
|
103
|
+
' n=$(name_of "$q")',
|
|
104
|
+
' case "$n" in sshd*) sshd_anc="$q"; break;; esac',
|
|
105
|
+
'done',
|
|
106
|
+
'in_chain() { case "$self_chain" in *" $1 "*) return 0;; esac; return 1; }',
|
|
107
|
+
// 返回值即优先级:2 = 与 sshd 会话同源(最准),1 = 仅 stdin 是 tty(tmux/su 等兜底),0 = 不匹配
|
|
108
|
+
'match_pri() {',
|
|
109
|
+
' pid=$1',
|
|
110
|
+
' if [ -n "$sshd_anc" ]; then',
|
|
111
|
+
' q=$pid; j=0',
|
|
112
|
+
' while [ $j -lt 12 ]; do',
|
|
113
|
+
' q=$(ppid_of "$q")',
|
|
114
|
+
' case "$q" in ""|0|1) break;; esac',
|
|
115
|
+
' [ "$q" = "$sshd_anc" ] && return 2',
|
|
116
|
+
' j=$((j+1))',
|
|
117
|
+
' done',
|
|
118
|
+
' fi',
|
|
119
|
+
' tty=$(readlink "/proc/$pid/fd/0" 2>/dev/null)',
|
|
120
|
+
' case "$tty" in /dev/pts/*|/dev/tty*|/dev/console) return 1;; esac',
|
|
121
|
+
' return 0',
|
|
122
|
+
'}',
|
|
123
|
+
// 进程深度(到 PID 1 的层数):多个候选时取最深的那个。
|
|
124
|
+
// 用户的登录 shell 可能只是外层进程(tmux/byobu/su 后真正交互的是它的子孙),
|
|
125
|
+
// 最内层的 shell 才是用户实际在执行命令的地方。
|
|
126
|
+
'depth_of() {',
|
|
127
|
+
' d=0; q=$1',
|
|
128
|
+
' while [ $d -lt 20 ]; do',
|
|
129
|
+
' pp=$(ppid_of "$q")',
|
|
130
|
+
' case "$pp" in ""|0|1) break;; esac',
|
|
131
|
+
' q=$pp; d=$((d+1))',
|
|
132
|
+
' done',
|
|
133
|
+
' echo $d',
|
|
134
|
+
'}',
|
|
135
|
+
'best_shell=""; best_shell_key=0',
|
|
136
|
+
'best_xfer=""; best_xfer_key=0',
|
|
137
|
+
'for pid in $(ls /proc 2>/dev/null | grep -E "^[0-9]+$"); do',
|
|
138
|
+
' in_chain "$pid" && continue',
|
|
139
|
+
' n=$(name_of "$pid")',
|
|
140
|
+
' case "$n" in',
|
|
141
|
+
' bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox) kind=shell;;',
|
|
142
|
+
' rz|sz|lrz|lsz|lrzsz) kind=xfer;;',
|
|
143
|
+
' *) continue;;',
|
|
144
|
+
' esac',
|
|
145
|
+
' c=$(cwd_of "$pid")',
|
|
146
|
+
' [ -n "$c" ] || continue',
|
|
147
|
+
' match_pri "$pid"',
|
|
148
|
+
' pri=$?',
|
|
149
|
+
' [ "$pri" = 0 ] && continue',
|
|
150
|
+
' dep=$(depth_of "$pid")',
|
|
151
|
+
' key=$((pri * 100 + dep))',
|
|
152
|
+
' echo "CAND:$kind:$pid:$c:$pri:$dep"',
|
|
153
|
+
' if [ "$kind" = shell ]; then',
|
|
154
|
+
' if [ "$key" -gt "$best_shell_key" ]; then best_shell="$pid:$c"; best_shell_key=$key; fi',
|
|
155
|
+
' else',
|
|
156
|
+
' if [ "$key" -gt "$best_xfer_key" ]; then best_xfer="$pid:$c"; best_xfer_key=$key; fi',
|
|
157
|
+
' fi',
|
|
158
|
+
'done',
|
|
159
|
+
'[ -n "$best_shell" ] && echo "SHELL:$best_shell"',
|
|
160
|
+
'[ -n "$best_xfer" ] && echo "XFER:$best_xfer"',
|
|
161
|
+
'exit 0',
|
|
162
|
+
].join('\n');
|
|
54
163
|
/**
|
|
55
164
|
* 终端会话管理服务
|
|
56
165
|
* 支持 SSH 远程连接和本地 Shell
|
|
@@ -287,8 +396,15 @@ class SSHService {
|
|
|
287
396
|
if (this.sessions.has(sessionId))
|
|
288
397
|
this.seedCwd(sessionId);
|
|
289
398
|
}, 1500);
|
|
399
|
+
// 终端输出静默后,在后台通过 exec 通道刷新一次 CWD。
|
|
400
|
+
// 这样即便用户 cd 之后立刻执行 rz,session.cwd 也已是最新值,
|
|
401
|
+
// 无需在 rz 等待接收文件时向交互式 shell 注入命令(那会打断 rz)。
|
|
402
|
+
stream.on('data', () => this.scheduleCwdRefresh(sessionId));
|
|
290
403
|
stream.on('close', () => {
|
|
291
404
|
log(`Shell 流已关闭`);
|
|
405
|
+
const closing = this.sessions.get(sessionId);
|
|
406
|
+
if (closing?.cwdRefreshTimer)
|
|
407
|
+
clearTimeout(closing.cwdRefreshTimer);
|
|
292
408
|
this.sessions.delete(sessionId);
|
|
293
409
|
});
|
|
294
410
|
// Execute startup script if configured (e.g. jump host SSH hop)
|
|
@@ -891,13 +1007,30 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
891
1007
|
/**
|
|
892
1008
|
* 根据用户输入的命令实时更新跟踪的 CWD。
|
|
893
1009
|
* 只处理简单形式的 cd/pushd/popd;遇到复杂结构(变量、管道、subshell 等)则重置为未知,
|
|
894
|
-
*
|
|
1010
|
+
* 由后台刷新 / 上传时的探测兜底。
|
|
1011
|
+
*
|
|
1012
|
+
* 注意:xterm 默认「逐字符」发送按键,writeData 每次收到的往往只是单个字符,
|
|
1013
|
+
* 因此必须先把输入累积成完整命令行、等回车提交后再解析,否则 cd 跟踪形同虚设。
|
|
895
1014
|
*/
|
|
896
1015
|
updateCwdFromInput(session, data) {
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
const
|
|
900
|
-
|
|
1016
|
+
let buf = (session.inputBuffer || '') + data;
|
|
1017
|
+
// Ctrl+U 清空行、Ctrl+C 取消当前输入:丢弃控制符之前的内容
|
|
1018
|
+
const uIdx = buf.lastIndexOf('\x15');
|
|
1019
|
+
if (uIdx >= 0)
|
|
1020
|
+
buf = buf.slice(uIdx + 1);
|
|
1021
|
+
const cIdx = buf.lastIndexOf('\x03');
|
|
1022
|
+
if (cIdx >= 0)
|
|
1023
|
+
buf = buf.slice(cIdx + 1);
|
|
1024
|
+
// 取最后一个换行/回车之前的内容作为「已提交的命令行」
|
|
1025
|
+
const idx = Math.max(buf.lastIndexOf('\r'), buf.lastIndexOf('\n'));
|
|
1026
|
+
if (idx < 0) {
|
|
1027
|
+
// 尚未提交:保留缓冲(限制长度,防止长时间输入导致内存膨胀)
|
|
1028
|
+
session.inputBuffer = buf.length > 4096 ? buf.slice(-2048) : buf;
|
|
1029
|
+
return;
|
|
1030
|
+
}
|
|
1031
|
+
const submitted = buf.slice(0, idx);
|
|
1032
|
+
session.inputBuffer = buf.slice(idx + 1);
|
|
1033
|
+
for (const raw of submitted.split(/[\r\n]+/)) {
|
|
901
1034
|
const line = raw.trim();
|
|
902
1035
|
if (!line)
|
|
903
1036
|
continue;
|
|
@@ -905,50 +1038,226 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
905
1038
|
if (!m)
|
|
906
1039
|
continue;
|
|
907
1040
|
const rest = m[1].trim();
|
|
1041
|
+
// Tab 补全(cd /data/se<Tab>)时输入流里只有补全前的片段,
|
|
1042
|
+
// 上下箭头调出的历史命令同理:输入的都不是完整路径,无法解析 -> 交给探测兜底。
|
|
1043
|
+
if (raw.includes('\t') || raw.includes('\x1b')) {
|
|
1044
|
+
console.log(`[SSH] cwd tracked: '${line}' skipped (completion/history, using probe)`);
|
|
1045
|
+
session.cwd = undefined;
|
|
1046
|
+
session.cwdAt = undefined;
|
|
1047
|
+
continue;
|
|
1048
|
+
}
|
|
908
1049
|
// 含 ; | && || $ ( ) ` ' " 等无法可靠解析的结构 -> 重置为未知
|
|
909
1050
|
if (/[;|&$()`'"]/.test(rest) || rest.includes('~')) {
|
|
910
1051
|
session.cwd = undefined;
|
|
1052
|
+
session.cwdAt = undefined;
|
|
911
1053
|
continue;
|
|
912
1054
|
}
|
|
913
1055
|
const target = rest.trim();
|
|
914
1056
|
if (!target || target === '-') {
|
|
915
1057
|
// cd 无参数回到 home,或 cd - 回到上一个目录:无法可靠跟踪,重置
|
|
916
1058
|
session.cwd = undefined;
|
|
1059
|
+
session.cwdAt = undefined;
|
|
917
1060
|
continue;
|
|
918
1061
|
}
|
|
1062
|
+
let next;
|
|
919
1063
|
if (target.startsWith('/')) {
|
|
920
|
-
|
|
1064
|
+
next = target;
|
|
921
1065
|
}
|
|
922
1066
|
else if (session.cwd && session.cwd.startsWith('/')) {
|
|
923
|
-
|
|
1067
|
+
next = path.posix.resolve(session.cwd, target);
|
|
924
1068
|
}
|
|
925
1069
|
else {
|
|
926
1070
|
// 当前目录未知,无法拼接相对路径,重置为未知
|
|
927
|
-
|
|
1071
|
+
next = undefined;
|
|
928
1072
|
}
|
|
1073
|
+
session.cwd = next;
|
|
1074
|
+
session.cwdAt = next ? Date.now() : undefined;
|
|
1075
|
+
console.log(`[SSH] cwd tracked: '${line}' -> ${next || '(unknown)'}`);
|
|
929
1076
|
}
|
|
930
1077
|
}
|
|
931
|
-
/**
|
|
1078
|
+
/** 连接后后台探测一次会话身份(shell PID + CWD)并缓存(不阻塞,失败忽略) */
|
|
932
1079
|
async seedCwd(sessionId) {
|
|
933
1080
|
const session = this.sessions.get(sessionId);
|
|
934
|
-
if (!session
|
|
1081
|
+
if (!session)
|
|
1082
|
+
return;
|
|
1083
|
+
// 只探测 SSH 会话;本地会话的 cwd 由 cd 跟踪维护
|
|
1084
|
+
if (session.type !== 'ssh' || !session.client)
|
|
1085
|
+
return;
|
|
1086
|
+
if (session.shellPid && session.cwd && session.cwd.startsWith('/'))
|
|
935
1087
|
return;
|
|
1088
|
+
try {
|
|
1089
|
+
await this.refreshCwd(sessionId);
|
|
1090
|
+
if (session.cwd)
|
|
1091
|
+
console.log(`[SSH] seeded cwd for ${sessionId}: ${session.cwd} (pid=${session.shellPid || '-'})`);
|
|
1092
|
+
}
|
|
1093
|
+
catch {
|
|
1094
|
+
// 忽略,上传时再探测
|
|
1095
|
+
}
|
|
1096
|
+
}
|
|
1097
|
+
/**
|
|
1098
|
+
* 调度一次后台 CWD 刷新(终端输出静默后执行)。
|
|
1099
|
+
*
|
|
1100
|
+
* 目的:让 rz/上传触发时 session.cwd 已经是最新值,从而完全避免在 rz 运行期间
|
|
1101
|
+
* 向交互式 shell 注入命令(那会打断 rz,且输入会被 rz 吞掉导致探测失败)。
|
|
1102
|
+
* 刷新走独立 exec 通道,对终端零影响。
|
|
1103
|
+
*/
|
|
1104
|
+
scheduleCwdRefresh(sessionId) {
|
|
1105
|
+
const session = this.sessions.get(sessionId);
|
|
1106
|
+
if (!session || session.type !== 'ssh' || !session.client)
|
|
1107
|
+
return;
|
|
1108
|
+
if (session.cwdRefreshTimer)
|
|
1109
|
+
clearTimeout(session.cwdRefreshTimer);
|
|
1110
|
+
session.cwdRefreshTimer = setTimeout(() => {
|
|
1111
|
+
session.cwdRefreshTimer = undefined;
|
|
1112
|
+
// 限流:距离上次刷新不足 1.5s 则跳过,避免高频 exec
|
|
1113
|
+
if (session.lastCwdRefreshAt && Date.now() - session.lastCwdRefreshAt < 1500)
|
|
1114
|
+
return;
|
|
1115
|
+
this.refreshCwd(sessionId).catch(() => { });
|
|
1116
|
+
}, 700);
|
|
1117
|
+
}
|
|
1118
|
+
/**
|
|
1119
|
+
* 刷新并缓存会话的当前工作目录(走 exec 通道,不干扰交互式终端)。
|
|
1120
|
+
* 优先用已缓存的 shell PID 直接读 /proc/<pid>/cwd(一次 readlink,极轻量),
|
|
1121
|
+
* 否则回退到完整进程探测。失败时保留旧值不清除。
|
|
1122
|
+
*/
|
|
1123
|
+
async refreshCwd(sessionId) {
|
|
1124
|
+
const session = this.sessions.get(sessionId);
|
|
1125
|
+
if (!session || session.type !== 'ssh' || !session.client)
|
|
1126
|
+
return session?.cwd || '';
|
|
1127
|
+
if (session.cwdRefreshing)
|
|
1128
|
+
return session.cwd || '';
|
|
1129
|
+
session.cwdRefreshing = true;
|
|
936
1130
|
try {
|
|
937
1131
|
let cwd = '';
|
|
938
|
-
if (session.
|
|
939
|
-
cwd = await this.
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
if (!cwd)
|
|
943
|
-
cwd = await this.probeCwdViaShell(sessionId);
|
|
944
|
-
if (cwd && cwd.startsWith('/') && !session.cwd) {
|
|
945
|
-
session.cwd = cwd;
|
|
946
|
-
console.log(`[SSH] seeded cwd for ${sessionId}: ${cwd}`);
|
|
1132
|
+
if (session.shellPid) {
|
|
1133
|
+
cwd = await this.readPidCwd(sessionId, session.shellPid);
|
|
1134
|
+
if (!cwd)
|
|
1135
|
+
session.shellPid = undefined; // 进程已退出或 PID 失效
|
|
947
1136
|
}
|
|
1137
|
+
if (!cwd) {
|
|
1138
|
+
const probe = await this.probeSessionProcess(sessionId);
|
|
1139
|
+
if (probe.shellPid)
|
|
1140
|
+
session.shellPid = probe.shellPid;
|
|
1141
|
+
cwd = probe.shellCwd;
|
|
1142
|
+
}
|
|
1143
|
+
if (cwd && cwd.startsWith('/')) {
|
|
1144
|
+
// 用户刚刚敲过 cd(cd 跟踪值很新鲜)时,不覆盖它:
|
|
1145
|
+
// cd 是用户的显式意图,比推断出的进程目录更可信,
|
|
1146
|
+
// 也能避免探测到错误进程时把正确目录改回成家目录。
|
|
1147
|
+
const trackedRecently = !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_TRACK_GRACE;
|
|
1148
|
+
if (trackedRecently && session.cwd !== cwd) {
|
|
1149
|
+
console.log(`[SSH] refreshCwd: keep tracked cwd '${session.cwd}' (probe said '${cwd}')`);
|
|
1150
|
+
}
|
|
1151
|
+
else {
|
|
1152
|
+
session.cwd = cwd;
|
|
1153
|
+
session.cwdAt = Date.now();
|
|
1154
|
+
}
|
|
1155
|
+
}
|
|
1156
|
+
return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
|
|
948
1157
|
}
|
|
949
1158
|
catch {
|
|
950
|
-
|
|
1159
|
+
return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
|
|
1160
|
+
}
|
|
1161
|
+
finally {
|
|
1162
|
+
session.cwdRefreshing = false;
|
|
1163
|
+
session.lastCwdRefreshAt = Date.now();
|
|
1164
|
+
}
|
|
1165
|
+
}
|
|
1166
|
+
/**
|
|
1167
|
+
* 通过 exec 通道读取指定 PID 的工作目录(远端 Linux /proc)。
|
|
1168
|
+
* 同时校验进程名,避免 PID 复用导致读到无关进程的目录。
|
|
1169
|
+
*/
|
|
1170
|
+
async readPidCwd(sessionId, pid) {
|
|
1171
|
+
if (!Number.isInteger(pid) || pid <= 0)
|
|
1172
|
+
return '';
|
|
1173
|
+
const out = await this.execRemote(sessionId, `cat /proc/${pid}/comm 2>/dev/null; readlink /proc/${pid}/cwd 2>/dev/null`, 4000);
|
|
1174
|
+
const lines = out.split('\n').map(l => l.trim()).filter(Boolean);
|
|
1175
|
+
if (lines.length < 2)
|
|
1176
|
+
return '';
|
|
1177
|
+
const comm = lines[0];
|
|
1178
|
+
const cwd = lines[lines.length - 1];
|
|
1179
|
+
if (!cwd.startsWith('/'))
|
|
1180
|
+
return '';
|
|
1181
|
+
if (!/^(bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox|rz|sz|lrz|lsz)$/.test(comm))
|
|
1182
|
+
return '';
|
|
1183
|
+
return cwd;
|
|
1184
|
+
}
|
|
1185
|
+
/**
|
|
1186
|
+
* 探测本会话的交互式 shell 与正在运行的 rz/sz 进程。
|
|
1187
|
+
* 走独立 exec 通道,不向交互式终端写入任何内容。
|
|
1188
|
+
*/
|
|
1189
|
+
async probeSessionProcess(sessionId) {
|
|
1190
|
+
const result = {
|
|
1191
|
+
shellPid: undefined,
|
|
1192
|
+
shellCwd: '',
|
|
1193
|
+
xferCwd: '',
|
|
1194
|
+
candidates: [],
|
|
1195
|
+
};
|
|
1196
|
+
const out = await this.execRemote(sessionId, SESSION_PROBE_SCRIPT, 5000);
|
|
1197
|
+
for (const raw of out.split('\n')) {
|
|
1198
|
+
const line = raw.trim();
|
|
1199
|
+
if (!line)
|
|
1200
|
+
continue;
|
|
1201
|
+
if (line.startsWith('CAND:')) {
|
|
1202
|
+
// 诊断用:列出全部候选进程(kind:pid:cwd:pri:depth)
|
|
1203
|
+
result.candidates.push(line.substring(5));
|
|
1204
|
+
continue;
|
|
1205
|
+
}
|
|
1206
|
+
const m = line.match(/^(SHELL|XFER):(\d+):(\/.*)$/);
|
|
1207
|
+
if (!m)
|
|
1208
|
+
continue;
|
|
1209
|
+
const pid = Number(m[2]);
|
|
1210
|
+
const cwd = m[3].trim();
|
|
1211
|
+
if (m[1] === 'SHELL') {
|
|
1212
|
+
result.shellPid = pid;
|
|
1213
|
+
result.shellCwd = cwd;
|
|
1214
|
+
}
|
|
1215
|
+
else {
|
|
1216
|
+
result.xferCwd = cwd;
|
|
1217
|
+
}
|
|
951
1218
|
}
|
|
1219
|
+
console.log(`[SSH] probeSessionProcess: shell=${result.shellPid || '-'}:${result.shellCwd || '-'} ` +
|
|
1220
|
+
`xfer=${result.xferCwd || '-'} cands=[${result.candidates.join(' | ')}]`);
|
|
1221
|
+
return result;
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* 在远端执行一条命令(独立 exec 通道),返回 stdout。
|
|
1225
|
+
* 不会向交互式终端写入任何内容,因此不会打断 rz/vim 等前台进程。
|
|
1226
|
+
*/
|
|
1227
|
+
execRemote(sessionId, command, timeoutMs = 5000) {
|
|
1228
|
+
return new Promise((resolve) => {
|
|
1229
|
+
const session = this.sessions.get(sessionId);
|
|
1230
|
+
if (!session?.client) {
|
|
1231
|
+
resolve('');
|
|
1232
|
+
return;
|
|
1233
|
+
}
|
|
1234
|
+
let stdout = '';
|
|
1235
|
+
let settled = false;
|
|
1236
|
+
const finish = () => {
|
|
1237
|
+
if (settled)
|
|
1238
|
+
return;
|
|
1239
|
+
settled = true;
|
|
1240
|
+
clearTimeout(timer);
|
|
1241
|
+
resolve(stdout);
|
|
1242
|
+
};
|
|
1243
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
1244
|
+
try {
|
|
1245
|
+
session.client.exec(command, (err, stream) => {
|
|
1246
|
+
if (err) {
|
|
1247
|
+
console.log('[SSH] execRemote error:', err.message);
|
|
1248
|
+
finish();
|
|
1249
|
+
return;
|
|
1250
|
+
}
|
|
1251
|
+
stream.on('data', (data) => { stdout += data.toString('utf-8'); });
|
|
1252
|
+
stream.stderr.on('data', () => { });
|
|
1253
|
+
stream.on('close', finish);
|
|
1254
|
+
stream.on('error', finish);
|
|
1255
|
+
});
|
|
1256
|
+
}
|
|
1257
|
+
catch (e) {
|
|
1258
|
+
finish();
|
|
1259
|
+
}
|
|
1260
|
+
});
|
|
952
1261
|
}
|
|
953
1262
|
/**
|
|
954
1263
|
* 注册输出监听器(用于 Agent 捕获终端输出)
|
|
@@ -983,35 +1292,46 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
983
1292
|
* @param timeoutMs 等待时间(毫秒),默认 2000
|
|
984
1293
|
* @returns 捕获的输出文本(已去除 ANSI 转义序列)
|
|
985
1294
|
*/
|
|
986
|
-
captureOutput(sessionId, timeoutMs = 2000) {
|
|
1295
|
+
captureOutput(sessionId, timeoutMs = 2000, stopWhen) {
|
|
987
1296
|
return new Promise((resolve) => {
|
|
988
1297
|
let output = '';
|
|
1298
|
+
let settled = false;
|
|
989
1299
|
// 直接在 SSH stream 上监听(避免 notifyOutput 重复捕获导致数据翻倍)
|
|
990
1300
|
const session = this.sessions.get(sessionId);
|
|
991
1301
|
let streamHandler = null;
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
else {
|
|
999
|
-
// 本地 shell fallback:通过 notifyOutput 机制
|
|
1000
|
-
const listener = (data) => { output += data; };
|
|
1001
|
-
this.addOutputListener(sessionId, listener);
|
|
1002
|
-
}
|
|
1003
|
-
setTimeout(() => {
|
|
1302
|
+
let listener = null;
|
|
1303
|
+
const finish = () => {
|
|
1304
|
+
if (settled)
|
|
1305
|
+
return;
|
|
1306
|
+
settled = true;
|
|
1307
|
+
clearTimeout(timer);
|
|
1004
1308
|
if (streamHandler && session?.stream) {
|
|
1005
1309
|
session.stream.removeListener('data', streamHandler);
|
|
1006
1310
|
}
|
|
1007
|
-
else {
|
|
1311
|
+
else if (listener) {
|
|
1008
1312
|
this.removeOutputListener(sessionId);
|
|
1009
1313
|
}
|
|
1010
1314
|
resolve(output
|
|
1011
1315
|
.replace(/\x1B\][^\x07]*\x07/g, '')
|
|
1012
1316
|
.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '')
|
|
1013
1317
|
.replace(/\x1B[^\x1B]*[a-zA-Z]/g, ''));
|
|
1014
|
-
}
|
|
1318
|
+
};
|
|
1319
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
1320
|
+
const onData = (text) => {
|
|
1321
|
+
output += text;
|
|
1322
|
+
// 拿到目标内容就立刻返回,不必每次都等满 timeout(探测 CWD 时可省下数秒)
|
|
1323
|
+
if (stopWhen && stopWhen(output))
|
|
1324
|
+
finish();
|
|
1325
|
+
};
|
|
1326
|
+
if (session?.stream) {
|
|
1327
|
+
streamHandler = (chunk) => onData(chunk.toString('utf-8'));
|
|
1328
|
+
session.stream.on('data', streamHandler);
|
|
1329
|
+
}
|
|
1330
|
+
else {
|
|
1331
|
+
// 本地 shell fallback:通过 notifyOutput 机制
|
|
1332
|
+
listener = onData;
|
|
1333
|
+
this.addOutputListener(sessionId, listener);
|
|
1334
|
+
}
|
|
1015
1335
|
});
|
|
1016
1336
|
}
|
|
1017
1337
|
/**
|
|
@@ -1041,6 +1361,10 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1041
1361
|
closeSession(sessionId) {
|
|
1042
1362
|
const session = this.sessions.get(sessionId);
|
|
1043
1363
|
if (session) {
|
|
1364
|
+
if (session.cwdRefreshTimer) {
|
|
1365
|
+
clearTimeout(session.cwdRefreshTimer);
|
|
1366
|
+
session.cwdRefreshTimer = undefined;
|
|
1367
|
+
}
|
|
1044
1368
|
try {
|
|
1045
1369
|
if (session.pty) {
|
|
1046
1370
|
session.pty.kill();
|
|
@@ -1069,38 +1393,102 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1069
1393
|
}
|
|
1070
1394
|
/**
|
|
1071
1395
|
* 获取 SSH 会话的当前工作目录。
|
|
1072
|
-
*
|
|
1073
|
-
* 1)
|
|
1074
|
-
* 2)
|
|
1075
|
-
* 3)
|
|
1396
|
+
* 优先级(前 3 步都走独立 exec 通道,对交互式终端零影响):
|
|
1397
|
+
* 1) 缓存的 session.cwd —— 由 cd 跟踪 + 后台刷新共同维护,绝大多数情况直接命中
|
|
1398
|
+
* 2) 缓存的 shell PID → readlink /proc/<pid>/cwd(一次调用,最准)
|
|
1399
|
+
* 3) 完整进程探测(shell + rz/sz):rz 运行时的 cwd 就是文件将要写入的目录
|
|
1400
|
+
* 4) 向交互式 shell 注入 printf $PWD —— 会 Ctrl+C 打断前台进程,
|
|
1401
|
+
* 仅在 allowShellProbe 为真(即确认不在 rz/文件上传过程中)时使用
|
|
1402
|
+
*
|
|
1403
|
+
* @param opts.allowShellProbe 是否允许注入式探测。rz 正在等待接收文件时必须传 false,
|
|
1404
|
+
* 否则 Ctrl+C 会打断 rz,且注入的命令会被 rz 当作数据吞掉。
|
|
1405
|
+
* @param opts.preferTransferProcess 优先采用 rz/sz 进程的 cwd(rz 写文件的目录就是它自己的
|
|
1406
|
+
* cwd,比推断出来的 shell 目录更权威)。
|
|
1407
|
+
* @param opts.force 强制重新探测,忽略缓存(用户手动点"重新检测"、上传前兜底时使用)。
|
|
1408
|
+
*
|
|
1409
|
+
* 缓存有效期 CWD_CACHE_TTL:超过该时间没能再次成功解析目录,就认为缓存不可信
|
|
1410
|
+
* (例如后台 exec 探测一直失败),此时宁可返回空让前端提示手填,
|
|
1411
|
+
* 也不能把陈旧的(很可能是家目录的)路径当成当前目录 —— 那会导致文件传错位置。
|
|
1076
1412
|
*/
|
|
1077
|
-
async getSessionCwd(sessionId) {
|
|
1413
|
+
async getSessionCwd(sessionId, opts = {}) {
|
|
1414
|
+
const allowShellProbe = opts.allowShellProbe !== false;
|
|
1078
1415
|
const session = this.sessions.get(sessionId);
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1416
|
+
if (!session)
|
|
1417
|
+
return '';
|
|
1418
|
+
const cached = session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
|
|
1419
|
+
const cacheFresh = !!cached && !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_CACHE_TTL;
|
|
1420
|
+
// 0) 强制刷新 + 允许注入探测:直接向 shell 询问,这是最权威的手段。
|
|
1421
|
+
// 调用方(上传前兜底、用户点"重新检测")已确保终端处于可打断状态,
|
|
1422
|
+
// 否则只靠 exec 探测,一旦 shellPid 指错进程就会一直拿到错误的目录。
|
|
1423
|
+
if (opts.force && allowShellProbe) {
|
|
1424
|
+
let probed = await this.probeCwdViaShell(sessionId);
|
|
1425
|
+
if (!probed)
|
|
1426
|
+
probed = await this.probeCwdViaShell(sessionId);
|
|
1427
|
+
if (probed && probed.startsWith('/')) {
|
|
1428
|
+
session.cwd = probed;
|
|
1429
|
+
session.cwdAt = Date.now();
|
|
1430
|
+
console.log(`[SSH] getSessionCwd (forced shell probe): '${probed}'`);
|
|
1431
|
+
return probed;
|
|
1432
|
+
}
|
|
1082
1433
|
}
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1434
|
+
// 0.5) rz/sz 正在等待传输:直接取 rz 进程自身的 cwd。
|
|
1435
|
+
// 这是最权威的来源 —— rz 由用户所在的 shell 启动,其 cwd 就是文件要写入的目录,
|
|
1436
|
+
// 不会受"登录 shell 与实际交互 shell 不是同一个进程"的影响。
|
|
1437
|
+
if (opts.preferTransferProcess && session.type === 'ssh' && session.client) {
|
|
1438
|
+
const probe = await this.probeSessionProcess(sessionId);
|
|
1439
|
+
if (probe.shellPid)
|
|
1440
|
+
session.shellPid = probe.shellPid;
|
|
1441
|
+
const cwd = probe.xferCwd || probe.shellCwd;
|
|
1442
|
+
if (cwd) {
|
|
1443
|
+
session.cwd = cwd;
|
|
1444
|
+
session.cwdAt = Date.now();
|
|
1445
|
+
return cwd;
|
|
1087
1446
|
}
|
|
1088
|
-
|
|
1089
|
-
|
|
1447
|
+
}
|
|
1448
|
+
// 1) 缓存命中(且未过期、未强制刷新)
|
|
1449
|
+
if (cached && cacheFresh && !opts.force) {
|
|
1450
|
+
return cached;
|
|
1451
|
+
}
|
|
1452
|
+
// 2) 已知 shell PID:直接读 /proc
|
|
1453
|
+
if (session.type === 'ssh' && session.client) {
|
|
1454
|
+
if (session.shellPid) {
|
|
1455
|
+
const cwd = await this.readPidCwd(sessionId, session.shellPid);
|
|
1456
|
+
if (cwd) {
|
|
1457
|
+
session.cwd = cwd;
|
|
1458
|
+
session.cwdAt = Date.now();
|
|
1459
|
+
return cwd;
|
|
1460
|
+
}
|
|
1461
|
+
session.shellPid = undefined;
|
|
1462
|
+
}
|
|
1463
|
+
// 3) 完整进程探测(默认 shell 优先,rz 场景下优先 rz 进程自身的 cwd)
|
|
1464
|
+
const probe = await this.probeSessionProcess(sessionId);
|
|
1465
|
+
if (probe.shellPid)
|
|
1466
|
+
session.shellPid = probe.shellPid;
|
|
1467
|
+
const cwd = (opts.preferTransferProcess && probe.xferCwd)
|
|
1468
|
+
? probe.xferCwd
|
|
1469
|
+
: (probe.shellCwd || probe.xferCwd);
|
|
1470
|
+
if (cwd) {
|
|
1471
|
+
session.cwd = cwd;
|
|
1472
|
+
session.cwdAt = Date.now();
|
|
1473
|
+
return cwd;
|
|
1090
1474
|
}
|
|
1091
1475
|
}
|
|
1092
|
-
|
|
1093
|
-
|
|
1476
|
+
// 4) 注入式探测(会打断前台进程)
|
|
1477
|
+
if (allowShellProbe) {
|
|
1478
|
+
let cwd = await this.probeCwdViaShell(sessionId);
|
|
1094
1479
|
if (!cwd)
|
|
1095
1480
|
cwd = await this.probeCwdViaShell(sessionId);
|
|
1481
|
+
if (cwd && cwd.startsWith('/')) {
|
|
1482
|
+
session.cwd = cwd;
|
|
1483
|
+
session.cwdAt = Date.now();
|
|
1484
|
+
return cwd;
|
|
1485
|
+
}
|
|
1096
1486
|
}
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
console.log(`[SSH] getSessionCwd: all probes failed for ${sessionId}`);
|
|
1103
|
-
return '';
|
|
1487
|
+
// 全部失败:缓存已过期时返回空(让前端提示手填),避免把陈旧目录当当前目录使用
|
|
1488
|
+
const fallback = cacheFresh ? cached : '';
|
|
1489
|
+
console.log(`[SSH] getSessionCwd: probes failed for ${sessionId} ` +
|
|
1490
|
+
`(allowShellProbe=${allowShellProbe}, force=${!!opts.force}, staleCache=${cached || '-'}, returning='${fallback || ''}')`);
|
|
1491
|
+
return fallback;
|
|
1104
1492
|
}
|
|
1105
1493
|
/** 向交互式 shell 注入 printf $PWD 探测 CWD(会先 Ctrl+C 打断前台进程) */
|
|
1106
1494
|
async probeCwdViaShell(sessionId) {
|
|
@@ -1109,8 +1497,15 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1109
1497
|
// 否则 printf 命令会被前台进程吞掉,shell 不会执行
|
|
1110
1498
|
this.writeData(sessionId, '\x03');
|
|
1111
1499
|
await new Promise(r => setTimeout(r, 200));
|
|
1112
|
-
//
|
|
1113
|
-
const
|
|
1500
|
+
// 启动捕获后发送命令(marker 行输出完整就立即返回,通常几百毫秒)
|
|
1501
|
+
const stopWhen = (text) => {
|
|
1502
|
+
const i = text.indexOf(marker);
|
|
1503
|
+
if (i < 0)
|
|
1504
|
+
return false;
|
|
1505
|
+
const after = text.slice(i + marker.length);
|
|
1506
|
+
return after.includes('\n') || after.length > 80;
|
|
1507
|
+
};
|
|
1508
|
+
const outputPromise = this.captureOutput(sessionId, 3000, stopWhen);
|
|
1114
1509
|
this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\r`);
|
|
1115
1510
|
const output = await outputPromise;
|
|
1116
1511
|
console.log(`[SSH] probeCwdViaShell: raw output: ${JSON.stringify(output.substring(0, 500))}`);
|
|
@@ -1151,67 +1546,6 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1151
1546
|
console.log(`[SSH] probeCwdViaShell: no marker found: ${JSON.stringify(cleaned.substring(0, 500))}`);
|
|
1152
1547
|
return '';
|
|
1153
1548
|
}
|
|
1154
|
-
/**
|
|
1155
|
-
* 通过 SSH exec 独立通道获取交互式 shell 的工作目录
|
|
1156
|
-
* 不依赖交互式 shell 状态,即使 shell 卡在 rz/vim/异常状态也能工作
|
|
1157
|
-
*/
|
|
1158
|
-
getSessionCwdViaExec(sessionId) {
|
|
1159
|
-
return new Promise((resolve) => {
|
|
1160
|
-
const session = this.sessions.get(sessionId);
|
|
1161
|
-
if (!session?.client) {
|
|
1162
|
-
resolve('');
|
|
1163
|
-
return;
|
|
1164
|
-
}
|
|
1165
|
-
// 通过 /proc 查找交互式 shell 进程的 CWD。
|
|
1166
|
-
// 关键:必须只匹配「stdin 是 tty(/dev/pts)」的 shell,排除本 exec 通道自己启动的
|
|
1167
|
-
// shell(它的 stdin 是管道、CWD 是 $HOME),否则会错误地返回家目录。
|
|
1168
|
-
const cmd = [
|
|
1169
|
-
'for pid in $(ls /proc 2>/dev/null | grep "^[0-9]*$"); do',
|
|
1170
|
-
' exe=$(readlink "/proc/$pid/exe" 2>/dev/null)',
|
|
1171
|
-
' case "$exe" in',
|
|
1172
|
-
' *bash*|*sh*|*zsh*|*dash*|*fish*|*tcsh*|*csh*)',
|
|
1173
|
-
' tty=$(readlink "/proc/$pid/fd/0" 2>/dev/null)',
|
|
1174
|
-
' case "$tty" in',
|
|
1175
|
-
' /dev/pts/*|/dev/tty*|/dev/console)',
|
|
1176
|
-
' cwd=$(readlink "/proc/$pid/cwd" 2>/dev/null)',
|
|
1177
|
-
' if [ -n "$cwd" ]; then echo "$cwd"; exit 0; fi',
|
|
1178
|
-
' ;;',
|
|
1179
|
-
' esac',
|
|
1180
|
-
' ;;',
|
|
1181
|
-
' esac',
|
|
1182
|
-
'done',
|
|
1183
|
-
'pwd'
|
|
1184
|
-
].join('\n');
|
|
1185
|
-
let stdout = '';
|
|
1186
|
-
let stderr = '';
|
|
1187
|
-
const timeout = setTimeout(() => {
|
|
1188
|
-
console.log('[SSH] getSessionCwdViaExec: timeout');
|
|
1189
|
-
resolve('');
|
|
1190
|
-
}, 5000);
|
|
1191
|
-
session.client.exec(cmd, (err, stream) => {
|
|
1192
|
-
if (err) {
|
|
1193
|
-
clearTimeout(timeout);
|
|
1194
|
-
console.log('[SSH] getSessionCwdViaExec error:', err.message);
|
|
1195
|
-
resolve('');
|
|
1196
|
-
return;
|
|
1197
|
-
}
|
|
1198
|
-
stream.on('data', (data) => { stdout += data.toString('utf-8'); });
|
|
1199
|
-
stream.stderr.on('data', (data) => { stderr += data.toString('utf-8'); });
|
|
1200
|
-
stream.on('close', () => {
|
|
1201
|
-
clearTimeout(timeout);
|
|
1202
|
-
const cwd = stdout.trim().split('\n')[0].trim();
|
|
1203
|
-
if (cwd && cwd.startsWith('/')) {
|
|
1204
|
-
console.log(`[SSH] getSessionCwdViaExec: '${cwd}'`);
|
|
1205
|
-
resolve(cwd);
|
|
1206
|
-
}
|
|
1207
|
-
else {
|
|
1208
|
-
console.log(`[SSH] getSessionCwdViaExec: no valid cwd, stdout: ${JSON.stringify(stdout.substring(0, 200))}, stderr: ${JSON.stringify(stderr.substring(0, 200))}`);
|
|
1209
|
-
resolve('');
|
|
1210
|
-
}
|
|
1211
|
-
});
|
|
1212
|
-
});
|
|
1213
|
-
});
|
|
1214
|
-
}
|
|
1215
1549
|
/**
|
|
1216
1550
|
* 通过 SFTP 上传文件到远程服务器(绕过 PTY,速度快)
|
|
1217
1551
|
* @param sessionId 会话 ID
|