@pyrokine/mcp-ssh 2.4.3 → 3.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.
@@ -7,17 +7,22 @@
7
7
  * - 自动重连
8
8
  * - 会话持久化
9
9
  */
10
- import { createHash } from 'crypto';
10
+ import { createHash, randomUUID } from 'crypto';
11
11
  import * as fs from 'fs';
12
12
  import * as os from 'os';
13
13
  import * as path from 'path';
14
14
  import { Client } from 'ssh2';
15
+ import { StringDecoder } from 'string_decoder';
16
+ import { isUtf8ContinuationByte, retainUtf8Suffix } from './utf8.js';
15
17
  import { clearRsyncCache } from './file-ops.js';
16
18
  import { ForwardManager } from './forward-manager.js';
17
19
  import { OperationManager } from './operation-manager.js';
20
+ import { OpenSshConnection, OpenSshError } from './openssh.js';
18
21
  import { PtyManager } from './pty-manager.js';
22
+ import { buildRemoteCommand, encodedPowershell, quotePowershell, remotePathStyle } from './remote-platform.js';
19
23
  import { sanitizeKeyError, validateKeyFile } from './security.js';
20
24
  import { escapeShellArg, expandTilde } from './tools/utils.js';
25
+ import { checkWindowsAcl } from './windows-acl.js';
21
26
  import { DEFAULT_EXEC_MAX_OUTPUT_SIZE, HARD_EXEC_MAX_OUTPUT_SIZE, } from './types.js';
22
27
  const OUTPUT_PREVIEW_CHARS = 4096;
23
28
  class CommandError extends Error {
@@ -46,6 +51,7 @@ export class SessionManager {
46
51
  forwardManager = new ForwardManager();
47
52
  operationManager;
48
53
  persistPath;
54
+ persistQueue = Promise.resolve();
49
55
  defaultKeepaliveInterval = 30000; // 30秒
50
56
  defaultKeepaliveCountMax = 3;
51
57
  defaultTimeout = 30000; // 30秒
@@ -56,7 +62,7 @@ export class SessionManager {
56
62
  this.persistPath = persistPath || path.join(os.homedir(), '.ssh-mcp-pro', 'sessions.json');
57
63
  this.operationManager = new OperationManager({
58
64
  openStream: (alias, command, marker, options, adopt) => this.openOperationStream(alias, command, marker, options, adopt),
59
- cancelRemote: (alias, pid, marker, processGroup, options) => this.cancelRemoteOperation(alias, pid, marker, processGroup, options),
65
+ cancelRemote: (alias, pid, marker, processGroup, options, processCreatedAt) => this.cancelRemoteOperation(alias, pid, marker, processGroup, options, processCreatedAt),
60
66
  });
61
67
  this.ensurePersistDir();
62
68
  }
@@ -64,6 +70,20 @@ export class SessionManager {
64
70
  * 建立 SSH 连接(per-alias mutex,防止并发 connect 同一 alias 重复建连)
65
71
  */
66
72
  async connect(config) {
73
+ const platform = config.remotePlatform ?? 'posix';
74
+ const shell = config.commandShell ?? (platform === 'windows' ? 'powershell' : 'posix');
75
+ if ((platform === 'windows') !== (shell !== 'posix')) {
76
+ throw new CommandError('commandShell must match remotePlatform', {
77
+ code: 'unsupported_remote_platform',
78
+ platform,
79
+ shell,
80
+ });
81
+ }
82
+ if (platform === 'windows' && config.runAs) {
83
+ throw new CommandError('runAs is not supported for Windows remote hosts', {
84
+ code: 'unsupported_remote_platform',
85
+ });
86
+ }
67
87
  const alias = this.generateAlias(config);
68
88
  const fingerprint = this.connectionFingerprint(config);
69
89
  const requestedIdentity = this.configIdentity(config);
@@ -85,14 +105,17 @@ export class SessionManager {
85
105
  const cancellation = new Promise((_resolve, reject) => {
86
106
  rejectCancellation = reject;
87
107
  });
108
+ const controller = new AbortController();
88
109
  const pendingConnection = {
89
110
  generation,
90
111
  fingerprint,
112
+ signal: controller.signal,
91
113
  cancel: (error) => {
92
114
  if (cancelled) {
93
115
  return;
94
116
  }
95
117
  cancelled = true;
118
+ controller.abort(error);
96
119
  try {
97
120
  pendingConnection.client?.end();
98
121
  }
@@ -132,7 +155,10 @@ export class SessionManager {
132
155
  }
133
156
  this.invalidateAliasResources(alias);
134
157
  try {
135
- session.client.end();
158
+ if (session.backend === 'openssh')
159
+ session.transport.close();
160
+ else
161
+ session.client.end();
136
162
  }
137
163
  catch {
138
164
  /* 忽略已关闭的连接 */
@@ -154,7 +180,10 @@ export class SessionManager {
154
180
  }
155
181
  this.invalidateAliasResources(alias);
156
182
  try {
157
- session.client.end();
183
+ if (session.backend === 'openssh')
184
+ session.transport.close();
185
+ else
186
+ session.client.end();
158
187
  }
159
188
  catch {
160
189
  /* 忽略已关闭的连接 */
@@ -180,14 +209,32 @@ export class SessionManager {
180
209
  if (!session) {
181
210
  throw new Error(`Session '${alias}' not found. Use ssh_connect first.`);
182
211
  }
212
+ if (session.backend === 'openssh')
213
+ session.transport.assertCurrent();
183
214
  if (!this.isAlive(session)) {
215
+ if (session.backend === 'openssh')
216
+ throw new OpenSshError('The bound OpenSSH master is no longer available', {
217
+ code: 'master_unavailable',
218
+ backend: 'openssh',
219
+ alias,
220
+ retryable: false,
221
+ });
184
222
  throw new Error(`Session '${alias}' is disconnected. Use ssh_connect to reconnect.`);
185
223
  }
186
224
  session.lastUsedAt = Date.now();
187
225
  return session;
188
226
  }
227
+ getOpenSshConnection(alias) {
228
+ const session = this.sessions.get(alias);
229
+ if (session?.backend !== 'openssh')
230
+ return undefined;
231
+ this.getSession(alias);
232
+ return session.transport;
233
+ }
189
234
  listSessions() {
190
235
  return Array.from(this.sessions, ([alias, session]) => ({
236
+ backend: session.backend ?? 'ssh2',
237
+ ...(session.backend === 'openssh' ? { masterReused: true, identityStatus: 'master_trusted' } : {}),
191
238
  alias,
192
239
  identity: this.sessionIdentity(session),
193
240
  runAs: session.config.runAs,
@@ -197,29 +244,38 @@ export class SessionManager {
197
244
  }
198
245
  listSessionDetails() {
199
246
  return Array.from(this.sessions, ([alias, session]) => ({
247
+ backend: session.backend ?? 'ssh2',
248
+ ...(session.backend === 'openssh' ? session.transport.info : {}),
200
249
  alias,
201
250
  identity: this.sessionIdentity(session),
202
251
  host: session.config.host,
203
252
  port: session.config.port ?? 22,
204
253
  username: session.config.username,
205
254
  runAs: session.config.runAs,
206
- authMethod: session.config.privateKeyPath
207
- ? 'key'
208
- : session.config.privateKey
209
- ? 'inline-key'
210
- : session.config.password
211
- ? 'password'
212
- : 'agent',
255
+ authMethod: session.backend === 'openssh'
256
+ ? 'master'
257
+ : session.config.privateKeyPath
258
+ ? 'key'
259
+ : session.config.privateKey
260
+ ? 'inline-key'
261
+ : session.config.password
262
+ ? 'password'
263
+ : 'agent',
213
264
  connected: this.isAlive(session),
214
265
  connectedAt: session.connectedAt,
215
266
  lastUsedAt: session.lastUsedAt,
216
267
  hasJumpHost: Boolean(session.config.jumpHost),
268
+ remotePlatform: session.config.remotePlatform ?? 'posix',
269
+ commandShell: session.config.commandShell ?? (session.config.remotePlatform === 'windows' ? 'powershell' : 'posix'),
270
+ remotePathStyle: remotePathStyle(session.config.remotePlatform ?? 'posix', session.config.remotePathStyle),
217
271
  }));
218
272
  }
219
273
  getSessionConnectionInfo(alias) {
220
274
  const session = this.getSession(alias);
221
275
  const config = session.config;
222
276
  return {
277
+ backend: session.backend ?? 'ssh2',
278
+ ...(session.backend === 'openssh' ? session.transport.info : {}),
223
279
  alias,
224
280
  identity: this.sessionIdentity(session),
225
281
  loginUser: config.username,
@@ -229,11 +285,57 @@ export class SessionManager {
229
285
  defaultEnvKeys: config.defaultEnv ? Object.keys(config.defaultEnv) : [],
230
286
  envKeys: config.env ? Object.keys(config.env) : [],
231
287
  hasJumpHost: Boolean(config.jumpHost),
288
+ remotePlatform: config.remotePlatform ?? 'posix',
289
+ commandShell: config.commandShell ?? (config.remotePlatform === 'windows' ? 'powershell' : 'posix'),
290
+ remotePathStyle: remotePathStyle(config.remotePlatform ?? 'posix', config.remotePathStyle),
291
+ keyAclStatus: process.platform === 'win32' && config.privateKeyPath
292
+ ? checkWindowsAcl(expandTilde(config.privateKeyPath))
293
+ : undefined,
232
294
  };
233
295
  }
296
+ requirePosixPrivilege(alias) {
297
+ if (this.getRemotePlatform(alias) === 'windows') {
298
+ throw new CommandError('Remote Windows does not support su/sudo/runAs', {
299
+ code: 'unsupported_remote_platform',
300
+ remotePlatform: 'windows',
301
+ });
302
+ }
303
+ }
304
+ getRemotePlatform(alias) {
305
+ return this.getSession(alias).config.remotePlatform ?? 'posix';
306
+ }
307
+ getRemotePathStyle(alias) {
308
+ const config = this.getSession(alias).config;
309
+ return remotePathStyle(config.remotePlatform ?? 'posix', config.remotePathStyle);
310
+ }
311
+ getCommandShell(alias) {
312
+ const config = this.getSession(alias).config;
313
+ return config.commandShell ?? (config.remotePlatform === 'windows' ? 'powershell' : 'posix');
314
+ }
234
315
  getExternalTransferCapability(alias) {
235
316
  const session = this.getSession(alias);
236
317
  const config = session.config;
318
+ if (session.backend === 'openssh') {
319
+ session.transport.assertCurrent();
320
+ return {
321
+ backend: 'openssh',
322
+ controlPath: config.controlPath,
323
+ alias,
324
+ identity: this.sessionIdentity(session),
325
+ host: config.host,
326
+ port: config.port,
327
+ username: config.username,
328
+ authMethod: 'master',
329
+ hasJumpHost: false,
330
+ routeSafeForOpenSsh: true,
331
+ rsyncEligible: true,
332
+ decisionReason: 'existing_openssh_master',
333
+ rsyncExecutable: config.rsyncExecutable,
334
+ rsyncProfile: 'posix',
335
+ commandShell: 'posix',
336
+ remotePathStyle: 'posix',
337
+ };
338
+ }
237
339
  const authMethod = config.privateKeyPath
238
340
  ? 'key-path'
239
341
  : config.privateKey
@@ -245,21 +347,27 @@ export class SessionManager {
245
347
  const routeSafeForOpenSsh = !hasJumpHost;
246
348
  const expandedKeyPath = config.privateKeyPath ? expandTilde(config.privateKeyPath) : undefined;
247
349
  const keyPathUsable = authMethod === 'key-path' && this.isOpenSshKeyPathUsable(expandedKeyPath);
248
- const agentAvailable = authMethod === 'agent' && this.isSshAgentAvailable();
249
- const rsyncEligible = routeSafeForOpenSsh && (keyPathUsable || agentAvailable);
350
+ const agent = session.authAgent ?? config.agent;
351
+ const agentAvailable = authMethod === 'agent' && this.isSshAgentAvailable(agent);
352
+ const profileRequired = (process.platform === 'win32' || config.remotePlatform === 'windows') && !config.rsyncProfile;
353
+ const rsyncEligible = routeSafeForOpenSsh && (keyPathUsable || agentAvailable) && !profileRequired;
250
354
  const decisionReason = hasJumpHost
251
355
  ? 'jump_host_route_requires_live_ssh_session'
252
356
  : authMethod === 'password'
253
357
  ? 'password_not_forwarded_to_openssh'
254
358
  : authMethod === 'inline-key'
255
359
  ? 'inline_private_key_not_written_to_disk'
256
- : authMethod === 'key-path'
257
- ? keyPathUsable
258
- ? 'direct_openssh_compatible_key_path'
259
- : 'key_path_not_openssh_compatible'
260
- : agentAvailable
261
- ? 'direct_ssh_agent_socket'
262
- : 'ssh_agent_socket_unavailable';
360
+ : authMethod === 'key-path' && !keyPathUsable
361
+ ? 'key_path_not_openssh_compatible'
362
+ : authMethod === 'agent' && !agentAvailable
363
+ ? agent
364
+ ? 'ssh_agent_not_openssh_compatible'
365
+ : 'ssh_agent_socket_unavailable'
366
+ : profileRequired
367
+ ? 'rsync_profile_required_for_windows'
368
+ : authMethod === 'key-path'
369
+ ? 'direct_openssh_compatible_key_path'
370
+ : 'direct_ssh_agent_socket';
263
371
  return {
264
372
  alias,
265
373
  identity: this.sessionIdentity(session),
@@ -272,6 +380,11 @@ export class SessionManager {
272
380
  routeSafeForOpenSsh,
273
381
  rsyncEligible,
274
382
  decisionReason,
383
+ agent: config.agent === 'none' ? 'none' : agentAvailable ? agent : undefined,
384
+ rsyncExecutable: config.rsyncExecutable,
385
+ rsyncProfile: config.rsyncProfile,
386
+ commandShell: config.commandShell ?? (config.remotePlatform === 'windows' ? 'powershell' : 'posix'),
387
+ remotePathStyle: remotePathStyle(config.remotePlatform ?? 'posix', config.remotePathStyle),
275
388
  };
276
389
  }
277
390
  /**
@@ -286,6 +399,9 @@ export class SessionManager {
286
399
  return this.execDirect(alias, command, options, { cwd: options.cwd });
287
400
  }
288
401
  operationStart(alias, command, options = {}) {
402
+ if (options.runAs || (this.getSession(alias).config.runAs && !options.useLoginUser)) {
403
+ this.requirePosixPrivilege(alias);
404
+ }
289
405
  return this.operationManager.start(alias, command, options);
290
406
  }
291
407
  operationStatus(operationId) {
@@ -309,6 +425,7 @@ export class SessionManager {
309
425
  * 支持 bash(.bashrc)、zsh(.zshrc) 及其他 shell(.profile)
310
426
  */
311
427
  async execAsUser(alias, command, targetUser, options = {}) {
428
+ this.requirePosixPrivilege(alias);
312
429
  // 校验用户名防止注入
313
430
  if (!this.isValidUsername(targetUser)) {
314
431
  throw new Error(`Invalid username: ${targetUser}`);
@@ -332,10 +449,11 @@ export class SessionManager {
332
449
  * 通过 stdin 传递密码,避免密码出现在进程列表和 audit 日志中
333
450
  */
334
451
  async execSudo(alias, command, sudoPassword, options = {}) {
452
+ this.requirePosixPrivilege(alias);
335
453
  if (!sudoPassword) {
336
454
  return this.exec(alias, `sudo ${command}`, options);
337
455
  }
338
- const session = this.getSession(alias);
456
+ const session = this.requireSsh2Session(alias, 'password-based sudo');
339
457
  const startTime = Date.now();
340
458
  const timeout = options.timeout ?? this.defaultTimeout;
341
459
  const maxOutputSize = this.normalizeMaxOutputSize(options.maxOutputSize);
@@ -370,8 +488,39 @@ export class SessionManager {
370
488
  let stderrTail = '';
371
489
  let stdoutBytes = 0;
372
490
  let stderrBytes = 0;
491
+ let stdoutKeptBytes = 0;
492
+ let stderrKeptBytes = 0;
373
493
  let stdoutTruncated = false;
374
494
  let stderrTruncated = false;
495
+ const stdoutDecoder = new StringDecoder('utf8');
496
+ const stderrDecoder = new StringDecoder('utf8');
497
+ let decodersEnded = false;
498
+ const appendStdout = (chunk) => {
499
+ stdoutTail = this.appendOutputTail(stdoutTail, chunk);
500
+ if (!stdoutTruncated) {
501
+ const appended = this.appendWithinByteLimit(stdout, chunk, maxOutputSize - stdoutKeptBytes);
502
+ stdout = appended.text;
503
+ stdoutKeptBytes += appended.appendedBytes;
504
+ stdoutTruncated = appended.truncated;
505
+ }
506
+ };
507
+ const appendStderr = (chunk) => {
508
+ stderrTail = this.appendOutputTail(stderrTail, chunk);
509
+ if (!stderrTruncated) {
510
+ const appended = this.appendWithinByteLimit(stderr, chunk, maxOutputSize - stderrKeptBytes);
511
+ stderr = appended.text;
512
+ stderrKeptBytes += appended.appendedBytes;
513
+ stderrTruncated = appended.truncated;
514
+ }
515
+ };
516
+ const endDecoders = () => {
517
+ if (decodersEnded) {
518
+ return;
519
+ }
520
+ decodersEnded = true;
521
+ appendStdout(stdoutDecoder.end());
522
+ appendStderr(stderrDecoder.end());
523
+ };
375
524
  const outputPreview = () => ({
376
525
  stdout,
377
526
  stderr,
@@ -388,6 +537,7 @@ export class SessionManager {
388
537
  return;
389
538
  }
390
539
  settled = true;
540
+ endDecoders();
391
541
  try {
392
542
  streamRef?.close();
393
543
  }
@@ -402,6 +552,7 @@ export class SessionManager {
402
552
  this.closeClientChannel(stream);
403
553
  if (!settled) {
404
554
  settled = true;
555
+ endDecoders();
405
556
  reject(new Error('Sudo exec was cancelled because the SSH session changed'));
406
557
  }
407
558
  return;
@@ -410,6 +561,7 @@ export class SessionManager {
410
561
  clearTimeout(timeoutId);
411
562
  if (!settled) {
412
563
  settled = true;
564
+ endDecoders();
413
565
  reject(new Error(`Exec failed: ${err.message}`));
414
566
  }
415
567
  return;
@@ -428,10 +580,11 @@ export class SessionManager {
428
580
  return;
429
581
  }
430
582
  settled = true;
583
+ endDecoders();
431
584
  resolve({
432
585
  success: code === 0,
433
- stdout: stdoutTruncated ? stdout + '\n... [truncated]' : stdout,
434
- stderr: stderrTruncated ? stderr + '\n... [truncated]' : stderr,
586
+ stdout,
587
+ stderr,
435
588
  exitCode: code,
436
589
  duration: Date.now() - startTime,
437
590
  failureKind: code === 0 ? undefined : 'remote_command',
@@ -443,32 +596,18 @@ export class SessionManager {
443
596
  });
444
597
  });
445
598
  stream.on('data', (data) => {
446
- const chunk = data.toString('utf-8');
447
- stdoutBytes += data.length;
448
- stdoutTail = this.appendOutputTail(stdoutTail, chunk);
449
- if (!stdoutTruncated) {
450
- if (stdout.length + chunk.length > maxOutputSize) {
451
- stdout += chunk.slice(0, maxOutputSize - stdout.length);
452
- stdoutTruncated = true;
453
- }
454
- else {
455
- stdout += chunk;
456
- }
599
+ if (settled) {
600
+ return;
457
601
  }
602
+ stdoutBytes += data.length;
603
+ appendStdout(stdoutDecoder.write(data));
458
604
  });
459
605
  stream.stderr.on('data', (data) => {
460
- const chunk = data.toString('utf-8');
461
- stderrBytes += data.length;
462
- stderrTail = this.appendOutputTail(stderrTail, chunk);
463
- if (!stderrTruncated) {
464
- if (stderr.length + chunk.length > maxOutputSize) {
465
- stderr += chunk.slice(0, maxOutputSize - stderr.length);
466
- stderrTruncated = true;
467
- }
468
- else {
469
- stderr += chunk;
470
- }
606
+ if (settled) {
607
+ return;
471
608
  }
609
+ stderrBytes += data.length;
610
+ appendStderr(stderrDecoder.write(data));
472
611
  });
473
612
  });
474
613
  });
@@ -477,7 +616,7 @@ export class SessionManager {
477
616
  * 获取 SFTP 客户端
478
617
  */
479
618
  getSftp(alias) {
480
- const session = this.getSession(alias);
619
+ const session = this.requireSsh2Session(alias, 'SFTP');
481
620
  return new Promise((resolve, reject) => {
482
621
  session.client.sftp((err, sftp) => {
483
622
  if (!this.isCurrentSession(alias, session)) {
@@ -515,27 +654,38 @@ export class SessionManager {
515
654
  return this.ptyManager.list();
516
655
  }
517
656
  async forwardLocal(alias, localPort, remoteHost, remotePort, localHost = '127.0.0.1') {
518
- return this.forwardManager.forwardLocal({ getClient: (a) => this.getSession(a).client }, alias, localPort, remoteHost, remotePort, localHost);
657
+ return this.forwardManager.forwardLocal({ getClient: (a) => this.requireSsh2Session(a, 'port forwarding').client }, alias, localPort, remoteHost, remotePort, localHost);
519
658
  }
520
659
  // ===== Forward 委托 =====
521
660
  async forwardRemote(alias, remotePort, localHost, localPort, remoteHost = '127.0.0.1') {
522
- return this.forwardManager.forwardRemote({ getClient: (a) => this.getSession(a).client }, alias, remotePort, localHost, localPort, remoteHost);
661
+ return this.forwardManager.forwardRemote({ getClient: (a) => this.requireSsh2Session(a, 'port forwarding').client }, alias, remotePort, localHost, localPort, remoteHost);
523
662
  }
524
663
  forwardClose(forwardId, options = {}) {
525
664
  return this.forwardManager.close(forwardId, {
526
- getClient: (a) => this.getSession(a).client,
665
+ getClient: (a) => this.requireSsh2Session(a, 'port forwarding').client,
527
666
  }, options);
528
667
  }
529
668
  forwardList() {
530
669
  return this.forwardManager.list();
531
670
  }
532
- isSshAgentAvailable() {
533
- const socketPath = process.env.SSH_AUTH_SOCK;
534
- if (!socketPath) {
535
- return false;
671
+ requireSsh2Session(alias, capability) {
672
+ const session = this.getSession(alias);
673
+ if (session.backend === 'openssh') {
674
+ throw new OpenSshError(`The OpenSSH backend does not support ${capability}`, {
675
+ code: 'unsupported_backend',
676
+ backend: 'openssh',
677
+ capability,
678
+ retryable: false,
679
+ });
680
+ }
681
+ return session;
682
+ }
683
+ isSshAgentAvailable(socketPath) {
684
+ if (!socketPath || socketPath === 'none' || socketPath === 'pageant') {
685
+ return false; // ssh2 can use Pageant, but the independent OpenSSH rsync process cannot inherit it.
536
686
  }
537
687
  if (process.platform === 'win32') {
538
- return true;
688
+ return /^\\\\\.\\pipe\\openssh-ssh-agent$/i.test(socketPath);
539
689
  }
540
690
  try {
541
691
  return fs.statSync(socketPath).isSocket();
@@ -550,6 +700,9 @@ export class SessionManager {
550
700
  if (!stats.isFile()) {
551
701
  return false;
552
702
  }
703
+ if (process.platform === 'win32' && checkWindowsAcl(keyPath) !== 'key_path_usable') {
704
+ return false;
705
+ }
553
706
  if (process.platform !== 'win32' && (stats.mode & 0o077) !== 0) {
554
707
  return false;
555
708
  }
@@ -572,6 +725,8 @@ export class SessionManager {
572
725
  ? undefined
573
726
  : Object.entries(values).sort(([left], [right]) => left.localeCompare(right));
574
727
  const payload = (value) => ({
728
+ backend: value.backend ?? 'ssh2',
729
+ controlPath: value.controlPath,
575
730
  host: value.host,
576
731
  port: value.port ?? 22,
577
732
  username: value.username,
@@ -585,6 +740,12 @@ export class SessionManager {
585
740
  readyTimeout: value.readyTimeout,
586
741
  lang: value.lang,
587
742
  shell: value.shell,
743
+ agent: value.agent,
744
+ remotePlatform: value.remotePlatform ?? 'posix',
745
+ commandShell: value.commandShell ?? (value.remotePlatform === 'windows' ? 'powershell' : 'posix'),
746
+ remotePathStyle: remotePathStyle(value.remotePlatform ?? 'posix', value.remotePathStyle),
747
+ rsyncExecutable: value.rsyncExecutable,
748
+ rsyncProfile: value.rsyncProfile,
588
749
  password: secretHash(value.password),
589
750
  privateKeyPath: value.privateKeyPath ? path.resolve(expandTilde(value.privateKeyPath)) : undefined,
590
751
  privateKey: secretHash(value.privateKey),
@@ -605,14 +766,25 @@ export class SessionManager {
605
766
  identity: this.sessionIdentity(session),
606
767
  cwd: context.cwd ?? options.cwd,
607
768
  resolvedCwd: context.cwd ?? options.cwd,
608
- shell: session.config.shell,
769
+ shell: session.config.commandShell ?? (session.config.remotePlatform === 'windows' ? 'powershell' : 'posix'),
609
770
  profileLoaded: context.loadProfile,
610
771
  envInjectedKeys: context.envInjectedKeys ?? Object.keys(env).filter((key) => this.isValidEnvKey(key)),
611
772
  };
612
773
  }
774
+ appendWithinByteLimit(current, chunk, available) {
775
+ const bytes = Buffer.from(chunk, 'utf8');
776
+ if (bytes.length <= available) {
777
+ return { text: current + chunk, appendedBytes: bytes.length, truncated: false };
778
+ }
779
+ let end = Math.max(0, available);
780
+ while (end > 0 && end < bytes.length && isUtf8ContinuationByte(bytes[end])) {
781
+ --end;
782
+ }
783
+ return { text: current + bytes.subarray(0, end).toString('utf8'), appendedBytes: end, truncated: true };
784
+ }
613
785
  appendOutputTail(current, chunk) {
614
- const next = current + chunk;
615
- return next.length > OUTPUT_PREVIEW_CHARS ? next.slice(-OUTPUT_PREVIEW_CHARS) : next;
786
+ const next = Buffer.from(current + chunk, 'utf8');
787
+ return retainUtf8Suffix(next, OUTPUT_PREVIEW_CHARS).toString('utf8');
616
788
  }
617
789
  recommendedReadCommand() {
618
790
  return ('将远端命令输出重定向到文件,例如 command > /tmp/mcp-ssh-output.txt 2>&1,' +
@@ -634,9 +806,13 @@ export class SessionManager {
634
806
  return {
635
807
  stdoutBytes: preview.stdoutBytes,
636
808
  stderrBytes: preview.stderrBytes,
637
- stdoutHead: preview.stdoutTruncated ? preview.stdout.slice(0, OUTPUT_PREVIEW_CHARS) : undefined,
809
+ stdoutHead: preview.stdoutTruncated
810
+ ? this.appendWithinByteLimit('', preview.stdout, OUTPUT_PREVIEW_CHARS).text
811
+ : undefined,
638
812
  stdoutTail: preview.stdoutTruncated ? preview.stdoutTail : undefined,
639
- stderrHead: preview.stderrTruncated ? preview.stderr.slice(0, OUTPUT_PREVIEW_CHARS) : undefined,
813
+ stderrHead: preview.stderrTruncated
814
+ ? this.appendWithinByteLimit('', preview.stderr, OUTPUT_PREVIEW_CHARS).text
815
+ : undefined,
640
816
  stderrTail: preview.stderrTruncated ? preview.stderrTail : undefined,
641
817
  recommendedReadCommand: truncated ? this.recommendedReadCommand() : undefined,
642
818
  maxOutputSize: truncated ? preview.maxOutputSize : undefined,
@@ -657,17 +833,55 @@ export class SessionManager {
657
833
  }
658
834
  return maxOutputSize;
659
835
  }
836
+ openCommandChannel(session, command, options, callback) {
837
+ if (session.backend === 'openssh') {
838
+ if (options.pty) {
839
+ callback(new OpenSshError('The OpenSSH backend does not support PTY', {
840
+ code: 'unsupported_backend',
841
+ backend: 'openssh',
842
+ capability: 'PTY',
843
+ retryable: false,
844
+ }));
845
+ return;
846
+ }
847
+ try {
848
+ callback(undefined, session.transport.open(command));
849
+ }
850
+ catch (error) {
851
+ callback(error instanceof Error ? error : new Error(String(error)));
852
+ }
853
+ }
854
+ else {
855
+ session.client.exec(command, options, callback);
856
+ }
857
+ }
660
858
  async openOperationStream(alias, command, marker, options, adopt) {
661
859
  const session = this.getSession(alias);
662
860
  const markerEnv = `MCP_SSH_OPERATION_MARKER=${this.escapeShellArg(marker)}`;
663
861
  const markerLine = `__MCP_SSH_OPERATION__:${marker}:%s:%s\\n`;
664
862
  const operationScript = this.escapeShellArg(`printf ${this.escapeShellArg(markerLine)} "$$" "$1" >&2; exec sh -c ${this.escapeShellArg(command)}`);
665
863
  const wrappedCommand = `if command -v setsid >/dev/null 2>&1; then ` +
666
- `exec env ${markerEnv} setsid sh -c ${operationScript} sh 1; ` +
864
+ `exec env ${markerEnv} setsid -w sh -c ${operationScript} sh 1; ` +
667
865
  `else exec env ${markerEnv} sh -c ${operationScript} sh 0; fi`;
668
866
  const runAs = options.useLoginUser ? undefined : (options.runAs ?? session.config.runAs);
669
867
  let fullCommand;
670
- if (runAs) {
868
+ if (session.config.remotePlatform === 'windows') {
869
+ if (runAs) {
870
+ this.requirePosixPrivilege(alias);
871
+ }
872
+ const execution = session.config.commandShell === 'cmd'
873
+ ? `& cmd.exe /D /C ${quotePowershell(command)}`
874
+ : `& { ${command} }`;
875
+ const script = [
876
+ `$operationMarker = ${quotePowershell(marker)}`,
877
+ '$created = (Get-Process -Id $PID).StartTime.ToUniversalTime().Ticks',
878
+ '[Console]::Error.WriteLine("__MCP_SSH_OPERATION__:{0}:{1}:0:{2}", $operationMarker, $PID, $created)',
879
+ execution,
880
+ 'if (-not $?) { exit 1 }',
881
+ ].join('; ');
882
+ fullCommand = this.buildCommand(encodedPowershell(script), session, options);
883
+ }
884
+ else if (runAs) {
671
885
  if (!this.isValidUsername(runAs)) {
672
886
  throw new Error(`Invalid username: ${runAs}`);
673
887
  }
@@ -679,19 +893,22 @@ export class SessionManager {
679
893
  fullCommand = this.buildCommand(wrappedCommand, session, options);
680
894
  }
681
895
  return new Promise((resolve, reject) => {
682
- session.client.exec(fullCommand, {}, (error, stream) => {
896
+ this.openCommandChannel(session, fullCommand, {}, (error, stream) => {
683
897
  if (!this.isCurrentSession(alias, session)) {
684
898
  this.closeClientChannel(stream);
685
899
  reject(new Error('Operation start was cancelled because the SSH session changed'));
686
900
  return;
687
901
  }
688
- if (error) {
689
- reject(new Error(`Operation start failed: ${error.message}`));
902
+ if (error || !stream) {
903
+ reject(error ?? new Error('Operation start did not return a command channel'));
690
904
  return;
691
905
  }
692
906
  try {
693
907
  adopt(stream);
694
- resolve();
908
+ if (stream.ready)
909
+ void stream.ready.then(resolve, reject);
910
+ else
911
+ resolve();
695
912
  }
696
913
  catch (adoptionError) {
697
914
  this.closeClientChannel(stream);
@@ -700,7 +917,43 @@ export class SessionManager {
700
917
  });
701
918
  });
702
919
  }
703
- async cancelRemoteOperation(alias, pid, marker, processGroup, options) {
920
+ async cancelRemoteOperation(alias, pid, marker, processGroup, options, processCreatedAt) {
921
+ if (this.getRemotePlatform(alias) === 'windows') {
922
+ if (!processCreatedAt || !/^[1-9]\d*$/.test(processCreatedAt)) {
923
+ return {
924
+ success: false,
925
+ cancellationStatus: 'unsupported',
926
+ error: 'unsupported_remote_platform: process creation time is unavailable',
927
+ };
928
+ }
929
+ const script = [
930
+ '$ErrorActionPreference = "Stop"',
931
+ `$remotePid = ${pid}`,
932
+ `$expectedTicks = ${quotePowershell(processCreatedAt)}`,
933
+ `$expectedMarker = ${quotePowershell(marker)}`,
934
+ '$process = Get-CimInstance Win32_Process -Filter "ProcessId=$remotePid"',
935
+ 'if (-not $process -or $process.CommandLine -notmatch "-EncodedCommand\\s+([A-Za-z0-9+/=]+)") { throw "process identity unavailable" }',
936
+ '$script = [Text.Encoding]::Unicode.GetString([Convert]::FromBase64String($Matches[1]))',
937
+ 'if (-not $script.Contains($expectedMarker)) { throw "operation marker mismatch" }',
938
+ '$start = (Get-Process -Id $remotePid).StartTime.ToUniversalTime().Ticks.ToString()',
939
+ 'if ($start -ne $expectedTicks) { throw "process creation time mismatch" }',
940
+ 'taskkill.exe /PID $remotePid /T /F',
941
+ 'if ($LASTEXITCODE -ne 0) { throw "tree termination failed" }',
942
+ ].join('; ');
943
+ try {
944
+ const result = await this.exec(alias, encodedPowershell(script), {
945
+ useLoginUser: true,
946
+ timeout: 5000,
947
+ maxOutputSize: 4096,
948
+ });
949
+ return result.success
950
+ ? { success: true }
951
+ : { success: false, error: result.stderr || `Remote cancel exited with code ${result.exitCode}` };
952
+ }
953
+ catch (error) {
954
+ return { success: false, error: error instanceof Error ? error.message : String(error) };
955
+ }
956
+ }
704
957
  const expectedMarker = `MCP_SSH_OPERATION_MARKER=${marker}`;
705
958
  const signalTarget = processGroup ? `-${pid}` : `${pid}`;
706
959
  const command = [
@@ -709,7 +962,7 @@ export class SessionManager {
709
962
  'if [ ! -r "/proc/$pid/environ" ]; then printf "operation marker unavailable" >&2; exit 3; fi',
710
963
  'if ! tr "\\000" "\\n" < "/proc/$pid/environ" | grep -Fqx -- "$expected"; then ' +
711
964
  'printf "operation marker mismatch" >&2; exit 4; fi',
712
- `kill -TERM -- ${signalTarget}`,
965
+ `kill -TERM ${signalTarget}`,
713
966
  ].join('; ');
714
967
  try {
715
968
  const result = await this.exec(alias, command, {
@@ -741,10 +994,41 @@ export class SessionManager {
741
994
  let stderrTail = '';
742
995
  let stdoutBytes = 0;
743
996
  let stderrBytes = 0;
997
+ let stdoutKeptBytes = 0;
998
+ let stderrKeptBytes = 0;
744
999
  let stdoutTruncated = false;
745
1000
  let stderrTruncated = false;
746
1001
  let settled = false;
747
1002
  let activeStream = null;
1003
+ const stdoutDecoder = new StringDecoder('utf8');
1004
+ const stderrDecoder = new StringDecoder('utf8');
1005
+ let decodersEnded = false;
1006
+ const appendStdout = (chunk) => {
1007
+ stdoutTail = this.appendOutputTail(stdoutTail, chunk);
1008
+ if (!stdoutTruncated) {
1009
+ const appended = this.appendWithinByteLimit(stdout, chunk, maxOutputSize - stdoutKeptBytes);
1010
+ stdout = appended.text;
1011
+ stdoutKeptBytes += appended.appendedBytes;
1012
+ stdoutTruncated = appended.truncated;
1013
+ }
1014
+ };
1015
+ const appendStderr = (chunk) => {
1016
+ stderrTail = this.appendOutputTail(stderrTail, chunk);
1017
+ if (!stderrTruncated) {
1018
+ const appended = this.appendWithinByteLimit(stderr, chunk, maxOutputSize - stderrKeptBytes);
1019
+ stderr = appended.text;
1020
+ stderrKeptBytes += appended.appendedBytes;
1021
+ stderrTruncated = appended.truncated;
1022
+ }
1023
+ };
1024
+ const endDecoders = () => {
1025
+ if (decodersEnded) {
1026
+ return;
1027
+ }
1028
+ decodersEnded = true;
1029
+ appendStdout(stdoutDecoder.end());
1030
+ appendStderr(stderrDecoder.end());
1031
+ };
748
1032
  const execOptions = {};
749
1033
  if (options.pty) {
750
1034
  execOptions.pty = {
@@ -775,21 +1059,23 @@ export class SessionManager {
775
1059
  return;
776
1060
  }
777
1061
  settled = true;
1062
+ endDecoders();
778
1063
  clearTimer();
779
1064
  activeStream?.close();
780
1065
  reject(error);
781
1066
  };
782
1067
  timeoutId = setTimeout(() => {
1068
+ endDecoders();
783
1069
  rejectOnce(this.createCommandTimeoutError(alias, timeout, context, outputPreview()));
784
1070
  }, timeout);
785
- session.client.exec(fullCommand, execOptions, (err, stream) => {
1071
+ this.openCommandChannel(session, fullCommand, execOptions, (err, stream) => {
786
1072
  if (!this.isCurrentSession(alias, session)) {
787
1073
  this.closeClientChannel(stream);
788
1074
  rejectOnce(new Error('Exec was cancelled because the SSH session changed'));
789
1075
  return;
790
1076
  }
791
- if (err) {
792
- rejectOnce(new Error(`Exec failed: ${err.message}`));
1077
+ if (err || !stream) {
1078
+ rejectOnce(err ?? new Error('Exec did not return a command channel'));
793
1079
  return;
794
1080
  }
795
1081
  if (settled) {
@@ -797,16 +1083,28 @@ export class SessionManager {
797
1083
  return;
798
1084
  }
799
1085
  activeStream = stream;
1086
+ stream.on('error', (error) => {
1087
+ rejectOnce(new CommandError(error.message, {
1088
+ failureKind: 'ssh_transport',
1089
+ operationStatus: 'unknown',
1090
+ retryable: false,
1091
+ stdout,
1092
+ stderr,
1093
+ ...this.outputMetadata(outputPreview()),
1094
+ ...this.resultMetadata(session, options, context),
1095
+ }));
1096
+ });
800
1097
  stream.on('close', (code) => {
801
1098
  if (settled) {
802
1099
  return;
803
1100
  }
804
1101
  settled = true;
1102
+ endDecoders();
805
1103
  clearTimer();
806
1104
  resolve({
807
1105
  success: code === 0,
808
- stdout: stdoutTruncated ? stdout + '\n... [truncated]' : stdout,
809
- stderr: stderrTruncated ? stderr + '\n... [truncated]' : stderr,
1106
+ stdout,
1107
+ stderr,
810
1108
  exitCode: code,
811
1109
  duration: Date.now() - startTime,
812
1110
  failureKind: code === 0 ? undefined : 'remote_command',
@@ -818,32 +1116,18 @@ export class SessionManager {
818
1116
  });
819
1117
  });
820
1118
  stream.on('data', (data) => {
821
- const chunk = data.toString('utf-8');
822
- stdoutBytes += data.length;
823
- stdoutTail = this.appendOutputTail(stdoutTail, chunk);
824
- if (!stdoutTruncated) {
825
- if (stdout.length + chunk.length > maxOutputSize) {
826
- stdout += chunk.slice(0, maxOutputSize - stdout.length);
827
- stdoutTruncated = true;
828
- }
829
- else {
830
- stdout += chunk;
831
- }
1119
+ if (settled) {
1120
+ return;
832
1121
  }
1122
+ stdoutBytes += data.length;
1123
+ appendStdout(stdoutDecoder.write(data));
833
1124
  });
834
1125
  stream.stderr.on('data', (data) => {
835
- const chunk = data.toString('utf-8');
836
- stderrBytes += data.length;
837
- stderrTail = this.appendOutputTail(stderrTail, chunk);
838
- if (!stderrTruncated) {
839
- if (stderr.length + chunk.length > maxOutputSize) {
840
- stderr += chunk.slice(0, maxOutputSize - stderr.length);
841
- stderrTruncated = true;
842
- }
843
- else {
844
- stderr += chunk;
845
- }
1126
+ if (settled) {
1127
+ return;
846
1128
  }
1129
+ stderrBytes += data.length;
1130
+ appendStderr(stderrDecoder.write(data));
847
1131
  });
848
1132
  });
849
1133
  });
@@ -865,6 +1149,35 @@ export class SessionManager {
865
1149
  existing.lastUsedAt = Date.now();
866
1150
  return alias;
867
1151
  }
1152
+ if (existing) {
1153
+ existing.manualClose = true;
1154
+ if (existing.reconnectTimer)
1155
+ clearTimeout(existing.reconnectTimer);
1156
+ this.invalidateAliasResources(alias);
1157
+ if (existing.backend === 'openssh')
1158
+ existing.transport.close();
1159
+ else
1160
+ existing.client.end();
1161
+ }
1162
+ if (config.backend === 'openssh') {
1163
+ const transport = await OpenSshConnection.connect(config, pendingConnection.signal);
1164
+ if (!this.isCurrentPendingConnection(alias, pendingConnection)) {
1165
+ transport.close();
1166
+ throw new Error(`Connection for alias '${alias}' was cancelled before ready`);
1167
+ }
1168
+ this.sessions.set(alias, {
1169
+ backend: 'openssh',
1170
+ transport,
1171
+ config,
1172
+ connectedAt: Date.now(),
1173
+ lastUsedAt: Date.now(),
1174
+ reconnectAttempts: 0,
1175
+ connected: true,
1176
+ manualClose: false,
1177
+ });
1178
+ this.persistSessions();
1179
+ return alias;
1180
+ }
868
1181
  const client = new Client();
869
1182
  pendingConnection.client = client;
870
1183
  const readyTimeout = config.readyTimeout ?? this.defaultTimeout;
@@ -884,6 +1197,12 @@ export class SessionManager {
884
1197
  const keyPath = expandTilde(config.privateKeyPath);
885
1198
  // 路径白名单 + 大小上限校验,避免任意文件读取
886
1199
  validateKeyFile(keyPath);
1200
+ if (process.platform === 'win32') {
1201
+ const aclStatus = checkWindowsAcl(keyPath);
1202
+ if (aclStatus !== 'key_path_usable') {
1203
+ throw new CommandError(`Private key ACL check failed: ${aclStatus}`, { code: aclStatus });
1204
+ }
1205
+ }
887
1206
  connectConfig.privateKey = fs.readFileSync(keyPath);
888
1207
  }
889
1208
  if (config.privateKey) {
@@ -892,6 +1211,19 @@ export class SessionManager {
892
1211
  if (config.passphrase) {
893
1212
  connectConfig.passphrase = config.passphrase;
894
1213
  }
1214
+ const agent = config.agent ??
1215
+ (!config.password && !config.privateKey && !config.privateKeyPath
1216
+ ? process.env.SSH_AUTH_SOCK
1217
+ : undefined);
1218
+ if (agent && agent !== 'none') {
1219
+ if (agent === 'pageant' && process.platform !== 'win32') {
1220
+ throw new Error('Pageant authentication is only available on Windows');
1221
+ }
1222
+ if (agent !== 'pageant' && !agent.startsWith('\\\\.\\pipe\\') && !fs.existsSync(agent)) {
1223
+ throw new Error('SSH agent socket or pipe is unavailable');
1224
+ }
1225
+ connectConfig.agent = agent;
1226
+ }
895
1227
  }
896
1228
  catch (error) {
897
1229
  throw this.createConnectionError(error, config, readyTimeout, 'key_read');
@@ -915,7 +1247,7 @@ export class SessionManager {
915
1247
  throw this.createConnectionError(error, jumpConfig, jumpConfig.readyTimeout, 'jump_connect');
916
1248
  }
917
1249
  const jumpSession = this.sessions.get(jumpAlias);
918
- if (!jumpSession || !this.isAlive(jumpSession)) {
1250
+ if (!jumpSession || jumpSession.backend === 'openssh' || !this.isAlive(jumpSession)) {
919
1251
  throw new ConnectionError(`Jump host session '${jumpAlias}' is unavailable`, {
920
1252
  failureStage: 'transport_or_handshake',
921
1253
  connectionStep: 'jump_connect',
@@ -960,6 +1292,7 @@ export class SessionManager {
960
1292
  const session = {
961
1293
  client,
962
1294
  config,
1295
+ authAgent: typeof connectConfig.agent === 'string' ? connectConfig.agent : undefined,
963
1296
  connectedAt: Date.now(),
964
1297
  lastUsedAt: Date.now(),
965
1298
  reconnectAttempts: 0,
@@ -972,14 +1305,14 @@ export class SessionManager {
972
1305
  });
973
1306
  client.on('error', (error) => {
974
1307
  const session = this.sessions.get(alias);
975
- if (session && session.client === client) {
1308
+ if (session && session.backend !== 'openssh' && session.client === client) {
976
1309
  session.connected = false;
977
1310
  }
978
1311
  rejectConnection(error);
979
1312
  });
980
1313
  client.on('close', () => {
981
1314
  const session = this.sessions.get(alias);
982
- if (session && session.client === client) {
1315
+ if (session && session.backend !== 'openssh' && session.client === client) {
983
1316
  session.connected = false;
984
1317
  this.invalidateAliasResources(alias);
985
1318
  if (!session.manualClose) {
@@ -992,6 +1325,7 @@ export class SessionManager {
992
1325
  });
993
1326
  try {
994
1327
  client.connect(connectConfig);
1328
+ client.setNoDelay(true);
995
1329
  }
996
1330
  catch (error) {
997
1331
  rejectConnection(error);
@@ -1002,7 +1336,7 @@ export class SessionManager {
1002
1336
  * 执行带 PTY 的命令,返回原始 stream(供 PtyManager 使用)
1003
1337
  */
1004
1338
  execPtyStream(alias, command, options) {
1005
- const session = this.getSession(alias);
1339
+ const session = this.requireSsh2Session(alias, 'PTY');
1006
1340
  const fullCommand = this.buildCommand(command, session, { env: options.env, cwd: options.cwd });
1007
1341
  return new Promise((resolve, reject) => {
1008
1342
  session.client.exec(fullCommand, {
@@ -1030,6 +1364,14 @@ export class SessionManager {
1030
1364
  if (!fs.existsSync(dir)) {
1031
1365
  fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
1032
1366
  }
1367
+ if (process.platform === 'win32') {
1368
+ if (checkWindowsAcl(dir, true) !== 'key_path_usable') {
1369
+ throw new Error('privacy_not_enforced_on_windows: session directory ACL could not be verified');
1370
+ }
1371
+ if (fs.existsSync(this.persistPath) && checkWindowsAcl(this.persistPath, true) !== 'key_path_usable') {
1372
+ throw new Error('privacy_not_enforced_on_windows: existing session file ACL could not be verified');
1373
+ }
1374
+ }
1033
1375
  }
1034
1376
  /**
1035
1377
  * 生成连接别名
@@ -1104,11 +1446,10 @@ export class SessionManager {
1104
1446
  * 检查连接是否存活
1105
1447
  */
1106
1448
  isAlive(session) {
1107
- return session.connected;
1449
+ return session.connected && (session.backend !== 'openssh' || session.transport.isAlive());
1108
1450
  }
1109
1451
  isCurrentSession(alias, session) {
1110
- const currentSession = this.sessions.get(alias);
1111
- return currentSession === session && currentSession.client === session.client && currentSession.connected;
1452
+ return this.sessions.get(alias) === session && this.isAlive(session);
1112
1453
  }
1113
1454
  closeClientChannel(stream) {
1114
1455
  try {
@@ -1137,7 +1478,7 @@ export class SessionManager {
1137
1478
  */
1138
1479
  scheduleReconnect(alias) {
1139
1480
  const session = this.sessions.get(alias);
1140
- if (!session || session.reconnectAttempts >= this.maxReconnectAttempts) {
1481
+ if (!session || session.backend === 'openssh' || session.reconnectAttempts >= this.maxReconnectAttempts) {
1141
1482
  return;
1142
1483
  }
1143
1484
  // 清掉旧的定时器,防止重复调度
@@ -1148,7 +1489,7 @@ export class SessionManager {
1148
1489
  const attempt = session.reconnectAttempts;
1149
1490
  session.reconnectTimer = setTimeout(async () => {
1150
1491
  const current = this.sessions.get(alias);
1151
- if (current !== session || current.client !== session.client) {
1492
+ if (current !== session) {
1152
1493
  return;
1153
1494
  }
1154
1495
  session.reconnectTimer = undefined;
@@ -1156,7 +1497,7 @@ export class SessionManager {
1156
1497
  await this.reconnect(alias);
1157
1498
  }
1158
1499
  catch (err) {
1159
- console.error(`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}):`, err.message);
1500
+ console.error(`Auto-reconnect failed for ${alias} (${attempt}/${this.maxReconnectAttempts}): ${err.message}`);
1160
1501
  if (this.sessions.get(alias) === session) {
1161
1502
  this.scheduleReconnect(alias);
1162
1503
  }
@@ -1174,9 +1515,9 @@ export class SessionManager {
1174
1515
  loadProfile: context.loadProfile,
1175
1516
  cwd: context.cwd,
1176
1517
  remoteProcessKnown: false,
1177
- stdoutHead: preview?.stdout.slice(0, OUTPUT_PREVIEW_CHARS),
1518
+ stdoutHead: preview ? this.appendWithinByteLimit('', preview.stdout, OUTPUT_PREVIEW_CHARS).text : undefined,
1178
1519
  stdoutTail: preview?.stdoutTail,
1179
- stderrHead: preview?.stderr.slice(0, OUTPUT_PREVIEW_CHARS),
1520
+ stderrHead: preview ? this.appendWithinByteLimit('', preview.stderr, OUTPUT_PREVIEW_CHARS).text : undefined,
1180
1521
  stderrTail: preview?.stderrTail,
1181
1522
  stdoutBytes: preview?.stdoutBytes,
1182
1523
  stderrBytes: preview?.stderrBytes,
@@ -1198,6 +1539,15 @@ export class SessionManager {
1198
1539
  connectionStep: error.details.connectionStep ?? connectionStep,
1199
1540
  });
1200
1541
  }
1542
+ if (error instanceof CommandError &&
1543
+ (error.details.code === 'key_acl_insecure' || error.details.code === 'key_acl_unverified')) {
1544
+ return new ConnectionError(error.message, {
1545
+ failureStage: 'preflight',
1546
+ connectionStep,
1547
+ retryable: false,
1548
+ keyAclStatus: error.details.code,
1549
+ });
1550
+ }
1201
1551
  const err = error instanceof Error ? error : new Error(String(error));
1202
1552
  const target = `${config.username}@${config.host}:${config.port ?? 22}`;
1203
1553
  return new ConnectionError(`SSH connection to ${target} failed: ${sanitizeKeyError(err.message)}`, {
@@ -1262,23 +1612,11 @@ export class SessionManager {
1262
1612
  * 构建完整命令:注入环境变量 + 切换工作目录
1263
1613
  */
1264
1614
  buildCommand(command, session, options) {
1265
- const segments = [];
1266
1615
  const env = options.skipSessionEnv
1267
1616
  ? { ...options.env }
1268
1617
  : { ...session.config.defaultEnv, ...session.config.env, ...options.env };
1269
- if (options.cwd) {
1270
- segments.push(`cd ${this.escapeShellArg(options.cwd)}`);
1271
- }
1272
- for (const [key, value] of Object.entries(env)) {
1273
- if (this.isValidEnvKey(key)) {
1274
- segments.push(`export ${key}=${this.escapeShellArg(value)}`);
1275
- }
1276
- }
1277
- if (segments.length === 0) {
1278
- return command;
1279
- }
1280
- segments.push(`eval ${this.escapeShellArg(command)}`);
1281
- return segments.join(' && ');
1618
+ const shell = session.config.commandShell ?? (session.config.remotePlatform === 'windows' ? 'powershell' : 'posix');
1619
+ return buildRemoteCommand(command, shell, options.cwd, env);
1282
1620
  }
1283
1621
  /**
1284
1622
  * 根据用户 shell 类型生成加载配置文件的命令
@@ -1307,6 +1645,31 @@ export class SessionManager {
1307
1645
  connectedAt: session.connectedAt,
1308
1646
  });
1309
1647
  }
1648
+ if (process.platform === 'win32') {
1649
+ const temporary = `${this.persistPath}.${randomUUID()}.tmp`;
1650
+ this.persistQueue = this.persistQueue
1651
+ .then(async () => {
1652
+ try {
1653
+ const handle = await fs.promises.open(temporary, 'wx', 0o600);
1654
+ try {
1655
+ if (checkWindowsAcl(temporary, true) !== 'key_path_usable') {
1656
+ throw new Error('privacy_not_enforced_on_windows: session file ACL could not be verified');
1657
+ }
1658
+ await handle.writeFile(JSON.stringify(data, null, 2));
1659
+ await handle.sync();
1660
+ }
1661
+ finally {
1662
+ await handle.close();
1663
+ }
1664
+ await fs.promises.rename(temporary, this.persistPath);
1665
+ }
1666
+ finally {
1667
+ await fs.promises.rm(temporary, { force: true });
1668
+ }
1669
+ })
1670
+ .catch((err) => console.error('[SSH] 会话持久化写入失败:', err));
1671
+ return;
1672
+ }
1310
1673
  fs.promises
1311
1674
  .writeFile(this.persistPath, JSON.stringify(data, null, 2), { mode: 0o600 })
1312
1675
  .catch((err) => console.error('[SSH] 会话持久化写入失败:', err));