@pyrokine/mcp-ssh 2.0.2 → 2.1.0
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/README.md +100 -19
- package/README_zh.md +94 -18
- package/dist/file-ops.d.ts +67 -5
- package/dist/file-ops.js +400 -81
- package/dist/pty-manager.d.ts +6 -0
- package/dist/pty-manager.js +19 -0
- package/dist/session-manager.d.ts +14 -0
- package/dist/session-manager.js +254 -78
- package/dist/tools/connection.js +106 -20
- package/dist/tools/exec.js +201 -9
- package/dist/tools/file.js +288 -8
- package/dist/tools/forward.js +2 -2
- package/dist/tools/pty.js +1 -1
- package/dist/tools/utils.js +9 -1
- package/dist/types.d.ts +38 -0
- package/package.json +7 -7
package/dist/pty-manager.d.ts
CHANGED
|
@@ -27,6 +27,12 @@ export declare class PtyManager {
|
|
|
27
27
|
active: boolean;
|
|
28
28
|
rows: number;
|
|
29
29
|
cols: number;
|
|
30
|
+
lastInputAt: number | null;
|
|
31
|
+
lastOutputAt: number | null;
|
|
32
|
+
lastReadAt: number;
|
|
33
|
+
unreadRawBytes: number;
|
|
34
|
+
rawBufferLimit: number;
|
|
35
|
+
foregroundProcess: string;
|
|
30
36
|
};
|
|
31
37
|
resize(ptyId: string, rows: number, cols: number): boolean;
|
|
32
38
|
close(ptyId: string): boolean;
|
package/dist/pty-manager.js
CHANGED
|
@@ -32,8 +32,11 @@ export class PtyManager {
|
|
|
32
32
|
rows,
|
|
33
33
|
cols,
|
|
34
34
|
createdAt: Date.now(),
|
|
35
|
+
lastInputAt: null,
|
|
36
|
+
lastOutputAt: null,
|
|
35
37
|
lastReadAt: Date.now(),
|
|
36
38
|
rawBuffer: '',
|
|
39
|
+
unreadRawBytes: 0,
|
|
37
40
|
maxBufferSize,
|
|
38
41
|
active: true,
|
|
39
42
|
};
|
|
@@ -43,12 +46,15 @@ export class PtyManager {
|
|
|
43
46
|
return;
|
|
44
47
|
}
|
|
45
48
|
const chunk = data.toString('utf-8');
|
|
49
|
+
ptySession.lastOutputAt = Date.now();
|
|
46
50
|
// 写入终端仿真器(解析 ANSI 序列)
|
|
47
51
|
terminal.write(chunk);
|
|
48
52
|
// 同时保留原始流(用于 raw 模式)
|
|
49
53
|
ptySession.rawBuffer += chunk;
|
|
54
|
+
ptySession.unreadRawBytes += Buffer.byteLength(chunk, 'utf-8');
|
|
50
55
|
if (ptySession.rawBuffer.length > maxBufferSize) {
|
|
51
56
|
ptySession.rawBuffer = ptySession.rawBuffer.slice(-maxBufferSize);
|
|
57
|
+
ptySession.unreadRawBytes = Math.min(ptySession.unreadRawBytes, Buffer.byteLength(ptySession.rawBuffer, 'utf-8'));
|
|
52
58
|
}
|
|
53
59
|
});
|
|
54
60
|
stream.on('close', () => {
|
|
@@ -73,6 +79,7 @@ export class PtyManager {
|
|
|
73
79
|
if (!session.active) {
|
|
74
80
|
throw new Error(`PTY session '${ptyId}' is closed`);
|
|
75
81
|
}
|
|
82
|
+
session.lastInputAt = Date.now();
|
|
76
83
|
return session.stream.write(data);
|
|
77
84
|
}
|
|
78
85
|
read(ptyId, options = {}) {
|
|
@@ -87,6 +94,7 @@ export class PtyManager {
|
|
|
87
94
|
data = session.rawBuffer;
|
|
88
95
|
if (clear) {
|
|
89
96
|
session.rawBuffer = '';
|
|
97
|
+
session.unreadRawBytes = 0;
|
|
90
98
|
}
|
|
91
99
|
}
|
|
92
100
|
session.lastReadAt = Date.now();
|
|
@@ -95,6 +103,12 @@ export class PtyManager {
|
|
|
95
103
|
active: session.active,
|
|
96
104
|
rows: session.rows,
|
|
97
105
|
cols: session.cols,
|
|
106
|
+
lastInputAt: session.lastInputAt,
|
|
107
|
+
lastOutputAt: session.lastOutputAt,
|
|
108
|
+
lastReadAt: session.lastReadAt,
|
|
109
|
+
unreadRawBytes: session.unreadRawBytes,
|
|
110
|
+
rawBufferLimit: session.maxBufferSize,
|
|
111
|
+
foregroundProcess: session.command,
|
|
98
112
|
};
|
|
99
113
|
}
|
|
100
114
|
resize(ptyId, rows, cols) {
|
|
@@ -147,8 +161,13 @@ export class PtyManager {
|
|
|
147
161
|
rows: pty.rows,
|
|
148
162
|
cols: pty.cols,
|
|
149
163
|
createdAt: pty.createdAt,
|
|
164
|
+
lastInputAt: pty.lastInputAt,
|
|
165
|
+
lastOutputAt: pty.lastOutputAt,
|
|
150
166
|
lastReadAt: pty.lastReadAt,
|
|
151
167
|
bufferSize: pty.rawBuffer.length,
|
|
168
|
+
unreadRawBytes: pty.unreadRawBytes,
|
|
169
|
+
rawBufferLimit: pty.maxBufferSize,
|
|
170
|
+
foregroundProcess: pty.command,
|
|
152
171
|
active: pty.active,
|
|
153
172
|
});
|
|
154
173
|
}
|
|
@@ -91,6 +91,12 @@ export declare class SessionManager {
|
|
|
91
91
|
active: boolean;
|
|
92
92
|
rows: number;
|
|
93
93
|
cols: number;
|
|
94
|
+
lastInputAt: number | null;
|
|
95
|
+
lastOutputAt: number | null;
|
|
96
|
+
lastReadAt: number;
|
|
97
|
+
unreadRawBytes: number;
|
|
98
|
+
rawBufferLimit: number;
|
|
99
|
+
foregroundProcess: string;
|
|
94
100
|
};
|
|
95
101
|
ptyResize(ptyId: string, rows: number, cols: number): boolean;
|
|
96
102
|
ptyClose(ptyId: string): boolean;
|
|
@@ -102,6 +108,13 @@ export declare class SessionManager {
|
|
|
102
108
|
forwardRemote(alias: string, remotePort: number, localHost: string, localPort: number, remoteHost?: string): Promise<string>;
|
|
103
109
|
forwardClose(forwardId: string): boolean;
|
|
104
110
|
forwardList(): PortForwardInfo[];
|
|
111
|
+
private sessionIdentity;
|
|
112
|
+
private configIdentity;
|
|
113
|
+
private resultMetadata;
|
|
114
|
+
private appendOutputTail;
|
|
115
|
+
private recommendedReadCommand;
|
|
116
|
+
private outputMetadata;
|
|
117
|
+
private execDirect;
|
|
105
118
|
private connectInternal;
|
|
106
119
|
/**
|
|
107
120
|
* 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
|
|
@@ -124,6 +137,7 @@ export declare class SessionManager {
|
|
|
124
137
|
* 调度自动重连(支持多次重试)
|
|
125
138
|
*/
|
|
126
139
|
private scheduleReconnect;
|
|
140
|
+
private createCommandTimeoutError;
|
|
127
141
|
/**
|
|
128
142
|
* 根据错误类型生成排查建议
|
|
129
143
|
*/
|
package/dist/session-manager.js
CHANGED
|
@@ -16,6 +16,15 @@ import { ForwardManager } from './forward-manager.js';
|
|
|
16
16
|
import { PtyManager } from './pty-manager.js';
|
|
17
17
|
import { sanitizeKeyError, validateKeyFile } from './security.js';
|
|
18
18
|
import { escapeShellArg, expandTilde } from './tools/utils.js';
|
|
19
|
+
const OUTPUT_PREVIEW_CHARS = 4096;
|
|
20
|
+
class CommandError extends Error {
|
|
21
|
+
details;
|
|
22
|
+
constructor(message, details) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.details = details;
|
|
25
|
+
this.name = 'CommandError';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
19
28
|
export class SessionManager {
|
|
20
29
|
sessions = new Map();
|
|
21
30
|
/** per-alias connect 进行中的 Promise,防止并发 connect 同一 alias 时重复建连 */
|
|
@@ -123,11 +132,21 @@ export class SessionManager {
|
|
|
123
132
|
listSessions() {
|
|
124
133
|
const result = [];
|
|
125
134
|
for (const [alias, session] of this.sessions) {
|
|
135
|
+
const authMethod = session.config.privateKeyPath
|
|
136
|
+
? 'key'
|
|
137
|
+
: session.config.password
|
|
138
|
+
? 'password'
|
|
139
|
+
: 'agent';
|
|
140
|
+
const port = session.config.port || 22;
|
|
126
141
|
result.push({
|
|
127
142
|
alias,
|
|
143
|
+
identity: this.sessionIdentity(session),
|
|
128
144
|
host: session.config.host,
|
|
129
|
-
port
|
|
145
|
+
port,
|
|
130
146
|
username: session.config.username,
|
|
147
|
+
runAs: session.config.runAs,
|
|
148
|
+
keyPath: session.config.privateKeyPath,
|
|
149
|
+
authMethod,
|
|
131
150
|
connected: this.isAlive(session),
|
|
132
151
|
connectedAt: session.connectedAt,
|
|
133
152
|
lastUsedAt: session.lastUsedAt,
|
|
@@ -140,73 +159,11 @@ export class SessionManager {
|
|
|
140
159
|
*/
|
|
141
160
|
async exec(alias, command, options = {}) {
|
|
142
161
|
const session = this.getSession(alias);
|
|
143
|
-
const
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
let timeoutId = null;
|
|
149
|
-
let stdout = '';
|
|
150
|
-
let stderr = '';
|
|
151
|
-
let stdoutTruncated = false;
|
|
152
|
-
let stderrTruncated = false;
|
|
153
|
-
const execOptions = {};
|
|
154
|
-
// PTY 模式
|
|
155
|
-
if (options.pty) {
|
|
156
|
-
execOptions.pty = {
|
|
157
|
-
rows: options.rows || 24,
|
|
158
|
-
cols: options.cols || 80,
|
|
159
|
-
term: options.term || 'xterm-256color',
|
|
160
|
-
};
|
|
161
|
-
}
|
|
162
|
-
session.client.exec(fullCommand, execOptions, (err, stream) => {
|
|
163
|
-
if (err) {
|
|
164
|
-
reject(new Error(`Exec failed: ${err.message}`));
|
|
165
|
-
return;
|
|
166
|
-
}
|
|
167
|
-
// 设置超时
|
|
168
|
-
timeoutId = setTimeout(() => {
|
|
169
|
-
stream.close();
|
|
170
|
-
reject(new Error(`Command timed out after ${timeout}ms`));
|
|
171
|
-
}, timeout);
|
|
172
|
-
stream.on('close', (code) => {
|
|
173
|
-
if (timeoutId) {
|
|
174
|
-
clearTimeout(timeoutId);
|
|
175
|
-
}
|
|
176
|
-
resolve({
|
|
177
|
-
success: code === 0,
|
|
178
|
-
stdout: stdoutTruncated ? stdout + '\n... [truncated]' : stdout,
|
|
179
|
-
stderr: stderrTruncated ? stderr + '\n... [truncated]' : stderr,
|
|
180
|
-
exitCode: code,
|
|
181
|
-
duration: Date.now() - startTime,
|
|
182
|
-
});
|
|
183
|
-
});
|
|
184
|
-
stream.on('data', (data) => {
|
|
185
|
-
if (!stdoutTruncated) {
|
|
186
|
-
const chunk = data.toString('utf-8');
|
|
187
|
-
if (stdout.length + chunk.length > maxOutputSize) {
|
|
188
|
-
stdout += chunk.slice(0, maxOutputSize - stdout.length);
|
|
189
|
-
stdoutTruncated = true;
|
|
190
|
-
}
|
|
191
|
-
else {
|
|
192
|
-
stdout += chunk;
|
|
193
|
-
}
|
|
194
|
-
}
|
|
195
|
-
});
|
|
196
|
-
stream.stderr.on('data', (data) => {
|
|
197
|
-
if (!stderrTruncated) {
|
|
198
|
-
const chunk = data.toString('utf-8');
|
|
199
|
-
if (stderr.length + chunk.length > maxOutputSize) {
|
|
200
|
-
stderr += chunk.slice(0, maxOutputSize - stderr.length);
|
|
201
|
-
stderrTruncated = true;
|
|
202
|
-
}
|
|
203
|
-
else {
|
|
204
|
-
stderr += chunk;
|
|
205
|
-
}
|
|
206
|
-
}
|
|
207
|
-
});
|
|
208
|
-
});
|
|
209
|
-
});
|
|
162
|
+
const runAs = options.useLoginUser ? undefined : (options.runAs ?? session.config.runAs);
|
|
163
|
+
if (runAs) {
|
|
164
|
+
return this.execAsUser(alias, command, runAs, options);
|
|
165
|
+
}
|
|
166
|
+
return this.execDirect(alias, command, options, { cwd: options.cwd });
|
|
210
167
|
}
|
|
211
168
|
/**
|
|
212
169
|
* 以其他用户身份执行命令
|
|
@@ -222,9 +179,17 @@ export class SessionManager {
|
|
|
222
179
|
throw new Error(`Invalid username: ${targetUser}`);
|
|
223
180
|
}
|
|
224
181
|
const { loadProfile = true, ...execOpts } = options;
|
|
182
|
+
const session = this.getSession(alias);
|
|
225
183
|
const wrappedCommand = loadProfile ? `${this.getLoadProfileCommand()}${command}` : command;
|
|
226
|
-
const
|
|
227
|
-
|
|
184
|
+
const targetCommand = this.buildCommand(wrappedCommand, session, execOpts);
|
|
185
|
+
const suCommand = `su - ${targetUser} -c ${this.escapeShellArg(targetCommand)}`;
|
|
186
|
+
const env = { ...session.config.defaultEnv, ...session.config.env, ...execOpts.env };
|
|
187
|
+
return this.execDirect(alias, suCommand, { ...execOpts, env: undefined, cwd: undefined, runAs: undefined, useLoginUser: true, skipSessionEnv: true }, {
|
|
188
|
+
runAs: targetUser,
|
|
189
|
+
loadProfile,
|
|
190
|
+
cwd: execOpts.cwd,
|
|
191
|
+
envInjectedKeys: Object.keys(env).filter((key) => this.isValidEnvKey(key)),
|
|
192
|
+
});
|
|
228
193
|
}
|
|
229
194
|
/**
|
|
230
195
|
* 使用 sudo 执行命令
|
|
@@ -243,6 +208,25 @@ export class SessionManager {
|
|
|
243
208
|
return new Promise((resolve, reject) => {
|
|
244
209
|
let settled = false;
|
|
245
210
|
let streamRef = null;
|
|
211
|
+
let stdout = '';
|
|
212
|
+
let stderr = '';
|
|
213
|
+
let stdoutTail = '';
|
|
214
|
+
let stderrTail = '';
|
|
215
|
+
let stdoutBytes = 0;
|
|
216
|
+
let stderrBytes = 0;
|
|
217
|
+
let stdoutTruncated = false;
|
|
218
|
+
let stderrTruncated = false;
|
|
219
|
+
const outputPreview = () => ({
|
|
220
|
+
stdout,
|
|
221
|
+
stderr,
|
|
222
|
+
stdoutTail,
|
|
223
|
+
stderrTail,
|
|
224
|
+
stdoutBytes,
|
|
225
|
+
stderrBytes,
|
|
226
|
+
stdoutTruncated,
|
|
227
|
+
stderrTruncated,
|
|
228
|
+
maxOutputSize,
|
|
229
|
+
});
|
|
246
230
|
const timeoutId = setTimeout(() => {
|
|
247
231
|
if (settled) {
|
|
248
232
|
return;
|
|
@@ -254,7 +238,7 @@ export class SessionManager {
|
|
|
254
238
|
catch {
|
|
255
239
|
// ignore
|
|
256
240
|
}
|
|
257
|
-
reject(
|
|
241
|
+
reject(this.createCommandTimeoutError(alias, timeout, { cwd: options.cwd }, outputPreview()));
|
|
258
242
|
}, timeout);
|
|
259
243
|
session.client.exec(fullCommand, {}, (err, stream) => {
|
|
260
244
|
if (err) {
|
|
@@ -267,10 +251,6 @@ export class SessionManager {
|
|
|
267
251
|
// 密码写入 stdin,sudo -S 从 stdin 读取,不出现在命令行
|
|
268
252
|
stream.write(sudoPassword + '\n');
|
|
269
253
|
stream.end();
|
|
270
|
-
let stdout = '';
|
|
271
|
-
let stderr = '';
|
|
272
|
-
let stdoutTruncated = false;
|
|
273
|
-
let stderrTruncated = false;
|
|
274
254
|
stream.on('close', (code) => {
|
|
275
255
|
clearTimeout(timeoutId);
|
|
276
256
|
if (settled) {
|
|
@@ -283,11 +263,18 @@ export class SessionManager {
|
|
|
283
263
|
stderr: stderrTruncated ? stderr + '\n... [truncated]' : stderr,
|
|
284
264
|
exitCode: code,
|
|
285
265
|
duration: Date.now() - startTime,
|
|
266
|
+
failureKind: code === 0 ? undefined : 'remote_command',
|
|
267
|
+
stdoutTruncated: stdoutTruncated || undefined,
|
|
268
|
+
stderrTruncated: stderrTruncated || undefined,
|
|
269
|
+
...this.outputMetadata(outputPreview()),
|
|
270
|
+
...this.resultMetadata(session, options, { cwd: options.cwd }),
|
|
286
271
|
});
|
|
287
272
|
});
|
|
288
273
|
stream.on('data', (data) => {
|
|
274
|
+
const chunk = data.toString('utf-8');
|
|
275
|
+
stdoutBytes += data.length;
|
|
276
|
+
stdoutTail = this.appendOutputTail(stdoutTail, chunk);
|
|
289
277
|
if (!stdoutTruncated) {
|
|
290
|
-
const chunk = data.toString('utf-8');
|
|
291
278
|
if (stdout.length + chunk.length > maxOutputSize) {
|
|
292
279
|
stdout += chunk.slice(0, maxOutputSize - stdout.length);
|
|
293
280
|
stdoutTruncated = true;
|
|
@@ -298,8 +285,10 @@ export class SessionManager {
|
|
|
298
285
|
}
|
|
299
286
|
});
|
|
300
287
|
stream.stderr.on('data', (data) => {
|
|
288
|
+
const chunk = data.toString('utf-8');
|
|
289
|
+
stderrBytes += data.length;
|
|
290
|
+
stderrTail = this.appendOutputTail(stderrTail, chunk);
|
|
301
291
|
if (!stderrTruncated) {
|
|
302
|
-
const chunk = data.toString('utf-8');
|
|
303
292
|
if (stderr.length + chunk.length > maxOutputSize) {
|
|
304
293
|
stderr += chunk.slice(0, maxOutputSize - stderr.length);
|
|
305
294
|
stderrTruncated = true;
|
|
@@ -364,10 +353,166 @@ export class SessionManager {
|
|
|
364
353
|
forwardList() {
|
|
365
354
|
return this.forwardManager.list();
|
|
366
355
|
}
|
|
356
|
+
sessionIdentity(session) {
|
|
357
|
+
return this.configIdentity(session.config);
|
|
358
|
+
}
|
|
359
|
+
configIdentity(config) {
|
|
360
|
+
return `${config.username}@${config.host}:${config.port || 22}`;
|
|
361
|
+
}
|
|
362
|
+
resultMetadata(session, options, context) {
|
|
363
|
+
const env = options.skipSessionEnv
|
|
364
|
+
? { ...options.env }
|
|
365
|
+
: { ...session.config.defaultEnv, ...session.config.env, ...options.env };
|
|
366
|
+
return {
|
|
367
|
+
loginUser: session.config.username,
|
|
368
|
+
effectiveUser: context.runAs ?? session.config.username,
|
|
369
|
+
identity: this.sessionIdentity(session),
|
|
370
|
+
cwd: context.cwd ?? options.cwd,
|
|
371
|
+
resolvedCwd: context.cwd ?? options.cwd,
|
|
372
|
+
shell: session.config.shell,
|
|
373
|
+
profileLoaded: context.loadProfile,
|
|
374
|
+
envInjectedKeys: context.envInjectedKeys ?? Object.keys(env).filter((key) => this.isValidEnvKey(key)),
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
appendOutputTail(current, chunk) {
|
|
378
|
+
const next = current + chunk;
|
|
379
|
+
return next.length > OUTPUT_PREVIEW_CHARS ? next.slice(-OUTPUT_PREVIEW_CHARS) : next;
|
|
380
|
+
}
|
|
381
|
+
recommendedReadCommand() {
|
|
382
|
+
return '将远端命令输出重定向到文件,例如 command > /tmp/mcp-ssh-output.txt 2>&1,然后用 ssh_read_file(remotePath="/tmp/mcp-ssh-output.txt", tail=true, maxBytes=65536) 分块读取';
|
|
383
|
+
}
|
|
384
|
+
outputMetadata(preview) {
|
|
385
|
+
const truncated = preview.stdoutTruncated || preview.stderrTruncated;
|
|
386
|
+
return {
|
|
387
|
+
stdoutBytes: preview.stdoutBytes,
|
|
388
|
+
stderrBytes: preview.stderrBytes,
|
|
389
|
+
stdoutHead: preview.stdoutTruncated ? preview.stdout.slice(0, OUTPUT_PREVIEW_CHARS) : undefined,
|
|
390
|
+
stdoutTail: preview.stdoutTruncated ? preview.stdoutTail : undefined,
|
|
391
|
+
stderrHead: preview.stderrTruncated ? preview.stderr.slice(0, OUTPUT_PREVIEW_CHARS) : undefined,
|
|
392
|
+
stderrTail: preview.stderrTruncated ? preview.stderrTail : undefined,
|
|
393
|
+
recommendedReadCommand: truncated ? this.recommendedReadCommand() : undefined,
|
|
394
|
+
maxOutputSize: truncated ? preview.maxOutputSize : undefined,
|
|
395
|
+
suggestion: truncated
|
|
396
|
+
? '输出已截断,请提高 maxOutputSize,或将远端输出重定向到文件后用 ssh_read_file 分块读取'
|
|
397
|
+
: undefined,
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
async execDirect(alias, command, options = {}, context = {}) {
|
|
401
|
+
const session = this.getSession(alias);
|
|
402
|
+
const startTime = Date.now();
|
|
403
|
+
const maxOutputSize = options.maxOutputSize ?? this.defaultMaxOutputSize;
|
|
404
|
+
const fullCommand = this.buildCommand(command, session, options);
|
|
405
|
+
return new Promise((resolve, reject) => {
|
|
406
|
+
const timeout = options.timeout ?? this.defaultTimeout;
|
|
407
|
+
let timeoutId = null;
|
|
408
|
+
let stdout = '';
|
|
409
|
+
let stderr = '';
|
|
410
|
+
let stdoutTail = '';
|
|
411
|
+
let stderrTail = '';
|
|
412
|
+
let stdoutBytes = 0;
|
|
413
|
+
let stderrBytes = 0;
|
|
414
|
+
let stdoutTruncated = false;
|
|
415
|
+
let stderrTruncated = false;
|
|
416
|
+
let settled = false;
|
|
417
|
+
const execOptions = {};
|
|
418
|
+
if (options.pty) {
|
|
419
|
+
execOptions.pty = {
|
|
420
|
+
rows: options.rows || 24,
|
|
421
|
+
cols: options.cols || 80,
|
|
422
|
+
term: options.term || 'xterm-256color',
|
|
423
|
+
};
|
|
424
|
+
}
|
|
425
|
+
session.client.exec(fullCommand, execOptions, (err, stream) => {
|
|
426
|
+
if (err) {
|
|
427
|
+
settled = true;
|
|
428
|
+
reject(new Error(`Exec failed: ${err.message}`));
|
|
429
|
+
return;
|
|
430
|
+
}
|
|
431
|
+
const outputPreview = () => ({
|
|
432
|
+
stdout,
|
|
433
|
+
stderr,
|
|
434
|
+
stdoutTail,
|
|
435
|
+
stderrTail,
|
|
436
|
+
stdoutBytes,
|
|
437
|
+
stderrBytes,
|
|
438
|
+
stdoutTruncated,
|
|
439
|
+
stderrTruncated,
|
|
440
|
+
maxOutputSize,
|
|
441
|
+
});
|
|
442
|
+
timeoutId = setTimeout(() => {
|
|
443
|
+
if (settled) {
|
|
444
|
+
return;
|
|
445
|
+
}
|
|
446
|
+
settled = true;
|
|
447
|
+
stream.close();
|
|
448
|
+
reject(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
|
|
449
|
+
}, timeout);
|
|
450
|
+
stream.on('close', (code) => {
|
|
451
|
+
if (timeoutId) {
|
|
452
|
+
clearTimeout(timeoutId);
|
|
453
|
+
}
|
|
454
|
+
if (settled) {
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
settled = true;
|
|
458
|
+
resolve({
|
|
459
|
+
success: code === 0,
|
|
460
|
+
stdout: stdoutTruncated ? stdout + '\n... [truncated]' : stdout,
|
|
461
|
+
stderr: stderrTruncated ? stderr + '\n... [truncated]' : stderr,
|
|
462
|
+
exitCode: code,
|
|
463
|
+
duration: Date.now() - startTime,
|
|
464
|
+
failureKind: code === 0 ? undefined : 'remote_command',
|
|
465
|
+
stdoutTruncated: stdoutTruncated || undefined,
|
|
466
|
+
stderrTruncated: stderrTruncated || undefined,
|
|
467
|
+
...this.outputMetadata(outputPreview()),
|
|
468
|
+
...this.resultMetadata(session, options, context),
|
|
469
|
+
});
|
|
470
|
+
});
|
|
471
|
+
stream.on('data', (data) => {
|
|
472
|
+
const chunk = data.toString('utf-8');
|
|
473
|
+
stdoutBytes += data.length;
|
|
474
|
+
stdoutTail = this.appendOutputTail(stdoutTail, chunk);
|
|
475
|
+
if (!stdoutTruncated) {
|
|
476
|
+
if (stdout.length + chunk.length > maxOutputSize) {
|
|
477
|
+
stdout += chunk.slice(0, maxOutputSize - stdout.length);
|
|
478
|
+
stdoutTruncated = true;
|
|
479
|
+
}
|
|
480
|
+
else {
|
|
481
|
+
stdout += chunk;
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
});
|
|
485
|
+
stream.stderr.on('data', (data) => {
|
|
486
|
+
const chunk = data.toString('utf-8');
|
|
487
|
+
stderrBytes += data.length;
|
|
488
|
+
stderrTail = this.appendOutputTail(stderrTail, chunk);
|
|
489
|
+
if (!stderrTruncated) {
|
|
490
|
+
if (stderr.length + chunk.length > maxOutputSize) {
|
|
491
|
+
stderr += chunk.slice(0, maxOutputSize - stderr.length);
|
|
492
|
+
stderrTruncated = true;
|
|
493
|
+
}
|
|
494
|
+
else {
|
|
495
|
+
stderr += chunk;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
});
|
|
499
|
+
});
|
|
500
|
+
});
|
|
501
|
+
}
|
|
367
502
|
async connectInternal(config, alias) {
|
|
368
503
|
// 检查是否已有活跃连接
|
|
369
504
|
const existing = this.sessions.get(alias);
|
|
370
505
|
if (existing && this.isAlive(existing)) {
|
|
506
|
+
const existingIdentity = this.sessionIdentity(existing);
|
|
507
|
+
const requestedIdentity = this.configIdentity(config);
|
|
508
|
+
if (existingIdentity !== requestedIdentity) {
|
|
509
|
+
throw new CommandError(`Alias '${alias}' is already connected to ${existingIdentity}`, {
|
|
510
|
+
alias,
|
|
511
|
+
existingIdentity,
|
|
512
|
+
requestedIdentity,
|
|
513
|
+
suggestion: '请换一个 alias,或先 ssh_disconnect 断开已有同名会话',
|
|
514
|
+
});
|
|
515
|
+
}
|
|
371
516
|
existing.lastUsedAt = Date.now();
|
|
372
517
|
return alias;
|
|
373
518
|
}
|
|
@@ -533,6 +678,34 @@ export class SessionManager {
|
|
|
533
678
|
}
|
|
534
679
|
}, this.reconnectDelay);
|
|
535
680
|
}
|
|
681
|
+
createCommandTimeoutError(alias, timeout, context, preview) {
|
|
682
|
+
const output = preview ? this.outputMetadata(preview) : undefined;
|
|
683
|
+
return new CommandError(`Command timed out after ${timeout}ms`, {
|
|
684
|
+
alias,
|
|
685
|
+
timeout,
|
|
686
|
+
timedOut: true,
|
|
687
|
+
failureKind: 'timeout',
|
|
688
|
+
runAs: context.runAs,
|
|
689
|
+
loadProfile: context.loadProfile,
|
|
690
|
+
cwd: context.cwd,
|
|
691
|
+
remoteProcessKnown: false,
|
|
692
|
+
stdoutHead: preview?.stdout.slice(0, OUTPUT_PREVIEW_CHARS),
|
|
693
|
+
stdoutTail: preview?.stdoutTail,
|
|
694
|
+
stderrHead: preview?.stderr.slice(0, OUTPUT_PREVIEW_CHARS),
|
|
695
|
+
stderrTail: preview?.stderrTail,
|
|
696
|
+
stdoutBytes: preview?.stdoutBytes,
|
|
697
|
+
stderrBytes: preview?.stderrBytes,
|
|
698
|
+
recommendedReadCommand: this.recommendedReadCommand(),
|
|
699
|
+
output,
|
|
700
|
+
suggestions: context.loadProfile
|
|
701
|
+
? ['设置 loadProfile=false 后重试', '提高 timeout', '长时间交互命令改用 ssh_pty_start']
|
|
702
|
+
: [
|
|
703
|
+
'提高 timeout',
|
|
704
|
+
'长时间交互命令改用 ssh_pty_start',
|
|
705
|
+
'大输出命令重定向到远端文件后用 ssh_read_file 分块读取',
|
|
706
|
+
],
|
|
707
|
+
});
|
|
708
|
+
}
|
|
536
709
|
/**
|
|
537
710
|
* 根据错误类型生成排查建议
|
|
538
711
|
*/
|
|
@@ -580,7 +753,9 @@ export class SessionManager {
|
|
|
580
753
|
*/
|
|
581
754
|
buildCommand(command, session, options) {
|
|
582
755
|
let fullCommand = command;
|
|
583
|
-
const env =
|
|
756
|
+
const env = options.skipSessionEnv
|
|
757
|
+
? { ...options.env }
|
|
758
|
+
: { ...session.config.defaultEnv, ...session.config.env, ...options.env };
|
|
584
759
|
if (Object.keys(env).length > 0) {
|
|
585
760
|
const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k));
|
|
586
761
|
if (validEntries.length > 0) {
|
|
@@ -616,6 +791,7 @@ export class SessionManager {
|
|
|
616
791
|
host: session.config.host,
|
|
617
792
|
port: session.config.port || 22,
|
|
618
793
|
username: session.config.username,
|
|
794
|
+
runAs: session.config.runAs,
|
|
619
795
|
connectedAt: session.connectedAt,
|
|
620
796
|
});
|
|
621
797
|
}
|