@fefeding/aicmd 1.0.11 → 1.0.13

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.
@@ -34,11 +34,13 @@ var __importStar = (this && this.__importStar) || (function () {
34
34
  })();
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  exports.SSHService = void 0;
37
+ exports.modeToPermissions = modeToPermissions;
37
38
  const ssh2_1 = require("ssh2");
38
39
  const child_process_1 = require("child_process");
39
40
  const child_process_2 = require("child_process");
40
41
  const os = __importStar(require("os"));
41
42
  const fs = __importStar(require("fs"));
43
+ const path = __importStar(require("path"));
42
44
  const data_dir_1 = require("../utils/data-dir");
43
45
  const shell_1 = require("../utils/shell");
44
46
  // 尝试加载 node-pty,如果可用则使用 PTY 模式
@@ -179,6 +181,7 @@ class SSHService {
179
181
  name: sessionName,
180
182
  pty: ptyProcess,
181
183
  createdAt: new Date(),
184
+ cwd: homeDir,
182
185
  };
183
186
  this.sessions.set(sessionId, session);
184
187
  // Windows: 启动时执行 chcp 65001 设置 UTF-8 编码
@@ -215,6 +218,7 @@ class SSHService {
215
218
  name: sessionName,
216
219
  childProcess: child,
217
220
  createdAt: new Date(),
221
+ cwd: homeDir,
218
222
  };
219
223
  this.sessions.set(sessionId, session);
220
224
  child.on('exit', () => {
@@ -270,6 +274,11 @@ class SSHService {
270
274
  createdAt: new Date(),
271
275
  };
272
276
  this.sessions.set(sessionId, session);
277
+ // 连接后后台探测初始 CWD(在 shell 初始化完成后),用于上传时定位当前目录
278
+ setTimeout(() => {
279
+ if (this.sessions.has(sessionId))
280
+ this.seedCwd(sessionId);
281
+ }, 1500);
273
282
  stream.on('close', () => {
274
283
  this.sessions.delete(sessionId);
275
284
  });
@@ -553,7 +562,7 @@ class SSHService {
553
562
  // Start capture, then send the command
554
563
  // Use longer timeout (5s) to account for slow SSH connections and MOTD output
555
564
  const outputPromise = this.captureOutput(sessionId, 5000);
556
- this.writeData(sessionId, cmd + '\n');
565
+ this.writeData(sessionId, cmd + '\r');
557
566
  const output = await outputPromise;
558
567
  // Clean ANSI escape codes for more reliable marker matching
559
568
  const cleaned = output.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '').replace(/\x1B\].*?\x07/g, '').replace(/\r/g, '');
@@ -848,6 +857,10 @@ Write-Output "__DOCKER__: $dockerVer"
848
857
  const session = this.sessions.get(sessionId);
849
858
  if (!session)
850
859
  return false;
860
+ // 通过解析用户发出的 cd/pushd/popd 命令,实时维护当前工作目录
861
+ if (typeof data === 'string') {
862
+ this.updateCwdFromInput(session, data);
863
+ }
851
864
  try {
852
865
  if (session.pty) {
853
866
  session.pty.write(data);
@@ -865,6 +878,68 @@ Write-Output "__DOCKER__: $dockerVer"
865
878
  return false;
866
879
  }
867
880
  }
881
+ /**
882
+ * 根据用户输入的命令实时更新跟踪的 CWD。
883
+ * 只处理简单形式的 cd/pushd/popd;遇到复杂结构(变量、管道、subshell 等)则重置为未知,
884
+ * 由上传时的探测逻辑兜底。这是获取当前目录最可靠、零延迟的方式。
885
+ */
886
+ updateCwdFromInput(session, data) {
887
+ if (!/[\r\n]/.test(data))
888
+ return; // 只有回车提交的命令才处理
889
+ const lines = data.split(/[\r\n]+/);
890
+ for (const raw of lines) {
891
+ const line = raw.trim();
892
+ if (!line)
893
+ continue;
894
+ const m = line.match(/^(?:cd|pushd|popd)\b(.*)$/);
895
+ if (!m)
896
+ continue;
897
+ const rest = m[1].trim();
898
+ // 含 ; | && || $ ( ) ` ' " 等无法可靠解析的结构 -> 重置为未知
899
+ if (/[;|&$()`'"]/.test(rest) || rest.includes('~')) {
900
+ session.cwd = undefined;
901
+ continue;
902
+ }
903
+ const target = rest.trim();
904
+ if (!target || target === '-') {
905
+ // cd 无参数回到 home,或 cd - 回到上一个目录:无法可靠跟踪,重置
906
+ session.cwd = undefined;
907
+ continue;
908
+ }
909
+ if (target.startsWith('/')) {
910
+ session.cwd = target;
911
+ }
912
+ else if (session.cwd && session.cwd.startsWith('/')) {
913
+ session.cwd = path.posix.resolve(session.cwd, target);
914
+ }
915
+ else {
916
+ // 当前目录未知,无法拼接相对路径,重置为未知
917
+ session.cwd = undefined;
918
+ }
919
+ }
920
+ }
921
+ /** 连接后后台探测一次初始 CWD 并缓存(不阻塞,失败忽略) */
922
+ async seedCwd(sessionId) {
923
+ const session = this.sessions.get(sessionId);
924
+ if (!session || (session.cwd && session.cwd.startsWith('/')))
925
+ return;
926
+ try {
927
+ let cwd = '';
928
+ if (session.client)
929
+ cwd = await this.getSessionCwdViaExec(sessionId);
930
+ if (!cwd)
931
+ cwd = await this.probeCwdViaShell(sessionId);
932
+ if (!cwd)
933
+ cwd = await this.probeCwdViaShell(sessionId);
934
+ if (cwd && cwd.startsWith('/') && !session.cwd) {
935
+ session.cwd = cwd;
936
+ console.log(`[SSH] seeded cwd for ${sessionId}: ${cwd}`);
937
+ }
938
+ }
939
+ catch {
940
+ // 忽略,上传时再探测
941
+ }
942
+ }
868
943
  /**
869
944
  * 注册输出监听器(用于 Agent 捕获终端输出)
870
945
  * 注意:此方法不拦截现有 WebSocket 转发,仅添加额外监听
@@ -901,33 +976,31 @@ Write-Output "__DOCKER__: $dockerVer"
901
976
  captureOutput(sessionId, timeoutMs = 2000) {
902
977
  return new Promise((resolve) => {
903
978
  let output = '';
904
- const listener = (data) => {
905
- output += data;
906
- };
907
- // 方式1: 通过 notifyOutput 机制捕获
908
- this.addOutputListener(sessionId, listener);
909
- // 方式2: 直接在 SSH stream 上监听(绕过 hasBinary 检查)
979
+ // 直接在 SSH stream 上监听(避免 notifyOutput 重复捕获导致数据翻倍)
910
980
  const session = this.sessions.get(sessionId);
911
981
  let streamHandler = null;
912
982
  if (session?.stream) {
913
983
  streamHandler = (chunk) => {
914
- // 只捕获可打印文本部分
915
- const text = chunk.toString('utf-8');
916
- output += text;
984
+ output += chunk.toString('utf-8');
917
985
  };
918
986
  session.stream.on('data', streamHandler);
919
987
  }
988
+ else {
989
+ // 本地 shell fallback:通过 notifyOutput 机制
990
+ const listener = (data) => { output += data; };
991
+ this.addOutputListener(sessionId, listener);
992
+ }
920
993
  setTimeout(() => {
921
- this.removeOutputListener(sessionId);
922
994
  if (streamHandler && session?.stream) {
923
995
  session.stream.removeListener('data', streamHandler);
924
996
  }
925
- // 去除 ANSI 转义序列(更彻底的清理)
997
+ else {
998
+ this.removeOutputListener(sessionId);
999
+ }
926
1000
  resolve(output
927
- .replace(/\x1B\][^\x07]*\x07/g, '') // OSC 序列
928
- .replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '') // CSI 序列
929
- .replace(/\x1B[^\x1B]*[a-zA-Z]/g, '') // 其他转义序列
930
- );
1001
+ .replace(/\x1B\][^\x07]*\x07/g, '')
1002
+ .replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '')
1003
+ .replace(/\x1B[^\x1B]*[a-zA-Z]/g, ''));
931
1004
  }, timeoutMs);
932
1005
  });
933
1006
  }
@@ -985,46 +1058,150 @@ Write-Output "__DOCKER__: $dockerVer"
985
1058
  }
986
1059
  }
987
1060
  /**
988
- * 获取 SSH 会话的当前工作目录(通过 shell stream 执行 pwd)
1061
+ * 获取 SSH 会话的当前工作目录。
1062
+ * 优先级:
1063
+ * 1) 实时跟踪的 session.cwd(解析 cd 命令维护,最可靠、零延迟)
1064
+ * 2) /proc 扫描(仅匹配交互式 shell,不依赖交互式 shell 状态)
1065
+ * 3) 向交互式 shell 注入 printf $PWD(会先 Ctrl+C 打断前台进程)
989
1066
  */
990
1067
  async getSessionCwd(sessionId) {
1068
+ const session = this.sessions.get(sessionId);
1069
+ // 优先使用实时跟踪到的目录
1070
+ if (session?.cwd && session.cwd.startsWith('/')) {
1071
+ return session.cwd;
1072
+ }
1073
+ let cwd = '';
1074
+ if (session?.client) {
1075
+ try {
1076
+ cwd = await this.getSessionCwdViaExec(sessionId);
1077
+ }
1078
+ catch (e) {
1079
+ console.warn('[SSH] getSessionCwd exec failed, fallback to shell:', e?.message);
1080
+ }
1081
+ }
1082
+ if (!cwd) {
1083
+ cwd = await this.probeCwdViaShell(sessionId);
1084
+ if (!cwd)
1085
+ cwd = await this.probeCwdViaShell(sessionId);
1086
+ }
1087
+ if (cwd && cwd.startsWith('/')) {
1088
+ if (session && !session.cwd)
1089
+ session.cwd = cwd; // 缓存探测结果
1090
+ return cwd;
1091
+ }
1092
+ console.log(`[SSH] getSessionCwd: all probes failed for ${sessionId}`);
1093
+ return '';
1094
+ }
1095
+ /** 向交互式 shell 注入 printf $PWD 探测 CWD(会先 Ctrl+C 打断前台进程) */
1096
+ async probeCwdViaShell(sessionId) {
991
1097
  const marker = `__AICmd_CWD_${Date.now()}__`;
992
- // 前加空格避免 shell 回显(HISTCONTROL=ignorespace),先启动捕获再发命令
993
- // 增加超时到 3000ms,确保慢速 SSH 连接也能捕获到输出
1098
+ // 先发送 Ctrl+C 中断可能正在运行的前台进程(如 rz、vim、top 等),
1099
+ // 否则 printf 命令会被前台进程吞掉,shell 不会执行
1100
+ this.writeData(sessionId, '\x03');
1101
+ await new Promise(r => setTimeout(r, 200));
1102
+ // 启动捕获后发送命令
994
1103
  const outputPromise = this.captureOutput(sessionId, 3000);
995
- // 使用 printf + $PWD,避免 echo/命令替换在不同 shell 下产生不可控输出
996
- this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\n`);
1104
+ this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\r`);
997
1105
  const output = await outputPromise;
998
- console.log(`[SSH] getSessionCwd: raw output: ${JSON.stringify(output.substring(0, 500))}`);
1106
+ console.log(`[SSH] probeCwdViaShell: raw output: ${JSON.stringify(output.substring(0, 500))}`);
999
1107
  // 更彻底的 ANSI 清理:包括 OSC 序列、CSI 序列、以及各种控制字符
1000
1108
  const cleaned = output
1001
1109
  .replace(/\x1B\][^\x07]*\x07/g, '') // OSC 序列
1002
1110
  .replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '') // CSI 序列
1003
1111
  .replace(/\x1B[^\x1B]*[a-zA-Z]/g, '') // 其他转义序列
1004
1112
  .replace(/\r/g, '');
1113
+ const isCommandEcho = (text) => (text.includes('printf') ||
1114
+ text.includes('$PWD') ||
1115
+ text.includes('%s') ||
1116
+ text.includes('echo') ||
1117
+ text.includes('$(pwd)'));
1118
+ const isValidCwd = (cwd) => cwd.startsWith('/') && !isCommandEcho(cwd);
1005
1119
  for (const line of cleaned.split('\n')) {
1006
1120
  const trimmed = line.trim();
1007
- // 匹配 marker 开头的行,跳过 echo 回显行
1121
+ if (!trimmed || isCommandEcho(trimmed))
1122
+ continue;
1123
+ // 匹配 marker 开头的真实输出行,跳过命令回显行
1008
1124
  if (trimmed.startsWith(marker + ':')) {
1009
1125
  const cwd = trimmed.substring(marker.length + 1).trim();
1010
- if (cwd && !cwd.includes('$(pwd)') && !cwd.includes('echo')) {
1011
- console.log(`[SSH] getSessionCwd parsed: '${cwd}' from line: '${trimmed}'`);
1126
+ if (isValidCwd(cwd)) {
1127
+ console.log(`[SSH] probeCwdViaShell parsed: '${cwd}'`);
1012
1128
  return cwd;
1013
1129
  }
1014
1130
  }
1015
1131
  // 兜底:如果 marker 被 ANSI 序列打断,尝试用 includes 匹配
1016
- if (trimmed.includes(marker + ':') && !trimmed.startsWith('echo')) {
1132
+ if (trimmed.includes(marker + ':')) {
1017
1133
  const idx = trimmed.indexOf(marker + ':');
1018
1134
  const cwd = trimmed.substring(idx + marker.length + 1).trim();
1019
- if (cwd && !cwd.includes('$(pwd)') && !cwd.includes('echo')) {
1020
- console.log(`[SSH] getSessionCwd parsed (fallback): '${cwd}' from line: '${trimmed}'`);
1135
+ if (isValidCwd(cwd)) {
1136
+ console.log(`[SSH] probeCwdViaShell parsed (fallback): '${cwd}'`);
1021
1137
  return cwd;
1022
1138
  }
1023
1139
  }
1024
1140
  }
1025
- console.log(`[SSH] getSessionCwd: no marker found in cleaned output: ${JSON.stringify(cleaned.substring(0, 500))}`);
1141
+ console.log(`[SSH] probeCwdViaShell: no marker found: ${JSON.stringify(cleaned.substring(0, 500))}`);
1026
1142
  return '';
1027
1143
  }
1144
+ /**
1145
+ * 通过 SSH exec 独立通道获取交互式 shell 的工作目录
1146
+ * 不依赖交互式 shell 状态,即使 shell 卡在 rz/vim/异常状态也能工作
1147
+ */
1148
+ getSessionCwdViaExec(sessionId) {
1149
+ return new Promise((resolve) => {
1150
+ const session = this.sessions.get(sessionId);
1151
+ if (!session?.client) {
1152
+ resolve('');
1153
+ return;
1154
+ }
1155
+ // 通过 /proc 查找交互式 shell 进程的 CWD。
1156
+ // 关键:必须只匹配「stdin 是 tty(/dev/pts)」的 shell,排除本 exec 通道自己启动的
1157
+ // shell(它的 stdin 是管道、CWD 是 $HOME),否则会错误地返回家目录。
1158
+ const cmd = [
1159
+ 'for pid in $(ls /proc 2>/dev/null | grep "^[0-9]*$"); do',
1160
+ ' exe=$(readlink "/proc/$pid/exe" 2>/dev/null)',
1161
+ ' case "$exe" in',
1162
+ ' *bash*|*sh*|*zsh*|*dash*|*fish*|*tcsh*|*csh*)',
1163
+ ' tty=$(readlink "/proc/$pid/fd/0" 2>/dev/null)',
1164
+ ' case "$tty" in',
1165
+ ' /dev/pts/*|/dev/tty*|/dev/console)',
1166
+ ' cwd=$(readlink "/proc/$pid/cwd" 2>/dev/null)',
1167
+ ' if [ -n "$cwd" ]; then echo "$cwd"; exit 0; fi',
1168
+ ' ;;',
1169
+ ' esac',
1170
+ ' ;;',
1171
+ ' esac',
1172
+ 'done',
1173
+ 'pwd'
1174
+ ].join('\n');
1175
+ let stdout = '';
1176
+ let stderr = '';
1177
+ const timeout = setTimeout(() => {
1178
+ console.log('[SSH] getSessionCwdViaExec: timeout');
1179
+ resolve('');
1180
+ }, 5000);
1181
+ session.client.exec(cmd, (err, stream) => {
1182
+ if (err) {
1183
+ clearTimeout(timeout);
1184
+ console.log('[SSH] getSessionCwdViaExec error:', err.message);
1185
+ resolve('');
1186
+ return;
1187
+ }
1188
+ stream.on('data', (data) => { stdout += data.toString('utf-8'); });
1189
+ stream.stderr.on('data', (data) => { stderr += data.toString('utf-8'); });
1190
+ stream.on('close', () => {
1191
+ clearTimeout(timeout);
1192
+ const cwd = stdout.trim().split('\n')[0].trim();
1193
+ if (cwd && cwd.startsWith('/')) {
1194
+ console.log(`[SSH] getSessionCwdViaExec: '${cwd}'`);
1195
+ resolve(cwd);
1196
+ }
1197
+ else {
1198
+ console.log(`[SSH] getSessionCwdViaExec: no valid cwd, stdout: ${JSON.stringify(stdout.substring(0, 200))}, stderr: ${JSON.stringify(stderr.substring(0, 200))}`);
1199
+ resolve('');
1200
+ }
1201
+ });
1202
+ });
1203
+ });
1204
+ }
1028
1205
  /**
1029
1206
  * 通过 SFTP 上传文件到远程服务器(绕过 PTY,速度快)
1030
1207
  * @param sessionId 会话 ID
@@ -1036,8 +1213,20 @@ Write-Output "__DOCKER__: $dockerVer"
1036
1213
  const session = this.sessions.get(sessionId);
1037
1214
  if (!session)
1038
1215
  throw new Error('Session not found: ' + sessionId);
1216
+ // 本地会话:直接写文件
1217
+ if (session.type === 'local') {
1218
+ let fullPath = remotePath;
1219
+ if (!remotePath.startsWith('/')) {
1220
+ const cwd = process.cwd();
1221
+ fullPath = path.resolve(cwd, remotePath);
1222
+ }
1223
+ const buf = Buffer.isBuffer(fileBuffer) ? fileBuffer : Buffer.from(fileBuffer);
1224
+ await fs.promises.writeFile(fullPath, buf);
1225
+ console.log(`[SSH] Local upload: ${buf.length} bytes -> ${fullPath}`);
1226
+ return buf.length;
1227
+ }
1039
1228
  if (session.type !== 'ssh' || !session.client) {
1040
- throw new Error('SFTP upload only supported for SSH sessions');
1229
+ throw new Error('File upload is only supported for SSH / local sessions');
1041
1230
  }
1042
1231
  console.log(`[SSH] SFTP upload: ${fileBuffer.length} bytes`);
1043
1232
  // 解析相对路径:必须通过交互式 shell 获取当前 CWD。
@@ -1150,7 +1339,7 @@ Write-Output "__DOCKER__: $dockerVer"
1150
1339
  console.log(`[SSH] Shell exec: ${mvCmd}`);
1151
1340
  const mvMarker = `__AICmd_MV_${Date.now()}__`;
1152
1341
  const captureP = this.captureOutput(sessionId, 5000);
1153
- this.writeData(sessionId, `${mvCmd} && echo ${mvMarker}:OK || echo ${mvMarker}:FAIL\n`);
1342
+ this.writeData(sessionId, `${mvCmd} && echo ${mvMarker}:OK || echo ${mvMarker}:FAIL\r`);
1154
1343
  const mvOutput = await captureP;
1155
1344
  console.log(`[SSH] mv output: ${JSON.stringify(mvOutput.substring(0, 200))}`);
1156
1345
  if (mvOutput.includes(`${mvMarker}:OK`)) {
@@ -1162,7 +1351,7 @@ Write-Output "__DOCKER__: $dockerVer"
1162
1351
  console.log(`[SSH] mv failed, trying sudo mv...`);
1163
1352
  const sudoMarker = `__AICmd_SUDO_${Date.now()}__`;
1164
1353
  const sudoCaptureP = this.captureOutput(sessionId, 5000);
1165
- this.writeData(sessionId, `sudo mv -f ${(0, shell_1.shellQuote)(tmpPath)} ${(0, shell_1.shellQuote)(fullPath)} && echo ${sudoMarker}:OK || echo ${sudoMarker}:FAIL\n`);
1354
+ this.writeData(sessionId, `sudo mv -f ${(0, shell_1.shellQuote)(tmpPath)} ${(0, shell_1.shellQuote)(fullPath)} && echo ${sudoMarker}:OK || echo ${sudoMarker}:FAIL\r`);
1166
1355
  const sudoOutput = await sudoCaptureP;
1167
1356
  console.log(`[SSH] sudo mv output: ${JSON.stringify(sudoOutput.substring(0, 200))}`);
1168
1357
  if (sudoOutput.includes(`${sudoMarker}:OK`)) {
@@ -1252,6 +1441,269 @@ Write-Output "__DOCKER__: $dockerVer"
1252
1441
  getActiveSessionIds() {
1253
1442
  return Array.from(this.sessions.keys());
1254
1443
  }
1444
+ // ========== 文件管理(SFTP / 本地 fs) ==========
1445
+ /**
1446
+ * 获取 SFTP 客户端(ssh2 的 sftp 子系统)
1447
+ */
1448
+ getSftp(sessionId) {
1449
+ const session = this.sessions.get(sessionId);
1450
+ if (!session || !session.client) {
1451
+ return Promise.reject(new Error('SFTP is only available for SSH sessions'));
1452
+ }
1453
+ return new Promise((resolve, reject) => {
1454
+ session.client.sftp((err, sftp) => {
1455
+ if (err)
1456
+ return reject(err);
1457
+ resolve(sftp);
1458
+ });
1459
+ });
1460
+ }
1461
+ /**
1462
+ * 列出远程(或本地)目录内容
1463
+ */
1464
+ async listDirectory(sessionId, remotePath) {
1465
+ const session = this.sessions.get(sessionId);
1466
+ if (!session)
1467
+ throw new Error('Session not found: ' + sessionId);
1468
+ if (session.type === 'ssh' && session.client) {
1469
+ return this.listViaSftp(sessionId, remotePath);
1470
+ }
1471
+ if (session.type === 'local') {
1472
+ return this.listViaLocal(remotePath);
1473
+ }
1474
+ throw new Error('File management is only supported for SSH / local sessions');
1475
+ }
1476
+ /**
1477
+ * 创建远程目录
1478
+ */
1479
+ async makeDirectory(sessionId, remotePath) {
1480
+ const session = this.sessions.get(sessionId);
1481
+ if (!session)
1482
+ throw new Error('Session not found: ' + sessionId);
1483
+ if (session.type === 'ssh' && session.client) {
1484
+ const sftp = await this.getSftp(sessionId);
1485
+ await new Promise((resolve, reject) => {
1486
+ sftp.mkdir(remotePath, (err) => err ? reject(err) : resolve());
1487
+ });
1488
+ return;
1489
+ }
1490
+ if (session.type === 'local') {
1491
+ await fs.promises.mkdir(remotePath, { recursive: true });
1492
+ return;
1493
+ }
1494
+ throw new Error('File management is only supported for SSH / local sessions');
1495
+ }
1496
+ /**
1497
+ * 删除远程文件或目录(目录递归删除)
1498
+ */
1499
+ async removePath(sessionId, remotePath) {
1500
+ const session = this.sessions.get(sessionId);
1501
+ if (!session)
1502
+ throw new Error('Session not found: ' + sessionId);
1503
+ if (session.type === 'ssh' && session.client) {
1504
+ const sftp = await this.getSftp(sessionId);
1505
+ await this.removeRecursive(sftp, remotePath);
1506
+ return;
1507
+ }
1508
+ if (session.type === 'local') {
1509
+ await fs.promises.rm(remotePath, { recursive: true, force: true });
1510
+ return;
1511
+ }
1512
+ throw new Error('File management is only supported for SSH / local sessions');
1513
+ }
1514
+ /**
1515
+ * 重命名 / 移动远程文件或目录
1516
+ */
1517
+ async renamePath(sessionId, oldPath, newPath) {
1518
+ const session = this.sessions.get(sessionId);
1519
+ if (!session)
1520
+ throw new Error('Session not found: ' + sessionId);
1521
+ if (session.type === 'ssh' && session.client) {
1522
+ const sftp = await this.getSftp(sessionId);
1523
+ await new Promise((resolve, reject) => {
1524
+ sftp.rename(oldPath, newPath, (err) => err ? reject(err) : resolve());
1525
+ });
1526
+ return;
1527
+ }
1528
+ if (session.type === 'local') {
1529
+ await fs.promises.rename(oldPath, newPath);
1530
+ return;
1531
+ }
1532
+ throw new Error('File management is only supported for SSH / local sessions');
1533
+ }
1534
+ /**
1535
+ * 下载远程文件,返回 Buffer
1536
+ */
1537
+ async downloadFile(sessionId, remotePath) {
1538
+ const session = this.sessions.get(sessionId);
1539
+ if (!session)
1540
+ throw new Error('Session not found: ' + sessionId);
1541
+ const MAX_DOWNLOAD_SIZE = 200 * 1024 * 1024; // 200MB
1542
+ if (session.type === 'ssh' && session.client) {
1543
+ const sftp = await this.getSftp(sessionId);
1544
+ // 预检查文件大小,防止大文件 OOM
1545
+ const stat = await new Promise((resolve, reject) => {
1546
+ sftp.stat(remotePath, (err, attrs) => err ? reject(err) : resolve(attrs));
1547
+ }).catch(() => null);
1548
+ if (stat && typeof stat.size === 'number' && stat.size > MAX_DOWNLOAD_SIZE) {
1549
+ throw new Error(`文件过大 (${(stat.size / 1024 / 1024).toFixed(1)}MB),超过 200MB 限制,请使用终端 scp/sz 下载`);
1550
+ }
1551
+ return new Promise((resolve, reject) => {
1552
+ const chunks = [];
1553
+ const stream = sftp.createReadStream(remotePath);
1554
+ stream.on('data', (c) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
1555
+ stream.on('end', () => resolve(Buffer.concat(chunks)));
1556
+ stream.on('error', (e) => reject(e));
1557
+ });
1558
+ }
1559
+ if (session.type === 'local') {
1560
+ // 预检查本地文件大小
1561
+ const localStat = await fs.promises.stat(remotePath).catch(() => null);
1562
+ if (localStat && localStat.size > MAX_DOWNLOAD_SIZE) {
1563
+ throw new Error(`文件过大 (${(localStat.size / 1024 / 1024).toFixed(1)}MB),超过 200MB 限制,请使用终端 scp/sz 下载`);
1564
+ }
1565
+ return fs.promises.readFile(remotePath);
1566
+ }
1567
+ throw new Error('File management is only supported for SSH / local sessions');
1568
+ }
1569
+ /**
1570
+ * 获取会话默认目录(SSH: SFTP 起始目录 / 本地: 用户家目录)
1571
+ */
1572
+ async getDefaultDirectory(sessionId) {
1573
+ const session = this.sessions.get(sessionId);
1574
+ if (!session)
1575
+ throw new Error('Session not found: ' + sessionId);
1576
+ if (session.type === 'ssh' && session.client) {
1577
+ const sftp = await this.getSftp(sessionId);
1578
+ return new Promise((resolve, reject) => {
1579
+ sftp.realpath('.', (err, p) => err ? reject(err) : resolve(p));
1580
+ });
1581
+ }
1582
+ if (session.type === 'local') {
1583
+ return process.env.HOME || require('os').homedir();
1584
+ }
1585
+ throw new Error('File management is only supported for SSH / local sessions');
1586
+ }
1587
+ async listViaSftp(sessionId, remotePath) {
1588
+ const sftp = await this.getSftp(sessionId);
1589
+ const list = await new Promise((resolve, reject) => {
1590
+ sftp.readdir(remotePath, (err, entries) => err ? reject(err) : resolve(entries));
1591
+ });
1592
+ const result = list
1593
+ .filter((e) => e.filename !== '.' && e.filename !== '..')
1594
+ .map((entry) => this.entryToInfo(entry, remotePath));
1595
+ return this.sortFileList(result);
1596
+ }
1597
+ async listViaLocal(localPath) {
1598
+ const base = localPath || process.env.HOME || require('os').homedir();
1599
+ const names = await fs.promises.readdir(base);
1600
+ const result = [];
1601
+ for (const name of names) {
1602
+ const full = path.join(base, name);
1603
+ let stats;
1604
+ try {
1605
+ stats = await fs.promises.lstat(full);
1606
+ }
1607
+ catch {
1608
+ continue;
1609
+ }
1610
+ result.push(this.statToInfo(name, full, stats));
1611
+ }
1612
+ return this.sortFileList(result);
1613
+ }
1614
+ entryToInfo(entry, parentPath) {
1615
+ const attrs = entry.attrs || {};
1616
+ const mode = attrs.mode || 0;
1617
+ const isDirectory = (mode & 0o170000) === 0o040000;
1618
+ const isSymbolicLink = (mode & 0o170000) === 0o120000;
1619
+ return {
1620
+ name: entry.filename,
1621
+ path: parentPath.replace(/\/$/, '') + '/' + entry.filename,
1622
+ size: attrs.size ?? 0,
1623
+ mtime: (attrs.mtime ?? 0) * 1000,
1624
+ atime: (attrs.atime ?? 0) * 1000,
1625
+ isDirectory,
1626
+ isFile: (mode & 0o170000) === 0o100000,
1627
+ isSymbolicLink,
1628
+ mode,
1629
+ permissions: modeToPermissions(mode),
1630
+ owner: String(attrs.uid ?? ''),
1631
+ group: String(attrs.gid ?? ''),
1632
+ };
1633
+ }
1634
+ statToInfo(name, full, stats) {
1635
+ const mode = stats.mode;
1636
+ const isDirectory = stats.isDirectory();
1637
+ const isSymbolicLink = stats.isSymbolicLink();
1638
+ return {
1639
+ name,
1640
+ path: full,
1641
+ size: stats.size,
1642
+ mtime: stats.mtimeMs,
1643
+ atime: stats.atimeMs,
1644
+ isDirectory,
1645
+ isFile: stats.isFile(),
1646
+ isSymbolicLink,
1647
+ mode,
1648
+ permissions: modeToPermissions(mode),
1649
+ owner: String(stats.uid),
1650
+ group: String(stats.gid),
1651
+ };
1652
+ }
1653
+ sortFileList(list) {
1654
+ return list.sort((a, b) => {
1655
+ if (a.isDirectory !== b.isDirectory)
1656
+ return a.isDirectory ? -1 : 1;
1657
+ return a.name.localeCompare(b.name);
1658
+ });
1659
+ }
1660
+ async removeRecursive(sftp, p) {
1661
+ const stat = await new Promise((resolve, reject) => {
1662
+ sftp.lstat(p, (err, attrs) => err ? reject(err) : resolve(attrs));
1663
+ }).catch((e) => { console.warn(`[SSH] removeRecursive: lstat failed for ${p}:`, e?.message || e); return null; });
1664
+ if (!stat) {
1665
+ console.warn(`[SSH] removeRecursive: skipping ${p} (unable to stat)`);
1666
+ return;
1667
+ }
1668
+ const mode = stat.mode || 0;
1669
+ if ((mode & 0o170000) === 0o040000) {
1670
+ const list = await new Promise((resolve, reject) => {
1671
+ sftp.readdir(p, (err, entries) => err ? reject(err) : resolve(entries));
1672
+ });
1673
+ for (const item of list) {
1674
+ if (item.filename === '.' || item.filename === '..')
1675
+ continue;
1676
+ await this.removeRecursive(sftp, p.replace(/\/$/, '') + '/' + item.filename);
1677
+ }
1678
+ await new Promise((resolve, reject) => {
1679
+ sftp.rmdir(p, (err) => err ? reject(err) : resolve());
1680
+ });
1681
+ }
1682
+ else {
1683
+ await new Promise((resolve, reject) => {
1684
+ sftp.unlink(p, (err) => err ? reject(err) : resolve());
1685
+ });
1686
+ }
1687
+ }
1255
1688
  }
1256
1689
  exports.SSHService = SSHService;
1690
+ /** 将数字权限位转换为 ls -l 风格的字符串(如 'rwxr-xr-x'),处理 setuid/setgid/sticky 位 */
1691
+ function modeToPermissions(mode) {
1692
+ const typeChar = (mode & 0o170000) === 0o040000 ? 'd'
1693
+ : (mode & 0o170000) === 0o120000 ? 'l'
1694
+ : '-';
1695
+ const symbols = 'rwxrwxrwx';
1696
+ let str = '';
1697
+ for (let i = 0; i < 9; i++) {
1698
+ str += (mode & (1 << (8 - i))) ? symbols[i] : '-';
1699
+ }
1700
+ // 处理特殊权限位:setuid(4)、setgid(2)、sticky(1)
1701
+ if (mode & 0o4000)
1702
+ str = str.slice(0, 2) + (str[2] === 'x' ? 's' : 'S') + str.slice(3);
1703
+ if (mode & 0o2000)
1704
+ str = str.slice(0, 5) + (str[5] === 'x' ? 's' : 'S') + str.slice(6);
1705
+ if (mode & 0o1000)
1706
+ str = str.slice(0, 8) + (str[8] === 'x' ? 't' : 'T');
1707
+ return typeChar + str;
1708
+ }
1257
1709
  //# sourceMappingURL=ssh.service.js.map