@fefeding/aicmd 1.0.24 → 1.0.26

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.
@@ -33,10 +33,141 @@ 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
+ /** 复用的 SFTP 实例(每个会话只建一次,避免 channel 泄漏) */
45
+ sftp?: any;
46
+ /** 后台刷新 CWD 的防抖定时器 */
47
+ cwdRefreshTimer?: NodeJS.Timeout;
48
+ /** 上次后台刷新 CWD 的时间戳 */
49
+ lastCwdRefreshAt?: number;
50
+ /** 是否正在刷新 CWD(避免并发 exec) */
51
+ cwdRefreshing?: boolean;
38
52
  }
39
53
 
54
+ /**
55
+ * CWD 缓存有效期:超过该时长没能再次成功解析目录,缓存即视为不可信。
56
+ * 后台刷新在终端静默 700ms 后就会跑,正常情况下 cwd 时间戳远新于此值。
57
+ */
58
+ const CWD_CACHE_TTL = 120000;
59
+
60
+ /**
61
+ * cd 跟踪值的保护期:这段时间内后台探测结果不会覆盖它(见 refreshCwd)。
62
+ */
63
+ const CWD_TRACK_GRACE = 5000;
64
+
65
+ /**
66
+ * 后台 CWD 刷新的最小间隔:目录刚解析过就跳过,避免频繁 exec 占用 SSH channel。
67
+ */
68
+ const CWD_REFRESH_MIN_INTERVAL = 15000;
69
+
70
+ /**
71
+ * 远端进程探测脚本(通过独立 exec 通道执行,不会向交互式终端写入任何内容)。
72
+ *
73
+ * 输出格式(每行一条,可能 0~2 行):
74
+ * SHELL:<pid>:<cwd> 本会话的交互式 shell
75
+ * XFER:<pid>:<cwd> 本会话正在运行的 rz/sz 进程(rz 的 cwd 即文件将写入的目录)
76
+ *
77
+ * 设计要点:
78
+ * 1) 只认与本 exec 通道同源(祖先链命中同一个 sshd 会话进程)的候选,
79
+ * 避免同一台机器开多个标签页时串台读到别的终端目录;
80
+ * 2) 排除 exec 通道自身及其祖先,避免把 exec 自己的 shell(cwd 恒为 $HOME)
81
+ * 误判成终端 —— 这正是"文件被传到家目录"的根因;
82
+ * 3) 不使用 exec 通道的 pwd 兜底,探测不到就返回空,宁可让用户手填。
83
+ */
84
+ const SESSION_PROBE_SCRIPT = [
85
+ // 无 /proc 的远端(macOS / BSD):改用 lsof 读取 shell 的 cwd
86
+ 'if [ ! -d /proc ]; then',
87
+ ' for pid in $(ps -eo pid=,comm= 2>/dev/null | awk \'$2 ~ /^(bash|zsh|sh|fish|dash|ksh|ksh93|mksh|tcsh|csh)$/ {print $1}\'); do',
88
+ ' d=$(lsof -a -p "$pid" -d cwd -Fn 2>/dev/null | sed -n "s/^n//p" | head -n 1)',
89
+ ' case "$d" in /*) echo "SHELL:$pid:$d"; break;; esac',
90
+ ' done',
91
+ ' exit 0',
92
+ 'fi',
93
+ 'self=$$',
94
+ 'ppid_of() { sed -n "s/^PPid:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
95
+ 'name_of() { sed -n "s/^Name:[[:space:]]*//p" "/proc/$1/status" 2>/dev/null | head -n 1; }',
96
+ 'cwd_of() { readlink "/proc/$1/cwd" 2>/dev/null; }',
97
+ // 收集 exec 通道自身的进程链(self + 祖先),这些必须排除
98
+ 'self_chain=" $self "',
99
+ 'p=$self',
100
+ 'i=0',
101
+ 'while [ $i -lt 12 ]; do',
102
+ ' p=$(ppid_of "$p")',
103
+ ' case "$p" in ""|0|1) break;; esac',
104
+ ' self_chain="$self_chain$p "',
105
+ ' i=$((i+1))',
106
+ 'done',
107
+ // 最近的 sshd 会话祖先:用于把候选限定在本 SSH 会话内
108
+ 'sshd_anc=""',
109
+ 'for q in $self_chain; do',
110
+ ' n=$(name_of "$q")',
111
+ ' case "$n" in sshd*) sshd_anc="$q"; break;; esac',
112
+ 'done',
113
+ 'in_chain() { case "$self_chain" in *" $1 "*) return 0;; esac; return 1; }',
114
+ // 返回值即优先级:2 = 与 sshd 会话同源(最准),1 = 仅 stdin 是 tty(tmux/su 等兜底),0 = 不匹配
115
+ 'match_pri() {',
116
+ ' pid=$1',
117
+ ' if [ -n "$sshd_anc" ]; then',
118
+ ' q=$pid; j=0',
119
+ ' while [ $j -lt 12 ]; do',
120
+ ' q=$(ppid_of "$q")',
121
+ ' case "$q" in ""|0|1) break;; esac',
122
+ ' [ "$q" = "$sshd_anc" ] && return 2',
123
+ ' j=$((j+1))',
124
+ ' done',
125
+ ' fi',
126
+ ' tty=$(readlink "/proc/$pid/fd/0" 2>/dev/null)',
127
+ ' case "$tty" in /dev/pts/*|/dev/tty*|/dev/console) return 1;; esac',
128
+ ' return 0',
129
+ '}',
130
+ // 进程深度(到 PID 1 的层数):多个候选时取最深的那个。
131
+ // 用户的登录 shell 可能只是外层进程(tmux/byobu/su 后真正交互的是它的子孙),
132
+ // 最内层的 shell 才是用户实际在执行命令的地方。
133
+ 'depth_of() {',
134
+ ' d=0; q=$1',
135
+ ' while [ $d -lt 20 ]; do',
136
+ ' pp=$(ppid_of "$q")',
137
+ ' case "$pp" in ""|0|1) break;; esac',
138
+ ' q=$pp; d=$((d+1))',
139
+ ' done',
140
+ ' echo $d',
141
+ '}',
142
+ 'best_shell=""; best_shell_key=0',
143
+ 'best_xfer=""; best_xfer_key=0',
144
+ 'for pid in $(ls /proc 2>/dev/null | grep -E "^[0-9]+$"); do',
145
+ ' in_chain "$pid" && continue',
146
+ ' n=$(name_of "$pid")',
147
+ ' case "$n" in',
148
+ ' bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox) kind=shell;;',
149
+ ' rz|sz|lrz|lsz|lrzsz) kind=xfer;;',
150
+ ' *) continue;;',
151
+ ' esac',
152
+ ' c=$(cwd_of "$pid")',
153
+ ' [ -n "$c" ] || continue',
154
+ ' match_pri "$pid"',
155
+ ' pri=$?',
156
+ ' [ "$pri" = 0 ] && continue',
157
+ ' dep=$(depth_of "$pid")',
158
+ ' key=$((pri * 100 + dep))',
159
+ ' echo "CAND:$kind:$pid:$c:$pri:$dep"',
160
+ ' if [ "$kind" = shell ]; then',
161
+ ' if [ "$key" -gt "$best_shell_key" ]; then best_shell="$pid:$c"; best_shell_key=$key; fi',
162
+ ' else',
163
+ ' if [ "$key" -gt "$best_xfer_key" ]; then best_xfer="$pid:$c"; best_xfer_key=$key; fi',
164
+ ' fi',
165
+ 'done',
166
+ '[ -n "$best_shell" ] && echo "SHELL:$best_shell"',
167
+ '[ -n "$best_xfer" ] && echo "XFER:$best_xfer"',
168
+ 'exit 0',
169
+ ].join('\n');
170
+
40
171
  /** Session 元数据(用于在 server 端持久化 tab 信息) */
41
172
  interface SessionMetadata {
42
173
  sessionId: string;
@@ -94,6 +225,8 @@ export class SSHService {
94
225
  private hasCreatedSession: boolean = false;
95
226
  /** 定时清理僵尸 session 的定时器 */
96
227
  private cleanupTimer: ReturnType<typeof setInterval> | null = null;
228
+ /** 正在建立中的 SFTP 连接(避免并发重复创建) */
229
+ private sftpPromises: Map<string, Promise<any>> = new Map();
97
230
 
98
231
  constructor(connectionService: ConnectionService) {
99
232
  this.connectionService = connectionService;
@@ -345,8 +478,15 @@ export class SSHService {
345
478
  if (this.sessions.has(sessionId)) this.seedCwd(sessionId);
346
479
  }, 1500);
347
480
 
481
+ // 终端输出静默后,在后台通过 exec 通道刷新一次 CWD。
482
+ // 这样即便用户 cd 之后立刻执行 rz,session.cwd 也已是最新值,
483
+ // 无需在 rz 等待接收文件时向交互式 shell 注入命令(那会打断 rz)。
484
+ stream.on('data', () => this.scheduleCwdRefresh(sessionId));
485
+
348
486
  stream.on('close', () => {
349
487
  log(`Shell 流已关闭`);
488
+ const closing = this.sessions.get(sessionId);
489
+ if (closing?.cwdRefreshTimer) clearTimeout(closing.cwdRefreshTimer);
350
490
  this.sessions.delete(sessionId);
351
491
  });
352
492
 
@@ -965,57 +1105,254 @@ Write-Output "__DOCKER__: $dockerVer"
965
1105
  /**
966
1106
  * 根据用户输入的命令实时更新跟踪的 CWD。
967
1107
  * 只处理简单形式的 cd/pushd/popd;遇到复杂结构(变量、管道、subshell 等)则重置为未知,
968
- * 由上传时的探测逻辑兜底。这是获取当前目录最可靠、零延迟的方式。
1108
+ * 由后台刷新 / 上传时的探测兜底。
1109
+ *
1110
+ * 注意:xterm 默认「逐字符」发送按键,writeData 每次收到的往往只是单个字符,
1111
+ * 因此必须先把输入累积成完整命令行、等回车提交后再解析,否则 cd 跟踪形同虚设。
969
1112
  */
970
1113
  private updateCwdFromInput(session: TerminalSession, data: string): void {
971
- if (!/[\r\n]/.test(data)) return; // 只有回车提交的命令才处理
972
- const lines = data.split(/[\r\n]+/);
973
- for (const raw of lines) {
1114
+ let buf = (session.inputBuffer || '') + data;
1115
+
1116
+ // Ctrl+U 清空行、Ctrl+C 取消当前输入:丢弃控制符之前的内容
1117
+ const uIdx = buf.lastIndexOf('\x15');
1118
+ if (uIdx >= 0) buf = buf.slice(uIdx + 1);
1119
+ const cIdx = buf.lastIndexOf('\x03');
1120
+ if (cIdx >= 0) buf = buf.slice(cIdx + 1);
1121
+
1122
+ // 取最后一个换行/回车之前的内容作为「已提交的命令行」
1123
+ const idx = Math.max(buf.lastIndexOf('\r'), buf.lastIndexOf('\n'));
1124
+ if (idx < 0) {
1125
+ // 尚未提交:保留缓冲(限制长度,防止长时间输入导致内存膨胀)
1126
+ session.inputBuffer = buf.length > 4096 ? buf.slice(-2048) : buf;
1127
+ return;
1128
+ }
1129
+ const submitted = buf.slice(0, idx);
1130
+ session.inputBuffer = buf.slice(idx + 1);
1131
+
1132
+ for (const raw of submitted.split(/[\r\n]+/)) {
974
1133
  const line = raw.trim();
975
1134
  if (!line) continue;
976
1135
  const m = line.match(/^(?:cd|pushd|popd)\b(.*)$/);
977
1136
  if (!m) continue;
978
1137
  const rest = m[1].trim();
1138
+ // Tab 补全(cd /data/se<Tab>)时输入流里只有补全前的片段,
1139
+ // 上下箭头调出的历史命令同理:输入的都不是完整路径,无法解析 -> 交给探测兜底。
1140
+ if (raw.includes('\t') || raw.includes('\x1b')) {
1141
+ console.log(`[SSH] cwd tracked: '${line}' skipped (completion/history, using probe)`);
1142
+ session.cwd = undefined;
1143
+ session.cwdAt = undefined;
1144
+ continue;
1145
+ }
979
1146
  // 含 ; | && || $ ( ) ` ' " 等无法可靠解析的结构 -> 重置为未知
980
1147
  if (/[;|&$()`'"]/.test(rest) || rest.includes('~')) {
981
1148
  session.cwd = undefined;
1149
+ session.cwdAt = undefined;
982
1150
  continue;
983
1151
  }
984
1152
  const target = rest.trim();
985
1153
  if (!target || target === '-') {
986
1154
  // cd 无参数回到 home,或 cd - 回到上一个目录:无法可靠跟踪,重置
987
1155
  session.cwd = undefined;
1156
+ session.cwdAt = undefined;
988
1157
  continue;
989
1158
  }
1159
+ let next: string | undefined;
990
1160
  if (target.startsWith('/')) {
991
- session.cwd = target;
1161
+ next = target;
992
1162
  } else if (session.cwd && session.cwd.startsWith('/')) {
993
- session.cwd = path.posix.resolve(session.cwd, target);
1163
+ next = path.posix.resolve(session.cwd, target);
994
1164
  } else {
995
1165
  // 当前目录未知,无法拼接相对路径,重置为未知
996
- session.cwd = undefined;
1166
+ next = undefined;
997
1167
  }
1168
+ session.cwd = next;
1169
+ session.cwdAt = next ? Date.now() : undefined;
1170
+ console.log(`[SSH] cwd tracked: '${line}' -> ${next || '(unknown)'}`);
998
1171
  }
999
1172
  }
1000
1173
 
1001
- /** 连接后后台探测一次初始 CWD 并缓存(不阻塞,失败忽略) */
1174
+ /** 连接后后台探测一次会话身份(shell PID + CWD)并缓存(不阻塞,失败忽略) */
1002
1175
  private async seedCwd(sessionId: string): Promise<void> {
1003
1176
  const session = this.sessions.get(sessionId);
1004
- if (!session || (session.cwd && session.cwd.startsWith('/'))) return;
1177
+ if (!session) return;
1178
+ // 只探测 SSH 会话;本地会话的 cwd 由 cd 跟踪维护
1179
+ if (session.type !== 'ssh' || !session.client) return;
1180
+ if (session.shellPid && session.cwd && session.cwd.startsWith('/')) return;
1181
+ try {
1182
+ await this.refreshCwd(sessionId);
1183
+ if (session.cwd) console.log(`[SSH] seeded cwd for ${sessionId}: ${session.cwd} (pid=${session.shellPid || '-'})`);
1184
+ } catch {
1185
+ // 忽略,上传时再探测
1186
+ }
1187
+ }
1188
+
1189
+ /**
1190
+ * 调度一次后台 CWD 刷新(终端输出静默后执行)。
1191
+ *
1192
+ * 目的:让 rz/上传触发时 session.cwd 已经是最新值,从而完全避免在 rz 运行期间
1193
+ * 向交互式 shell 注入命令(那会打断 rz,且输入会被 rz 吞掉导致探测失败)。
1194
+ * 刷新走独立 exec 通道,对终端零影响。
1195
+ */
1196
+ private scheduleCwdRefresh(sessionId: string): void {
1197
+ const session = this.sessions.get(sessionId);
1198
+ if (!session || session.type !== 'ssh' || !session.client) return;
1199
+ // 目录刚解析过就别再跑 exec 了:每次 exec 都要占用一个 channel,
1200
+ // 频繁调用会挤占 SFTP 的 channel 配额(MaxSessions)。
1201
+ if (session.cwdAt && (Date.now() - session.cwdAt) < CWD_REFRESH_MIN_INTERVAL) return;
1202
+ if (session.cwdRefreshTimer) clearTimeout(session.cwdRefreshTimer);
1203
+ session.cwdRefreshTimer = setTimeout(() => {
1204
+ session.cwdRefreshTimer = undefined;
1205
+ // 限流:距离上次刷新不足 1.5s 则跳过,避免高频 exec
1206
+ if (session.lastCwdRefreshAt && Date.now() - session.lastCwdRefreshAt < 1500) return;
1207
+ this.refreshCwd(sessionId).catch(() => {});
1208
+ }, 700);
1209
+ }
1210
+
1211
+ /**
1212
+ * 刷新并缓存会话的当前工作目录(走 exec 通道,不干扰交互式终端)。
1213
+ * 优先用已缓存的 shell PID 直接读 /proc/<pid>/cwd(一次 readlink,极轻量),
1214
+ * 否则回退到完整进程探测。失败时保留旧值不清除。
1215
+ */
1216
+ private async refreshCwd(sessionId: string): Promise<string> {
1217
+ const session = this.sessions.get(sessionId);
1218
+ if (!session || session.type !== 'ssh' || !session.client) return session?.cwd || '';
1219
+ if (session.cwdRefreshing) return session.cwd || '';
1220
+ session.cwdRefreshing = true;
1005
1221
  try {
1006
1222
  let cwd = '';
1007
- if (session.client) cwd = await this.getSessionCwdViaExec(sessionId);
1008
- if (!cwd) cwd = await this.probeCwdViaShell(sessionId);
1009
- if (!cwd) cwd = await this.probeCwdViaShell(sessionId);
1010
- if (cwd && cwd.startsWith('/') && !session.cwd) {
1011
- session.cwd = cwd;
1012
- console.log(`[SSH] seeded cwd for ${sessionId}: ${cwd}`);
1223
+ if (session.shellPid) {
1224
+ cwd = await this.readPidCwd(sessionId, session.shellPid);
1225
+ if (!cwd) session.shellPid = undefined; // 进程已退出或 PID 失效
1013
1226
  }
1227
+ if (!cwd) {
1228
+ const probe = await this.probeSessionProcess(sessionId);
1229
+ if (probe.shellPid) session.shellPid = probe.shellPid;
1230
+ cwd = probe.shellCwd;
1231
+ }
1232
+ if (cwd && cwd.startsWith('/')) {
1233
+ // 用户刚刚敲过 cd(cd 跟踪值很新鲜)时,不覆盖它:
1234
+ // cd 是用户的显式意图,比推断出的进程目录更可信,
1235
+ // 也能避免探测到错误进程时把正确目录改回成家目录。
1236
+ const trackedRecently = !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_TRACK_GRACE;
1237
+ if (trackedRecently && session.cwd !== cwd) {
1238
+ console.log(`[SSH] refreshCwd: keep tracked cwd '${session.cwd}' (probe said '${cwd}')`);
1239
+ } else {
1240
+ session.cwd = cwd;
1241
+ session.cwdAt = Date.now();
1242
+ }
1243
+ }
1244
+ return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
1014
1245
  } catch {
1015
- // 忽略,上传时再探测
1246
+ return session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
1247
+ } finally {
1248
+ session.cwdRefreshing = false;
1249
+ session.lastCwdRefreshAt = Date.now();
1016
1250
  }
1017
1251
  }
1018
1252
 
1253
+ /**
1254
+ * 通过 exec 通道读取指定 PID 的工作目录(远端 Linux /proc)。
1255
+ * 同时校验进程名,避免 PID 复用导致读到无关进程的目录。
1256
+ */
1257
+ private async readPidCwd(sessionId: string, pid: number): Promise<string> {
1258
+ if (!Number.isInteger(pid) || pid <= 0) return '';
1259
+ const out = await this.execRemote(
1260
+ sessionId,
1261
+ `cat /proc/${pid}/comm 2>/dev/null; readlink /proc/${pid}/cwd 2>/dev/null`,
1262
+ 4000,
1263
+ );
1264
+ const lines = out.split('\n').map(l => l.trim()).filter(Boolean);
1265
+ if (lines.length < 2) return '';
1266
+ const comm = lines[0];
1267
+ const cwd = lines[lines.length - 1];
1268
+ if (!cwd.startsWith('/')) return '';
1269
+ if (!/^(bash|sh|zsh|fish|dash|ksh|ksh93|mksh|tcsh|csh|ash|busybox|rz|sz|lrz|lsz)$/.test(comm)) return '';
1270
+ return cwd;
1271
+ }
1272
+
1273
+ /**
1274
+ * 探测本会话的交互式 shell 与正在运行的 rz/sz 进程。
1275
+ * 走独立 exec 通道,不向交互式终端写入任何内容。
1276
+ */
1277
+ private async probeSessionProcess(
1278
+ sessionId: string,
1279
+ ): Promise<{ shellPid?: number; shellCwd: string; xferCwd: string; candidates: string[] }> {
1280
+ const result = {
1281
+ shellPid: undefined as number | undefined,
1282
+ shellCwd: '',
1283
+ xferCwd: '',
1284
+ candidates: [] as string[],
1285
+ };
1286
+ const out = await this.execRemote(sessionId, SESSION_PROBE_SCRIPT, 5000);
1287
+ for (const raw of out.split('\n')) {
1288
+ const line = raw.trim();
1289
+ if (!line) continue;
1290
+ if (line.startsWith('CAND:')) {
1291
+ // 诊断用:列出全部候选进程(kind:pid:cwd:pri:depth)
1292
+ result.candidates.push(line.substring(5));
1293
+ continue;
1294
+ }
1295
+ const m = line.match(/^(SHELL|XFER):(\d+):(\/.*)$/);
1296
+ if (!m) continue;
1297
+ const pid = Number(m[2]);
1298
+ const cwd = m[3].trim();
1299
+ if (m[1] === 'SHELL') {
1300
+ result.shellPid = pid;
1301
+ result.shellCwd = cwd;
1302
+ } else {
1303
+ result.xferCwd = cwd;
1304
+ }
1305
+ }
1306
+ console.log(
1307
+ `[SSH] probeSessionProcess: shell=${result.shellPid || '-'}:${result.shellCwd || '-'} ` +
1308
+ `xfer=${result.xferCwd || '-'} cands=[${result.candidates.join(' | ')}]`,
1309
+ );
1310
+ return result;
1311
+ }
1312
+
1313
+ /**
1314
+ * 在远端执行一条命令(独立 exec 通道),返回 stdout。
1315
+ * 不会向交互式终端写入任何内容,因此不会打断 rz/vim 等前台进程。
1316
+ */
1317
+ private execRemote(sessionId: string, command: string, timeoutMs = 5000): Promise<string> {
1318
+ return new Promise((resolve) => {
1319
+ const session = this.sessions.get(sessionId);
1320
+ if (!session?.client) {
1321
+ resolve('');
1322
+ return;
1323
+ }
1324
+ let stdout = '';
1325
+ let settled = false;
1326
+ let streamRef: ClientChannel | null = null;
1327
+ const finish = () => {
1328
+ if (settled) return;
1329
+ settled = true;
1330
+ clearTimeout(timer);
1331
+ // 必须显式关闭 channel:OpenSSH 默认 MaxSessions=10,
1332
+ // 泄漏的 channel 累积后会导致后续 SFTP channel 打开失败(上传时好时坏)。
1333
+ try { streamRef?.end(); } catch { /* ignore */ }
1334
+ resolve(stdout);
1335
+ };
1336
+ const timer = setTimeout(finish, timeoutMs);
1337
+ try {
1338
+ session.client.exec(command, (err: Error | undefined, stream: ClientChannel) => {
1339
+ if (err) {
1340
+ console.log('[SSH] execRemote error:', err.message);
1341
+ finish();
1342
+ return;
1343
+ }
1344
+ streamRef = stream;
1345
+ stream.on('data', (data: Buffer) => { stdout += data.toString('utf-8'); });
1346
+ stream.stderr.on('data', () => {});
1347
+ stream.on('close', finish);
1348
+ stream.on('error', finish);
1349
+ });
1350
+ } catch (e) {
1351
+ finish();
1352
+ }
1353
+ });
1354
+ }
1355
+
1019
1356
  /**
1020
1357
  * 注册输出监听器(用于 Agent 捕获终端输出)
1021
1358
  * 注意:此方法不拦截现有 WebSocket 转发,仅添加额外监听
@@ -1051,27 +1388,26 @@ Write-Output "__DOCKER__: $dockerVer"
1051
1388
  * @param timeoutMs 等待时间(毫秒),默认 2000
1052
1389
  * @returns 捕获的输出文本(已去除 ANSI 转义序列)
1053
1390
  */
1054
- captureOutput(sessionId: string, timeoutMs: number = 2000): Promise<string> {
1391
+ captureOutput(
1392
+ sessionId: string,
1393
+ timeoutMs: number = 2000,
1394
+ stopWhen?: (text: string) => boolean,
1395
+ ): Promise<string> {
1055
1396
  return new Promise((resolve) => {
1056
1397
  let output = '';
1398
+ let settled = false;
1057
1399
  // 直接在 SSH stream 上监听(避免 notifyOutput 重复捕获导致数据翻倍)
1058
1400
  const session = this.sessions.get(sessionId);
1059
1401
  let streamHandler: ((chunk: Buffer) => void) | null = null;
1060
- if (session?.stream) {
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
- }
1402
+ let listener: ((data: string) => void) | null = null;
1070
1403
 
1071
- setTimeout(() => {
1404
+ const finish = () => {
1405
+ if (settled) return;
1406
+ settled = true;
1407
+ clearTimeout(timer);
1072
1408
  if (streamHandler && session?.stream) {
1073
1409
  session.stream.removeListener('data', streamHandler);
1074
- } else {
1410
+ } else if (listener) {
1075
1411
  this.removeOutputListener(sessionId);
1076
1412
  }
1077
1413
  resolve(output
@@ -1079,7 +1415,23 @@ Write-Output "__DOCKER__: $dockerVer"
1079
1415
  .replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '')
1080
1416
  .replace(/\x1B[^\x1B]*[a-zA-Z]/g, '')
1081
1417
  );
1082
- }, timeoutMs);
1418
+ };
1419
+
1420
+ const timer = setTimeout(finish, timeoutMs);
1421
+ const onData = (text: string) => {
1422
+ output += text;
1423
+ // 拿到目标内容就立刻返回,不必每次都等满 timeout(探测 CWD 时可省下数秒)
1424
+ if (stopWhen && stopWhen(output)) finish();
1425
+ };
1426
+
1427
+ if (session?.stream) {
1428
+ streamHandler = (chunk: Buffer) => onData(chunk.toString('utf-8'));
1429
+ session.stream.on('data', streamHandler);
1430
+ } else {
1431
+ // 本地 shell fallback:通过 notifyOutput 机制
1432
+ listener = onData;
1433
+ this.addOutputListener(sessionId, listener);
1434
+ }
1083
1435
  });
1084
1436
  }
1085
1437
 
@@ -1109,6 +1461,13 @@ Write-Output "__DOCKER__: $dockerVer"
1109
1461
  closeSession(sessionId: string): void {
1110
1462
  const session = this.sessions.get(sessionId);
1111
1463
  if (session) {
1464
+ if (session.cwdRefreshTimer) {
1465
+ clearTimeout(session.cwdRefreshTimer);
1466
+ session.cwdRefreshTimer = undefined;
1467
+ }
1468
+ // 关闭复用的 SFTP channel,避免连接关闭后仍占用资源
1469
+ this.invalidateSftp(sessionId);
1470
+ this.sftpPromises.delete(sessionId);
1112
1471
  try {
1113
1472
  if (session.pty) {
1114
1473
  session.pty.kill();
@@ -1136,35 +1495,110 @@ Write-Output "__DOCKER__: $dockerVer"
1136
1495
 
1137
1496
  /**
1138
1497
  * 获取 SSH 会话的当前工作目录。
1139
- * 优先级:
1140
- * 1) 实时跟踪的 session.cwd(解析 cd 命令维护,最可靠、零延迟)
1141
- * 2) /proc 扫描(仅匹配交互式 shell,不依赖交互式 shell 状态)
1142
- * 3) 向交互式 shell 注入 printf $PWD(会先 Ctrl+C 打断前台进程)
1498
+ * 优先级(前 3 步都走独立 exec 通道,对交互式终端零影响):
1499
+ * 1) 缓存的 session.cwd —— 由 cd 跟踪 + 后台刷新共同维护,绝大多数情况直接命中
1500
+ * 2) 缓存的 shell PID → readlink /proc/<pid>/cwd(一次调用,最准)
1501
+ * 3) 完整进程探测(shell + rz/sz):rz 运行时的 cwd 就是文件将要写入的目录
1502
+ * 4) 向交互式 shell 注入 printf $PWD —— 会 Ctrl+C 打断前台进程,
1503
+ * 仅在 allowShellProbe 为真(即确认不在 rz/文件上传过程中)时使用
1504
+ *
1505
+ * @param opts.allowShellProbe 是否允许注入式探测。rz 正在等待接收文件时必须传 false,
1506
+ * 否则 Ctrl+C 会打断 rz,且注入的命令会被 rz 当作数据吞掉。
1507
+ * @param opts.preferTransferProcess 优先采用 rz/sz 进程的 cwd(rz 写文件的目录就是它自己的
1508
+ * cwd,比推断出来的 shell 目录更权威)。
1509
+ * @param opts.force 强制重新探测,忽略缓存(用户手动点"重新检测"、上传前兜底时使用)。
1510
+ *
1511
+ * 缓存有效期 CWD_CACHE_TTL:超过该时间没能再次成功解析目录,就认为缓存不可信
1512
+ * (例如后台 exec 探测一直失败),此时宁可返回空让前端提示手填,
1513
+ * 也不能把陈旧的(很可能是家目录的)路径当成当前目录 —— 那会导致文件传错位置。
1143
1514
  */
1144
- async getSessionCwd(sessionId: string): Promise<string> {
1515
+ async getSessionCwd(
1516
+ sessionId: string,
1517
+ opts: { allowShellProbe?: boolean; preferTransferProcess?: boolean; force?: boolean } = {},
1518
+ ): Promise<string> {
1519
+ const allowShellProbe = opts.allowShellProbe !== false;
1145
1520
  const session = this.sessions.get(sessionId);
1146
- // 优先使用实时跟踪到的目录
1147
- if (session?.cwd && session.cwd.startsWith('/')) {
1148
- return session.cwd;
1521
+ if (!session) return '';
1522
+
1523
+ const cached = session.cwd && session.cwd.startsWith('/') ? session.cwd : '';
1524
+ const cacheFresh = !!cached && !!session.cwdAt && (Date.now() - session.cwdAt) < CWD_CACHE_TTL;
1525
+
1526
+ // 0) 强制刷新 + 允许注入探测:直接向 shell 询问,这是最权威的手段。
1527
+ // 调用方(上传前兜底、用户点"重新检测")已确保终端处于可打断状态,
1528
+ // 否则只靠 exec 探测,一旦 shellPid 指错进程就会一直拿到错误的目录。
1529
+ if (opts.force && allowShellProbe) {
1530
+ let probed = await this.probeCwdViaShell(sessionId);
1531
+ if (!probed) probed = await this.probeCwdViaShell(sessionId);
1532
+ if (probed && probed.startsWith('/')) {
1533
+ session.cwd = probed;
1534
+ session.cwdAt = Date.now();
1535
+ console.log(`[SSH] getSessionCwd (forced shell probe): '${probed}'`);
1536
+ return probed;
1537
+ }
1149
1538
  }
1150
- let cwd = '';
1151
- if (session?.client) {
1152
- try {
1153
- cwd = await this.getSessionCwdViaExec(sessionId);
1154
- } catch (e) {
1155
- console.warn('[SSH] getSessionCwd exec failed, fallback to shell:', (e as Error)?.message);
1539
+
1540
+ // 0.5) rz/sz 正在等待传输:直接取 rz 进程自身的 cwd。
1541
+ // 这是最权威的来源 —— rz 由用户所在的 shell 启动,其 cwd 就是文件要写入的目录,
1542
+ // 不会受"登录 shell 与实际交互 shell 不是同一个进程"的影响。
1543
+ if (opts.preferTransferProcess && session.type === 'ssh' && session.client) {
1544
+ const probe = await this.probeSessionProcess(sessionId);
1545
+ if (probe.shellPid) session.shellPid = probe.shellPid;
1546
+ const cwd = probe.xferCwd || probe.shellCwd;
1547
+ if (cwd) {
1548
+ session.cwd = cwd;
1549
+ session.cwdAt = Date.now();
1550
+ return cwd;
1156
1551
  }
1157
1552
  }
1158
- if (!cwd) {
1159
- cwd = await this.probeCwdViaShell(sessionId);
1160
- if (!cwd) cwd = await this.probeCwdViaShell(sessionId);
1553
+
1554
+ // 1) 缓存命中(且未过期、未强制刷新)
1555
+ if (cached && cacheFresh && !opts.force) {
1556
+ return cached;
1161
1557
  }
1162
- if (cwd && cwd.startsWith('/')) {
1163
- if (session && !session.cwd) session.cwd = cwd; // 缓存探测结果
1164
- return cwd;
1558
+
1559
+ // 2) 已知 shell PID:直接读 /proc
1560
+ if (session.type === 'ssh' && session.client) {
1561
+ if (session.shellPid) {
1562
+ const cwd = await this.readPidCwd(sessionId, session.shellPid);
1563
+ if (cwd) {
1564
+ session.cwd = cwd;
1565
+ session.cwdAt = Date.now();
1566
+ return cwd;
1567
+ }
1568
+ session.shellPid = undefined;
1569
+ }
1570
+
1571
+ // 3) 完整进程探测(默认 shell 优先,rz 场景下优先 rz 进程自身的 cwd)
1572
+ const probe = await this.probeSessionProcess(sessionId);
1573
+ if (probe.shellPid) session.shellPid = probe.shellPid;
1574
+ const cwd = (opts.preferTransferProcess && probe.xferCwd)
1575
+ ? probe.xferCwd
1576
+ : (probe.shellCwd || probe.xferCwd);
1577
+ if (cwd) {
1578
+ session.cwd = cwd;
1579
+ session.cwdAt = Date.now();
1580
+ return cwd;
1581
+ }
1165
1582
  }
1166
- console.log(`[SSH] getSessionCwd: all probes failed for ${sessionId}`);
1167
- return '';
1583
+
1584
+ // 4) 注入式探测(会打断前台进程)
1585
+ if (allowShellProbe) {
1586
+ let cwd = await this.probeCwdViaShell(sessionId);
1587
+ if (!cwd) cwd = await this.probeCwdViaShell(sessionId);
1588
+ if (cwd && cwd.startsWith('/')) {
1589
+ session.cwd = cwd;
1590
+ session.cwdAt = Date.now();
1591
+ return cwd;
1592
+ }
1593
+ }
1594
+
1595
+ // 全部失败:缓存已过期时返回空(让前端提示手填),避免把陈旧目录当当前目录使用
1596
+ const fallback = cacheFresh ? cached : '';
1597
+ console.log(
1598
+ `[SSH] getSessionCwd: probes failed for ${sessionId} ` +
1599
+ `(allowShellProbe=${allowShellProbe}, force=${!!opts.force}, staleCache=${cached || '-'}, returning='${fallback || ''}')`,
1600
+ );
1601
+ return fallback;
1168
1602
  }
1169
1603
 
1170
1604
  /** 向交互式 shell 注入 printf $PWD 探测 CWD(会先 Ctrl+C 打断前台进程) */
@@ -1175,8 +1609,14 @@ Write-Output "__DOCKER__: $dockerVer"
1175
1609
  this.writeData(sessionId, '\x03');
1176
1610
  await new Promise(r => setTimeout(r, 200));
1177
1611
 
1178
- // 启动捕获后发送命令
1179
- const outputPromise = this.captureOutput(sessionId, 3000);
1612
+ // 启动捕获后发送命令(marker 行输出完整就立即返回,通常几百毫秒)
1613
+ const stopWhen = (text: string) => {
1614
+ const i = text.indexOf(marker);
1615
+ if (i < 0) return false;
1616
+ const after = text.slice(i + marker.length);
1617
+ return after.includes('\n') || after.length > 80;
1618
+ };
1619
+ const outputPromise = this.captureOutput(sessionId, 3000, stopWhen);
1180
1620
  this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\r`);
1181
1621
  const output = await outputPromise;
1182
1622
  console.log(`[SSH] probeCwdViaShell: raw output: ${JSON.stringify(output.substring(0, 500))}`);
@@ -1221,70 +1661,6 @@ Write-Output "__DOCKER__: $dockerVer"
1221
1661
  return '';
1222
1662
  }
1223
1663
 
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
1664
  /**
1289
1665
  * 通过 SFTP 上传文件到远程服务器(绕过 PTY,速度快)
1290
1666
  * @param sessionId 会话 ID
@@ -1344,20 +1720,23 @@ Write-Output "__DOCKER__: $dockerVer"
1344
1720
  if (err) reject(err); else resolve(bytes!);
1345
1721
  };
1346
1722
 
1347
- const doSftpWrite = (targetPath: string, callback: (err: Error | null) => void) => {
1348
- console.log(`[SSH] SFTP opening subsystem...`);
1349
- session.client!.sftp((sftpErr: Error | undefined, sftp: any) => {
1723
+ const doSftpWrite = (targetPath: string, callback: (err: Error | null) => void, isRetry = false) => {
1724
+ console.log(`[SSH] SFTP getting subsystem (reuse=${!!session.sftp})...`);
1725
+ this.getSftp(sessionId).then((sftp) => {
1350
1726
  if (done) return;
1351
- if (sftpErr) {
1352
- callback(new Error('SFTP init failed: ' + sftpErr.message));
1353
- return;
1354
- }
1355
1727
  console.log(`[SSH] SFTP writing ${fileBuffer.length} bytes to ${targetPath}...`);
1356
1728
 
1357
1729
  sftp.open(targetPath, 'w', (openErr: Error | undefined, fd: number) => {
1358
1730
  if (done) return;
1359
1731
  if (openErr) {
1360
1732
  console.error(`[SSH] SFTP open error: ${openErr.message}`);
1733
+ // channel 类故障(达到 MaxSessions 上限 / channel 已失效):重建实例后重试一次
1734
+ if (!isRetry && /channel|not open|closed|failure/i.test(openErr.message)) {
1735
+ console.log('[SSH] SFTP channel broken, recreating subsystem and retrying once');
1736
+ this.invalidateSftp(sessionId);
1737
+ setTimeout(() => { if (!done) doSftpWrite(targetPath, callback, true); }, 300);
1738
+ return;
1739
+ }
1361
1740
  callback(new Error('SFTP open failed: ' + openErr.message));
1362
1741
  return;
1363
1742
  }
@@ -1381,6 +1760,16 @@ Write-Output "__DOCKER__: $dockerVer"
1381
1760
  });
1382
1761
  });
1383
1762
  });
1763
+ }).catch((initErr: any) => {
1764
+ if (done) return;
1765
+ // 建立 subsystem 就可能 "Channel open failure"(MaxSessions 上限):重建后重试一次
1766
+ if (!isRetry && /channel|failure|closed|not open/i.test(initErr?.message || '')) {
1767
+ console.log('[SSH] SFTP init failed, recreating subsystem and retrying once');
1768
+ this.invalidateSftp(sessionId);
1769
+ setTimeout(() => { if (!done) doSftpWrite(targetPath, callback, true); }, 300);
1770
+ return;
1771
+ }
1772
+ callback(new Error(initErr?.message || 'SFTP init failed'));
1384
1773
  });
1385
1774
  };
1386
1775
 
@@ -1390,8 +1779,10 @@ Write-Output "__DOCKER__: $dockerVer"
1390
1779
  if (!err) {
1391
1780
  // 直接写入成功,验证文件
1392
1781
  console.log(`[SSH] SFTP direct write succeeded, verifying...`);
1393
- session.client!.sftp((_, sftp) => {
1782
+ this.getSftp(sessionId).then((sftp) => {
1783
+ if (done) return;
1394
1784
  sftp.stat(fullPath, (statErr: Error | undefined, stats: any) => {
1785
+ if (done) return;
1395
1786
  if (statErr || stats.size !== fileBuffer.length) {
1396
1787
  finish(new Error('SFTP verify failed'));
1397
1788
  } else {
@@ -1399,6 +1790,9 @@ Write-Output "__DOCKER__: $dockerVer"
1399
1790
  finish(null, fileBuffer.length);
1400
1791
  }
1401
1792
  });
1793
+ }).catch((statInitErr: any) => {
1794
+ if (done) return;
1795
+ finish(new Error(statInitErr?.message || 'SFTP verify init failed'));
1402
1796
  });
1403
1797
  return;
1404
1798
  }
@@ -1534,19 +1928,53 @@ Write-Output "__DOCKER__: $dockerVer"
1534
1928
  // ========== 文件管理(SFTP / 本地 fs) ==========
1535
1929
 
1536
1930
  /**
1537
- * 获取 SFTP 客户端(ssh2 的 sftp 子系统)
1931
+ * 获取(并复用)SFTP 客户端(ssh2 的 sftp 子系统)
1932
+ *
1933
+ * 必须复用:OpenSSH 默认 MaxSessions=10,而每次 client.sftp() 都会新开一个
1934
+ * subsystem channel。若每次调用都新建且不关闭,几次之后就会
1935
+ * "Channel open failure: open failed",表现为上传时好时坏、重连后又正常。
1538
1936
  */
1539
1937
  private getSftp(sessionId: string): Promise<any> {
1540
1938
  const session = this.sessions.get(sessionId);
1541
1939
  if (!session || !session.client) {
1542
1940
  return Promise.reject(new Error('SFTP is only available for SSH sessions'));
1543
1941
  }
1544
- return new Promise((resolve, reject) => {
1942
+ if (session.sftp) return Promise.resolve(session.sftp);
1943
+
1944
+ const pending = this.sftpPromises.get(sessionId);
1945
+ if (pending) return pending;
1946
+
1947
+ const p = new Promise<any>((resolve, reject) => {
1545
1948
  session.client!.sftp((err: Error | undefined, sftp: any) => {
1546
- if (err) return reject(err);
1949
+ this.sftpPromises.delete(sessionId);
1950
+ if (err || !sftp) {
1951
+ reject(new Error('SFTP init failed: ' + (err?.message || 'unknown')));
1952
+ return;
1953
+ }
1954
+ session.sftp = sftp;
1955
+ // 实例出错/关闭后丢弃,下次自动重建
1956
+ const drop = () => {
1957
+ if (session.sftp === sftp) session.sftp = undefined;
1958
+ };
1959
+ try {
1960
+ sftp.on('error', drop);
1961
+ sftp.on('close', drop);
1962
+ } catch { /* ignore */ }
1547
1963
  resolve(sftp);
1548
1964
  });
1549
1965
  });
1966
+ this.sftpPromises.set(sessionId, p);
1967
+ return p;
1968
+ }
1969
+
1970
+ /** 丢弃并关闭失效的 SFTP 实例(下次使用时重建) */
1971
+ private invalidateSftp(sessionId: string): void {
1972
+ const session = this.sessions.get(sessionId);
1973
+ const sftp = session?.sftp;
1974
+ if (!sftp) return;
1975
+ session!.sftp = undefined;
1976
+ this.sftpPromises.delete(sessionId);
1977
+ try { sftp.end(); } catch { /* ignore */ }
1550
1978
  }
1551
1979
 
1552
1980
  /**