@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.
- package/dist/public/index.js +76 -0
- package/dist/public/views.css +282 -56
- package/dist/public/views.js +1013 -337
- package/dist/server/index.d.ts +1 -1
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +39 -0
- package/dist/server/index.js.map +1 -1
- package/dist/server/index.ts +40 -0
- package/dist/server/service/connection.service.d.ts +1 -0
- package/dist/server/service/connection.service.d.ts.map +1 -1
- package/dist/server/service/connection.service.js +43 -3
- package/dist/server/service/connection.service.js.map +1 -1
- package/dist/server/service/connection.service.ts +42 -3
- package/dist/server/service/ssh.service.d.ts +77 -1
- package/dist/server/service/ssh.service.d.ts.map +1 -1
- package/dist/server/service/ssh.service.js +484 -32
- package/dist/server/service/ssh.service.js.map +1 -1
- package/dist/server/service/ssh.service.ts +507 -32
- package/electron/main.js +48 -0
- package/electron/preload.js +6 -0
- package/package.json +1 -1
- package/server.js +49 -0
|
@@ -33,6 +33,8 @@ interface TerminalSession {
|
|
|
33
33
|
// 本地 shell 降级: child_process
|
|
34
34
|
childProcess?: ChildProcess;
|
|
35
35
|
createdAt: Date;
|
|
36
|
+
/** 实时跟踪的当前工作目录(通过解析 cd 命令维护,最可靠) */
|
|
37
|
+
cwd?: string;
|
|
36
38
|
}
|
|
37
39
|
|
|
38
40
|
/** Session 元数据(用于在 server 端持久化 tab 信息) */
|
|
@@ -55,6 +57,26 @@ export interface SessionInfo {
|
|
|
55
57
|
systemContext?: string;
|
|
56
58
|
}
|
|
57
59
|
|
|
60
|
+
/** 远程文件信息(用于文件管理面板) */
|
|
61
|
+
export interface RemoteFileInfo {
|
|
62
|
+
name: string;
|
|
63
|
+
/** 完整路径 */
|
|
64
|
+
path: string;
|
|
65
|
+
size: number;
|
|
66
|
+
/** 修改时间(毫秒时间戳) */
|
|
67
|
+
mtime: number;
|
|
68
|
+
atime: number;
|
|
69
|
+
isDirectory: boolean;
|
|
70
|
+
isFile: boolean;
|
|
71
|
+
isSymbolicLink: boolean;
|
|
72
|
+
/** 数字权限位(如 0o755) */
|
|
73
|
+
mode: number;
|
|
74
|
+
/** ls -l 风格权限字符串(如 'rwxr-xr-x') */
|
|
75
|
+
permissions: string;
|
|
76
|
+
owner: string;
|
|
77
|
+
group: string;
|
|
78
|
+
}
|
|
79
|
+
|
|
58
80
|
/**
|
|
59
81
|
* 终端会话管理服务
|
|
60
82
|
* 支持 SSH 远程连接和本地 Shell
|
|
@@ -199,6 +221,7 @@ export class SSHService {
|
|
|
199
221
|
name: sessionName,
|
|
200
222
|
pty: ptyProcess,
|
|
201
223
|
createdAt: new Date(),
|
|
224
|
+
cwd: homeDir,
|
|
202
225
|
};
|
|
203
226
|
|
|
204
227
|
this.sessions.set(sessionId, session);
|
|
@@ -240,6 +263,7 @@ export class SSHService {
|
|
|
240
263
|
name: sessionName,
|
|
241
264
|
childProcess: child,
|
|
242
265
|
createdAt: new Date(),
|
|
266
|
+
cwd: homeDir,
|
|
243
267
|
};
|
|
244
268
|
|
|
245
269
|
this.sessions.set(sessionId, session);
|
|
@@ -306,6 +330,11 @@ export class SSHService {
|
|
|
306
330
|
|
|
307
331
|
this.sessions.set(sessionId, session);
|
|
308
332
|
|
|
333
|
+
// 连接后后台探测初始 CWD(在 shell 初始化完成后),用于上传时定位当前目录
|
|
334
|
+
setTimeout(() => {
|
|
335
|
+
if (this.sessions.has(sessionId)) this.seedCwd(sessionId);
|
|
336
|
+
}, 1500);
|
|
337
|
+
|
|
309
338
|
stream.on('close', () => {
|
|
310
339
|
this.sessions.delete(sessionId);
|
|
311
340
|
});
|
|
@@ -604,7 +633,7 @@ export class SSHService {
|
|
|
604
633
|
// Start capture, then send the command
|
|
605
634
|
// Use longer timeout (5s) to account for slow SSH connections and MOTD output
|
|
606
635
|
const outputPromise = this.captureOutput(sessionId, 5000);
|
|
607
|
-
this.writeData(sessionId, cmd + '\
|
|
636
|
+
this.writeData(sessionId, cmd + '\r');
|
|
608
637
|
const output = await outputPromise;
|
|
609
638
|
// Clean ANSI escape codes for more reliable marker matching
|
|
610
639
|
const cleaned = output.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '').replace(/\x1B\].*?\x07/g, '').replace(/\r/g, '');
|
|
@@ -901,6 +930,11 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
901
930
|
const session = this.sessions.get(sessionId);
|
|
902
931
|
if (!session) return false;
|
|
903
932
|
|
|
933
|
+
// 通过解析用户发出的 cd/pushd/popd 命令,实时维护当前工作目录
|
|
934
|
+
if (typeof data === 'string') {
|
|
935
|
+
this.updateCwdFromInput(session, data);
|
|
936
|
+
}
|
|
937
|
+
|
|
904
938
|
try {
|
|
905
939
|
if (session.pty) {
|
|
906
940
|
session.pty.write(data);
|
|
@@ -916,6 +950,60 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
916
950
|
}
|
|
917
951
|
}
|
|
918
952
|
|
|
953
|
+
/**
|
|
954
|
+
* 根据用户输入的命令实时更新跟踪的 CWD。
|
|
955
|
+
* 只处理简单形式的 cd/pushd/popd;遇到复杂结构(变量、管道、subshell 等)则重置为未知,
|
|
956
|
+
* 由上传时的探测逻辑兜底。这是获取当前目录最可靠、零延迟的方式。
|
|
957
|
+
*/
|
|
958
|
+
private updateCwdFromInput(session: TerminalSession, data: string): void {
|
|
959
|
+
if (!/[\r\n]/.test(data)) return; // 只有回车提交的命令才处理
|
|
960
|
+
const lines = data.split(/[\r\n]+/);
|
|
961
|
+
for (const raw of lines) {
|
|
962
|
+
const line = raw.trim();
|
|
963
|
+
if (!line) continue;
|
|
964
|
+
const m = line.match(/^(?:cd|pushd|popd)\b(.*)$/);
|
|
965
|
+
if (!m) continue;
|
|
966
|
+
const rest = m[1].trim();
|
|
967
|
+
// 含 ; | && || $ ( ) ` ' " 等无法可靠解析的结构 -> 重置为未知
|
|
968
|
+
if (/[;|&$()`'"]/.test(rest) || rest.includes('~')) {
|
|
969
|
+
session.cwd = undefined;
|
|
970
|
+
continue;
|
|
971
|
+
}
|
|
972
|
+
const target = rest.trim();
|
|
973
|
+
if (!target || target === '-') {
|
|
974
|
+
// cd 无参数回到 home,或 cd - 回到上一个目录:无法可靠跟踪,重置
|
|
975
|
+
session.cwd = undefined;
|
|
976
|
+
continue;
|
|
977
|
+
}
|
|
978
|
+
if (target.startsWith('/')) {
|
|
979
|
+
session.cwd = target;
|
|
980
|
+
} else if (session.cwd && session.cwd.startsWith('/')) {
|
|
981
|
+
session.cwd = path.posix.resolve(session.cwd, target);
|
|
982
|
+
} else {
|
|
983
|
+
// 当前目录未知,无法拼接相对路径,重置为未知
|
|
984
|
+
session.cwd = undefined;
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
/** 连接后后台探测一次初始 CWD 并缓存(不阻塞,失败忽略) */
|
|
990
|
+
private async seedCwd(sessionId: string): Promise<void> {
|
|
991
|
+
const session = this.sessions.get(sessionId);
|
|
992
|
+
if (!session || (session.cwd && session.cwd.startsWith('/'))) return;
|
|
993
|
+
try {
|
|
994
|
+
let cwd = '';
|
|
995
|
+
if (session.client) cwd = await this.getSessionCwdViaExec(sessionId);
|
|
996
|
+
if (!cwd) cwd = await this.probeCwdViaShell(sessionId);
|
|
997
|
+
if (!cwd) cwd = await this.probeCwdViaShell(sessionId);
|
|
998
|
+
if (cwd && cwd.startsWith('/') && !session.cwd) {
|
|
999
|
+
session.cwd = cwd;
|
|
1000
|
+
console.log(`[SSH] seeded cwd for ${sessionId}: ${cwd}`);
|
|
1001
|
+
}
|
|
1002
|
+
} catch {
|
|
1003
|
+
// 忽略,上传时再探测
|
|
1004
|
+
}
|
|
1005
|
+
}
|
|
1006
|
+
|
|
919
1007
|
/**
|
|
920
1008
|
* 注册输出监听器(用于 Agent 捕获终端输出)
|
|
921
1009
|
* 注意:此方法不拦截现有 WebSocket 转发,仅添加额外监听
|
|
@@ -954,34 +1042,30 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
954
1042
|
captureOutput(sessionId: string, timeoutMs: number = 2000): Promise<string> {
|
|
955
1043
|
return new Promise((resolve) => {
|
|
956
1044
|
let output = '';
|
|
957
|
-
|
|
958
|
-
output += data;
|
|
959
|
-
};
|
|
960
|
-
// 方式1: 通过 notifyOutput 机制捕获
|
|
961
|
-
this.addOutputListener(sessionId, listener);
|
|
962
|
-
|
|
963
|
-
// 方式2: 直接在 SSH stream 上监听(绕过 hasBinary 检查)
|
|
1045
|
+
// 直接在 SSH stream 上监听(避免 notifyOutput 重复捕获导致数据翻倍)
|
|
964
1046
|
const session = this.sessions.get(sessionId);
|
|
965
1047
|
let streamHandler: ((chunk: Buffer) => void) | null = null;
|
|
966
1048
|
if (session?.stream) {
|
|
967
1049
|
streamHandler = (chunk: Buffer) => {
|
|
968
|
-
|
|
969
|
-
const text = chunk.toString('utf-8');
|
|
970
|
-
output += text;
|
|
1050
|
+
output += chunk.toString('utf-8');
|
|
971
1051
|
};
|
|
972
1052
|
session.stream.on('data', streamHandler);
|
|
1053
|
+
} else {
|
|
1054
|
+
// 本地 shell fallback:通过 notifyOutput 机制
|
|
1055
|
+
const listener = (data: string) => { output += data; };
|
|
1056
|
+
this.addOutputListener(sessionId, listener);
|
|
973
1057
|
}
|
|
974
1058
|
|
|
975
1059
|
setTimeout(() => {
|
|
976
|
-
this.removeOutputListener(sessionId);
|
|
977
1060
|
if (streamHandler && session?.stream) {
|
|
978
1061
|
session.stream.removeListener('data', streamHandler);
|
|
1062
|
+
} else {
|
|
1063
|
+
this.removeOutputListener(sessionId);
|
|
979
1064
|
}
|
|
980
|
-
// 去除 ANSI 转义序列(更彻底的清理)
|
|
981
1065
|
resolve(output
|
|
982
|
-
.replace(/\x1B\][^\x07]*\x07/g, '')
|
|
983
|
-
.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '')
|
|
984
|
-
.replace(/\x1B[^\x1B]*[a-zA-Z]/g, '')
|
|
1066
|
+
.replace(/\x1B\][^\x07]*\x07/g, '')
|
|
1067
|
+
.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '')
|
|
1068
|
+
.replace(/\x1B[^\x1B]*[a-zA-Z]/g, '')
|
|
985
1069
|
);
|
|
986
1070
|
}, timeoutMs);
|
|
987
1071
|
});
|
|
@@ -1039,47 +1123,156 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1039
1123
|
}
|
|
1040
1124
|
|
|
1041
1125
|
/**
|
|
1042
|
-
* 获取 SSH
|
|
1126
|
+
* 获取 SSH 会话的当前工作目录。
|
|
1127
|
+
* 优先级:
|
|
1128
|
+
* 1) 实时跟踪的 session.cwd(解析 cd 命令维护,最可靠、零延迟)
|
|
1129
|
+
* 2) /proc 扫描(仅匹配交互式 shell,不依赖交互式 shell 状态)
|
|
1130
|
+
* 3) 向交互式 shell 注入 printf $PWD(会先 Ctrl+C 打断前台进程)
|
|
1043
1131
|
*/
|
|
1044
1132
|
async getSessionCwd(sessionId: string): Promise<string> {
|
|
1133
|
+
const session = this.sessions.get(sessionId);
|
|
1134
|
+
// 优先使用实时跟踪到的目录
|
|
1135
|
+
if (session?.cwd && session.cwd.startsWith('/')) {
|
|
1136
|
+
return session.cwd;
|
|
1137
|
+
}
|
|
1138
|
+
let cwd = '';
|
|
1139
|
+
if (session?.client) {
|
|
1140
|
+
try {
|
|
1141
|
+
cwd = await this.getSessionCwdViaExec(sessionId);
|
|
1142
|
+
} catch (e) {
|
|
1143
|
+
console.warn('[SSH] getSessionCwd exec failed, fallback to shell:', (e as Error)?.message);
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
if (!cwd) {
|
|
1147
|
+
cwd = await this.probeCwdViaShell(sessionId);
|
|
1148
|
+
if (!cwd) cwd = await this.probeCwdViaShell(sessionId);
|
|
1149
|
+
}
|
|
1150
|
+
if (cwd && cwd.startsWith('/')) {
|
|
1151
|
+
if (session && !session.cwd) session.cwd = cwd; // 缓存探测结果
|
|
1152
|
+
return cwd;
|
|
1153
|
+
}
|
|
1154
|
+
console.log(`[SSH] getSessionCwd: all probes failed for ${sessionId}`);
|
|
1155
|
+
return '';
|
|
1156
|
+
}
|
|
1157
|
+
|
|
1158
|
+
/** 向交互式 shell 注入 printf $PWD 探测 CWD(会先 Ctrl+C 打断前台进程) */
|
|
1159
|
+
private async probeCwdViaShell(sessionId: string): Promise<string> {
|
|
1045
1160
|
const marker = `__AICmd_CWD_${Date.now()}__`;
|
|
1046
|
-
//
|
|
1047
|
-
//
|
|
1161
|
+
// 先发送 Ctrl+C 中断可能正在运行的前台进程(如 rz、vim、top 等),
|
|
1162
|
+
// 否则 printf 命令会被前台进程吞掉,shell 不会执行
|
|
1163
|
+
this.writeData(sessionId, '\x03');
|
|
1164
|
+
await new Promise(r => setTimeout(r, 200));
|
|
1165
|
+
|
|
1166
|
+
// 启动捕获后发送命令
|
|
1048
1167
|
const outputPromise = this.captureOutput(sessionId, 3000);
|
|
1049
|
-
|
|
1050
|
-
this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\n`);
|
|
1168
|
+
this.writeData(sessionId, ` printf '\\n${marker}:%s\\n' "$PWD"\r`);
|
|
1051
1169
|
const output = await outputPromise;
|
|
1052
|
-
console.log(`[SSH]
|
|
1170
|
+
console.log(`[SSH] probeCwdViaShell: raw output: ${JSON.stringify(output.substring(0, 500))}`);
|
|
1053
1171
|
// 更彻底的 ANSI 清理:包括 OSC 序列、CSI 序列、以及各种控制字符
|
|
1054
1172
|
const cleaned = output
|
|
1055
1173
|
.replace(/\x1B\][^\x07]*\x07/g, '') // OSC 序列
|
|
1056
1174
|
.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, '') // CSI 序列
|
|
1057
1175
|
.replace(/\x1B[^\x1B]*[a-zA-Z]/g, '') // 其他转义序列
|
|
1058
1176
|
.replace(/\r/g, '');
|
|
1177
|
+
const isCommandEcho = (text: string) => (
|
|
1178
|
+
text.includes('printf') ||
|
|
1179
|
+
text.includes('$PWD') ||
|
|
1180
|
+
text.includes('%s') ||
|
|
1181
|
+
text.includes('echo') ||
|
|
1182
|
+
text.includes('$(pwd)')
|
|
1183
|
+
);
|
|
1184
|
+
const isValidCwd = (cwd: string) => cwd.startsWith('/') && !isCommandEcho(cwd);
|
|
1185
|
+
|
|
1059
1186
|
for (const line of cleaned.split('\n')) {
|
|
1060
1187
|
const trimmed = line.trim();
|
|
1061
|
-
|
|
1188
|
+
if (!trimmed || isCommandEcho(trimmed)) continue;
|
|
1189
|
+
|
|
1190
|
+
// 匹配 marker 开头的真实输出行,跳过命令回显行
|
|
1062
1191
|
if (trimmed.startsWith(marker + ':')) {
|
|
1063
1192
|
const cwd = trimmed.substring(marker.length + 1).trim();
|
|
1064
|
-
if (
|
|
1065
|
-
console.log(`[SSH]
|
|
1193
|
+
if (isValidCwd(cwd)) {
|
|
1194
|
+
console.log(`[SSH] probeCwdViaShell parsed: '${cwd}'`);
|
|
1066
1195
|
return cwd;
|
|
1067
1196
|
}
|
|
1068
1197
|
}
|
|
1069
1198
|
// 兜底:如果 marker 被 ANSI 序列打断,尝试用 includes 匹配
|
|
1070
|
-
if (trimmed.includes(marker + ':')
|
|
1199
|
+
if (trimmed.includes(marker + ':')) {
|
|
1071
1200
|
const idx = trimmed.indexOf(marker + ':');
|
|
1072
1201
|
const cwd = trimmed.substring(idx + marker.length + 1).trim();
|
|
1073
|
-
if (
|
|
1074
|
-
console.log(`[SSH]
|
|
1202
|
+
if (isValidCwd(cwd)) {
|
|
1203
|
+
console.log(`[SSH] probeCwdViaShell parsed (fallback): '${cwd}'`);
|
|
1075
1204
|
return cwd;
|
|
1076
1205
|
}
|
|
1077
1206
|
}
|
|
1078
1207
|
}
|
|
1079
|
-
console.log(`[SSH]
|
|
1208
|
+
console.log(`[SSH] probeCwdViaShell: no marker found: ${JSON.stringify(cleaned.substring(0, 500))}`);
|
|
1080
1209
|
return '';
|
|
1081
1210
|
}
|
|
1082
1211
|
|
|
1212
|
+
/**
|
|
1213
|
+
* 通过 SSH exec 独立通道获取交互式 shell 的工作目录
|
|
1214
|
+
* 不依赖交互式 shell 状态,即使 shell 卡在 rz/vim/异常状态也能工作
|
|
1215
|
+
*/
|
|
1216
|
+
private getSessionCwdViaExec(sessionId: string): Promise<string> {
|
|
1217
|
+
return new Promise((resolve) => {
|
|
1218
|
+
const session = this.sessions.get(sessionId);
|
|
1219
|
+
if (!session?.client) {
|
|
1220
|
+
resolve('');
|
|
1221
|
+
return;
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
// 通过 /proc 查找交互式 shell 进程的 CWD。
|
|
1225
|
+
// 关键:必须只匹配「stdin 是 tty(/dev/pts)」的 shell,排除本 exec 通道自己启动的
|
|
1226
|
+
// shell(它的 stdin 是管道、CWD 是 $HOME),否则会错误地返回家目录。
|
|
1227
|
+
const cmd = [
|
|
1228
|
+
'for pid in $(ls /proc 2>/dev/null | grep "^[0-9]*$"); do',
|
|
1229
|
+
' exe=$(readlink "/proc/$pid/exe" 2>/dev/null)',
|
|
1230
|
+
' case "$exe" in',
|
|
1231
|
+
' *bash*|*sh*|*zsh*|*dash*|*fish*|*tcsh*|*csh*)',
|
|
1232
|
+
' tty=$(readlink "/proc/$pid/fd/0" 2>/dev/null)',
|
|
1233
|
+
' case "$tty" in',
|
|
1234
|
+
' /dev/pts/*|/dev/tty*|/dev/console)',
|
|
1235
|
+
' cwd=$(readlink "/proc/$pid/cwd" 2>/dev/null)',
|
|
1236
|
+
' if [ -n "$cwd" ]; then echo "$cwd"; exit 0; fi',
|
|
1237
|
+
' ;;',
|
|
1238
|
+
' esac',
|
|
1239
|
+
' ;;',
|
|
1240
|
+
' esac',
|
|
1241
|
+
'done',
|
|
1242
|
+
'pwd'
|
|
1243
|
+
].join('\n');
|
|
1244
|
+
|
|
1245
|
+
let stdout = '';
|
|
1246
|
+
let stderr = '';
|
|
1247
|
+
const timeout = setTimeout(() => {
|
|
1248
|
+
console.log('[SSH] getSessionCwdViaExec: timeout');
|
|
1249
|
+
resolve('');
|
|
1250
|
+
}, 5000);
|
|
1251
|
+
|
|
1252
|
+
session.client.exec(cmd, (err: Error | undefined, stream: ClientChannel) => {
|
|
1253
|
+
if (err) {
|
|
1254
|
+
clearTimeout(timeout);
|
|
1255
|
+
console.log('[SSH] getSessionCwdViaExec error:', err.message);
|
|
1256
|
+
resolve('');
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
stream.on('data', (data: Buffer) => { stdout += data.toString('utf-8'); });
|
|
1260
|
+
stream.stderr.on('data', (data: Buffer) => { stderr += data.toString('utf-8'); });
|
|
1261
|
+
stream.on('close', () => {
|
|
1262
|
+
clearTimeout(timeout);
|
|
1263
|
+
const cwd = stdout.trim().split('\n')[0].trim();
|
|
1264
|
+
if (cwd && cwd.startsWith('/')) {
|
|
1265
|
+
console.log(`[SSH] getSessionCwdViaExec: '${cwd}'`);
|
|
1266
|
+
resolve(cwd);
|
|
1267
|
+
} else {
|
|
1268
|
+
console.log(`[SSH] getSessionCwdViaExec: no valid cwd, stdout: ${JSON.stringify(stdout.substring(0, 200))}, stderr: ${JSON.stringify(stderr.substring(0, 200))}`);
|
|
1269
|
+
resolve('');
|
|
1270
|
+
}
|
|
1271
|
+
});
|
|
1272
|
+
});
|
|
1273
|
+
});
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1083
1276
|
/**
|
|
1084
1277
|
* 通过 SFTP 上传文件到远程服务器(绕过 PTY,速度快)
|
|
1085
1278
|
* @param sessionId 会话 ID
|
|
@@ -1090,8 +1283,22 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1090
1283
|
async uploadFileViaSftp(sessionId: string, remotePath: string, fileBuffer: Buffer): Promise<number> {
|
|
1091
1284
|
const session = this.sessions.get(sessionId);
|
|
1092
1285
|
if (!session) throw new Error('Session not found: ' + sessionId);
|
|
1286
|
+
|
|
1287
|
+
// 本地会话:直接写文件
|
|
1288
|
+
if (session.type === 'local') {
|
|
1289
|
+
let fullPath = remotePath;
|
|
1290
|
+
if (!remotePath.startsWith('/')) {
|
|
1291
|
+
const cwd = process.cwd();
|
|
1292
|
+
fullPath = path.resolve(cwd, remotePath);
|
|
1293
|
+
}
|
|
1294
|
+
const buf = Buffer.isBuffer(fileBuffer) ? fileBuffer : Buffer.from(fileBuffer);
|
|
1295
|
+
await fs.promises.writeFile(fullPath, buf);
|
|
1296
|
+
console.log(`[SSH] Local upload: ${buf.length} bytes -> ${fullPath}`);
|
|
1297
|
+
return buf.length;
|
|
1298
|
+
}
|
|
1299
|
+
|
|
1093
1300
|
if (session.type !== 'ssh' || !session.client) {
|
|
1094
|
-
throw new Error('
|
|
1301
|
+
throw new Error('File upload is only supported for SSH / local sessions');
|
|
1095
1302
|
}
|
|
1096
1303
|
|
|
1097
1304
|
console.log(`[SSH] SFTP upload: ${fileBuffer.length} bytes`);
|
|
@@ -1202,7 +1409,7 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1202
1409
|
console.log(`[SSH] Shell exec: ${mvCmd}`);
|
|
1203
1410
|
const mvMarker = `__AICmd_MV_${Date.now()}__`;
|
|
1204
1411
|
const captureP = this.captureOutput(sessionId, 5000);
|
|
1205
|
-
this.writeData(sessionId, `${mvCmd} && echo ${mvMarker}:OK || echo ${mvMarker}:FAIL\
|
|
1412
|
+
this.writeData(sessionId, `${mvCmd} && echo ${mvMarker}:OK || echo ${mvMarker}:FAIL\r`);
|
|
1206
1413
|
const mvOutput = await captureP;
|
|
1207
1414
|
console.log(`[SSH] mv output: ${JSON.stringify(mvOutput.substring(0, 200))}`);
|
|
1208
1415
|
|
|
@@ -1216,7 +1423,7 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1216
1423
|
console.log(`[SSH] mv failed, trying sudo mv...`);
|
|
1217
1424
|
const sudoMarker = `__AICmd_SUDO_${Date.now()}__`;
|
|
1218
1425
|
const sudoCaptureP = this.captureOutput(sessionId, 5000);
|
|
1219
|
-
this.writeData(sessionId, `sudo mv -f ${shellQuote(tmpPath)} ${shellQuote(fullPath)} && echo ${sudoMarker}:OK || echo ${sudoMarker}:FAIL\
|
|
1426
|
+
this.writeData(sessionId, `sudo mv -f ${shellQuote(tmpPath)} ${shellQuote(fullPath)} && echo ${sudoMarker}:OK || echo ${sudoMarker}:FAIL\r`);
|
|
1220
1427
|
const sudoOutput = await sudoCaptureP;
|
|
1221
1428
|
console.log(`[SSH] sudo mv output: ${JSON.stringify(sudoOutput.substring(0, 200))}`);
|
|
1222
1429
|
|
|
@@ -1311,4 +1518,272 @@ Write-Output "__DOCKER__: $dockerVer"
|
|
|
1311
1518
|
getActiveSessionIds(): string[] {
|
|
1312
1519
|
return Array.from(this.sessions.keys());
|
|
1313
1520
|
}
|
|
1521
|
+
|
|
1522
|
+
// ========== 文件管理(SFTP / 本地 fs) ==========
|
|
1523
|
+
|
|
1524
|
+
/**
|
|
1525
|
+
* 获取 SFTP 客户端(ssh2 的 sftp 子系统)
|
|
1526
|
+
*/
|
|
1527
|
+
private getSftp(sessionId: string): Promise<any> {
|
|
1528
|
+
const session = this.sessions.get(sessionId);
|
|
1529
|
+
if (!session || !session.client) {
|
|
1530
|
+
return Promise.reject(new Error('SFTP is only available for SSH sessions'));
|
|
1531
|
+
}
|
|
1532
|
+
return new Promise((resolve, reject) => {
|
|
1533
|
+
session.client!.sftp((err: Error | undefined, sftp: any) => {
|
|
1534
|
+
if (err) return reject(err);
|
|
1535
|
+
resolve(sftp);
|
|
1536
|
+
});
|
|
1537
|
+
});
|
|
1538
|
+
}
|
|
1539
|
+
|
|
1540
|
+
/**
|
|
1541
|
+
* 列出远程(或本地)目录内容
|
|
1542
|
+
*/
|
|
1543
|
+
async listDirectory(sessionId: string, remotePath: string): Promise<RemoteFileInfo[]> {
|
|
1544
|
+
const session = this.sessions.get(sessionId);
|
|
1545
|
+
if (!session) throw new Error('Session not found: ' + sessionId);
|
|
1546
|
+
|
|
1547
|
+
if (session.type === 'ssh' && session.client) {
|
|
1548
|
+
return this.listViaSftp(sessionId, remotePath);
|
|
1549
|
+
}
|
|
1550
|
+
if (session.type === 'local') {
|
|
1551
|
+
return this.listViaLocal(remotePath);
|
|
1552
|
+
}
|
|
1553
|
+
throw new Error('File management is only supported for SSH / local sessions');
|
|
1554
|
+
}
|
|
1555
|
+
|
|
1556
|
+
/**
|
|
1557
|
+
* 创建远程目录
|
|
1558
|
+
*/
|
|
1559
|
+
async makeDirectory(sessionId: string, remotePath: string): Promise<void> {
|
|
1560
|
+
const session = this.sessions.get(sessionId);
|
|
1561
|
+
if (!session) throw new Error('Session not found: ' + sessionId);
|
|
1562
|
+
if (session.type === 'ssh' && session.client) {
|
|
1563
|
+
const sftp = await this.getSftp(sessionId);
|
|
1564
|
+
await new Promise<void>((resolve, reject) => {
|
|
1565
|
+
sftp.mkdir(remotePath, (err: Error | undefined) => err ? reject(err) : resolve());
|
|
1566
|
+
});
|
|
1567
|
+
return;
|
|
1568
|
+
}
|
|
1569
|
+
if (session.type === 'local') {
|
|
1570
|
+
await fs.promises.mkdir(remotePath, { recursive: true });
|
|
1571
|
+
return;
|
|
1572
|
+
}
|
|
1573
|
+
throw new Error('File management is only supported for SSH / local sessions');
|
|
1574
|
+
}
|
|
1575
|
+
|
|
1576
|
+
/**
|
|
1577
|
+
* 删除远程文件或目录(目录递归删除)
|
|
1578
|
+
*/
|
|
1579
|
+
async removePath(sessionId: string, remotePath: string): Promise<void> {
|
|
1580
|
+
const session = this.sessions.get(sessionId);
|
|
1581
|
+
if (!session) throw new Error('Session not found: ' + sessionId);
|
|
1582
|
+
if (session.type === 'ssh' && session.client) {
|
|
1583
|
+
const sftp = await this.getSftp(sessionId);
|
|
1584
|
+
await this.removeRecursive(sftp, remotePath);
|
|
1585
|
+
return;
|
|
1586
|
+
}
|
|
1587
|
+
if (session.type === 'local') {
|
|
1588
|
+
await fs.promises.rm(remotePath, { recursive: true, force: true });
|
|
1589
|
+
return;
|
|
1590
|
+
}
|
|
1591
|
+
throw new Error('File management is only supported for SSH / local sessions');
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
/**
|
|
1595
|
+
* 重命名 / 移动远程文件或目录
|
|
1596
|
+
*/
|
|
1597
|
+
async renamePath(sessionId: string, oldPath: string, newPath: string): Promise<void> {
|
|
1598
|
+
const session = this.sessions.get(sessionId);
|
|
1599
|
+
if (!session) throw new Error('Session not found: ' + sessionId);
|
|
1600
|
+
if (session.type === 'ssh' && session.client) {
|
|
1601
|
+
const sftp = await this.getSftp(sessionId);
|
|
1602
|
+
await new Promise<void>((resolve, reject) => {
|
|
1603
|
+
sftp.rename(oldPath, newPath, (err: Error | undefined) => err ? reject(err) : resolve());
|
|
1604
|
+
});
|
|
1605
|
+
return;
|
|
1606
|
+
}
|
|
1607
|
+
if (session.type === 'local') {
|
|
1608
|
+
await fs.promises.rename(oldPath, newPath);
|
|
1609
|
+
return;
|
|
1610
|
+
}
|
|
1611
|
+
throw new Error('File management is only supported for SSH / local sessions');
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
/**
|
|
1615
|
+
* 下载远程文件,返回 Buffer
|
|
1616
|
+
*/
|
|
1617
|
+
async downloadFile(sessionId: string, remotePath: string): Promise<Buffer> {
|
|
1618
|
+
const session = this.sessions.get(sessionId);
|
|
1619
|
+
if (!session) throw new Error('Session not found: ' + sessionId);
|
|
1620
|
+
|
|
1621
|
+
const MAX_DOWNLOAD_SIZE = 200 * 1024 * 1024; // 200MB
|
|
1622
|
+
|
|
1623
|
+
if (session.type === 'ssh' && session.client) {
|
|
1624
|
+
const sftp = await this.getSftp(sessionId);
|
|
1625
|
+
// 预检查文件大小,防止大文件 OOM
|
|
1626
|
+
const stat = await new Promise<any>((resolve, reject) => {
|
|
1627
|
+
sftp.stat(remotePath, (err: Error | undefined, attrs: any) => err ? reject(err) : resolve(attrs));
|
|
1628
|
+
}).catch(() => null);
|
|
1629
|
+
if (stat && typeof stat.size === 'number' && stat.size > MAX_DOWNLOAD_SIZE) {
|
|
1630
|
+
throw new Error(`文件过大 (${(stat.size / 1024 / 1024).toFixed(1)}MB),超过 200MB 限制,请使用终端 scp/sz 下载`);
|
|
1631
|
+
}
|
|
1632
|
+
return new Promise<Buffer>((resolve, reject) => {
|
|
1633
|
+
const chunks: Buffer[] = [];
|
|
1634
|
+
const stream = sftp.createReadStream(remotePath);
|
|
1635
|
+
stream.on('data', (c: Buffer) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
|
|
1636
|
+
stream.on('end', () => resolve(Buffer.concat(chunks)));
|
|
1637
|
+
stream.on('error', (e: Error) => reject(e));
|
|
1638
|
+
});
|
|
1639
|
+
}
|
|
1640
|
+
if (session.type === 'local') {
|
|
1641
|
+
// 预检查本地文件大小
|
|
1642
|
+
const localStat = await fs.promises.stat(remotePath).catch(() => null);
|
|
1643
|
+
if (localStat && localStat.size > MAX_DOWNLOAD_SIZE) {
|
|
1644
|
+
throw new Error(`文件过大 (${(localStat.size / 1024 / 1024).toFixed(1)}MB),超过 200MB 限制,请使用终端 scp/sz 下载`);
|
|
1645
|
+
}
|
|
1646
|
+
return fs.promises.readFile(remotePath);
|
|
1647
|
+
}
|
|
1648
|
+
throw new Error('File management is only supported for SSH / local sessions');
|
|
1649
|
+
}
|
|
1650
|
+
|
|
1651
|
+
/**
|
|
1652
|
+
* 获取会话默认目录(SSH: SFTP 起始目录 / 本地: 用户家目录)
|
|
1653
|
+
*/
|
|
1654
|
+
async getDefaultDirectory(sessionId: string): Promise<string> {
|
|
1655
|
+
const session = this.sessions.get(sessionId);
|
|
1656
|
+
if (!session) throw new Error('Session not found: ' + sessionId);
|
|
1657
|
+
if (session.type === 'ssh' && session.client) {
|
|
1658
|
+
const sftp = await this.getSftp(sessionId);
|
|
1659
|
+
return new Promise<string>((resolve, reject) => {
|
|
1660
|
+
sftp.realpath('.', (err: Error | undefined, p: string) => err ? reject(err) : resolve(p));
|
|
1661
|
+
});
|
|
1662
|
+
}
|
|
1663
|
+
if (session.type === 'local') {
|
|
1664
|
+
return process.env.HOME || require('os').homedir();
|
|
1665
|
+
}
|
|
1666
|
+
throw new Error('File management is only supported for SSH / local sessions');
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
private async listViaSftp(sessionId: string, remotePath: string): Promise<RemoteFileInfo[]> {
|
|
1670
|
+
const sftp = await this.getSftp(sessionId);
|
|
1671
|
+
const list = await new Promise<any[]>((resolve, reject) => {
|
|
1672
|
+
sftp.readdir(remotePath, (err: Error | undefined, entries: any[]) => err ? reject(err) : resolve(entries));
|
|
1673
|
+
});
|
|
1674
|
+
const result: RemoteFileInfo[] = list
|
|
1675
|
+
.filter((e) => e.filename !== '.' && e.filename !== '..')
|
|
1676
|
+
.map((entry) => this.entryToInfo(entry, remotePath));
|
|
1677
|
+
return this.sortFileList(result);
|
|
1678
|
+
}
|
|
1679
|
+
|
|
1680
|
+
private async listViaLocal(localPath: string): Promise<RemoteFileInfo[]> {
|
|
1681
|
+
const base = localPath || process.env.HOME || require('os').homedir();
|
|
1682
|
+
const names = await fs.promises.readdir(base);
|
|
1683
|
+
const result: RemoteFileInfo[] = [];
|
|
1684
|
+
for (const name of names) {
|
|
1685
|
+
const full = path.join(base, name);
|
|
1686
|
+
let stats;
|
|
1687
|
+
try {
|
|
1688
|
+
stats = await fs.promises.lstat(full);
|
|
1689
|
+
} catch {
|
|
1690
|
+
continue;
|
|
1691
|
+
}
|
|
1692
|
+
result.push(this.statToInfo(name, full, stats));
|
|
1693
|
+
}
|
|
1694
|
+
return this.sortFileList(result);
|
|
1695
|
+
}
|
|
1696
|
+
|
|
1697
|
+
private entryToInfo(entry: any, parentPath: string): RemoteFileInfo {
|
|
1698
|
+
const attrs = entry.attrs || {};
|
|
1699
|
+
const mode = attrs.mode || 0;
|
|
1700
|
+
const isDirectory = (mode & 0o170000) === 0o040000;
|
|
1701
|
+
const isSymbolicLink = (mode & 0o170000) === 0o120000;
|
|
1702
|
+
return {
|
|
1703
|
+
name: entry.filename,
|
|
1704
|
+
path: parentPath.replace(/\/$/, '') + '/' + entry.filename,
|
|
1705
|
+
size: attrs.size ?? 0,
|
|
1706
|
+
mtime: (attrs.mtime ?? 0) * 1000,
|
|
1707
|
+
atime: (attrs.atime ?? 0) * 1000,
|
|
1708
|
+
isDirectory,
|
|
1709
|
+
isFile: (mode & 0o170000) === 0o100000,
|
|
1710
|
+
isSymbolicLink,
|
|
1711
|
+
mode,
|
|
1712
|
+
permissions: modeToPermissions(mode),
|
|
1713
|
+
owner: String(attrs.uid ?? ''),
|
|
1714
|
+
group: String(attrs.gid ?? ''),
|
|
1715
|
+
};
|
|
1716
|
+
}
|
|
1717
|
+
|
|
1718
|
+
private statToInfo(name: string, full: string, stats: fs.Stats): RemoteFileInfo {
|
|
1719
|
+
const mode = stats.mode;
|
|
1720
|
+
const isDirectory = stats.isDirectory();
|
|
1721
|
+
const isSymbolicLink = stats.isSymbolicLink();
|
|
1722
|
+
return {
|
|
1723
|
+
name,
|
|
1724
|
+
path: full,
|
|
1725
|
+
size: stats.size,
|
|
1726
|
+
mtime: stats.mtimeMs,
|
|
1727
|
+
atime: stats.atimeMs,
|
|
1728
|
+
isDirectory,
|
|
1729
|
+
isFile: stats.isFile(),
|
|
1730
|
+
isSymbolicLink,
|
|
1731
|
+
mode,
|
|
1732
|
+
permissions: modeToPermissions(mode),
|
|
1733
|
+
owner: String(stats.uid),
|
|
1734
|
+
group: String(stats.gid),
|
|
1735
|
+
};
|
|
1736
|
+
}
|
|
1737
|
+
|
|
1738
|
+
private sortFileList(list: RemoteFileInfo[]): RemoteFileInfo[] {
|
|
1739
|
+
return list.sort((a, b) => {
|
|
1740
|
+
if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;
|
|
1741
|
+
return a.name.localeCompare(b.name);
|
|
1742
|
+
});
|
|
1743
|
+
}
|
|
1744
|
+
|
|
1745
|
+
private async removeRecursive(sftp: any, p: string): Promise<void> {
|
|
1746
|
+
const stat = await new Promise<any>((resolve, reject) => {
|
|
1747
|
+
sftp.lstat(p, (err: Error | undefined, attrs: any) => err ? reject(err) : resolve(attrs));
|
|
1748
|
+
}).catch((e) => { console.warn(`[SSH] removeRecursive: lstat failed for ${p}:`, e?.message || e); return null; });
|
|
1749
|
+
if (!stat) {
|
|
1750
|
+
console.warn(`[SSH] removeRecursive: skipping ${p} (unable to stat)`);
|
|
1751
|
+
return;
|
|
1752
|
+
}
|
|
1753
|
+
const mode = stat.mode || 0;
|
|
1754
|
+
if ((mode & 0o170000) === 0o040000) {
|
|
1755
|
+
const list = await new Promise<any[]>((resolve, reject) => {
|
|
1756
|
+
sftp.readdir(p, (err: Error | undefined, entries: any[]) => err ? reject(err) : resolve(entries));
|
|
1757
|
+
});
|
|
1758
|
+
for (const item of list) {
|
|
1759
|
+
if (item.filename === '.' || item.filename === '..') continue;
|
|
1760
|
+
await this.removeRecursive(sftp, p.replace(/\/$/, '') + '/' + item.filename);
|
|
1761
|
+
}
|
|
1762
|
+
await new Promise<void>((resolve, reject) => {
|
|
1763
|
+
sftp.rmdir(p, (err: Error | undefined) => err ? reject(err) : resolve());
|
|
1764
|
+
});
|
|
1765
|
+
} else {
|
|
1766
|
+
await new Promise<void>((resolve, reject) => {
|
|
1767
|
+
sftp.unlink(p, (err: Error | undefined) => err ? reject(err) : resolve());
|
|
1768
|
+
});
|
|
1769
|
+
}
|
|
1770
|
+
}
|
|
1771
|
+
}
|
|
1772
|
+
|
|
1773
|
+
/** 将数字权限位转换为 ls -l 风格的字符串(如 'rwxr-xr-x'),处理 setuid/setgid/sticky 位 */
|
|
1774
|
+
export function modeToPermissions(mode: number): string {
|
|
1775
|
+
const typeChar =
|
|
1776
|
+
(mode & 0o170000) === 0o040000 ? 'd'
|
|
1777
|
+
: (mode & 0o170000) === 0o120000 ? 'l'
|
|
1778
|
+
: '-';
|
|
1779
|
+
const symbols = 'rwxrwxrwx';
|
|
1780
|
+
let str = '';
|
|
1781
|
+
for (let i = 0; i < 9; i++) {
|
|
1782
|
+
str += (mode & (1 << (8 - i))) ? symbols[i] : '-';
|
|
1783
|
+
}
|
|
1784
|
+
// 处理特殊权限位:setuid(4)、setgid(2)、sticky(1)
|
|
1785
|
+
if (mode & 0o4000) str = str.slice(0, 2) + (str[2] === 'x' ? 's' : 'S') + str.slice(3);
|
|
1786
|
+
if (mode & 0o2000) str = str.slice(0, 5) + (str[5] === 'x' ? 's' : 'S') + str.slice(6);
|
|
1787
|
+
if (mode & 0o1000) str = str.slice(0, 8) + (str[8] === 'x' ? 't' : 'T');
|
|
1788
|
+
return typeChar + str;
|
|
1314
1789
|
}
|