@pyrokine/mcp-ssh 2.4.2 → 3.0.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.
@@ -8,9 +8,12 @@ import { createHash, randomBytes } from 'crypto';
8
8
  import * as fs from 'fs';
9
9
  import * as path from 'path';
10
10
  import { z } from 'zod';
11
- import { buildRemoteDirectoryManifestCommand, compareDirectoryManifests, createEmptyDirectoryManifest, createLocalDirectoryManifest, DIRECTORY_VERIFY_MAX_ENTRIES, DIRECTORY_VERIFY_MAX_FILE_BYTES, DIRECTORY_VERIFY_MAX_TOTAL_BYTES, parseRemoteDirectoryManifest, } from '../directory-verification.js';
11
+ import { compareDirectoryManifests, createEmptyDirectoryManifest, createLocalDirectoryManifest, createRemoteDirectoryManifest, DIRECTORY_VERIFY_MAX_ENTRIES, DIRECTORY_VERIFY_MAX_FILE_BYTES, DIRECTORY_VERIFY_MAX_TOTAL_BYTES, } from '../directory-verification.js';
12
+ import { FILE_CREATE_MODE_MASK, formatFileMode, parseExpectedFileMode } from '../file-mode.js';
12
13
  import * as fileOps from '../file-ops.js';
13
14
  import { sessionManager } from '../session-manager.js';
15
+ import { withSftpOperationTimeout } from '../sftp-timeout.js';
16
+ import { encodedPowershell, quotePowershell, remoteDirname, remoteJoin, remoteShellPath, sftpPath, } from '../remote-platform.js';
14
17
  import { buildTransferOutcome } from '../transfer-outcome.js';
15
18
  import { operationTimeoutSchema } from './schema.js';
16
19
  import { escapeShellArg, formatError, formatResult } from './utils.js';
@@ -21,7 +24,7 @@ const uploadSchema = z.object({
21
24
  remotePath: z.string().describe('远程目标路径'),
22
25
  atomic: z.boolean().optional().describe('是否先上传到同目录临时文件,校验后 rename 到目标路径'),
23
26
  verifyOwner: z.union([z.string(), z.number()]).optional().describe('上传后校验远端 owner(用户名或 uid)'),
24
- verifyMode: z.string().optional().describe('上传后校验远端权限,例如 0644 或 -rw-r--r--'),
27
+ verifyMode: z.string().optional().describe('上传后校验远端权限,例如 0644、4755 或 -rwsr-xr-x'),
25
28
  verifyMd5: z.boolean().optional().describe('上传后比对本地和远端 MD5'),
26
29
  verifySize: z.boolean().optional().describe('上传后校验文件大小'),
27
30
  verifyMtime: z.boolean().optional().describe('上传后返回并比较本地和远端 mtime'),
@@ -50,7 +53,15 @@ const readFileSchema = z.object({
50
53
  .optional()
51
54
  .describe('从 UTF-8 字符边界的字节偏移读取,与 tail/lineRange 互斥;使用上次返回的 next_offset'),
52
55
  tail: z.boolean().optional().describe('读取文件尾部 maxBytes 字节,与 offset/lineRange 互斥'),
53
- lineRange: z.string().optional().describe('按行号读取,格式为 "start-end" 或 "start",与 offset/tail 互斥'),
56
+ lineRange: z
57
+ .string()
58
+ .optional()
59
+ .describe('通过 SFTP 按行号读取,格式为 "start-end" 或 "start",与 offset/tail 互斥'),
60
+ encoding: z
61
+ .enum(['auto', 'utf8', 'utf16le', 'utf16be', 'gbk'])
62
+ .optional()
63
+ .describe('文本编码;auto 在文件起始处检测 UTF-16 BOM,否则用 UTF-8'),
64
+ binary: z.boolean().optional().describe('无损 base64 输出,不执行文本解码'),
54
65
  timeout: operationTimeoutSchema.optional(),
55
66
  });
56
67
  const writeFileSchema = z.object({
@@ -94,13 +105,19 @@ const syncSchema = z.object({
94
105
  connectTimeout: z.number().int().positive().max(120000).optional().describe('rsync SSH 连接超时,默认 30000ms'),
95
106
  operationTimeout: z.number().int().positive().max(3600000).optional().describe('同步操作超时,默认 600000ms'),
96
107
  verifyOwner: z.union([z.string(), z.number()]).optional().describe('upload 后校验远端 owner(用户名或 uid)'),
97
- verifyMode: z.string().optional().describe('upload 后校验远端权限,例如 0644 或 -rw-r--r--'),
108
+ verifyMode: z.string().optional().describe('upload 后校验远端权限,例如 0644、4755 或 -rwsr-xr-x'),
98
109
  verify: z
99
110
  .object({
100
111
  count: z.boolean().optional().describe('校验目录条目数'),
101
112
  sha256: z.boolean().optional().describe('校验 SHA-256 root manifest'),
102
113
  owner: z.boolean().optional().describe('逐项校验 owner'),
103
- mode: z.boolean().optional().describe('逐项校验 mode'),
114
+ mode: z.boolean().optional().describe('逐项校验 POSIX mode;Windows 不支持'),
115
+ aclSddl: z
116
+ .string()
117
+ .min(1)
118
+ .max(8192)
119
+ .optional()
120
+ .describe('Windows 远端目录根路径的预期 DACL SDDL,独立于 POSIX mode/owner'),
104
121
  deletions: z.boolean().optional().describe('校验请求删除后没有额外条目'),
105
122
  staleFiles: z.boolean().optional().describe('校验没有旧文件残留'),
106
123
  maxEntries: z
@@ -195,6 +212,9 @@ function summarizeLocalPathProbe(probe) {
195
212
  if ('mode' in probe) {
196
213
  summary.mode = probe.mode;
197
214
  }
215
+ if ('modeValue' in probe) {
216
+ summary.modeValue = probe.modeValue;
217
+ }
198
218
  if ('mtimeMs' in probe) {
199
219
  summary.mtimeMs = probe.mtimeMs;
200
220
  }
@@ -217,8 +237,11 @@ function uploadPathError(code, message, diagnostics) {
217
237
  diagnostics,
218
238
  });
219
239
  }
240
+ function normalizeRemotePath(alias, remotePath) {
241
+ return sftpPath(remotePath, sessionManager.getRemotePathStyle(alias));
242
+ }
220
243
  async function probeRemoteParent(alias, remotePath) {
221
- const parent = path.posix.dirname(remotePath);
244
+ const parent = remoteDirname(sessionManager.getRemotePathStyle(alias), remotePath);
222
245
  try {
223
246
  const result = await probeRemoteFile(alias, parent);
224
247
  return {
@@ -294,26 +317,6 @@ async function resolveExpectedOwnerId(alias, owner) {
294
317
  }
295
318
  return ownerId;
296
319
  }
297
- function permissionStringToOctal(permissions) {
298
- const bits = permissions.slice(-9);
299
- if (bits.length !== 9) {
300
- return undefined;
301
- }
302
- const values = [bits.slice(0, 3), bits.slice(3, 6), bits.slice(6, 9)].map((part) => {
303
- let value = 0;
304
- if (part[0] === 'r') {
305
- value += 4;
306
- }
307
- if (part[1] === 'w') {
308
- value += 2;
309
- }
310
- if (part[2] === 'x' || part[2] === 's' || part[2] === 't') {
311
- value += 1;
312
- }
313
- return value;
314
- });
315
- return `0${values.join('')}`;
316
- }
317
320
  function isRemoteMissingError(error) {
318
321
  if (!error || typeof error !== 'object') {
319
322
  return false;
@@ -333,13 +336,6 @@ async function probeRemoteFile(alias, remotePath, timeout = 10000) {
333
336
  }
334
337
  throw new VerificationStageError('remote_probe', `Remote SFTP stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod: 'sftp' });
335
338
  }
336
- const mode = permissionStringToOctal(info.permissions);
337
- if (!mode) {
338
- throw new VerificationStageError('remote_probe', 'Remote SFTP stat returned invalid mode metadata', false, {
339
- operation: 'stat',
340
- probeMethod: 'sftp',
341
- });
342
- }
343
339
  return {
344
340
  exists: true,
345
341
  remotePath,
@@ -348,7 +344,9 @@ async function probeRemoteFile(alias, remotePath, timeout = 10000) {
348
344
  ownerId: info.owner,
349
345
  groupName: undefined,
350
346
  groupId: info.group,
351
- mode,
347
+ mode: formatFileMode(info.mode),
348
+ modeValue: info.mode,
349
+ permissions: info.permissions,
352
350
  size: info.size,
353
351
  mtimeMs: info.mtime.getTime(),
354
352
  fileType: info.isDirectory
@@ -374,7 +372,7 @@ async function buildUploadVerification(args, local, verificationRemotePath = arg
374
372
  }
375
373
  if (args.verifyMode) {
376
374
  const expectedMode = normalizeExpectedMode(args.verifyMode);
377
- checks.mode = remote.exists && expectedMode !== undefined && remote.mode === expectedMode;
375
+ checks.mode = remote.exists && expectedMode !== undefined && remote.modeValue === expectedMode;
378
376
  }
379
377
  if (args.verifyOwner !== undefined) {
380
378
  const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner);
@@ -389,7 +387,7 @@ async function buildUploadVerification(args, local, verificationRemotePath = arg
389
387
  return {
390
388
  expected: {
391
389
  owner: args.verifyOwner,
392
- mode: args.verifyMode ? normalizeExpectedMode(args.verifyMode) : undefined,
390
+ mode: args.verifyMode ? displayExpectedMode(args.verifyMode) : undefined,
393
391
  size: args.verifySize && local.exists ? local.size : undefined,
394
392
  mtimeMs: args.verifyMtime && local.exists ? local.mtimeMs : undefined,
395
393
  md5: localMd5,
@@ -403,7 +401,7 @@ async function buildUploadVerification(args, local, verificationRemotePath = arg
403
401
  return {
404
402
  expected: {
405
403
  owner: args.verifyOwner,
406
- mode: args.verifyMode ? normalizeExpectedMode(args.verifyMode) : undefined,
404
+ mode: args.verifyMode ? displayExpectedMode(args.verifyMode) : undefined,
407
405
  size: args.verifySize && local.exists ? local.size : undefined,
408
406
  mtimeMs: args.verifyMtime && local.exists ? local.mtimeMs : undefined,
409
407
  },
@@ -414,11 +412,11 @@ async function buildUploadVerification(args, local, verificationRemotePath = arg
414
412
  };
415
413
  }
416
414
  function normalizeExpectedMode(mode) {
417
- const trimmed = mode.trim();
418
- if (/^[0-7]{3,4}$/.test(trimmed)) {
419
- return trimmed.length === 3 ? `0${trimmed}` : trimmed;
420
- }
421
- return permissionStringToOctal(trimmed);
415
+ return parseExpectedFileMode(mode);
416
+ }
417
+ function displayExpectedMode(mode) {
418
+ const parsed = normalizeExpectedMode(mode);
419
+ return parsed === undefined ? undefined : formatFileMode(parsed);
422
420
  }
423
421
  async function buildSyncVerificationChecks(args, remote) {
424
422
  const checks = {};
@@ -428,17 +426,17 @@ async function buildSyncVerificationChecks(args, remote) {
428
426
  }
429
427
  if (args.verifyMode !== undefined) {
430
428
  const expectedMode = normalizeExpectedMode(args.verifyMode);
431
- checks.mode = remote.exists && expectedMode !== undefined && remote.mode === expectedMode;
429
+ checks.mode = remote.exists && expectedMode !== undefined && remote.modeValue === expectedMode;
432
430
  }
433
431
  return checks;
434
432
  }
435
433
  async function resolveSyncUploadVerificationPath(args, local, timeout) {
436
434
  const requestedRemote = await probeRemoteFile(args.alias, args.remotePath, timeout);
437
435
  if (requestedRemote.exists && requestedRemote.isDirectory) {
438
- return path.posix.join(args.remotePath, path.basename(local.resolvedPath));
436
+ return remoteJoin(sessionManager.getRemotePathStyle(args.alias), args.remotePath, path.basename(local.resolvedPath));
439
437
  }
440
438
  if (!requestedRemote.exists && args.remotePath.endsWith('/')) {
441
- return path.posix.join(args.remotePath, path.basename(local.resolvedPath));
439
+ return remoteJoin(sessionManager.getRemotePathStyle(args.alias), args.remotePath, path.basename(local.resolvedPath));
442
440
  }
443
441
  return args.remotePath;
444
442
  }
@@ -474,7 +472,7 @@ async function buildSyncUploadVerification(args, local, timeout) {
474
472
  expected: {
475
473
  owner: args.verifyOwner,
476
474
  mode: args.verifyMode,
477
- normalizedMode: args.verifyMode ? normalizeExpectedMode(args.verifyMode) : undefined,
475
+ normalizedMode: args.verifyMode ? displayExpectedMode(args.verifyMode) : undefined,
478
476
  },
479
477
  requestedRemotePath: args.remotePath,
480
478
  remote,
@@ -485,37 +483,18 @@ async function buildSyncUploadVerification(args, local, timeout) {
485
483
  };
486
484
  }
487
485
  async function captureRemoteDirectoryManifest(alias, remotePath, request, exclude, followSymlinks, timeout) {
488
- const remoteCommand = buildRemoteDirectoryManifestCommand(remotePath, request, exclude, followSymlinks);
489
- let remoteResult;
486
+ const requestSftp = sessionManager.getSftp(alias);
487
+ const sftp = await withSftpOperationTimeout(requestSftp, timeout, () => {
488
+ void requestSftp.then((late) => late.end(), () => undefined);
489
+ });
490
490
  try {
491
- remoteResult = await sessionManager.exec(alias, remoteCommand, {
492
- timeout,
493
- useLoginUser: true,
494
- maxOutputSize: 16 * 1024 * 1024,
495
- });
491
+ return await withSftpOperationTimeout(createRemoteDirectoryManifest(sftp, remotePath, request, exclude, followSymlinks, sessionManager.getRemotePathStyle(alias)), timeout, () => sftp.end());
496
492
  }
497
493
  catch (error) {
498
- const details = error && typeof error === 'object' && 'details' in error
499
- ? error.details
500
- : undefined;
501
- throw new VerificationStageError('remote_manifest_command', boundedDiagnostic(error instanceof Error ? error.message : String(error)).text, true, { timeout, ...details });
502
- }
503
- if (!remoteResult.success) {
504
- const detail = boundedDiagnostic(remoteResult.stderr || remoteResult.stdout || 'remote directory manifest failed');
505
- throw new VerificationStageError('remote_manifest_command', detail.text, remoteResult.failureKind !== 'remote_command', {
506
- ...commandFailureDetails(remoteResult),
507
- diagnosticBytes: detail.bytes,
508
- diagnosticTruncated: detail.truncated || undefined,
509
- });
494
+ throw new VerificationStageError('remote_manifest_output', error instanceof Error ? error.message : String(error), true);
510
495
  }
511
- if (remoteResult.stdoutTruncated) {
512
- throw new VerificationStageError('remote_manifest_output', 'remote directory manifest output exceeded the 16MB response limit', false, { maxOutputSize: 16 * 1024 * 1024 });
513
- }
514
- try {
515
- return parseRemoteDirectoryManifest(remoteResult.stdout);
516
- }
517
- catch (error) {
518
- throw new VerificationStageError('remote_manifest_parse', error instanceof Error ? error.message : String(error), false);
496
+ finally {
497
+ sftp.end();
519
498
  }
520
499
  }
521
500
  function directoryVerificationFollowsSymlinks(args) {
@@ -591,9 +570,26 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
591
570
  catch (error) {
592
571
  throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
593
572
  }
594
- return args.direction === 'upload'
573
+ const comparison = args.direction === 'upload'
595
574
  ? compareDirectoryManifests(localManifest, remoteManifest, request, deletionBaseline)
596
575
  : compareDirectoryManifests(remoteManifest, localManifest, request, deletionBaseline);
576
+ if (request.aclSddl && !('skipped' in comparison)) {
577
+ const command = encodedPowershell(`$acl = Get-Acl -LiteralPath ${quotePowershell(remoteShellPath(args.remotePath, sessionManager.getRemotePathStyle(args.alias)))}; $acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)`);
578
+ const result = await sessionManager.exec(args.alias, command, {
579
+ timeout,
580
+ useLoginUser: true,
581
+ maxOutputSize: 8192,
582
+ });
583
+ if (!result.success || result.stdoutTruncated) {
584
+ throw new VerificationStageError('remote_probe', 'Windows remote ACL could not be verified', true);
585
+ }
586
+ const aclMatch = result.stdout.trim() === request.aclSddl;
587
+ const checks = comparison.checks;
588
+ checks.acl = aclMatch;
589
+ comparison.matched = comparison.matched === true && aclMatch;
590
+ comparison.acl = { matched: aclMatch, expected: request.aclSddl, actual: result.stdout.trim() };
591
+ }
592
+ return comparison;
597
593
  }
598
594
  function mergeSyncVerification(existing, ownerMode, directory) {
599
595
  const parts = [existing, ownerMode, directory].filter((part) => Boolean(part));
@@ -639,6 +635,20 @@ function addUploadVerificationPaths(verification, args, verificationRemotePath)
639
635
  };
640
636
  }
641
637
  async function handleUpload(args) {
638
+ try {
639
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
640
+ if (sessionManager.getRemotePlatform(args.alias) === 'windows' &&
641
+ (args.verifyOwner !== undefined || args.verifyMode !== undefined)) {
642
+ return formatResult({
643
+ success: false,
644
+ code: 'unsupported_remote_platform',
645
+ error: 'Windows SFTP owner/mode metadata cannot verify POSIX permissions; use Windows ACL verification',
646
+ });
647
+ }
648
+ }
649
+ catch (error) {
650
+ return formatError(error);
651
+ }
642
652
  let local;
643
653
  try {
644
654
  fileOps.validateUploadFileSource(args.localPath);
@@ -686,10 +696,35 @@ async function handleUpload(args) {
686
696
  },
687
697
  });
688
698
  }
689
- const sourceMode = local.exists && 'mode' in local && typeof local.mode === 'string'
690
- ? Number.parseInt(local.mode, 8) & 0o777
699
+ let atomicReplaceSupported = null;
700
+ if (args.atomic && remoteBefore.exists) {
701
+ try {
702
+ const capability = await fileOps.atomicReplaceCapability(args.alias, args.timeout);
703
+ atomicReplaceSupported = capability.atomicReplaceSupported;
704
+ if (!capability.atomicReplaceSupported) {
705
+ return formatResult({
706
+ success: false,
707
+ code: 'atomic_replace_unsupported',
708
+ atomicReplaceSupported: false,
709
+ targetReplaced: false,
710
+ error: capability.reason,
711
+ });
712
+ }
713
+ }
714
+ catch (error) {
715
+ return formatResult({
716
+ success: false,
717
+ code: 'atomic_replace_unverified',
718
+ atomicReplaceSupported: null,
719
+ targetReplaced: false,
720
+ error: error instanceof Error ? error.message : String(error),
721
+ });
722
+ }
723
+ }
724
+ const sourceMode = local.exists && 'modeValue' in local && typeof local.modeValue === 'number'
725
+ ? local.modeValue & FILE_CREATE_MODE_MASK
691
726
  : undefined;
692
- const existingMode = remoteBefore.exists && remoteBefore.mode ? Number.parseInt(remoteBefore.mode, 8) & 0o777 : undefined;
727
+ const existingMode = remoteBefore.exists ? remoteBefore.modeValue & FILE_CREATE_MODE_MASK : undefined;
693
728
  const createMode = args.atomic && existingMode !== undefined ? existingMode : sourceMode;
694
729
  const tempRemotePath = args.atomic ? createAtomicUploadPath(args.remotePath) : args.remotePath;
695
730
  const verificationRequested = Boolean(args.verifyOwner !== undefined ||
@@ -697,8 +732,16 @@ async function handleUpload(args) {
697
732
  args.verifyMd5 ||
698
733
  args.verifySize ||
699
734
  args.verifyMtime);
735
+ let privateTempCreated = false;
736
+ let uploadedTempCreated = false;
700
737
  try {
701
- const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath, undefined, undefined, createMode, undefined, false, args.atomic === true, args.timeout);
738
+ if (args.atomic && sessionManager.getRemotePlatform(args.alias) === 'windows') {
739
+ const shellPath = remoteShellPath(tempRemotePath, sessionManager.getRemotePathStyle(args.alias));
740
+ await fileOps.prepareWindowsRemotePrivateFile(args.alias, tempRemotePath, args.timeout, shellPath);
741
+ privateTempCreated = true;
742
+ }
743
+ const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath, undefined, undefined, createMode, undefined, false, args.atomic === true && !privateTempCreated, args.timeout);
744
+ uploadedTempCreated = args.atomic === true;
702
745
  let verification;
703
746
  let verificationError;
704
747
  if (verificationRequested) {
@@ -731,6 +774,7 @@ async function handleUpload(args) {
731
774
  : `Atomic upload verification failed: ${verificationMessage}`,
732
775
  cleanupWarning,
733
776
  atomic: true,
777
+ atomicReplaceSupported,
734
778
  targetReplaced: false,
735
779
  ...pathDetails,
736
780
  createMode: uploadResult.createMode,
@@ -770,6 +814,7 @@ async function handleUpload(args) {
770
814
  : `Atomic SFTP rename response failed; target replacement state is unknown: ${renameError}`,
771
815
  cleanupWarning,
772
816
  atomic: true,
817
+ atomicReplaceSupported,
773
818
  targetReplaced: renameNotStarted ? false : null,
774
819
  targetReplacementStatus: renameNotStarted ? 'not_replaced' : 'unknown',
775
820
  ...pathDetails,
@@ -794,6 +839,7 @@ async function handleUpload(args) {
794
839
  ? undefined
795
840
  : `Upload completed, but verification failed: ${verificationMessage}`,
796
841
  atomic: args.atomic === true,
842
+ atomicReplaceSupported,
797
843
  targetReplaced: args.atomic ? true : undefined,
798
844
  ...pathDetails,
799
845
  createMode: uploadResult.createMode,
@@ -811,7 +857,10 @@ async function handleUpload(args) {
811
857
  }
812
858
  catch (error) {
813
859
  let cleanupWarning;
814
- const shouldCleanupTemporaryUpload = args.atomic && (!(error instanceof fileOps.UploadFileError) || error.remoteCreated);
860
+ const shouldCleanupTemporaryUpload = args.atomic &&
861
+ (privateTempCreated ||
862
+ uploadedTempCreated ||
863
+ (error instanceof fileOps.UploadFileError && error.remoteCreated));
815
864
  if (shouldCleanupTemporaryUpload) {
816
865
  try {
817
866
  await cleanupRemotePath(args.alias, tempRemotePath);
@@ -825,6 +874,7 @@ async function handleUpload(args) {
825
874
  ...sftpOperationOutcome(error),
826
875
  error: error instanceof Error ? error.message : String(error),
827
876
  cleanupWarning,
877
+ atomicReplaceSupported,
828
878
  finalRemotePath: args.remotePath,
829
879
  diagnostics: {
830
880
  local: summarizeLocalPathProbe(local),
@@ -838,6 +888,7 @@ async function handleUpload(args) {
838
888
  }
839
889
  async function handleDownload(args) {
840
890
  try {
891
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
841
892
  const downloadResult = await fileOps.downloadFile(args.alias, args.remotePath, args.localPath, undefined, undefined, undefined, args.timeout);
842
893
  return formatResult({ ...downloadResult, message: `Downloaded to ${args.localPath}` });
843
894
  }
@@ -856,11 +907,14 @@ async function handleDownload(args) {
856
907
  }
857
908
  async function handleReadFile(args) {
858
909
  try {
910
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
859
911
  const readResult = await fileOps.readFile(args.alias, args.remotePath, {
860
912
  maxBytes: args.maxBytes,
861
913
  offset: args.offset,
862
914
  tail: args.tail,
863
915
  lineRange: args.lineRange,
916
+ encoding: args.encoding,
917
+ binary: args.binary,
864
918
  timeout: args.timeout,
865
919
  });
866
920
  return formatResult({ success: true, ...readResult });
@@ -871,6 +925,7 @@ async function handleReadFile(args) {
871
925
  }
872
926
  async function handleWriteFile(args) {
873
927
  try {
928
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
874
929
  const result = await fileOps.writeFile(args.alias, args.remotePath, args.content, args.append, args.timeout);
875
930
  return formatResult(result);
876
931
  }
@@ -880,7 +935,8 @@ async function handleWriteFile(args) {
880
935
  }
881
936
  async function handleListDir(args) {
882
937
  try {
883
- const files = await fileOps.listDir(args.alias, args.remotePath, args.showHidden, undefined, args.timeout);
938
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
939
+ const files = await fileOps.listDir(args.alias, args.remotePath, args.showHidden, undefined, args.timeout, sessionManager.getRemotePathStyle(args.alias));
884
940
  return formatResult({
885
941
  success: true,
886
942
  path: args.remotePath,
@@ -894,7 +950,8 @@ async function handleListDir(args) {
894
950
  }
895
951
  async function handleFileInfo(args) {
896
952
  try {
897
- const info = await fileOps.getFileInfo(args.alias, args.remotePath, args.timeout);
953
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
954
+ const info = await fileOps.getFileInfo(args.alias, args.remotePath, args.timeout, sessionManager.getRemotePathStyle(args.alias));
898
955
  return formatResult({ success: true, ...info });
899
956
  }
900
957
  catch (error) {
@@ -903,7 +960,8 @@ async function handleFileInfo(args) {
903
960
  }
904
961
  async function handleMkdir(args) {
905
962
  try {
906
- const success = await fileOps.mkdir(args.alias, args.remotePath, args.recursive, undefined, args.timeout);
963
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
964
+ const success = await fileOps.mkdir(args.alias, args.remotePath, args.recursive, undefined, args.timeout, sessionManager.getRemotePathStyle(args.alias));
907
965
  return formatResult({ success, path: args.remotePath });
908
966
  }
909
967
  catch (error) {
@@ -912,6 +970,28 @@ async function handleMkdir(args) {
912
970
  }
913
971
  async function handleSync(args) {
914
972
  const startedAt = Date.now();
973
+ try {
974
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
975
+ const windows = sessionManager.getRemotePlatform(args.alias) === 'windows';
976
+ if (windows &&
977
+ (args.verifyOwner !== undefined || args.verifyMode !== undefined || args.verify?.owner || args.verify?.mode)) {
978
+ return formatResult({
979
+ success: false,
980
+ code: 'unsupported_remote_platform',
981
+ error: 'Windows SFTP owner/mode metadata cannot verify POSIX permissions; use verify.aclSddl',
982
+ });
983
+ }
984
+ if (!windows && args.verify?.aclSddl) {
985
+ return formatResult({
986
+ success: false,
987
+ code: 'unsupported_remote_platform',
988
+ error: 'verify.aclSddl requires a Windows remote platform',
989
+ });
990
+ }
991
+ }
992
+ catch (error) {
993
+ return formatError(error);
994
+ }
915
995
  if (args.verify?.deletions && args.delete !== true) {
916
996
  return formatResult({
917
997
  success: false,
@@ -989,6 +1069,7 @@ async function handleSync(args) {
989
1069
  preflightTimeout: args.preflightTimeout,
990
1070
  connectTimeout: args.connectTimeout,
991
1071
  operationTimeout: transferTimeout,
1072
+ remotePathStyle: sessionManager.getRemotePathStyle(args.alias),
992
1073
  });
993
1074
  const localAfter = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
994
1075
  diagnostics.localAfter = summarizeLocalPathProbe(localAfter);
@@ -1037,7 +1118,7 @@ export function registerFileTools(server) {
1037
1118
  inputSchema: uploadSchema,
1038
1119
  }, (args) => handleUpload(args));
1039
1120
  server.registerTool('ssh_download', {
1040
- description: '从远程服务器下载文件。timeout 限制单个 SFTP 操作,超时后远端传输状态可能未知。',
1121
+ description: '从远程服务器原子下载文件。新文件使用 0600,替换普通文件时保留其 rwx 权限;symlink、目录和其他非普通目标会被拒绝。timeout 限制单个 SFTP 操作,超时后远端传输状态可能未知。',
1041
1122
  inputSchema: downloadSchema,
1042
1123
  }, (args) => handleDownload(args));
1043
1124
  server.registerTool('ssh_read_file', {
@@ -1049,11 +1130,11 @@ export function registerFileTools(server) {
1049
1130
  inputSchema: writeFileSchema,
1050
1131
  }, (args) => handleWriteFile(args));
1051
1132
  server.registerTool('ssh_list_dir', {
1052
- description: '列出远程目录内容',
1133
+ description: '列出远程目录内容,返回包含特殊权限位的数值 mode 和 permissions 文本',
1053
1134
  inputSchema: listDirSchema,
1054
1135
  }, (args) => handleListDir(args));
1055
1136
  server.registerTool('ssh_file_info', {
1056
- description: '获取远程文件信息(大小、权限、修改时间等)',
1137
+ description: '获取远程文件信息(大小、数值 mode、权限文本、修改时间等)',
1057
1138
  inputSchema: fileInfoSchema,
1058
1139
  }, (args) => handleFileInfo(args));
1059
1140
  server.registerTool('ssh_mkdir', {
@@ -125,7 +125,7 @@ export function registerOperationTools(server) {
125
125
  inputSchema: operationReadSchema,
126
126
  }, (args) => handleOperationRead(args));
127
127
  server.registerTool('ssh_operation_cancel', {
128
- description: '校验远端 operation marker 后发送 TERM;marker 无法证明时拒绝取消',
128
+ description: '校验远端 operation marker 和进程身份后执行取消;POSIX 发送 TERM,Windows 在 PID、创建时间和 marker 验证后执行 taskkill /T /F;无法证明身份时拒绝取消',
129
129
  inputSchema: operationIdSchema,
130
130
  }, (args) => handleOperationCancel(args));
131
131
  server.registerTool('ssh_operation_list', {
package/dist/tools/pty.js CHANGED
@@ -31,7 +31,7 @@ const ptyWriteSchema = z.object({
31
31
  const ptyReadSchema = z.object({
32
32
  ptyId: z.string().describe('PTY 会话 ID'),
33
33
  mode: z.enum(['screen', 'raw']).optional().describe('输出模式:screen(当前屏幕)或 raw(原始流),默认 screen'),
34
- clear: z.boolean().optional().describe('(仅 raw 模式) 读取后是否清空缓冲区,默认 true'),
34
+ clear: z.boolean().optional().describe('(仅 raw 模式) 读取后是否清空缓冲区并重置 rawBufferTruncated,默认 true'),
35
35
  });
36
36
  const ptyResizeSchema = z.object({
37
37
  ptyId: z.string().describe('PTY 会话 ID'),
@@ -163,7 +163,9 @@ write 返回 accepted=true 表示数据已被本地 stream 接收。backpressure
163
163
 
164
164
  两种模式:
165
165
  - screen(默认):返回当前屏幕内容(解析后的纯文本,适合 top/btop/htop 等全屏刷新工具)
166
- - raw:返回原始 ANSI 流(包含转义序列,适合需要完整终端数据的场景)
166
+ - raw:data 为 UTF-8 文本预览,dataBase64 为原始 ANSI/二进制字节的无损 base64
167
+
168
+ bufferSize、unreadRawBytes 和 rawBufferLimit 均按原始字节计数。rawBufferTruncated=true 表示本次 clear 之后已有更早的 raw 输出因上限被丢弃;raw 读取使用默认 clear=true 时,响应返回清理前的计数和标志,然后重置缓冲区。
167
169
 
168
170
  示例:
169
171
  - 获取 top 当前画面: ssh_pty_read(ptyId="xxx")
@@ -179,7 +181,7 @@ write 返回 accepted=true 表示数据已被本地 stream 接收。backpressure
179
181
  inputSchema: ptyCloseSchema,
180
182
  }, (args) => handlePtyClose(args));
181
183
  server.registerTool('ssh_pty_list', {
182
- description: '列出所有 PTY 会话',
184
+ description: '列出所有 PTY 会话。bufferSize、unreadRawBytes 和 rawBufferLimit 使用原始字节,rawBufferTruncated 表示更早的 raw 输出已因缓冲区上限被丢弃。',
183
185
  inputSchema: ptyListSchema,
184
186
  }, () => handlePtyList());
185
187
  }
@@ -12,8 +12,8 @@ export function expandTilde(p) {
12
12
  if (p === '~') {
13
13
  return os.homedir();
14
14
  }
15
- if (p.startsWith('~/')) {
16
- return path.join(os.homedir(), p.slice(2));
15
+ if (p.startsWith('~/') || p.startsWith('~\\')) {
16
+ return path.join(os.homedir(), p.slice(2).replace(/\\/g, path.sep));
17
17
  }
18
18
  return p;
19
19
  }
package/dist/types.d.ts CHANGED
@@ -3,6 +3,10 @@
3
3
  */
4
4
  export declare const DEFAULT_EXEC_MAX_OUTPUT_SIZE: number;
5
5
  export declare const HARD_EXEC_MAX_OUTPUT_SIZE: number;
6
+ export type RemotePlatform = 'posix' | 'windows';
7
+ export type CommandShell = 'posix' | 'cmd' | 'powershell';
8
+ export type RemotePathStyle = 'posix' | 'win32' | 'sftp-posix';
9
+ export type RsyncProfile = 'posix' | 'native-win32' | 'msys2' | 'cygwin';
6
10
  export interface SSHConnectionConfig {
7
11
  host: string;
8
12
  port: number;
@@ -11,6 +15,12 @@ export interface SSHConnectionConfig {
11
15
  privateKeyPath?: string;
12
16
  privateKey?: string;
13
17
  passphrase?: string;
18
+ agent?: string;
19
+ remotePlatform?: RemotePlatform;
20
+ commandShell?: CommandShell;
21
+ remotePathStyle?: RemotePathStyle;
22
+ rsyncExecutable?: string;
23
+ rsyncProfile?: RsyncProfile;
14
24
  alias?: string;
15
25
  template?: string;
16
26
  runAs?: string;
@@ -37,6 +47,9 @@ export interface SSHSessionDetail extends SSHSessionBrief {
37
47
  authMethod: 'key' | 'password' | 'agent' | 'inline-key';
38
48
  connectedAt: number;
39
49
  hasJumpHost: boolean;
50
+ remotePlatform: RemotePlatform;
51
+ commandShell: CommandShell;
52
+ remotePathStyle: RemotePathStyle;
40
53
  }
41
54
  export interface ExternalTransferCapability {
42
55
  alias: string;
@@ -50,6 +63,11 @@ export interface ExternalTransferCapability {
50
63
  routeSafeForOpenSsh: boolean;
51
64
  rsyncEligible: boolean;
52
65
  decisionReason: string;
66
+ agent?: string;
67
+ rsyncExecutable?: string;
68
+ rsyncProfile?: RsyncProfile;
69
+ commandShell?: CommandShell;
70
+ remotePathStyle?: RemotePathStyle;
53
71
  }
54
72
  export type ConnectionFailureStage = 'preflight' | 'authentication' | 'ready_timeout' | 'transport_or_handshake' | 'unknown';
55
73
  export type ConnectionStep = 'key_read' | 'jump_connect' | 'jump_forward' | 'target_connect';
@@ -58,6 +76,7 @@ export interface ConnectionFailureDetails {
58
76
  connectionStep?: ConnectionStep;
59
77
  retryable: boolean;
60
78
  suggestion?: string;
79
+ keyAclStatus?: 'key_path_usable' | 'key_acl_insecure' | 'key_acl_unverified';
61
80
  }
62
81
  export interface ExecOptions {
63
82
  timeout?: number;
@@ -120,6 +139,7 @@ export interface OperationInfo {
120
139
  pid: number | null;
121
140
  processGroup: boolean;
122
141
  markerVerified: boolean;
142
+ processCreatedAt?: string;
123
143
  cancelRequested: boolean;
124
144
  startedAt: number;
125
145
  finishedAt: number | null;
@@ -150,6 +170,7 @@ export interface OperationCancelResult extends OperationInfo {
150
170
  success: boolean;
151
171
  cancelRequested: boolean;
152
172
  retryable: boolean;
173
+ cancellationStatus: 'requested' | 'unknown' | 'unsupported' | 'not_applicable';
153
174
  verificationError?: string;
154
175
  }
155
176
  export interface FileInfo {
@@ -159,6 +180,7 @@ export interface FileInfo {
159
180
  isDirectory: boolean;
160
181
  isFile: boolean;
161
182
  isSymlink: boolean;
183
+ mode: number;
162
184
  permissions: string;
163
185
  owner: number;
164
186
  group: number;
@@ -199,9 +221,24 @@ export interface PtySessionInfo {
199
221
  bufferSize: number;
200
222
  unreadRawBytes: number;
201
223
  rawBufferLimit: number;
224
+ rawBufferTruncated: boolean;
202
225
  foregroundProcess: string;
203
226
  active: boolean;
204
227
  }
228
+ export interface PtyReadResult {
229
+ data: string;
230
+ dataBase64?: string;
231
+ active: boolean;
232
+ rows: number;
233
+ cols: number;
234
+ lastInputAt: number | null;
235
+ lastOutputAt: number | null;
236
+ lastReadAt: number;
237
+ unreadRawBytes: number;
238
+ rawBufferLimit: number;
239
+ rawBufferTruncated: boolean;
240
+ foregroundProcess: string;
241
+ }
205
242
  export interface PtyWriteResult {
206
243
  accepted: true;
207
244
  backpressured: boolean;