@pyrokine/mcp-ssh 2.0.2 → 2.2.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.
@@ -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;
@@ -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,14 @@ 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 normalizeMaxOutputSize;
118
+ private execDirect;
105
119
  private connectInternal;
106
120
  /**
107
121
  * 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
@@ -124,6 +138,7 @@ export declare class SessionManager {
124
138
  * 调度自动重连(支持多次重试)
125
139
  */
126
140
  private scheduleReconnect;
141
+ private createCommandTimeoutError;
127
142
  /**
128
143
  * 根据错误类型生成排查建议
129
144
  */
@@ -16,6 +16,16 @@ 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
+ import { DEFAULT_EXEC_MAX_OUTPUT_SIZE, HARD_EXEC_MAX_OUTPUT_SIZE, } from './types.js';
20
+ const OUTPUT_PREVIEW_CHARS = 4096;
21
+ class CommandError extends Error {
22
+ details;
23
+ constructor(message, details) {
24
+ super(message);
25
+ this.details = details;
26
+ this.name = 'CommandError';
27
+ }
28
+ }
19
29
  export class SessionManager {
20
30
  sessions = new Map();
21
31
  /** per-alias connect 进行中的 Promise,防止并发 connect 同一 alias 时重复建连 */
@@ -27,7 +37,7 @@ export class SessionManager {
27
37
  defaultKeepaliveCountMax = 3;
28
38
  defaultTimeout = 30000; // 30秒
29
39
  maxReconnectAttempts = 3;
30
- defaultMaxOutputSize = 10 * 1024 * 1024; // 10*1024*1024 UTF-16 chars(ASCII 时约 10MB 字节)
40
+ defaultMaxOutputSize = DEFAULT_EXEC_MAX_OUTPUT_SIZE;
31
41
  reconnectDelay = 5000; // 5秒
32
42
  constructor(persistPath) {
33
43
  this.persistPath = persistPath || path.join(os.homedir(), '.ssh-mcp-pro', 'sessions.json');
@@ -123,11 +133,21 @@ export class SessionManager {
123
133
  listSessions() {
124
134
  const result = [];
125
135
  for (const [alias, session] of this.sessions) {
136
+ const authMethod = session.config.privateKeyPath
137
+ ? 'key'
138
+ : session.config.password
139
+ ? 'password'
140
+ : 'agent';
141
+ const port = session.config.port || 22;
126
142
  result.push({
127
143
  alias,
144
+ identity: this.sessionIdentity(session),
128
145
  host: session.config.host,
129
- port: session.config.port || 22,
146
+ port,
130
147
  username: session.config.username,
148
+ runAs: session.config.runAs,
149
+ keyPath: session.config.privateKeyPath,
150
+ authMethod,
131
151
  connected: this.isAlive(session),
132
152
  connectedAt: session.connectedAt,
133
153
  lastUsedAt: session.lastUsedAt,
@@ -140,73 +160,11 @@ export class SessionManager {
140
160
  */
141
161
  async exec(alias, command, options = {}) {
142
162
  const session = this.getSession(alias);
143
- const startTime = Date.now();
144
- const maxOutputSize = options.maxOutputSize ?? this.defaultMaxOutputSize;
145
- const fullCommand = this.buildCommand(command, session, options);
146
- return new Promise((resolve, reject) => {
147
- const timeout = options.timeout ?? this.defaultTimeout;
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
- });
163
+ const runAs = options.useLoginUser ? undefined : (options.runAs ?? session.config.runAs);
164
+ if (runAs) {
165
+ return this.execAsUser(alias, command, runAs, options);
166
+ }
167
+ return this.execDirect(alias, command, options, { cwd: options.cwd });
210
168
  }
211
169
  /**
212
170
  * 以其他用户身份执行命令
@@ -222,9 +180,17 @@ export class SessionManager {
222
180
  throw new Error(`Invalid username: ${targetUser}`);
223
181
  }
224
182
  const { loadProfile = true, ...execOpts } = options;
183
+ const session = this.getSession(alias);
225
184
  const wrappedCommand = loadProfile ? `${this.getLoadProfileCommand()}${command}` : command;
226
- const suCommand = `su - ${targetUser} -c ${this.escapeShellArg(wrappedCommand)}`;
227
- return this.exec(alias, suCommand, execOpts);
185
+ const targetCommand = this.buildCommand(wrappedCommand, session, execOpts);
186
+ const suCommand = `su - ${targetUser} -c ${this.escapeShellArg(targetCommand)}`;
187
+ const env = { ...session.config.defaultEnv, ...session.config.env, ...execOpts.env };
188
+ return this.execDirect(alias, suCommand, { ...execOpts, env: undefined, cwd: undefined, runAs: undefined, useLoginUser: true, skipSessionEnv: true }, {
189
+ runAs: targetUser,
190
+ loadProfile,
191
+ cwd: execOpts.cwd,
192
+ envInjectedKeys: Object.keys(env).filter((key) => this.isValidEnvKey(key)),
193
+ });
228
194
  }
229
195
  /**
230
196
  * 使用 sudo 执行命令
@@ -238,11 +204,30 @@ export class SessionManager {
238
204
  const session = this.getSession(alias);
239
205
  const startTime = Date.now();
240
206
  const timeout = options.timeout ?? this.defaultTimeout;
241
- const maxOutputSize = options.maxOutputSize ?? this.defaultMaxOutputSize;
207
+ const maxOutputSize = this.normalizeMaxOutputSize(options.maxOutputSize);
242
208
  const fullCommand = this.buildCommand(`sudo -S ${command}`, session, options);
243
209
  return new Promise((resolve, reject) => {
244
210
  let settled = false;
245
211
  let streamRef = null;
212
+ let stdout = '';
213
+ let stderr = '';
214
+ let stdoutTail = '';
215
+ let stderrTail = '';
216
+ let stdoutBytes = 0;
217
+ let stderrBytes = 0;
218
+ let stdoutTruncated = false;
219
+ let stderrTruncated = false;
220
+ const outputPreview = () => ({
221
+ stdout,
222
+ stderr,
223
+ stdoutTail,
224
+ stderrTail,
225
+ stdoutBytes,
226
+ stderrBytes,
227
+ stdoutTruncated,
228
+ stderrTruncated,
229
+ maxOutputSize,
230
+ });
246
231
  const timeoutId = setTimeout(() => {
247
232
  if (settled) {
248
233
  return;
@@ -254,7 +239,7 @@ export class SessionManager {
254
239
  catch {
255
240
  // ignore
256
241
  }
257
- reject(new Error(`Command timed out after ${timeout}ms`));
242
+ reject(this.createCommandTimeoutError(alias, timeout, { cwd: options.cwd }, outputPreview()));
258
243
  }, timeout);
259
244
  session.client.exec(fullCommand, {}, (err, stream) => {
260
245
  if (err) {
@@ -267,10 +252,6 @@ export class SessionManager {
267
252
  // 密码写入 stdin,sudo -S 从 stdin 读取,不出现在命令行
268
253
  stream.write(sudoPassword + '\n');
269
254
  stream.end();
270
- let stdout = '';
271
- let stderr = '';
272
- let stdoutTruncated = false;
273
- let stderrTruncated = false;
274
255
  stream.on('close', (code) => {
275
256
  clearTimeout(timeoutId);
276
257
  if (settled) {
@@ -283,11 +264,18 @@ export class SessionManager {
283
264
  stderr: stderrTruncated ? stderr + '\n... [truncated]' : stderr,
284
265
  exitCode: code,
285
266
  duration: Date.now() - startTime,
267
+ failureKind: code === 0 ? undefined : 'remote_command',
268
+ stdoutTruncated: stdoutTruncated || undefined,
269
+ stderrTruncated: stderrTruncated || undefined,
270
+ ...this.outputMetadata(outputPreview()),
271
+ ...this.resultMetadata(session, options, { cwd: options.cwd }),
286
272
  });
287
273
  });
288
274
  stream.on('data', (data) => {
275
+ const chunk = data.toString('utf-8');
276
+ stdoutBytes += data.length;
277
+ stdoutTail = this.appendOutputTail(stdoutTail, chunk);
289
278
  if (!stdoutTruncated) {
290
- const chunk = data.toString('utf-8');
291
279
  if (stdout.length + chunk.length > maxOutputSize) {
292
280
  stdout += chunk.slice(0, maxOutputSize - stdout.length);
293
281
  stdoutTruncated = true;
@@ -298,8 +286,10 @@ export class SessionManager {
298
286
  }
299
287
  });
300
288
  stream.stderr.on('data', (data) => {
289
+ const chunk = data.toString('utf-8');
290
+ stderrBytes += data.length;
291
+ stderrTail = this.appendOutputTail(stderrTail, chunk);
301
292
  if (!stderrTruncated) {
302
- const chunk = data.toString('utf-8');
303
293
  if (stderr.length + chunk.length > maxOutputSize) {
304
294
  stderr += chunk.slice(0, maxOutputSize - stderr.length);
305
295
  stderrTruncated = true;
@@ -364,10 +354,178 @@ export class SessionManager {
364
354
  forwardList() {
365
355
  return this.forwardManager.list();
366
356
  }
357
+ sessionIdentity(session) {
358
+ return this.configIdentity(session.config);
359
+ }
360
+ configIdentity(config) {
361
+ return `${config.username}@${config.host}:${config.port || 22}`;
362
+ }
363
+ resultMetadata(session, options, context) {
364
+ const env = options.skipSessionEnv
365
+ ? { ...options.env }
366
+ : { ...session.config.defaultEnv, ...session.config.env, ...options.env };
367
+ return {
368
+ loginUser: session.config.username,
369
+ effectiveUser: context.runAs ?? session.config.username,
370
+ identity: this.sessionIdentity(session),
371
+ cwd: context.cwd ?? options.cwd,
372
+ resolvedCwd: context.cwd ?? options.cwd,
373
+ shell: session.config.shell,
374
+ profileLoaded: context.loadProfile,
375
+ envInjectedKeys: context.envInjectedKeys ?? Object.keys(env).filter((key) => this.isValidEnvKey(key)),
376
+ };
377
+ }
378
+ appendOutputTail(current, chunk) {
379
+ const next = current + chunk;
380
+ return next.length > OUTPUT_PREVIEW_CHARS ? next.slice(-OUTPUT_PREVIEW_CHARS) : next;
381
+ }
382
+ recommendedReadCommand() {
383
+ return '将远端命令输出重定向到文件,例如 command > /tmp/mcp-ssh-output.txt 2>&1,然后用 ssh_read_file(remotePath="/tmp/mcp-ssh-output.txt", tail=true, maxBytes=65536) 分块读取';
384
+ }
385
+ outputMetadata(preview) {
386
+ const truncated = preview.stdoutTruncated || preview.stderrTruncated;
387
+ return {
388
+ stdoutBytes: preview.stdoutBytes,
389
+ stderrBytes: preview.stderrBytes,
390
+ stdoutHead: preview.stdoutTruncated ? preview.stdout.slice(0, OUTPUT_PREVIEW_CHARS) : undefined,
391
+ stdoutTail: preview.stdoutTruncated ? preview.stdoutTail : undefined,
392
+ stderrHead: preview.stderrTruncated ? preview.stderr.slice(0, OUTPUT_PREVIEW_CHARS) : undefined,
393
+ stderrTail: preview.stderrTruncated ? preview.stderrTail : undefined,
394
+ recommendedReadCommand: truncated ? this.recommendedReadCommand() : undefined,
395
+ maxOutputSize: truncated ? preview.maxOutputSize : undefined,
396
+ suggestion: truncated
397
+ ? '输出已截断,请提高 maxOutputSize,或将远端输出重定向到文件后用 ssh_read_file 分块读取'
398
+ : undefined,
399
+ };
400
+ }
401
+ normalizeMaxOutputSize(value) {
402
+ const maxOutputSize = value ?? this.defaultMaxOutputSize;
403
+ if (!Number.isInteger(maxOutputSize) || maxOutputSize <= 0 || maxOutputSize > HARD_EXEC_MAX_OUTPUT_SIZE) {
404
+ throw new CommandError('Invalid maxOutputSize', {
405
+ maxOutputSize,
406
+ min: 1,
407
+ max: HARD_EXEC_MAX_OUTPUT_SIZE,
408
+ suggestion: '使用 1 到 HARD_EXEC_MAX_OUTPUT_SIZE 之间的整数,超大输出请重定向到远端文件后用 ssh_read_file 分块读取',
409
+ });
410
+ }
411
+ return maxOutputSize;
412
+ }
413
+ async execDirect(alias, command, options = {}, context = {}) {
414
+ const session = this.getSession(alias);
415
+ const startTime = Date.now();
416
+ const maxOutputSize = this.normalizeMaxOutputSize(options.maxOutputSize);
417
+ const fullCommand = this.buildCommand(command, session, options);
418
+ return new Promise((resolve, reject) => {
419
+ const timeout = options.timeout ?? this.defaultTimeout;
420
+ let timeoutId = null;
421
+ let stdout = '';
422
+ let stderr = '';
423
+ let stdoutTail = '';
424
+ let stderrTail = '';
425
+ let stdoutBytes = 0;
426
+ let stderrBytes = 0;
427
+ let stdoutTruncated = false;
428
+ let stderrTruncated = false;
429
+ let settled = false;
430
+ const execOptions = {};
431
+ if (options.pty) {
432
+ execOptions.pty = {
433
+ rows: options.rows || 24,
434
+ cols: options.cols || 80,
435
+ term: options.term || 'xterm-256color',
436
+ };
437
+ }
438
+ session.client.exec(fullCommand, execOptions, (err, stream) => {
439
+ if (err) {
440
+ settled = true;
441
+ reject(new Error(`Exec failed: ${err.message}`));
442
+ return;
443
+ }
444
+ const outputPreview = () => ({
445
+ stdout,
446
+ stderr,
447
+ stdoutTail,
448
+ stderrTail,
449
+ stdoutBytes,
450
+ stderrBytes,
451
+ stdoutTruncated,
452
+ stderrTruncated,
453
+ maxOutputSize,
454
+ });
455
+ timeoutId = setTimeout(() => {
456
+ if (settled) {
457
+ return;
458
+ }
459
+ settled = true;
460
+ stream.close();
461
+ reject(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
462
+ }, timeout);
463
+ stream.on('close', (code) => {
464
+ if (timeoutId) {
465
+ clearTimeout(timeoutId);
466
+ }
467
+ if (settled) {
468
+ return;
469
+ }
470
+ settled = true;
471
+ resolve({
472
+ success: code === 0,
473
+ stdout: stdoutTruncated ? stdout + '\n... [truncated]' : stdout,
474
+ stderr: stderrTruncated ? stderr + '\n... [truncated]' : stderr,
475
+ exitCode: code,
476
+ duration: Date.now() - startTime,
477
+ failureKind: code === 0 ? undefined : 'remote_command',
478
+ stdoutTruncated: stdoutTruncated || undefined,
479
+ stderrTruncated: stderrTruncated || undefined,
480
+ ...this.outputMetadata(outputPreview()),
481
+ ...this.resultMetadata(session, options, context),
482
+ });
483
+ });
484
+ stream.on('data', (data) => {
485
+ const chunk = data.toString('utf-8');
486
+ stdoutBytes += data.length;
487
+ stdoutTail = this.appendOutputTail(stdoutTail, chunk);
488
+ if (!stdoutTruncated) {
489
+ if (stdout.length + chunk.length > maxOutputSize) {
490
+ stdout += chunk.slice(0, maxOutputSize - stdout.length);
491
+ stdoutTruncated = true;
492
+ }
493
+ else {
494
+ stdout += chunk;
495
+ }
496
+ }
497
+ });
498
+ stream.stderr.on('data', (data) => {
499
+ const chunk = data.toString('utf-8');
500
+ stderrBytes += data.length;
501
+ stderrTail = this.appendOutputTail(stderrTail, chunk);
502
+ if (!stderrTruncated) {
503
+ if (stderr.length + chunk.length > maxOutputSize) {
504
+ stderr += chunk.slice(0, maxOutputSize - stderr.length);
505
+ stderrTruncated = true;
506
+ }
507
+ else {
508
+ stderr += chunk;
509
+ }
510
+ }
511
+ });
512
+ });
513
+ });
514
+ }
367
515
  async connectInternal(config, alias) {
368
516
  // 检查是否已有活跃连接
369
517
  const existing = this.sessions.get(alias);
370
518
  if (existing && this.isAlive(existing)) {
519
+ const existingIdentity = this.sessionIdentity(existing);
520
+ const requestedIdentity = this.configIdentity(config);
521
+ if (existingIdentity !== requestedIdentity) {
522
+ throw new CommandError(`Alias '${alias}' is already connected to ${existingIdentity}`, {
523
+ alias,
524
+ existingIdentity,
525
+ requestedIdentity,
526
+ suggestion: '请换一个 alias,或先 ssh_disconnect 断开已有同名会话',
527
+ });
528
+ }
371
529
  existing.lastUsedAt = Date.now();
372
530
  return alias;
373
531
  }
@@ -533,6 +691,34 @@ export class SessionManager {
533
691
  }
534
692
  }, this.reconnectDelay);
535
693
  }
694
+ createCommandTimeoutError(alias, timeout, context, preview) {
695
+ const output = preview ? this.outputMetadata(preview) : undefined;
696
+ return new CommandError(`Command timed out after ${timeout}ms`, {
697
+ alias,
698
+ timeout,
699
+ timedOut: true,
700
+ failureKind: 'timeout',
701
+ runAs: context.runAs,
702
+ loadProfile: context.loadProfile,
703
+ cwd: context.cwd,
704
+ remoteProcessKnown: false,
705
+ stdoutHead: preview?.stdout.slice(0, OUTPUT_PREVIEW_CHARS),
706
+ stdoutTail: preview?.stdoutTail,
707
+ stderrHead: preview?.stderr.slice(0, OUTPUT_PREVIEW_CHARS),
708
+ stderrTail: preview?.stderrTail,
709
+ stdoutBytes: preview?.stdoutBytes,
710
+ stderrBytes: preview?.stderrBytes,
711
+ recommendedReadCommand: this.recommendedReadCommand(),
712
+ output,
713
+ suggestions: context.loadProfile
714
+ ? ['设置 loadProfile=false 后重试', '提高 timeout', '长时间交互命令改用 ssh_pty_start']
715
+ : [
716
+ '提高 timeout',
717
+ '长时间交互命令改用 ssh_pty_start',
718
+ '大输出命令重定向到远端文件后用 ssh_read_file 分块读取',
719
+ ],
720
+ });
721
+ }
536
722
  /**
537
723
  * 根据错误类型生成排查建议
538
724
  */
@@ -580,7 +766,9 @@ export class SessionManager {
580
766
  */
581
767
  buildCommand(command, session, options) {
582
768
  let fullCommand = command;
583
- const env = { ...session.config.env, ...options.env };
769
+ const env = options.skipSessionEnv
770
+ ? { ...options.env }
771
+ : { ...session.config.defaultEnv, ...session.config.env, ...options.env };
584
772
  if (Object.keys(env).length > 0) {
585
773
  const validEntries = Object.entries(env).filter(([k]) => this.isValidEnvKey(k));
586
774
  if (validEntries.length > 0) {
@@ -616,6 +804,7 @@ export class SessionManager {
616
804
  host: session.config.host,
617
805
  port: session.config.port || 22,
618
806
  username: session.config.username,
807
+ runAs: session.config.runAs,
619
808
  connectedAt: session.connectedAt,
620
809
  });
621
810
  }