@fefeding/aicmd 1.0.12 → 1.0.14

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.
@@ -57,6 +57,26 @@ export interface SessionInfo {
57
57
  systemContext?: string;
58
58
  }
59
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
+
60
80
  /**
61
81
  * 终端会话管理服务
62
82
  * 支持 SSH 远程连接和本地 Shell
@@ -85,7 +105,7 @@ export class SSHService {
85
105
  /**
86
106
  * 创建会话(自动判断 SSH 或本地 shell)
87
107
  */
88
- async createSession(sessionId: string, connectionId: string, cols: number = 80, rows: number = 24, name?: string): Promise<TerminalSession> {
108
+ async createSession(sessionId: string, connectionId: string, cols: number = 80, rows: number = 24, name?: string, onLog?: (msg: string) => void): Promise<TerminalSession> {
89
109
  // 标记本实例曾创建过 session(用于定时清理判断)
90
110
  this.hasCreatedSession = true;
91
111
  // 如果已存在同 ID 的会话,先关闭
@@ -110,7 +130,7 @@ export class SSHService {
110
130
  createdAt: new Date(),
111
131
  updatedAt: new Date(),
112
132
  };
113
- const localSession = await this.createLocalSession(sessionId, connectionId, localConn, cols, rows, name);
133
+ const localSession = await this.createLocalSession(sessionId, connectionId, localConn, cols, rows, name, onLog);
114
134
  // 保存 session 元数据到 server 端
115
135
  this.sessionMetadata.set(sessionId, {
116
136
  sessionId,
@@ -131,9 +151,9 @@ export class SSHService {
131
151
 
132
152
  let session: TerminalSession;
133
153
  if (connection.type === 'local') {
134
- session = await this.createLocalSession(sessionId, connectionId, connection, cols, rows, name);
154
+ session = await this.createLocalSession(sessionId, connectionId, connection, cols, rows, name, onLog);
135
155
  } else {
136
- session = await this.createSSHSession(sessionId, connectionId, connection, cols, rows, name);
156
+ session = await this.createSSHSession(sessionId, connectionId, connection, cols, rows, name, onLog);
137
157
  }
138
158
 
139
159
  // 保存 session 元数据(SSH 会话的 systemContext 通过 MOTD 自动采集)
@@ -163,12 +183,14 @@ export class SSHService {
163
183
  /**
164
184
  * 创建本地 Shell 会话(优先使用 node-pty,降级使用 child_process.spawn)
165
185
  */
166
- private createLocalSession(sessionId: string, connectionId: string, connection: ConnectionEntity, cols: number, rows: number, name?: string): Promise<TerminalSession> {
186
+ private createLocalSession(sessionId: string, connectionId: string, connection: ConnectionEntity, cols: number, rows: number, name?: string, onLog?: (msg: string) => void): Promise<TerminalSession> {
187
+ const log = (msg: string) => { console.log(`[SSH] ${msg}`); onLog?.(msg); };
167
188
  return new Promise<TerminalSession>((resolve, reject) => {
168
189
  try {
169
190
  const sessionName = name || connection.name || '本地 Shell';
170
191
  const shell = connection.shell || this.getDefaultShell();
171
192
  const homeDir = os.homedir();
193
+ log(`启动本地 Shell: ${shell}`);
172
194
 
173
195
  // 构建干净的 Shell 环境(过滤掉 Node.js / npm 相关变量,避免 nvm 等工具警告)
174
196
  const cleanEnv = this.buildShellEnv(cols, rows);
@@ -267,19 +289,24 @@ export class SSHService {
267
289
  /**
268
290
  * 创建 SSH 会话
269
291
  */
270
- private createSSHSession(sessionId: string, connectionId: string, connection: ConnectionEntity, cols: number, rows: number, name?: string): Promise<TerminalSession> {
292
+ private createSSHSession(sessionId: string, connectionId: string, connection: ConnectionEntity, cols: number, rows: number, name?: string, onLog?: (msg: string) => void): Promise<TerminalSession> {
293
+ const log = (msg: string) => { console.log(`[SSH] ${msg}`); onLog?.(msg); };
271
294
  return new Promise<TerminalSession>((resolve, reject) => {
272
- const sshConfig = this.connectionService.getSSHConfig(connection);
295
+ const sshConfig = this.connectionService.getSSHConfig(connection, onLog);
273
296
  const client = new Client();
274
297
  const sessionName = name || connection.name || 'SSH';
275
298
 
299
+ log(`正在连接到 ${connection.host}:${connection.port || 22} (用户: ${connection.username})`);
300
+
276
301
  const timeout = setTimeout(() => {
277
302
  client.end();
303
+ log(`连接超时 (30s)`);
278
304
  reject(new Error('SSH 连接超时'));
279
305
  }, 30000);
280
306
 
281
307
  client.on('ready', () => {
282
308
  clearTimeout(timeout);
309
+ log(`SSH 认证成功,正在打开 shell...`);
283
310
 
284
311
  const shellOpts: any = {
285
312
  term: 'xterm-256color',
@@ -293,11 +320,14 @@ export class SSHService {
293
320
 
294
321
  client.shell(shellOpts, (err: Error | undefined, stream: ClientChannel) => {
295
322
  if (err) {
323
+ log(`打开 shell 失败: ${err.message}`);
296
324
  client.end();
297
325
  reject(err);
298
326
  return;
299
327
  }
300
328
 
329
+ log(`Shell 会话已建立`);
330
+
301
331
  const session: TerminalSession = {
302
332
  id: sessionId,
303
333
  connectionId,
@@ -316,13 +346,14 @@ export class SSHService {
316
346
  }, 1500);
317
347
 
318
348
  stream.on('close', () => {
349
+ log(`Shell 流已关闭`);
319
350
  this.sessions.delete(sessionId);
320
351
  });
321
352
 
322
353
  // Execute startup script if configured (e.g. jump host SSH hop)
323
354
  if (connection.startupScript && connection.startupScript.trim()) {
324
355
  const script = connection.startupScript.trim();
325
- console.log(`[SSH] Executing startup script for session ${sessionId}: ${script.substring(0, 80)}`);
356
+ log(`执行启动脚本: ${script.substring(0, 80)}`);
326
357
  // Delay slightly to let the remote shell fully initialize
327
358
  setTimeout(() => {
328
359
  if (this.sessions.has(sessionId)) {
@@ -335,6 +366,7 @@ export class SSHService {
335
366
  });
336
367
  }).on('error', (err: Error) => {
337
368
  clearTimeout(timeout);
369
+ log(`连接错误: ${err.message}`);
338
370
  reject(err);
339
371
  }).connect(sshConfig);
340
372
  });
@@ -1263,8 +1295,22 @@ Write-Output "__DOCKER__: $dockerVer"
1263
1295
  async uploadFileViaSftp(sessionId: string, remotePath: string, fileBuffer: Buffer): Promise<number> {
1264
1296
  const session = this.sessions.get(sessionId);
1265
1297
  if (!session) throw new Error('Session not found: ' + sessionId);
1298
+
1299
+ // 本地会话:直接写文件
1300
+ if (session.type === 'local') {
1301
+ let fullPath = remotePath;
1302
+ if (!remotePath.startsWith('/')) {
1303
+ const cwd = process.cwd();
1304
+ fullPath = path.resolve(cwd, remotePath);
1305
+ }
1306
+ const buf = Buffer.isBuffer(fileBuffer) ? fileBuffer : Buffer.from(fileBuffer);
1307
+ await fs.promises.writeFile(fullPath, buf);
1308
+ console.log(`[SSH] Local upload: ${buf.length} bytes -> ${fullPath}`);
1309
+ return buf.length;
1310
+ }
1311
+
1266
1312
  if (session.type !== 'ssh' || !session.client) {
1267
- throw new Error('SFTP upload only supported for SSH sessions');
1313
+ throw new Error('File upload is only supported for SSH / local sessions');
1268
1314
  }
1269
1315
 
1270
1316
  console.log(`[SSH] SFTP upload: ${fileBuffer.length} bytes`);
@@ -1484,4 +1530,272 @@ Write-Output "__DOCKER__: $dockerVer"
1484
1530
  getActiveSessionIds(): string[] {
1485
1531
  return Array.from(this.sessions.keys());
1486
1532
  }
1533
+
1534
+ // ========== 文件管理(SFTP / 本地 fs) ==========
1535
+
1536
+ /**
1537
+ * 获取 SFTP 客户端(ssh2 的 sftp 子系统)
1538
+ */
1539
+ private getSftp(sessionId: string): Promise<any> {
1540
+ const session = this.sessions.get(sessionId);
1541
+ if (!session || !session.client) {
1542
+ return Promise.reject(new Error('SFTP is only available for SSH sessions'));
1543
+ }
1544
+ return new Promise((resolve, reject) => {
1545
+ session.client!.sftp((err: Error | undefined, sftp: any) => {
1546
+ if (err) return reject(err);
1547
+ resolve(sftp);
1548
+ });
1549
+ });
1550
+ }
1551
+
1552
+ /**
1553
+ * 列出远程(或本地)目录内容
1554
+ */
1555
+ async listDirectory(sessionId: string, remotePath: string): Promise<RemoteFileInfo[]> {
1556
+ const session = this.sessions.get(sessionId);
1557
+ if (!session) throw new Error('Session not found: ' + sessionId);
1558
+
1559
+ if (session.type === 'ssh' && session.client) {
1560
+ return this.listViaSftp(sessionId, remotePath);
1561
+ }
1562
+ if (session.type === 'local') {
1563
+ return this.listViaLocal(remotePath);
1564
+ }
1565
+ throw new Error('File management is only supported for SSH / local sessions');
1566
+ }
1567
+
1568
+ /**
1569
+ * 创建远程目录
1570
+ */
1571
+ async makeDirectory(sessionId: string, remotePath: string): Promise<void> {
1572
+ const session = this.sessions.get(sessionId);
1573
+ if (!session) throw new Error('Session not found: ' + sessionId);
1574
+ if (session.type === 'ssh' && session.client) {
1575
+ const sftp = await this.getSftp(sessionId);
1576
+ await new Promise<void>((resolve, reject) => {
1577
+ sftp.mkdir(remotePath, (err: Error | undefined) => err ? reject(err) : resolve());
1578
+ });
1579
+ return;
1580
+ }
1581
+ if (session.type === 'local') {
1582
+ await fs.promises.mkdir(remotePath, { recursive: true });
1583
+ return;
1584
+ }
1585
+ throw new Error('File management is only supported for SSH / local sessions');
1586
+ }
1587
+
1588
+ /**
1589
+ * 删除远程文件或目录(目录递归删除)
1590
+ */
1591
+ async removePath(sessionId: string, remotePath: string): Promise<void> {
1592
+ const session = this.sessions.get(sessionId);
1593
+ if (!session) throw new Error('Session not found: ' + sessionId);
1594
+ if (session.type === 'ssh' && session.client) {
1595
+ const sftp = await this.getSftp(sessionId);
1596
+ await this.removeRecursive(sftp, remotePath);
1597
+ return;
1598
+ }
1599
+ if (session.type === 'local') {
1600
+ await fs.promises.rm(remotePath, { recursive: true, force: true });
1601
+ return;
1602
+ }
1603
+ throw new Error('File management is only supported for SSH / local sessions');
1604
+ }
1605
+
1606
+ /**
1607
+ * 重命名 / 移动远程文件或目录
1608
+ */
1609
+ async renamePath(sessionId: string, oldPath: string, newPath: string): Promise<void> {
1610
+ const session = this.sessions.get(sessionId);
1611
+ if (!session) throw new Error('Session not found: ' + sessionId);
1612
+ if (session.type === 'ssh' && session.client) {
1613
+ const sftp = await this.getSftp(sessionId);
1614
+ await new Promise<void>((resolve, reject) => {
1615
+ sftp.rename(oldPath, newPath, (err: Error | undefined) => err ? reject(err) : resolve());
1616
+ });
1617
+ return;
1618
+ }
1619
+ if (session.type === 'local') {
1620
+ await fs.promises.rename(oldPath, newPath);
1621
+ return;
1622
+ }
1623
+ throw new Error('File management is only supported for SSH / local sessions');
1624
+ }
1625
+
1626
+ /**
1627
+ * 下载远程文件,返回 Buffer
1628
+ */
1629
+ async downloadFile(sessionId: string, remotePath: string): Promise<Buffer> {
1630
+ const session = this.sessions.get(sessionId);
1631
+ if (!session) throw new Error('Session not found: ' + sessionId);
1632
+
1633
+ const MAX_DOWNLOAD_SIZE = 200 * 1024 * 1024; // 200MB
1634
+
1635
+ if (session.type === 'ssh' && session.client) {
1636
+ const sftp = await this.getSftp(sessionId);
1637
+ // 预检查文件大小,防止大文件 OOM
1638
+ const stat = await new Promise<any>((resolve, reject) => {
1639
+ sftp.stat(remotePath, (err: Error | undefined, attrs: any) => err ? reject(err) : resolve(attrs));
1640
+ }).catch(() => null);
1641
+ if (stat && typeof stat.size === 'number' && stat.size > MAX_DOWNLOAD_SIZE) {
1642
+ throw new Error(`文件过大 (${(stat.size / 1024 / 1024).toFixed(1)}MB),超过 200MB 限制,请使用终端 scp/sz 下载`);
1643
+ }
1644
+ return new Promise<Buffer>((resolve, reject) => {
1645
+ const chunks: Buffer[] = [];
1646
+ const stream = sftp.createReadStream(remotePath);
1647
+ stream.on('data', (c: Buffer) => chunks.push(Buffer.isBuffer(c) ? c : Buffer.from(c)));
1648
+ stream.on('end', () => resolve(Buffer.concat(chunks)));
1649
+ stream.on('error', (e: Error) => reject(e));
1650
+ });
1651
+ }
1652
+ if (session.type === 'local') {
1653
+ // 预检查本地文件大小
1654
+ const localStat = await fs.promises.stat(remotePath).catch(() => null);
1655
+ if (localStat && localStat.size > MAX_DOWNLOAD_SIZE) {
1656
+ throw new Error(`文件过大 (${(localStat.size / 1024 / 1024).toFixed(1)}MB),超过 200MB 限制,请使用终端 scp/sz 下载`);
1657
+ }
1658
+ return fs.promises.readFile(remotePath);
1659
+ }
1660
+ throw new Error('File management is only supported for SSH / local sessions');
1661
+ }
1662
+
1663
+ /**
1664
+ * 获取会话默认目录(SSH: SFTP 起始目录 / 本地: 用户家目录)
1665
+ */
1666
+ async getDefaultDirectory(sessionId: string): Promise<string> {
1667
+ const session = this.sessions.get(sessionId);
1668
+ if (!session) throw new Error('Session not found: ' + sessionId);
1669
+ if (session.type === 'ssh' && session.client) {
1670
+ const sftp = await this.getSftp(sessionId);
1671
+ return new Promise<string>((resolve, reject) => {
1672
+ sftp.realpath('.', (err: Error | undefined, p: string) => err ? reject(err) : resolve(p));
1673
+ });
1674
+ }
1675
+ if (session.type === 'local') {
1676
+ return process.env.HOME || require('os').homedir();
1677
+ }
1678
+ throw new Error('File management is only supported for SSH / local sessions');
1679
+ }
1680
+
1681
+ private async listViaSftp(sessionId: string, remotePath: string): Promise<RemoteFileInfo[]> {
1682
+ const sftp = await this.getSftp(sessionId);
1683
+ const list = await new Promise<any[]>((resolve, reject) => {
1684
+ sftp.readdir(remotePath, (err: Error | undefined, entries: any[]) => err ? reject(err) : resolve(entries));
1685
+ });
1686
+ const result: RemoteFileInfo[] = list
1687
+ .filter((e) => e.filename !== '.' && e.filename !== '..')
1688
+ .map((entry) => this.entryToInfo(entry, remotePath));
1689
+ return this.sortFileList(result);
1690
+ }
1691
+
1692
+ private async listViaLocal(localPath: string): Promise<RemoteFileInfo[]> {
1693
+ const base = localPath || process.env.HOME || require('os').homedir();
1694
+ const names = await fs.promises.readdir(base);
1695
+ const result: RemoteFileInfo[] = [];
1696
+ for (const name of names) {
1697
+ const full = path.join(base, name);
1698
+ let stats;
1699
+ try {
1700
+ stats = await fs.promises.lstat(full);
1701
+ } catch {
1702
+ continue;
1703
+ }
1704
+ result.push(this.statToInfo(name, full, stats));
1705
+ }
1706
+ return this.sortFileList(result);
1707
+ }
1708
+
1709
+ private entryToInfo(entry: any, parentPath: string): RemoteFileInfo {
1710
+ const attrs = entry.attrs || {};
1711
+ const mode = attrs.mode || 0;
1712
+ const isDirectory = (mode & 0o170000) === 0o040000;
1713
+ const isSymbolicLink = (mode & 0o170000) === 0o120000;
1714
+ return {
1715
+ name: entry.filename,
1716
+ path: parentPath.replace(/\/$/, '') + '/' + entry.filename,
1717
+ size: attrs.size ?? 0,
1718
+ mtime: (attrs.mtime ?? 0) * 1000,
1719
+ atime: (attrs.atime ?? 0) * 1000,
1720
+ isDirectory,
1721
+ isFile: (mode & 0o170000) === 0o100000,
1722
+ isSymbolicLink,
1723
+ mode,
1724
+ permissions: modeToPermissions(mode),
1725
+ owner: String(attrs.uid ?? ''),
1726
+ group: String(attrs.gid ?? ''),
1727
+ };
1728
+ }
1729
+
1730
+ private statToInfo(name: string, full: string, stats: fs.Stats): RemoteFileInfo {
1731
+ const mode = stats.mode;
1732
+ const isDirectory = stats.isDirectory();
1733
+ const isSymbolicLink = stats.isSymbolicLink();
1734
+ return {
1735
+ name,
1736
+ path: full,
1737
+ size: stats.size,
1738
+ mtime: stats.mtimeMs,
1739
+ atime: stats.atimeMs,
1740
+ isDirectory,
1741
+ isFile: stats.isFile(),
1742
+ isSymbolicLink,
1743
+ mode,
1744
+ permissions: modeToPermissions(mode),
1745
+ owner: String(stats.uid),
1746
+ group: String(stats.gid),
1747
+ };
1748
+ }
1749
+
1750
+ private sortFileList(list: RemoteFileInfo[]): RemoteFileInfo[] {
1751
+ return list.sort((a, b) => {
1752
+ if (a.isDirectory !== b.isDirectory) return a.isDirectory ? -1 : 1;
1753
+ return a.name.localeCompare(b.name);
1754
+ });
1755
+ }
1756
+
1757
+ private async removeRecursive(sftp: any, p: string): Promise<void> {
1758
+ const stat = await new Promise<any>((resolve, reject) => {
1759
+ sftp.lstat(p, (err: Error | undefined, attrs: any) => err ? reject(err) : resolve(attrs));
1760
+ }).catch((e) => { console.warn(`[SSH] removeRecursive: lstat failed for ${p}:`, e?.message || e); return null; });
1761
+ if (!stat) {
1762
+ console.warn(`[SSH] removeRecursive: skipping ${p} (unable to stat)`);
1763
+ return;
1764
+ }
1765
+ const mode = stat.mode || 0;
1766
+ if ((mode & 0o170000) === 0o040000) {
1767
+ const list = await new Promise<any[]>((resolve, reject) => {
1768
+ sftp.readdir(p, (err: Error | undefined, entries: any[]) => err ? reject(err) : resolve(entries));
1769
+ });
1770
+ for (const item of list) {
1771
+ if (item.filename === '.' || item.filename === '..') continue;
1772
+ await this.removeRecursive(sftp, p.replace(/\/$/, '') + '/' + item.filename);
1773
+ }
1774
+ await new Promise<void>((resolve, reject) => {
1775
+ sftp.rmdir(p, (err: Error | undefined) => err ? reject(err) : resolve());
1776
+ });
1777
+ } else {
1778
+ await new Promise<void>((resolve, reject) => {
1779
+ sftp.unlink(p, (err: Error | undefined) => err ? reject(err) : resolve());
1780
+ });
1781
+ }
1782
+ }
1783
+ }
1784
+
1785
+ /** 将数字权限位转换为 ls -l 风格的字符串(如 'rwxr-xr-x'),处理 setuid/setgid/sticky 位 */
1786
+ export function modeToPermissions(mode: number): string {
1787
+ const typeChar =
1788
+ (mode & 0o170000) === 0o040000 ? 'd'
1789
+ : (mode & 0o170000) === 0o120000 ? 'l'
1790
+ : '-';
1791
+ const symbols = 'rwxrwxrwx';
1792
+ let str = '';
1793
+ for (let i = 0; i < 9; i++) {
1794
+ str += (mode & (1 << (8 - i))) ? symbols[i] : '-';
1795
+ }
1796
+ // 处理特殊权限位:setuid(4)、setgid(2)、sticky(1)
1797
+ if (mode & 0o4000) str = str.slice(0, 2) + (str[2] === 'x' ? 's' : 'S') + str.slice(3);
1798
+ if (mode & 0o2000) str = str.slice(0, 5) + (str[5] === 'x' ? 's' : 'S') + str.slice(6);
1799
+ if (mode & 0o1000) str = str.slice(0, 8) + (str[8] === 'x' ? 't' : 'T');
1800
+ return typeChar + str;
1487
1801
  }
package/electron/main.js CHANGED
@@ -132,6 +132,35 @@ function setupApiIPC() {
132
132
  }
133
133
  });
134
134
 
135
+ // 文件下载 IPC 处理(app:// 协议下 fetch 不可用;直接在主进程保存到用户选择路径)
136
+ ipcMain.handle('file:download', async (_event, payload) => {
137
+ const services = getServices();
138
+ if (!services) {
139
+ return { success: false, error: 'Services not available' };
140
+ }
141
+ try {
142
+ const { sessionId, remotePath, fileName } = payload || {};
143
+ if (!sessionId || !remotePath) {
144
+ return { success: false, error: 'Missing sessionId or remotePath' };
145
+ }
146
+ const buffer = await services.sshService.downloadFile(sessionId, remotePath);
147
+ const { dialog } = require('electron');
148
+ const defaultName = fileName || path.basename(remotePath) || 'download';
149
+ const { canceled, filePath } = await dialog.showSaveDialog({
150
+ title: 'Save file as',
151
+ defaultPath: path.join(os.homedir(), defaultName),
152
+ });
153
+ if (canceled || !filePath) {
154
+ return { success: false, canceled: true };
155
+ }
156
+ fs.writeFileSync(filePath, buffer);
157
+ return { success: true, filePath, size: buffer.length };
158
+ } catch (err) {
159
+ console.error('[IPC] File download error:', err);
160
+ return { success: false, error: err.message };
161
+ }
162
+ });
163
+
135
164
  // 查询当前终端所在目录(Electron 模式:上传前由前端拉取,确保文件落到当前目录)
136
165
  ipcMain.handle('terminal:get-cwd', async (_event, payload) => {
137
166
  const services = getServices();
@@ -63,6 +63,9 @@ const api = {
63
63
  getCwd(sessionId) {
64
64
  return ipcRenderer.invoke('terminal:get-cwd', { sessionId });
65
65
  },
66
+ downloadFile(sessionId, remotePath, fileName) {
67
+ return ipcRenderer.invoke('file:download', { sessionId, remotePath, fileName });
68
+ },
66
69
  };
67
70
 
68
71
  // 剪贴板操作
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fefeding/aicmd",
3
- "version": "1.0.12",
3
+ "version": "1.0.14",
4
4
  "private": false,
5
5
  "type": "commonjs",
6
6
  "description": "AI-powered web SSH terminal with autonomous agent, skills, and file transfer",
package/server.js CHANGED
@@ -159,6 +159,27 @@ app.get('/api/cwd', async (req, res) => {
159
159
  }
160
160
  });
161
161
 
162
+ // 文件下载端点:通过 SFTP 读取远程文件并以二进制流返回
163
+ app.get('/api/file/download', async (req, res) => {
164
+ const sessionId = req.headers['x-session-id'] || req.query.sessionId;
165
+ const filePath = req.query.path;
166
+ if (!sessionId || !filePath) {
167
+ return res.status(400).json({ success: false, error: 'Missing sessionId or path' });
168
+ }
169
+ try {
170
+ const serverModule = require('./dist/server/index.js');
171
+ const { sshService } = serverModule;
172
+ const buf = await sshService.downloadFile(String(sessionId), String(filePath));
173
+ const baseName = path.basename(String(filePath)) || 'download';
174
+ res.setHeader('Content-Disposition', `attachment; filename="${encodeURIComponent(baseName)}"`);
175
+ res.setHeader('Content-Type', 'application/octet-stream');
176
+ res.setHeader('Content-Length', buf.length);
177
+ res.end(buf);
178
+ } catch (err) {
179
+ res.status(500).json({ success: false, error: err.message || String(err) });
180
+ }
181
+ });
182
+
162
183
  // 处理 API 请求
163
184
  app.use('/api/', async (req, res, next) => {
164
185
  if (req.method === 'POST') {
@@ -206,7 +227,8 @@ try {
206
227
  serverModule.monitorService.onEvent((sid, event) => {
207
228
  const targetWs = wsBySessionId.get(sid);
208
229
  if (targetWs && targetWs.readyState === WebSocket.OPEN) {
209
- targetWs.send(JSON.stringify({ type: 'monitor-event', sessionId: sid, event }));
230
+ try { targetWs.send(JSON.stringify({ type: 'monitor-event', sessionId: sid, event })); }
231
+ catch(e) { console.warn('[WS] monitor-event send error:', e.code, e.message); }
210
232
  }
211
233
  });
212
234
  }
@@ -224,6 +246,23 @@ wss.on('connection', async (ws, req) => {
224
246
  let sessionId = null;
225
247
  console.log(`[WS] Client connected from ${req.socket.remoteAddress}`);
226
248
 
249
+ // 安全发送 WebSocket 消息:捕获 EAGAIN 等写入异常,防止未处理的 'error' 事件导致进程崩溃
250
+ // highFreq=true 时启用背压检测,缓冲区超过阈值则丢弃该消息(终端输出可丢帧,不影响连接)
251
+ const WS_BACKPRESSURE_LIMIT = 4 * 1024 * 1024; // 4MB
252
+ function safeSend(data, highFreq = false) {
253
+ if (ws.readyState !== WebSocket.OPEN) return;
254
+ if (highFreq && ws.bufferedAmount > WS_BACKPRESSURE_LIMIT) {
255
+ console.warn(`[WS] Backpressure: dropping message (buffered: ${ws.bufferedAmount} bytes)`);
256
+ return;
257
+ }
258
+ try {
259
+ ws.send(data);
260
+ } catch (err) {
261
+ // EAGAIN / ECONNRESET / EPIPE 等 — 记录但不崩溃
262
+ console.warn(`[WS] safeSend error (code=${err.code}): ${err.message}`);
263
+ }
264
+ }
265
+
227
266
  // 提取会话创建逻辑,供 create 和 reconnect 复用
228
267
  async function createSSHSession(sid, data) {
229
268
  const serverModule = require('./dist/server/index.js');
@@ -237,30 +276,32 @@ wss.on('connection', async (ws, req) => {
237
276
  sessionId = sid || `ssh-${Date.now()}-${Math.random().toString(36).substr(2, 8)}`;
238
277
  console.log(`[WS] Creating SSH session: ${sessionId}, connectionId: ${connectionId}`);
239
278
 
240
- const session = await sshService.createSession(sessionId, connectionId, cols || 80, rows || 24, name);
279
+ // 将连接过程日志推送到前端终端信息流
280
+ // 使用独立的 conn-log 类型,避免经过 ZMODEM sentry 处理被吞掉
281
+ const sendLog = (msg) => {
282
+ safeSend(JSON.stringify({ type: 'conn-log', sessionId, data: msg }));
283
+ };
284
+
285
+ const session = await sshService.createSession(sessionId, connectionId, cols || 80, rows || 24, name, sendLog);
241
286
  console.log(`[WS] SSH session created: ${sessionId}`);
242
287
 
243
288
  // 根据会话类型绑定输出和关闭事件
244
289
  const sendOutput = (chunk) => {
245
- if (ws.readyState === WebSocket.OPEN) {
246
- const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
247
- const hasBinary = buf.some(b => b > 127);
248
- // 通知输出监听器(用于 Agent 捕获输出)
249
- if (!hasBinary) {
250
- try { sshService.notifyOutput(sessionId, buf.toString('utf-8')); } catch(e) {}
251
- }
252
- if (hasBinary) {
253
- ws.send(JSON.stringify({ type: 'terminal', sessionId, data: buf.toString('base64'), binary: true }));
254
- } else {
255
- ws.send(JSON.stringify({ type: 'terminal', sessionId, data: buf.toString('utf-8') }));
256
- }
290
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
291
+ const hasBinary = buf.some(b => b > 127);
292
+ // 通知输出监听器(用于 Agent 捕获输出)
293
+ if (!hasBinary) {
294
+ try { sshService.notifyOutput(sessionId, buf.toString('utf-8')); } catch(e) {}
295
+ }
296
+ if (hasBinary) {
297
+ safeSend(JSON.stringify({ type: 'terminal', sessionId, data: buf.toString('base64'), binary: true }), true);
298
+ } else {
299
+ safeSend(JSON.stringify({ type: 'terminal', sessionId, data: buf.toString('utf-8') }), true);
257
300
  }
258
301
  };
259
302
  const sendClose = (source) => () => {
260
303
  console.log(`[WS] ${source} closed: ${sessionId}`);
261
- if (ws.readyState === WebSocket.OPEN) {
262
- ws.send(JSON.stringify({ type: 'close', sessionId }));
263
- }
304
+ safeSend(JSON.stringify({ type: 'close', sessionId }));
264
305
  };
265
306
 
266
307
  if (session.pty) {
@@ -275,7 +316,7 @@ wss.on('connection', async (ws, req) => {
275
316
  session.stream.on('close', sendClose('SSH stream'));
276
317
  }
277
318
 
278
- ws.send(JSON.stringify({ type: 'status', sessionId, data: 'connected' }));
319
+ safeSend(JSON.stringify({ type: 'status', sessionId, data: 'connected' }));
279
320
  // 注册 sessionId -> ws 映射
280
321
  wsBySessionId.set(sessionId, ws);
281
322
  console.log(`[WS] Session ${sessionId} connected, status sent`);
@@ -565,8 +606,24 @@ wss.on('connection', async (ws, req) => {
565
606
  });
566
607
 
567
608
  ws.on('error', (err) => {
609
+ // EAGAIN 等可恢复错误仅警告,不中断连接
610
+ if (err && (err.code === 'EAGAIN' || err.code === 'ECONNRESET' || err.code === 'EPIPE')) {
611
+ console.warn('[WS] Recoverable socket error (code=%s): %s', err.code, err.message);
612
+ return;
613
+ }
568
614
  console.error('[WS] WebSocket error:', err);
569
615
  });
616
+
617
+ // 捕获底层 socket 的 error 事件,防止 EAGAIN 等错误成为未捕获异常导致进程崩溃
618
+ if (ws._socket) {
619
+ ws._socket.on('error', (err) => {
620
+ if (err && (err.code === 'EAGAIN' || err.code === 'ECONNRESET' || err.code === 'EPIPE')) {
621
+ console.warn('[WS] Socket recoverable error (code=%s): %s', err.code, err.message);
622
+ } else {
623
+ console.error('[WS] Socket error:', err);
624
+ }
625
+ });
626
+ }
570
627
  });
571
628
 
572
629
  // 解析命令行参数获取端口
@@ -601,14 +658,19 @@ process.on('exit', () => { cleanupPid(); logStream.end(); });
601
658
  process.on('SIGTERM', () => { cleanupPid(); process.exit(0); });
602
659
  process.on('SIGINT', () => { cleanupPid(); process.exit(0); });
603
660
  process.on('uncaughtException', (err) => {
661
+ // EAGAIN 等可恢复错误不退出进程
662
+ if (err && (err.code === 'EAGAIN' || err.code === 'ECONNRESET' || err.code === 'EPIPE')) {
663
+ console.warn('[Process] Recoverable socket error (code=%s): %s', err.code, err.message);
664
+ return;
665
+ }
604
666
  console.error('Uncaught exception:', err);
605
- cleanupPid();
606
- logStream.end();
667
+ try { cleanupPid(); } catch(e) {}
668
+ try { logStream.end(); } catch(e) {}
607
669
  process.exit(1);
608
670
  });
609
671
  process.on('unhandledRejection', (err) => {
610
672
  console.error('Unhandled rejection:', err);
611
- cleanupPid();
612
- logStream.end();
673
+ try { cleanupPid(); } catch(e) {}
674
+ try { logStream.end(); } catch(e) {}
613
675
  process.exit(1);
614
676
  });