@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
|
@@ -33,10 +33,134 @@ interface TerminalSession {
|
|
|
33
33
|
// 本地 shell 降级: child_process
|
|
34
34
|
childProcess?: ChildProcess;
|
|
35
35
|
createdAt: Date;
|
|
36
|
-
/** 实时跟踪的当前工作目录(通过解析 cd
|
|
36
|
+
/** 实时跟踪的当前工作目录(通过解析 cd 命令维护 + 后台 /proc 刷新) */
|
|
37
37
|
cwd?: string;
|
|
38
|
+
/** cwd 最后一次被成功解析的时间戳(用于判断缓存是否过期) */
|
|
39
|
+
cwdAt?: number;
|
|
40
|
+
/** 未提交的输入行缓冲(xterm 逐字符发送,需累积成完整命令行才能解析 cd) */
|
|
41
|
+
inputBuffer?: string;
|
|
42
|
+
/** 远端交互式 shell 的 PID(用于 /proc/<pid>/cwd 精确读取当前目录,不影响终端) */
|
|
43
|
+
shellPid?: number;
|
|
44
|
+
/** 后台刷新 CWD 的防抖定时器 */
|
|
45
|
+
cwdRefreshTimer?: NodeJS.Timeout;
|
|
46
|
+
/** 上次后台刷新 CWD 的时间戳 */
|
|
47
|
+
lastCwdRefreshAt?: number;
|
|
48
|
+
/** 是否正在刷新 CWD(避免并发 exec) */
|
|
49
|
+
cwdRefreshing?: boolean;
|
|
38
50
|
}
|
|
39
51
|
|
|
52
|
+
/**
|
|
53
|
+
* CWD 缓存有效期:超过该时长没能再次成功解析目录,缓存即视为不可信。
|
|
54
|
+
* 后台刷新在终端静默 700ms 后就会跑,正常情况下 cwd 时间戳远新于此值。
|
|
55
|
+
*/
|
|
56
|
+
const CWD_CACHE_TTL = 120000;
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* cd 跟踪值的保护期:这段时间内后台探测结果不会覆盖它(见 refreshCwd)。
|
|
60
|
+
*/
|
|
61
|
+
const CWD_TRACK_GRACE = 5000;
|
|
62
|
+
|
|
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');
|
|
163
|
+
|
|
40
164
|
/** Session 元数据(用于在 server 端持久化 tab 信息) */
|
|
41
165
|
interface SessionMetadata {
|
|
42
166
|
sessionId: string;
|
|
@@ -345,8 +469,15 @@ export class SSHService {
|
|
|
345
469
|
if (this.sessions.has(sessionId)) this.seedCwd(sessionId);
|
|
346
470
|
}, 1500);
|
|
347
471
|
|
|
472
|
+
// 终端输出静默后,在后台通过 exec 通道刷新一次 CWD。
|
|
473
|
+
// 这样即便用户 cd 之后立刻执行 rz,session.cwd 也已是最新值,
|
|
474
|
+
// 无需在 rz 等待接收文件时向交互式 shell 注入命令(那会打断 rz)。
|
|
475
|
+
stream.on('data', () => this.scheduleCwdRefresh(sessionId));
|
|
476
|
+
|
|
348
477
|
stream.on('close', () => {
|
|
349
478
|
log(`Shell 流已关闭`);
|
|
479
|
+
const closing = this.sessions.get(sessionId);
|
|
480
|
+
if (closing?.cwdRefreshTimer) clearTimeout(closing.cwdRefreshTimer);
|
|
350
481
|
this.sessions.delete(sessionId);
|
|
351
482
|
});
|
|
352
483
|
|
|
@@ -965,55 +1096,244 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
965
1096
|
/**
|
|
966
1097
|
* 根据用户输入的命令实时更新跟踪的 CWD。
|
|
967
1098
|
* 只处理简单形式的 cd/pushd/popd;遇到复杂结构(变量、管道、subshell 等)则重置为未知,
|
|
968
|
-
*
|
|
1099
|
+
* 由后台刷新 / 上传时的探测兜底。
|
|
1100
|
+
*
|
|
1101
|
+
* 注意:xterm 默认「逐字符」发送按键,writeData 每次收到的往往只是单个字符,
|
|
1102
|
+
* 因此必须先把输入累积成完整命令行、等回车提交后再解析,否则 cd 跟踪形同虚设。
|
|
969
1103
|
*/
|
|
970
1104
|
private updateCwdFromInput(session: TerminalSession, data: string): void {
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
1105
|
+
let buf = (session.inputBuffer || '') + data;
|
|
1106
|
+
|
|
1107
|
+
// Ctrl+U 清空行、Ctrl+C 取消当前输入:丢弃控制符之前的内容
|
|
1108
|
+
const uIdx = buf.lastIndexOf('\x15');
|
|
1109
|
+
if (uIdx >= 0) buf = buf.slice(uIdx + 1);
|
|
1110
|
+
const cIdx = buf.lastIndexOf('\x03');
|
|
1111
|
+
if (cIdx >= 0) buf = buf.slice(cIdx + 1);
|
|
1112
|
+
|
|
1113
|
+
// 取最后一个换行/回车之前的内容作为「已提交的命令行」
|
|
1114
|
+
const idx = Math.max(buf.lastIndexOf('\r'), buf.lastIndexOf('\n'));
|
|
1115
|
+
if (idx < 0) {
|
|
1116
|
+
// 尚未提交:保留缓冲(限制长度,防止长时间输入导致内存膨胀)
|
|
1117
|
+
session.inputBuffer = buf.length > 4096 ? buf.slice(-2048) : buf;
|
|
1118
|
+
return;
|
|
1119
|
+
}
|
|
1120
|
+
const submitted = buf.slice(0, idx);
|
|
1121
|
+
session.inputBuffer = buf.slice(idx + 1);
|
|
1122
|
+
|
|
1123
|
+
for (const raw of submitted.split(/[\r\n]+/)) {
|
|
974
1124
|
const line = raw.trim();
|
|
975
1125
|
if (!line) continue;
|
|
976
1126
|
const m = line.match(/^(?:cd|pushd|popd)\b(.*)$/);
|
|
977
1127
|
if (!m) continue;
|
|
978
1128
|
const rest = m[1].trim();
|
|
1129
|
+
// Tab 补全(cd /data/se<Tab>)时输入流里只有补全前的片段,
|
|
1130
|
+
// 上下箭头调出的历史命令同理:输入的都不是完整路径,无法解析 -> 交给探测兜底。
|
|
1131
|
+
if (raw.includes('\t') || raw.includes('\x1b')) {
|
|
1132
|
+
console.log(`[SSH] cwd tracked: '${line}' skipped (completion/history, using probe)`);
|
|
1133
|
+
session.cwd = undefined;
|
|
1134
|
+
session.cwdAt = undefined;
|
|
1135
|
+
continue;
|
|
1136
|
+
}
|
|
979
1137
|
// 含 ; | && || $ ( ) ` ' " 等无法可靠解析的结构 -> 重置为未知
|
|
980
1138
|
if (/[;|&$()`'"]/.test(rest) || rest.includes('~')) {
|
|
981
1139
|
session.cwd = undefined;
|
|
1140
|
+
session.cwdAt = undefined;
|
|
982
1141
|
continue;
|
|
983
1142
|
}
|
|
984
1143
|
const target = rest.trim();
|
|
985
1144
|
if (!target || target === '-') {
|
|
986
1145
|
// cd 无参数回到 home,或 cd - 回到上一个目录:无法可靠跟踪,重置
|
|
987
1146
|
session.cwd = undefined;
|
|
1147
|
+
session.cwdAt = undefined;
|
|
988
1148
|
continue;
|
|
989
1149
|
}
|
|
1150
|
+
let next: string | undefined;
|
|
990
1151
|
if (target.startsWith('/')) {
|
|
991
|
-
|
|
1152
|
+
next = target;
|
|
992
1153
|
} else if (session.cwd && session.cwd.startsWith('/')) {
|
|
993
|
-
|
|
1154
|
+
next = path.posix.resolve(session.cwd, target);
|
|
994
1155
|
} else {
|
|
995
1156
|
// 当前目录未知,无法拼接相对路径,重置为未知
|
|
996
|
-
|
|
1157
|
+
next = undefined;
|
|
997
1158
|
}
|
|
1159
|
+
session.cwd = next;
|
|
1160
|
+
session.cwdAt = next ? Date.now() : undefined;
|
|
1161
|
+
console.log(`[SSH] cwd tracked: '${line}' -> ${next || '(unknown)'}`);
|
|
998
1162
|
}
|
|
999
1163
|
}
|
|
1000
1164
|
|
|
1001
|
-
/**
|
|
1165
|
+
/** 连接后后台探测一次会话身份(shell PID + CWD)并缓存(不阻塞,失败忽略) */
|
|
1002
1166
|
private async seedCwd(sessionId: string): Promise<void> {
|
|
1003
1167
|
const session = this.sessions.get(sessionId);
|
|
1004
|
-
if (!session
|
|
1168
|
+
if (!session) return;
|
|
1169
|
+
// 只探测 SSH 会话;本地会话的 cwd 由 cd 跟踪维护
|
|
1170
|
+
if (session.type !== 'ssh' || !session.client) return;
|
|
1171
|
+
if (session.shellPid && session.cwd && session.cwd.startsWith('/')) return;
|
|
1172
|
+
try {
|
|
1173
|
+
await this.refreshCwd(sessionId);
|
|
1174
|
+
if (session.cwd) console.log(`[SSH] seeded cwd for ${sessionId}: ${session.cwd} (pid=${session.shellPid || '-'})`);
|
|
1175
|
+
} catch {
|
|
1176
|
+
// 忽略,上传时再探测
|
|
1177
|
+
}
|
|
1178
|
+
}
|
|
1179
|
+
|
|
1180
|
+
/**
|
|
1181
|
+
* 调度一次后台 CWD 刷新(终端输出静默后执行)。
|
|
1182
|
+
*
|
|
1183
|
+
* 目的:让 rz/上传触发时 session.cwd 已经是最新值,从而完全避免在 rz 运行期间
|
|
1184
|
+
* 向交互式 shell 注入命令(那会打断 rz,且输入会被 rz 吞掉导致探测失败)。
|
|
1185
|
+
* 刷新走独立 exec 通道,对终端零影响。
|
|
1186
|
+
*/
|
|
1187
|
+
private scheduleCwdRefresh(sessionId: string): void {
|
|
1188
|
+
const session = this.sessions.get(sessionId);
|
|
1189
|
+
if (!session || session.type !== 'ssh' || !session.client) return;
|
|
1190
|
+
if (session.cwdRefreshTimer) clearTimeout(session.cwdRefreshTimer);
|
|
1191
|
+
session.cwdRefreshTimer = setTimeout(() => {
|
|
1192
|
+
session.cwdRefreshTimer = undefined;
|
|
1193
|
+
// 限流:距离上次刷新不足 1.5s 则跳过,避免高频 exec
|
|
1194
|
+
if (session.lastCwdRefreshAt && Date.now() - session.lastCwdRefreshAt < 1500) return;
|
|
1195
|
+
this.refreshCwd(sessionId).catch(() => {});
|
|
1196
|
+
}, 700);
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
/**
|
|
1200
|
+
* 刷新并缓存会话的当前工作目录(走 exec 通道,不干扰交互式终端)。
|
|
1201
|
+
* 优先用已缓存的 shell PID 直接读 /proc/<pid>/cwd(一次 readlink,极轻量),
|
|
1202
|
+
* 否则回退到完整进程探测。失败时保留旧值不清除。
|
|
1203
|
+
*/
|
|
1204
|
+
private async refreshCwd(sessionId: string): Promise<string> {
|
|
1205
|
+
const session = this.sessions.get(sessionId);
|
|
1206
|
+
if (!session || session.type !== 'ssh' || !session.client) return session?.cwd || '';
|
|
1207
|
+
if (session.cwdRefreshing) return session.cwd || '';
|
|
1208
|
+
session.cwdRefreshing = true;
|
|
1005
1209
|
try {
|
|
1006
1210
|
let cwd = '';
|
|
1007
|
-
if (session.
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1211
|
+
if (session.shellPid) {
|
|
1212
|
+
cwd = await this.readPidCwd(sessionId, session.shellPid);
|
|
1213
|
+
if (!cwd) session.shellPid = undefined; // 进程已退出或 PID 失效
|
|
1214
|
+
}
|
|
1215
|
+
if (!cwd) {
|
|
1216
|
+
const probe = await this.probeSessionProcess(sessionId);
|
|
1217
|
+
if (probe.shellPid) session.shellPid = probe.shellPid;
|
|
1218
|
+
cwd = probe.shellCwd;
|
|
1013
1219
|
}
|
|
1220
|
+
if (cwd && cwd.startsWith('/')) {
|
|
1221
|
+
// 用户刚刚敲过 cd(cd 跟踪值很新鲜)时,不覆盖它:
|
|
1222
|
+
// cd 是用户的显式意图,比推断出的进程目录更可信,
|
|
1223
|
+
// 也能避免探测到错误进程时把正确目录改回成家目录。
|
|
1224
|
+
const trackedRecently = !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_TRACK_GRACE;
|
|
1225
|
+
if (trackedRecently && session.cwd !== cwd) {
|
|
1226
|
+
console.log(`[SSH] refreshCwd: keep tracked cwd '${session.cwd}' (probe said '${cwd}')`);
|
|
1227
|
+
} else {
|
|
1228
|
+
session.cwd = cwd;
|
|
1229
|
+
session.cwdAt = Date.now();
|
|
1230
|
+
}
|
|
1231
|
+
}
|
|
1232
|
+
return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
|
|
1014
1233
|
} catch {
|
|
1015
|
-
|
|
1234
|
+
return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
|
|
1235
|
+
} finally {
|
|
1236
|
+
session.cwdRefreshing = false;
|
|
1237
|
+
session.lastCwdRefreshAt = Date.now();
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
/**
|
|
1242
|
+
* 通过 exec 通道读取指定 PID 的工作目录(远端 Linux /proc)。
|
|
1243
|
+
* 同时校验进程名,避免 PID 复用导致读到无关进程的目录。
|
|
1244
|
+
*/
|
|
1245
|
+
private async readPidCwd(sessionId: string, pid: number): Promise<string> {
|
|
1246
|
+
if (!Number.isInteger(pid) || pid <= 0) return '';
|
|
1247
|
+
const out = await this.execRemote(
|
|
1248
|
+
sessionId,
|
|
1249
|
+
`cat /proc/${pid}/comm 2>/dev/null; readlink /proc/${pid}/cwd 2>/dev/null`,
|
|
1250
|
+
4000,
|
|
1251
|
+
);
|
|
1252
|
+
const lines = out.split('\n').map(l => l.trim()).filter(Boolean);
|
|
1253
|
+
if (lines.length < 2) return '';
|
|
1254
|
+
const comm = lines[0];
|
|
1255
|
+
const cwd = lines[lines.length - 1];
|
|
1256
|
+
if (!cwd.startsWith('/')) return '';
|
|
1257
|
+
if (!/^(bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox|rz|sz|lrz|lsz)$/.test(comm)) return '';
|
|
1258
|
+
return cwd;
|
|
1259
|
+
}
|
|
1260
|
+
|
|
1261
|
+
/**
|
|
1262
|
+
* 探测本会话的交互式 shell 与正在运行的 rz/sz 进程。
|
|
1263
|
+
* 走独立 exec 通道,不向交互式终端写入任何内容。
|
|
1264
|
+
*/
|
|
1265
|
+
private async probeSessionProcess(
|
|
1266
|
+
sessionId: string,
|
|
1267
|
+
): Promise<{ shellPid?: number; shellCwd: string; xferCwd: string; candidates: string[] }> {
|
|
1268
|
+
const result = {
|
|
1269
|
+
shellPid: undefined as number | undefined,
|
|
1270
|
+
shellCwd: '',
|
|
1271
|
+
xferCwd: '',
|
|
1272
|
+
candidates: [] as string[],
|
|
1273
|
+
};
|
|
1274
|
+
const out = await this.execRemote(sessionId, SESSION_PROBE_SCRIPT, 5000);
|
|
1275
|
+
for (const raw of out.split('\n')) {
|
|
1276
|
+
const line = raw.trim();
|
|
1277
|
+
if (!line) continue;
|
|
1278
|
+
if (line.startsWith('CAND:')) {
|
|
1279
|
+
// 诊断用:列出全部候选进程(kind:pid:cwd:pri:depth)
|
|
1280
|
+
result.candidates.push(line.substring(5));
|
|
1281
|
+
continue;
|
|
1282
|
+
}
|
|
1283
|
+
const m = line.match(/^(SHELL|XFER):(\d+):(\/.*)$/);
|
|
1284
|
+
if (!m) continue;
|
|
1285
|
+
const pid = Number(m[2]);
|
|
1286
|
+
const cwd = m[3].trim();
|
|
1287
|
+
if (m[1] === 'SHELL') {
|
|
1288
|
+
result.shellPid = pid;
|
|
1289
|
+
result.shellCwd = cwd;
|
|
1290
|
+
} else {
|
|
1291
|
+
result.xferCwd = cwd;
|
|
1292
|
+
}
|
|
1016
1293
|
}
|
|
1294
|
+
console.log(
|
|
1295
|
+
`[SSH] probeSessionProcess: shell=${result.shellPid || '-'}:${result.shellCwd || '-'} ` +
|
|
1296
|
+
`xfer=${result.xferCwd || '-'} cands=[${result.candidates.join(' | ')}]`,
|
|
1297
|
+
);
|
|
1298
|
+
return result;
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
/**
|
|
1302
|
+
* 在远端执行一条命令(独立 exec 通道),返回 stdout。
|
|
1303
|
+
* 不会向交互式终端写入任何内容,因此不会打断 rz/vim 等前台进程。
|
|
1304
|
+
*/
|
|
1305
|
+
private execRemote(sessionId: string, command: string, timeoutMs = 5000): Promise<string> {
|
|
1306
|
+
return new Promise((resolve) => {
|
|
1307
|
+
const session = this.sessions.get(sessionId);
|
|
1308
|
+
if (!session?.client) {
|
|
1309
|
+
resolve('');
|
|
1310
|
+
return;
|
|
1311
|
+
}
|
|
1312
|
+
let stdout = '';
|
|
1313
|
+
let settled = false;
|
|
1314
|
+
const finish = () => {
|
|
1315
|
+
if (settled) return;
|
|
1316
|
+
settled = true;
|
|
1317
|
+
clearTimeout(timer);
|
|
1318
|
+
resolve(stdout);
|
|
1319
|
+
};
|
|
1320
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
1321
|
+
try {
|
|
1322
|
+
session.client.exec(command, (err: Error | undefined, stream: ClientChannel) => {
|
|
1323
|
+
if (err) {
|
|
1324
|
+
console.log('[SSH] execRemote error:', err.message);
|
|
1325
|
+
finish();
|
|
1326
|
+
return;
|
|
1327
|
+
}
|
|
1328
|
+
stream.on('data', (data: Buffer) => { stdout += data.toString('utf-8'); });
|
|
1329
|
+
stream.stderr.on('data', () => {});
|
|
1330
|
+
stream.on('close', finish);
|
|
1331
|
+
stream.on('error', finish);
|
|
1332
|
+
});
|
|
1333
|
+
} catch (e) {
|
|
1334
|
+
finish();
|
|
1335
|
+
}
|
|
1336
|
+
});
|
|
1017
1337
|
}
|
|
1018
1338
|
|
|
1019
1339
|
/**
|
|
@@ -1051,27 +1371,26 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1051
1371
|
* @param timeoutMs 等待时间(毫秒),默认 2000
|
|
1052
1372
|
* @returns 捕获的输出文本(已去除 ANSI 转义序列)
|
|
1053
1373
|
*/
|
|
1054
|
-
captureOutput(
|
|
1374
|
+
captureOutput(
|
|
1375
|
+
sessionId: string,
|
|
1376
|
+
timeoutMs: number = 2000,
|
|
1377
|
+
stopWhen?: (text: string) => boolean,
|
|
1378
|
+
): Promise<string> {
|
|
1055
1379
|
return new Promise((resolve) => {
|
|
1056
1380
|
let output = '';
|
|
1381
|
+
let settled = false;
|
|
1057
1382
|
// 直接在 SSH stream 上监听(避免 notifyOutput 重复捕获导致数据翻倍)
|
|
1058
1383
|
const session = this.sessions.get(sessionId);
|
|
1059
1384
|
let streamHandler: ((chunk: Buffer) => void) | null = null;
|
|
1060
|
-
|
|
1061
|
-
streamHandler = (chunk: Buffer) => {
|
|
1062
|
-
output += chunk.toString('utf-8');
|
|
1063
|
-
};
|
|
1064
|
-
session.stream.on('data', streamHandler);
|
|
1065
|
-
} else {
|
|
1066
|
-
// 本地 shell fallback:通过 notifyOutput 机制
|
|
1067
|
-
const listener = (data: string) => { output += data; };
|
|
1068
|
-
this.addOutputListener(sessionId, listener);
|
|
1069
|
-
}
|
|
1385
|
+
let listener: ((data: string) => void) | null = null;
|
|
1070
1386
|
|
|
1071
|
-
|
|
1387
|
+
const finish = () => {
|
|
1388
|
+
if (settled) return;
|
|
1389
|
+
settled = true;
|
|
1390
|
+
clearTimeout(timer);
|
|
1072
1391
|
if (streamHandler && session?.stream) {
|
|
1073
1392
|
session.stream.removeListener('data', streamHandler);
|
|
1074
|
-
} else {
|
|
1393
|
+
} else if (listener) {
|
|
1075
1394
|
this.removeOutputListener(sessionId);
|
|
1076
1395
|
}
|
|
1077
1396
|
resolve(output
|
|
@@ -1079,7 +1398,23 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1079
1398
|
.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '')
|
|
1080
1399
|
.replace(/\x1B[^\x1B]*[a-zA-Z]/g, '')
|
|
1081
1400
|
);
|
|
1082
|
-
}
|
|
1401
|
+
};
|
|
1402
|
+
|
|
1403
|
+
const timer = setTimeout(finish, timeoutMs);
|
|
1404
|
+
const onData = (text: string) => {
|
|
1405
|
+
output += text;
|
|
1406
|
+
// 拿到目标内容就立刻返回,不必每次都等满 timeout(探测 CWD 时可省下数秒)
|
|
1407
|
+
if (stopWhen && stopWhen(output)) finish();
|
|
1408
|
+
};
|
|
1409
|
+
|
|
1410
|
+
if (session?.stream) {
|
|
1411
|
+
streamHandler = (chunk: Buffer) => onData(chunk.toString('utf-8'));
|
|
1412
|
+
session.stream.on('data', streamHandler);
|
|
1413
|
+
} else {
|
|
1414
|
+
// 本地 shell fallback:通过 notifyOutput 机制
|
|
1415
|
+
listener = onData;
|
|
1416
|
+
this.addOutputListener(sessionId, listener);
|
|
1417
|
+
}
|
|
1083
1418
|
});
|
|
1084
1419
|
}
|
|
1085
1420
|
|
|
@@ -1109,6 +1444,10 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1109
1444
|
closeSession(sessionId: string): void {
|
|
1110
1445
|
const session = this.sessions.get(sessionId);
|
|
1111
1446
|
if (session) {
|
|
1447
|
+
if (session.cwdRefreshTimer) {
|
|
1448
|
+
clearTimeout(session.cwdRefreshTimer);
|
|
1449
|
+
session.cwdRefreshTimer = undefined;
|
|
1450
|
+
}
|
|
1112
1451
|
try {
|
|
1113
1452
|
if (session.pty) {
|
|
1114
1453
|
session.pty.kill();
|
|
@@ -1136,35 +1475,110 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1136
1475
|
|
|
1137
1476
|
/**
|
|
1138
1477
|
* 获取 SSH 会话的当前工作目录。
|
|
1139
|
-
*
|
|
1140
|
-
* 1)
|
|
1141
|
-
* 2)
|
|
1142
|
-
* 3)
|
|
1478
|
+
* 优先级(前 3 步都走独立 exec 通道,对交互式终端零影响):
|
|
1479
|
+
* 1) 缓存的 session.cwd —— 由 cd 跟踪 + 后台刷新共同维护,绝大多数情况直接命中
|
|
1480
|
+
* 2) 缓存的 shell PID → readlink /proc/<pid>/cwd(一次调用,最准)
|
|
1481
|
+
* 3) 完整进程探测(shell + rz/sz):rz 运行时的 cwd 就是文件将要写入的目录
|
|
1482
|
+
* 4) 向交互式 shell 注入 printf $PWD —— 会 Ctrl+C 打断前台进程,
|
|
1483
|
+
* 仅在 allowShellProbe 为真(即确认不在 rz/文件上传过程中)时使用
|
|
1484
|
+
*
|
|
1485
|
+
* @param opts.allowShellProbe 是否允许注入式探测。rz 正在等待接收文件时必须传 false,
|
|
1486
|
+
* 否则 Ctrl+C 会打断 rz,且注入的命令会被 rz 当作数据吞掉。
|
|
1487
|
+
* @param opts.preferTransferProcess 优先采用 rz/sz 进程的 cwd(rz 写文件的目录就是它自己的
|
|
1488
|
+
* cwd,比推断出来的 shell 目录更权威)。
|
|
1489
|
+
* @param opts.force 强制重新探测,忽略缓存(用户手动点"重新检测"、上传前兜底时使用)。
|
|
1490
|
+
*
|
|
1491
|
+
* 缓存有效期 CWD_CACHE_TTL:超过该时间没能再次成功解析目录,就认为缓存不可信
|
|
1492
|
+
* (例如后台 exec 探测一直失败),此时宁可返回空让前端提示手填,
|
|
1493
|
+
* 也不能把陈旧的(很可能是家目录的)路径当成当前目录 —— 那会导致文件传错位置。
|
|
1143
1494
|
*/
|
|
1144
|
-
async getSessionCwd(
|
|
1495
|
+
async getSessionCwd(
|
|
1496
|
+
sessionId: string,
|
|
1497
|
+
opts: { allowShellProbe?: boolean; preferTransferProcess?: boolean; force?: boolean } = {},
|
|
1498
|
+
): Promise<string> {
|
|
1499
|
+
const allowShellProbe = opts.allowShellProbe !== false;
|
|
1145
1500
|
const session = this.sessions.get(sessionId);
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1501
|
+
if (!session) return '';
|
|
1502
|
+
|
|
1503
|
+
const cached = session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
|
|
1504
|
+
const cacheFresh = !!cached && !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_CACHE_TTL;
|
|
1505
|
+
|
|
1506
|
+
// 0) 强制刷新 + 允许注入探测:直接向 shell 询问,这是最权威的手段。
|
|
1507
|
+
// 调用方(上传前兜底、用户点"重新检测")已确保终端处于可打断状态,
|
|
1508
|
+
// 否则只靠 exec 探测,一旦 shellPid 指错进程就会一直拿到错误的目录。
|
|
1509
|
+
if (opts.force && allowShellProbe) {
|
|
1510
|
+
let probed = await this.probeCwdViaShell(sessionId);
|
|
1511
|
+
if (!probed) probed = await this.probeCwdViaShell(sessionId);
|
|
1512
|
+
if (probed && probed.startsWith('/')) {
|
|
1513
|
+
session.cwd = probed;
|
|
1514
|
+
session.cwdAt = Date.now();
|
|
1515
|
+
console.log(`[SSH] getSessionCwd (forced shell probe): '${probed}'`);
|
|
1516
|
+
return probed;
|
|
1517
|
+
}
|
|
1149
1518
|
}
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1519
|
+
|
|
1520
|
+
// 0.5) rz/sz 正在等待传输:直接取 rz 进程自身的 cwd。
|
|
1521
|
+
// 这是最权威的来源 —— rz 由用户所在的 shell 启动,其 cwd 就是文件要写入的目录,
|
|
1522
|
+
// 不会受"登录 shell 与实际交互 shell 不是同一个进程"的影响。
|
|
1523
|
+
if (opts.preferTransferProcess && session.type === 'ssh' && session.client) {
|
|
1524
|
+
const probe = await this.probeSessionProcess(sessionId);
|
|
1525
|
+
if (probe.shellPid) session.shellPid = probe.shellPid;
|
|
1526
|
+
const cwd = probe.xferCwd || probe.shellCwd;
|
|
1527
|
+
if (cwd) {
|
|
1528
|
+
session.cwd = cwd;
|
|
1529
|
+
session.cwdAt = Date.now();
|
|
1530
|
+
return cwd;
|
|
1156
1531
|
}
|
|
1157
1532
|
}
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1533
|
+
|
|
1534
|
+
// 1) 缓存命中(且未过期、未强制刷新)
|
|
1535
|
+
if (cached && cacheFresh && !opts.force) {
|
|
1536
|
+
return cached;
|
|
1161
1537
|
}
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1538
|
+
|
|
1539
|
+
// 2) 已知 shell PID:直接读 /proc
|
|
1540
|
+
if (session.type === 'ssh' && session.client) {
|
|
1541
|
+
if (session.shellPid) {
|
|
1542
|
+
const cwd = await this.readPidCwd(sessionId, session.shellPid);
|
|
1543
|
+
if (cwd) {
|
|
1544
|
+
session.cwd = cwd;
|
|
1545
|
+
session.cwdAt = Date.now();
|
|
1546
|
+
return cwd;
|
|
1547
|
+
}
|
|
1548
|
+
session.shellPid = undefined;
|
|
1549
|
+
}
|
|
1550
|
+
|
|
1551
|
+
// 3) 完整进程探测(默认 shell 优先,rz 场景下优先 rz 进程自身的 cwd)
|
|
1552
|
+
const probe = await this.probeSessionProcess(sessionId);
|
|
1553
|
+
if (probe.shellPid) session.shellPid = probe.shellPid;
|
|
1554
|
+
const cwd = (opts.preferTransferProcess && probe.xferCwd)
|
|
1555
|
+
? probe.xferCwd
|
|
1556
|
+
: (probe.shellCwd || probe.xferCwd);
|
|
1557
|
+
if (cwd) {
|
|
1558
|
+
session.cwd = cwd;
|
|
1559
|
+
session.cwdAt = Date.now();
|
|
1560
|
+
return cwd;
|
|
1561
|
+
}
|
|
1165
1562
|
}
|
|
1166
|
-
|
|
1167
|
-
|
|
1563
|
+
|
|
1564
|
+
// 4) 注入式探测(会打断前台进程)
|
|
1565
|
+
if (allowShellProbe) {
|
|
1566
|
+
let cwd = await this.probeCwdViaShell(sessionId);
|
|
1567
|
+
if (!cwd) cwd = await this.probeCwdViaShell(sessionId);
|
|
1568
|
+
if (cwd && cwd.startsWith('/')) {
|
|
1569
|
+
session.cwd = cwd;
|
|
1570
|
+
session.cwdAt = Date.now();
|
|
1571
|
+
return cwd;
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
// 全部失败:缓存已过期时返回空(让前端提示手填),避免把陈旧目录当当前目录使用
|
|
1576
|
+
const fallback = cacheFresh ? cached : '';
|
|
1577
|
+
console.log(
|
|
1578
|
+
`[SSH] getSessionCwd: probes failed for ${sessionId} ` +
|
|
1579
|
+
`(allowShellProbe=${allowShellProbe}, force=${!!opts.force}, staleCache=${cached || '-'}, returning='${fallback || ''}')`,
|
|
1580
|
+
);
|
|
1581
|
+
return fallback;
|
|
1168
1582
|
}
|
|
1169
1583
|
|
|
1170
1584
|
/** 向交互式 shell 注入 printf $PWD 探测 CWD(会先 Ctrl+C 打断前台进程) */
|
|
@@ -1175,8 +1589,14 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1175
1589
|
this.writeData(sessionId, '\x03');
|
|
1176
1590
|
await new Promise(r => setTimeout(r, 200));
|
|
1177
1591
|
|
|
1178
|
-
//
|
|
1179
|
-
const
|
|
1592
|
+
// 启动捕获后发送命令(marker 行输出完整就立即返回,通常几百毫秒)
|
|
1593
|
+
const stopWhen = (text: string) => {
|
|
1594
|
+
const i = text.indexOf(marker);
|
|
1595
|
+
if (i < 0) return false;
|
|
1596
|
+
const after = text.slice(i + marker.length);
|
|
1597
|
+
return after.includes('\n') || after.length > 80;
|
|
1598
|
+
};
|
|
1599
|
+
const outputPromise = this.captureOutput(sessionId, 3000, stopWhen);
|
|
1180
1600
|
this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\r`);
|
|
1181
1601
|
const output = await outputPromise;
|
|
1182
1602
|
console.log(`[SSH] probeCwdViaShell: raw output: ${JSON.stringify(output.substring(0, 500))}`);
|
|
@@ -1221,70 +1641,6 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1221
1641
|
return '';
|
|
1222
1642
|
}
|
|
1223
1643
|
|
|
1224
|
-
/**
|
|
1225
|
-
* 通过 SSH exec 独立通道获取交互式 shell 的工作目录
|
|
1226
|
-
* 不依赖交互式 shell 状态,即使 shell 卡在 rz/vim/异常状态也能工作
|
|
1227
|
-
*/
|
|
1228
|
-
private getSessionCwdViaExec(sessionId: string): Promise<string> {
|
|
1229
|
-
return new Promise((resolve) => {
|
|
1230
|
-
const session = this.sessions.get(sessionId);
|
|
1231
|
-
if (!session?.client) {
|
|
1232
|
-
resolve('');
|
|
1233
|
-
return;
|
|
1234
|
-
}
|
|
1235
|
-
|
|
1236
|
-
// 通过 /proc 查找交互式 shell 进程的 CWD。
|
|
1237
|
-
// 关键:必须只匹配「stdin 是 tty(/dev/pts)」的 shell,排除本 exec 通道自己启动的
|
|
1238
|
-
// shell(它的 stdin 是管道、CWD 是 $HOME),否则会错误地返回家目录。
|
|
1239
|
-
const cmd = [
|
|
1240
|
-
'for pid in $(ls /proc 2>/dev/null | grep "^[0-9]*$"); do',
|
|
1241
|
-
' exe=$(readlink "/proc/$pid/exe" 2>/dev/null)',
|
|
1242
|
-
' case "$exe" in',
|
|
1243
|
-
' *bash*|*sh*|*zsh*|*dash*|*fish*|*tcsh*|*csh*)',
|
|
1244
|
-
' tty=$(readlink "/proc/$pid/fd/0" 2>/dev/null)',
|
|
1245
|
-
' case "$tty" in',
|
|
1246
|
-
' /dev/pts/*|/dev/tty*|/dev/console)',
|
|
1247
|
-
' cwd=$(readlink "/proc/$pid/cwd" 2>/dev/null)',
|
|
1248
|
-
' if [ -n "$cwd" ]; then echo "$cwd"; exit 0; fi',
|
|
1249
|
-
' ;;',
|
|
1250
|
-
' esac',
|
|
1251
|
-
' ;;',
|
|
1252
|
-
' esac',
|
|
1253
|
-
'done',
|
|
1254
|
-
'pwd'
|
|
1255
|
-
].join('\n');
|
|
1256
|
-
|
|
1257
|
-
let stdout = '';
|
|
1258
|
-
let stderr = '';
|
|
1259
|
-
const timeout = setTimeout(() => {
|
|
1260
|
-
console.log('[SSH] getSessionCwdViaExec: timeout');
|
|
1261
|
-
resolve('');
|
|
1262
|
-
}, 5000);
|
|
1263
|
-
|
|
1264
|
-
session.client.exec(cmd, (err: Error | undefined, stream: ClientChannel) => {
|
|
1265
|
-
if (err) {
|
|
1266
|
-
clearTimeout(timeout);
|
|
1267
|
-
console.log('[SSH] getSessionCwdViaExec error:', err.message);
|
|
1268
|
-
resolve('');
|
|
1269
|
-
return;
|
|
1270
|
-
}
|
|
1271
|
-
stream.on('data', (data: Buffer) => { stdout += data.toString('utf-8'); });
|
|
1272
|
-
stream.stderr.on('data', (data: Buffer) => { stderr += data.toString('utf-8'); });
|
|
1273
|
-
stream.on('close', () => {
|
|
1274
|
-
clearTimeout(timeout);
|
|
1275
|
-
const cwd = stdout.trim().split('\n')[0].trim();
|
|
1276
|
-
if (cwd && cwd.startsWith('/')) {
|
|
1277
|
-
console.log(`[SSH] getSessionCwdViaExec: '${cwd}'`);
|
|
1278
|
-
resolve(cwd);
|
|
1279
|
-
} else {
|
|
1280
|
-
console.log(`[SSH] getSessionCwdViaExec: no valid cwd, stdout: ${JSON.stringify(stdout.substring(0, 200))}, stderr: ${JSON.stringify(stderr.substring(0, 200))}`);
|
|
1281
|
-
resolve('');
|
|
1282
|
-
}
|
|
1283
|
-
});
|
|
1284
|
-
});
|
|
1285
|
-
});
|
|
1286
|
-
}
|
|
1287
|
-
|
|
1288
1644
|
/**
|
|
1289
1645
|
* 通过 SFTP 上传文件到远程服务器(绕过 PTY,速度快)
|
|
1290
1646
|
* @param sessionId 会话 ID
|