@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.
@@ -4,13 +4,16 @@
4
4
  * ssh_upload, ssh_download, ssh_read_file, ssh_write_file,
5
5
  * ssh_list_dir, ssh_file_info, ssh_mkdir, ssh_sync
6
6
  */
7
- import { createHash, randomBytes } from 'crypto';
7
+ import { 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, createOpenSshDirectoryManifest, matchesDirectoryExclude, DIRECTORY_VERIFY_MAX_ENTRIES, DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES, DIRECTORY_VERIFY_DEFAULT_MAX_TOTAL_BYTES, 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, remotePathModule, 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({
@@ -60,12 +71,43 @@ const writeFileSchema = z.object({
60
71
  append: z.boolean().optional().describe('是否追加模式,默认覆盖'),
61
72
  timeout: operationTimeoutSchema.optional(),
62
73
  });
63
- const listDirSchema = z.object({
74
+ function compareDirectoryTimes(left, right) {
75
+ const milliseconds = Date.parse(left) - Date.parse(right);
76
+ if (milliseconds !== 0)
77
+ return milliseconds;
78
+ // 保留 ISO 8601 的亚毫秒部分,避免 Date.parse 截断时间边界
79
+ const [leftFraction, rightFraction] = [left, right].map((value) => (value.match(/\.(\d+)/)?.[1].slice(3) ?? '').replace(/0+$/, ''));
80
+ return leftFraction < rightFraction ? -1 : leftFraction > rightFraction ? 1 : 0;
81
+ }
82
+ const listDirSchema = z
83
+ .object({
64
84
  alias: z.string().describe('连接别名'),
65
85
  remotePath: z.string().describe('远程目录路径'),
66
86
  showHidden: z.boolean().optional().describe('是否显示隐藏文件'),
87
+ namePattern: z.string().optional().describe('名称通配模式,复用同步 exclude 的 * 和 ? 规则,区分大小写'),
88
+ modifiedAfter: z
89
+ .string()
90
+ .datetime({ offset: true })
91
+ .optional()
92
+ .describe('修改时间下界,包含;使用带时区的 ISO 8601 时间'),
93
+ modifiedBefore: z
94
+ .string()
95
+ .datetime({ offset: true })
96
+ .optional()
97
+ .describe('修改时间上界,不包含;使用带时区的 ISO 8601 时间'),
98
+ offset: z.number().int().nonnegative().optional().describe('筛选并排序后的条目偏移,默认 0'),
99
+ limit: z.number().int().positive().optional().describe('单页最多条数,使用任一新参数时默认 100'),
100
+ maxBytes: z
101
+ .number()
102
+ .int()
103
+ .positive()
104
+ .optional()
105
+ .describe('响应 JSON 文本的 UTF-8 字节预算,包含分页元数据;使用任一新参数时默认 65536'),
67
106
  timeout: operationTimeoutSchema.optional(),
68
- });
107
+ })
108
+ .refine((args) => args.modifiedAfter === undefined ||
109
+ args.modifiedBefore === undefined ||
110
+ compareDirectoryTimes(args.modifiedAfter, args.modifiedBefore) <= 0, { message: 'modifiedAfter must be at or before modifiedBefore', path: ['modifiedAfter'] });
69
111
  const fileInfoSchema = z.object({
70
112
  alias: z.string().describe('连接别名'),
71
113
  remotePath: z.string().describe('远程路径'),
@@ -94,13 +136,19 @@ const syncSchema = z.object({
94
136
  connectTimeout: z.number().int().positive().max(120000).optional().describe('rsync SSH 连接超时,默认 30000ms'),
95
137
  operationTimeout: z.number().int().positive().max(3600000).optional().describe('同步操作超时,默认 600000ms'),
96
138
  verifyOwner: z.union([z.string(), z.number()]).optional().describe('upload 后校验远端 owner(用户名或 uid)'),
97
- verifyMode: z.string().optional().describe('upload 后校验远端权限,例如 0644 或 -rw-r--r--'),
139
+ verifyMode: z.string().optional().describe('upload 后校验远端权限,例如 0644、4755 或 -rwsr-xr-x'),
98
140
  verify: z
99
141
  .object({
100
142
  count: z.boolean().optional().describe('校验目录条目数'),
101
- sha256: z.boolean().optional().describe('校验 SHA-256 root manifest'),
143
+ sha256: z.boolean().optional().describe('校验文件 SHA-256 或目录 SHA-256 root manifest'),
102
144
  owner: z.boolean().optional().describe('逐项校验 owner'),
103
- mode: z.boolean().optional().describe('逐项校验 mode'),
145
+ mode: z.boolean().optional().describe('逐项校验 POSIX mode;Windows 不支持'),
146
+ aclSddl: z
147
+ .string()
148
+ .min(1)
149
+ .max(8192)
150
+ .optional()
151
+ .describe('Windows 远端文件或目录根路径的预期 DACL SDDL,独立于 POSIX mode/owner'),
104
152
  deletions: z.boolean().optional().describe('校验请求删除后没有额外条目'),
105
153
  staleFiles: z.boolean().optional().describe('校验没有旧文件残留'),
106
154
  maxEntries: z
@@ -126,7 +174,7 @@ const syncSchema = z.object({
126
174
  .describe('SHA-256 校验的总字节上限,默认 1GB,最大 16GB'),
127
175
  })
128
176
  .optional()
129
- .describe('有界目录校验;未传时不执行额外远端扫描'),
177
+ .describe('有界文件或目录校验;count/deletions/staleFiles 仅适用于目录,未传时不执行额外远端扫描'),
130
178
  });
131
179
  // ========== Handlers ==========
132
180
  const LARGE_UPLOAD_THRESHOLD = 100 * 1024 * 1024;
@@ -195,6 +243,9 @@ function summarizeLocalPathProbe(probe) {
195
243
  if ('mode' in probe) {
196
244
  summary.mode = probe.mode;
197
245
  }
246
+ if ('modeValue' in probe) {
247
+ summary.modeValue = probe.modeValue;
248
+ }
198
249
  if ('mtimeMs' in probe) {
199
250
  summary.mtimeMs = probe.mtimeMs;
200
251
  }
@@ -217,29 +268,24 @@ function uploadPathError(code, message, diagnostics) {
217
268
  diagnostics,
218
269
  });
219
270
  }
220
- async function probeRemoteParent(alias, remotePath) {
221
- const parent = path.posix.dirname(remotePath);
271
+ function normalizeRemotePath(alias, remotePath) {
272
+ return sftpPath(remotePath, sessionManager.getRemotePathStyle(alias));
273
+ }
274
+ async function probeRemoteParent(alias, remotePath, timeout) {
275
+ const parent = remoteDirname(sessionManager.getRemotePathStyle(alias), remotePath);
276
+ const probeMethod = sessionManager.getOpenSshConnection(alias) ? 'openssh' : 'sftp';
222
277
  try {
223
- const result = await probeRemoteFile(alias, parent);
278
+ const result = await probeRemoteFile(alias, parent, timeout);
224
279
  return {
225
280
  exists: result.exists,
226
281
  isDirectory: result.exists ? result.isDirectory : false,
227
- probeMethod: 'sftp',
282
+ probeMethod,
228
283
  };
229
284
  }
230
285
  catch (error) {
231
- return { error: error instanceof Error ? error.message : String(error), probeMethod: 'sftp' };
286
+ return { error: error instanceof Error ? error.message : String(error), probeMethod };
232
287
  }
233
288
  }
234
- function hashLocalFileMd5(filePath) {
235
- return new Promise((resolve, reject) => {
236
- const hash = createHash('md5');
237
- const stream = fs.createReadStream(filePath);
238
- stream.on('data', (chunk) => hash.update(chunk));
239
- stream.on('error', reject);
240
- stream.on('end', () => resolve(hash.digest('hex')));
241
- });
242
- }
243
289
  function boundedDiagnostic(value, maxBytes = 2048) {
244
290
  const buffer = Buffer.from(value, 'utf8');
245
291
  if (buffer.length <= maxBytes) {
@@ -266,21 +312,21 @@ function commandFailureDetails(result) {
266
312
  stderrTruncated: result.stderrTruncated || stderr.truncated || undefined,
267
313
  };
268
314
  }
269
- async function hashRemoteFileMd5(alias, remotePath) {
315
+ async function hashRemoteFileMd5(alias, remotePath, timeout) {
270
316
  try {
271
- return await fileOps.hashRemoteFileDigest(alias, remotePath, 'md5');
317
+ return await fileOps.hashRemoteFileDigest(alias, remotePath, 'md5', timeout);
272
318
  }
273
319
  catch (error) {
274
320
  throw new VerificationStageError('remote_probe', `Remote SFTP MD5 read failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'md5', probeMethod: 'sftp' });
275
321
  }
276
322
  }
277
- async function resolveExpectedOwnerId(alias, owner) {
323
+ async function resolveExpectedOwnerId(alias, owner, timeout = 10000) {
278
324
  const ownerText = String(owner);
279
325
  if (/^\d+$/.test(ownerText)) {
280
326
  return ownerText;
281
327
  }
282
328
  const result = await sessionManager.exec(alias, `id -u ${escapeShellArg(ownerText)}`, {
283
- timeout: 10000,
329
+ timeout,
284
330
  useLoginUser: true,
285
331
  maxOutputSize: 4096,
286
332
  });
@@ -294,26 +340,6 @@ async function resolveExpectedOwnerId(alias, owner) {
294
340
  }
295
341
  return ownerId;
296
342
  }
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
343
  function isRemoteMissingError(error) {
318
344
  if (!error || typeof error !== 'object') {
319
345
  return false;
@@ -323,32 +349,28 @@ function isRemoteMissingError(error) {
323
349
  return code === 2 || code === 'ENOENT' || /no such file|not found/i.test(message);
324
350
  }
325
351
  async function probeRemoteFile(alias, remotePath, timeout = 10000) {
352
+ const probeMethod = sessionManager.getOpenSshConnection(alias) ? 'openssh' : 'sftp';
326
353
  let info;
327
354
  try {
328
355
  info = await fileOps.getFileInfo(alias, remotePath, timeout);
329
356
  }
330
357
  catch (error) {
331
358
  if (isRemoteMissingError(error)) {
332
- return { exists: false, remotePath, probeMethod: 'sftp' };
359
+ return { exists: false, remotePath, probeMethod };
333
360
  }
334
- throw new VerificationStageError('remote_probe', `Remote SFTP stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod: 'sftp' });
335
- }
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
- });
361
+ throw new VerificationStageError('remote_probe', `Remote file stat failed: ${error instanceof Error ? error.message : String(error)}`, true, { operation: 'stat', probeMethod });
342
362
  }
343
363
  return {
344
364
  exists: true,
345
365
  remotePath,
346
- probeMethod: 'sftp',
366
+ probeMethod,
347
367
  ownerName: undefined,
348
368
  ownerId: info.owner,
349
369
  groupName: undefined,
350
370
  groupId: info.group,
351
- mode,
371
+ mode: formatFileMode(info.mode),
372
+ modeValue: info.mode,
373
+ permissions: info.permissions,
352
374
  size: info.size,
353
375
  mtimeMs: info.mtime.getTime(),
354
376
  fileType: info.isDirectory
@@ -363,7 +385,7 @@ async function probeRemoteFile(alias, remotePath, timeout = 10000) {
363
385
  };
364
386
  }
365
387
  async function buildUploadVerification(args, local, verificationRemotePath = args.remotePath) {
366
- const remote = await probeRemoteFile(args.alias, verificationRemotePath);
388
+ const remote = await probeRemoteFile(args.alias, verificationRemotePath, args.timeout);
367
389
  const checks = {};
368
390
  if (args.verifySize) {
369
391
  checks.size = local.exists && remote.exists ? local.size === remote.size : false;
@@ -374,22 +396,22 @@ async function buildUploadVerification(args, local, verificationRemotePath = arg
374
396
  }
375
397
  if (args.verifyMode) {
376
398
  const expectedMode = normalizeExpectedMode(args.verifyMode);
377
- checks.mode = remote.exists && expectedMode !== undefined && remote.mode === expectedMode;
399
+ checks.mode = remote.exists && expectedMode !== undefined && remote.modeValue === expectedMode;
378
400
  }
379
401
  if (args.verifyOwner !== undefined) {
380
- const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner);
402
+ const expectedOwnerId = await resolveExpectedOwnerId(args.alias, args.verifyOwner, args.timeout);
381
403
  checks.owner = remote.exists && String(remote.ownerId) === expectedOwnerId;
382
404
  }
383
405
  if (args.verifyMd5 && local.exists) {
384
406
  const [localMd5, remoteMd5] = await Promise.all([
385
- hashLocalFileMd5(local.resolvedPath),
386
- hashRemoteFileMd5(args.alias, verificationRemotePath),
407
+ fileOps.hashLocalFile(local.resolvedPath, 'md5', args.timeout),
408
+ hashRemoteFileMd5(args.alias, verificationRemotePath, args.timeout),
387
409
  ]);
388
410
  checks.md5 = remoteMd5 ? localMd5 === remoteMd5 : undefined;
389
411
  return {
390
412
  expected: {
391
413
  owner: args.verifyOwner,
392
- mode: args.verifyMode ? normalizeExpectedMode(args.verifyMode) : undefined,
414
+ mode: args.verifyMode ? displayExpectedMode(args.verifyMode) : undefined,
393
415
  size: args.verifySize && local.exists ? local.size : undefined,
394
416
  mtimeMs: args.verifyMtime && local.exists ? local.mtimeMs : undefined,
395
417
  md5: localMd5,
@@ -403,7 +425,7 @@ async function buildUploadVerification(args, local, verificationRemotePath = arg
403
425
  return {
404
426
  expected: {
405
427
  owner: args.verifyOwner,
406
- mode: args.verifyMode ? normalizeExpectedMode(args.verifyMode) : undefined,
428
+ mode: args.verifyMode ? displayExpectedMode(args.verifyMode) : undefined,
407
429
  size: args.verifySize && local.exists ? local.size : undefined,
408
430
  mtimeMs: args.verifyMtime && local.exists ? local.mtimeMs : undefined,
409
431
  },
@@ -414,11 +436,11 @@ async function buildUploadVerification(args, local, verificationRemotePath = arg
414
436
  };
415
437
  }
416
438
  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);
439
+ return parseExpectedFileMode(mode);
440
+ }
441
+ function displayExpectedMode(mode) {
442
+ const parsed = normalizeExpectedMode(mode);
443
+ return parsed === undefined ? undefined : formatFileMode(parsed);
422
444
  }
423
445
  async function buildSyncVerificationChecks(args, remote) {
424
446
  const checks = {};
@@ -428,17 +450,17 @@ async function buildSyncVerificationChecks(args, remote) {
428
450
  }
429
451
  if (args.verifyMode !== undefined) {
430
452
  const expectedMode = normalizeExpectedMode(args.verifyMode);
431
- checks.mode = remote.exists && expectedMode !== undefined && remote.mode === expectedMode;
453
+ checks.mode = remote.exists && expectedMode !== undefined && remote.modeValue === expectedMode;
432
454
  }
433
455
  return checks;
434
456
  }
435
457
  async function resolveSyncUploadVerificationPath(args, local, timeout) {
436
458
  const requestedRemote = await probeRemoteFile(args.alias, args.remotePath, timeout);
437
459
  if (requestedRemote.exists && requestedRemote.isDirectory) {
438
- return path.posix.join(args.remotePath, path.basename(local.resolvedPath));
460
+ return remoteJoin(sessionManager.getRemotePathStyle(args.alias), args.remotePath, path.basename(local.expandedPath));
439
461
  }
440
462
  if (!requestedRemote.exists && args.remotePath.endsWith('/')) {
441
- return path.posix.join(args.remotePath, path.basename(local.resolvedPath));
463
+ return remoteJoin(sessionManager.getRemotePathStyle(args.alias), args.remotePath, path.basename(local.expandedPath));
442
464
  }
443
465
  return args.remotePath;
444
466
  }
@@ -474,7 +496,7 @@ async function buildSyncUploadVerification(args, local, timeout) {
474
496
  expected: {
475
497
  owner: args.verifyOwner,
476
498
  mode: args.verifyMode,
477
- normalizedMode: args.verifyMode ? normalizeExpectedMode(args.verifyMode) : undefined,
499
+ normalizedMode: args.verifyMode ? displayExpectedMode(args.verifyMode) : undefined,
478
500
  },
479
501
  requestedRemotePath: args.remotePath,
480
502
  remote,
@@ -485,37 +507,21 @@ async function buildSyncUploadVerification(args, local, timeout) {
485
507
  };
486
508
  }
487
509
  async function captureRemoteDirectoryManifest(alias, remotePath, request, exclude, followSymlinks, timeout) {
488
- const remoteCommand = buildRemoteDirectoryManifestCommand(remotePath, request, exclude, followSymlinks);
489
- let remoteResult;
510
+ const connection = sessionManager.getOpenSshConnection(alias);
511
+ if (connection)
512
+ return createOpenSshDirectoryManifest(connection, remotePath, request, timeout, exclude, followSymlinks);
513
+ const requestSftp = sessionManager.getSftp(alias);
514
+ const sftp = await withSftpOperationTimeout(requestSftp, timeout, () => {
515
+ void requestSftp.then((late) => late.end(), () => undefined);
516
+ });
490
517
  try {
491
- remoteResult = await sessionManager.exec(alias, remoteCommand, {
492
- timeout,
493
- useLoginUser: true,
494
- maxOutputSize: 16 * 1024 * 1024,
495
- });
518
+ return await withSftpOperationTimeout(createRemoteDirectoryManifest(sftp, remotePath, request, exclude, followSymlinks, sessionManager.getRemotePathStyle(alias)), timeout, () => sftp.end());
496
519
  }
497
520
  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
- });
521
+ throw new VerificationStageError('remote_manifest_output', error instanceof Error ? error.message : String(error), true);
510
522
  }
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);
523
+ finally {
524
+ sftp.end();
519
525
  }
520
526
  }
521
527
  function directoryVerificationFollowsSymlinks(args) {
@@ -569,6 +575,79 @@ async function captureDeletionBaseline(args, remainingTimeout) {
569
575
  throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
570
576
  }
571
577
  }
578
+ async function buildSingleFileSyncVerification(args, local, timeout) {
579
+ if (!args.verify)
580
+ return undefined;
581
+ if (args.dryRun)
582
+ return { kind: 'single_file', skipped: true, reason: 'file verification is not executed during dryRun' };
583
+ if (!local.exists || !local.isFile)
584
+ throw new VerificationStageError('local_manifest', 'File verification requires the transferred local file', false);
585
+ const deadline = Date.now() + timeout;
586
+ const remaining = () => {
587
+ const value = deadline - Date.now();
588
+ if (value <= 0)
589
+ throw new VerificationStageError('verification_timeout', 'sync operation timeout was exhausted during file verification', true);
590
+ return value;
591
+ };
592
+ const remotePath = args.direction === 'upload'
593
+ ? await resolveSyncUploadVerificationPath(args, local, remaining())
594
+ : args.remotePath;
595
+ const remote = await probeRemoteFile(args.alias, remotePath, remaining());
596
+ const checks = {
597
+ file: remote.exists && remote.isFile,
598
+ size: remote.exists && remote.size === local.size,
599
+ };
600
+ if (args.verify.owner)
601
+ checks.owner = remote.exists && String(remote.ownerId) === String(fs.statSync(local.resolvedPath).uid);
602
+ if (args.verify.mode)
603
+ checks.mode = remote.exists && remote.modeValue === local.modeValue;
604
+ let localSha256;
605
+ let remoteSha256;
606
+ if (args.verify.sha256 && remote.exists && remote.isFile) {
607
+ const maxBytes = Math.min(args.verify.maxFileBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES, args.verify.maxTotalBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_TOTAL_BYTES);
608
+ if (local.size > maxBytes || remote.size > maxBytes)
609
+ return { kind: 'single_file', skipped: true, reason: 'file verification byte budget exceeded', maxBytes };
610
+ [localSha256, remoteSha256] = await Promise.all([
611
+ fileOps.hashLocalFile(local.resolvedPath, 'sha256', remaining(), { maxBytes, expectedSize: local.size }),
612
+ fileOps.hashRemoteFileDigest(args.alias, remotePath, 'sha256', remaining(), {
613
+ maxBytes,
614
+ expectedSize: remote.size,
615
+ }),
616
+ ]);
617
+ checks.sha256 = localSha256 === remoteSha256;
618
+ const after = await probeRemoteFile(args.alias, remotePath, remaining());
619
+ if (!after.exists ||
620
+ after.size !== remote.size ||
621
+ after.mtimeMs !== remote.mtimeMs ||
622
+ after.modeValue !== remote.modeValue ||
623
+ after.ownerId !== remote.ownerId) {
624
+ throw new VerificationStageError('remote_probe', 'Remote file changed during sync verification', true);
625
+ }
626
+ }
627
+ else if (args.verify.sha256)
628
+ checks.sha256 = false;
629
+ if (args.verify.aclSddl) {
630
+ const command = encodedPowershell(`$acl = Get-Acl -LiteralPath ${quotePowershell(remoteShellPath(remotePath, sessionManager.getRemotePathStyle(args.alias)))}; $acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)`);
631
+ const result = await sessionManager.exec(args.alias, command, {
632
+ timeout: remaining(),
633
+ useLoginUser: true,
634
+ maxOutputSize: 8192,
635
+ });
636
+ if (!result.success || result.stdoutTruncated)
637
+ throw new VerificationStageError('remote_probe', 'Windows remote ACL could not be verified', true);
638
+ checks.acl = result.stdout.trim() === args.verify.aclSddl;
639
+ }
640
+ return {
641
+ kind: 'single_file',
642
+ matched: Object.values(checks).every(Boolean),
643
+ checks,
644
+ direction: args.direction,
645
+ remotePath,
646
+ localPath: local.expandedPath,
647
+ local: { ...summarizeLocalPathProbe(local), sha256: localSha256 },
648
+ remote: { ...remote, sha256: remoteSha256 },
649
+ };
650
+ }
572
651
  async function buildDirectorySyncVerification(args, local, timeout, deletionBaseline) {
573
652
  if (!args.verify) {
574
653
  return undefined;
@@ -591,12 +670,37 @@ async function buildDirectorySyncVerification(args, local, timeout, deletionBase
591
670
  catch (error) {
592
671
  throw new VerificationStageError('local_manifest', error instanceof Error ? error.message : String(error), false);
593
672
  }
594
- return args.direction === 'upload'
673
+ const comparison = args.direction === 'upload'
595
674
  ? compareDirectoryManifests(localManifest, remoteManifest, request, deletionBaseline)
596
675
  : compareDirectoryManifests(remoteManifest, localManifest, request, deletionBaseline);
676
+ if (remoteManifest.skippedSymlinks > 0 ||
677
+ localManifest.skippedSymlinks > 0 ||
678
+ (deletionBaseline?.skippedSymlinks ?? 0) > 0) {
679
+ comparison.suggestion =
680
+ args.direction === 'upload' && !args.followSymlinks
681
+ ? '排除符号链接后重新同步和校验,或显式设置 followSymlinks=true 上传并校验链接目标'
682
+ : '排除符号链接后重新同步和校验;download 保持跳过链接目标,followSymlinks 仅适用于 upload';
683
+ }
684
+ if (request.aclSddl && !('skipped' in comparison)) {
685
+ const command = encodedPowershell(`$acl = Get-Acl -LiteralPath ${quotePowershell(remoteShellPath(args.remotePath, sessionManager.getRemotePathStyle(args.alias)))}; $acl.GetSecurityDescriptorSddlForm([System.Security.AccessControl.AccessControlSections]::Access)`);
686
+ const result = await sessionManager.exec(args.alias, command, {
687
+ timeout,
688
+ useLoginUser: true,
689
+ maxOutputSize: 8192,
690
+ });
691
+ if (!result.success || result.stdoutTruncated) {
692
+ throw new VerificationStageError('remote_probe', 'Windows remote ACL could not be verified', true);
693
+ }
694
+ const aclMatch = result.stdout.trim() === request.aclSddl;
695
+ const checks = comparison.checks;
696
+ checks.acl = aclMatch;
697
+ comparison.matched = comparison.matched === true && aclMatch;
698
+ comparison.acl = { matched: aclMatch, expected: request.aclSddl, actual: result.stdout.trim() };
699
+ }
700
+ return comparison;
597
701
  }
598
- function mergeSyncVerification(existing, ownerMode, directory) {
599
- const parts = [existing, ownerMode, directory].filter((part) => Boolean(part));
702
+ function mergeSyncVerification(existing, ownerMode, content) {
703
+ const parts = [existing, ownerMode, content].filter((part) => Boolean(part));
600
704
  if (parts.length === 0) {
601
705
  return undefined;
602
706
  }
@@ -606,12 +710,13 @@ function mergeSyncVerification(existing, ownerMode, directory) {
606
710
  return {
607
711
  transport: existing,
608
712
  ownerMode,
609
- directory,
713
+ directory: content?.kind === 'directory' ? content : undefined,
714
+ singleFile: content?.kind === 'single_file' ? content : undefined,
610
715
  };
611
716
  }
612
- async function cleanupRemotePath(alias, remotePath) {
717
+ async function cleanupRemotePath(alias, remotePath, timeout) {
613
718
  try {
614
- await fileOps.removeRemoteFile(alias, remotePath);
719
+ await fileOps.removeRemoteFile(alias, remotePath, timeout);
615
720
  }
616
721
  catch (error) {
617
722
  throw new Error(`Temporary remote file cleanup failed: ${error instanceof Error ? error.message : String(error)}`, {
@@ -639,6 +744,20 @@ function addUploadVerificationPaths(verification, args, verificationRemotePath)
639
744
  };
640
745
  }
641
746
  async function handleUpload(args) {
747
+ try {
748
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
749
+ if (sessionManager.getRemotePlatform(args.alias) === 'windows' &&
750
+ (args.verifyOwner !== undefined || args.verifyMode !== undefined)) {
751
+ return formatResult({
752
+ success: false,
753
+ code: 'unsupported_remote_platform',
754
+ error: 'Windows SFTP owner/mode metadata cannot verify POSIX permissions; use Windows ACL verification',
755
+ });
756
+ }
757
+ }
758
+ catch (error) {
759
+ return formatError(error);
760
+ }
642
761
  let local;
643
762
  try {
644
763
  fileOps.validateUploadFileSource(args.localPath);
@@ -669,10 +788,10 @@ async function handleUpload(args) {
669
788
  'direction="upload")',
670
789
  ].join(', ')
671
790
  : undefined;
672
- const remoteParent = await probeRemoteParent(args.alias, args.remotePath);
791
+ const remoteParent = await probeRemoteParent(args.alias, args.remotePath, args.timeout);
673
792
  let remoteBefore;
674
793
  try {
675
- remoteBefore = await probeRemoteFile(args.alias, args.remotePath);
794
+ remoteBefore = await probeRemoteFile(args.alias, args.remotePath, args.timeout);
676
795
  }
677
796
  catch (error) {
678
797
  return formatResult({
@@ -686,10 +805,35 @@ async function handleUpload(args) {
686
805
  },
687
806
  });
688
807
  }
689
- const sourceMode = local.exists && 'mode' in local && typeof local.mode === 'string'
690
- ? Number.parseInt(local.mode, 8) & 0o777
808
+ let atomicReplaceSupported = null;
809
+ if (args.atomic && remoteBefore.exists) {
810
+ try {
811
+ const capability = await fileOps.atomicReplaceCapability(args.alias, args.timeout);
812
+ atomicReplaceSupported = capability.atomicReplaceSupported;
813
+ if (!capability.atomicReplaceSupported) {
814
+ return formatResult({
815
+ success: false,
816
+ code: 'atomic_replace_unsupported',
817
+ atomicReplaceSupported: false,
818
+ targetReplaced: false,
819
+ error: capability.reason,
820
+ });
821
+ }
822
+ }
823
+ catch (error) {
824
+ return formatResult({
825
+ success: false,
826
+ code: 'atomic_replace_unverified',
827
+ atomicReplaceSupported: null,
828
+ targetReplaced: false,
829
+ error: error instanceof Error ? error.message : String(error),
830
+ });
831
+ }
832
+ }
833
+ const sourceMode = local.exists && 'modeValue' in local && typeof local.modeValue === 'number'
834
+ ? local.modeValue & FILE_CREATE_MODE_MASK
691
835
  : undefined;
692
- const existingMode = remoteBefore.exists && remoteBefore.mode ? Number.parseInt(remoteBefore.mode, 8) & 0o777 : undefined;
836
+ const existingMode = remoteBefore.exists ? remoteBefore.modeValue & FILE_CREATE_MODE_MASK : undefined;
693
837
  const createMode = args.atomic && existingMode !== undefined ? existingMode : sourceMode;
694
838
  const tempRemotePath = args.atomic ? createAtomicUploadPath(args.remotePath) : args.remotePath;
695
839
  const verificationRequested = Boolean(args.verifyOwner !== undefined ||
@@ -697,8 +841,16 @@ async function handleUpload(args) {
697
841
  args.verifyMd5 ||
698
842
  args.verifySize ||
699
843
  args.verifyMtime);
844
+ let privateTempCreated = false;
845
+ let uploadedTempCreated = false;
700
846
  try {
701
- const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath, undefined, undefined, createMode, undefined, false, args.atomic === true, args.timeout);
847
+ if (args.atomic && sessionManager.getRemotePlatform(args.alias) === 'windows') {
848
+ const shellPath = remoteShellPath(tempRemotePath, sessionManager.getRemotePathStyle(args.alias));
849
+ await fileOps.prepareWindowsRemotePrivateFile(args.alias, tempRemotePath, args.timeout, shellPath);
850
+ privateTempCreated = true;
851
+ }
852
+ const uploadResult = await fileOps.uploadFile(args.alias, args.localPath, tempRemotePath, undefined, undefined, createMode, undefined, false, args.atomic === true && !privateTempCreated, args.timeout);
853
+ uploadedTempCreated = args.atomic === true;
702
854
  let verification;
703
855
  let verificationError;
704
856
  if (verificationRequested) {
@@ -716,7 +868,7 @@ async function handleUpload(args) {
716
868
  if (args.atomic && !outcome.success) {
717
869
  let cleanupWarning;
718
870
  try {
719
- await cleanupRemotePath(args.alias, tempRemotePath);
871
+ await cleanupRemotePath(args.alias, tempRemotePath, args.timeout);
720
872
  }
721
873
  catch (cleanupError) {
722
874
  cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
@@ -731,6 +883,7 @@ async function handleUpload(args) {
731
883
  : `Atomic upload verification failed: ${verificationMessage}`,
732
884
  cleanupWarning,
733
885
  atomic: true,
886
+ atomicReplaceSupported,
734
887
  targetReplaced: false,
735
888
  ...pathDetails,
736
889
  createMode: uploadResult.createMode,
@@ -755,7 +908,7 @@ async function handleUpload(args) {
755
908
  const renameError = error instanceof Error ? error.message : String(error);
756
909
  let cleanupWarning;
757
910
  try {
758
- await cleanupRemotePath(args.alias, tempRemotePath);
911
+ await cleanupRemotePath(args.alias, tempRemotePath, args.timeout);
759
912
  }
760
913
  catch (cleanupError) {
761
914
  cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
@@ -770,6 +923,7 @@ async function handleUpload(args) {
770
923
  : `Atomic SFTP rename response failed; target replacement state is unknown: ${renameError}`,
771
924
  cleanupWarning,
772
925
  atomic: true,
926
+ atomicReplaceSupported,
773
927
  targetReplaced: renameNotStarted ? false : null,
774
928
  targetReplacementStatus: renameNotStarted ? 'not_replaced' : 'unknown',
775
929
  ...pathDetails,
@@ -794,6 +948,7 @@ async function handleUpload(args) {
794
948
  ? undefined
795
949
  : `Upload completed, but verification failed: ${verificationMessage}`,
796
950
  atomic: args.atomic === true,
951
+ atomicReplaceSupported,
797
952
  targetReplaced: args.atomic ? true : undefined,
798
953
  ...pathDetails,
799
954
  createMode: uploadResult.createMode,
@@ -811,10 +966,13 @@ async function handleUpload(args) {
811
966
  }
812
967
  catch (error) {
813
968
  let cleanupWarning;
814
- const shouldCleanupTemporaryUpload = args.atomic && (!(error instanceof fileOps.UploadFileError) || error.remoteCreated);
969
+ const shouldCleanupTemporaryUpload = args.atomic &&
970
+ (privateTempCreated ||
971
+ uploadedTempCreated ||
972
+ (error instanceof fileOps.UploadFileError && error.remoteCreated));
815
973
  if (shouldCleanupTemporaryUpload) {
816
974
  try {
817
- await cleanupRemotePath(args.alias, tempRemotePath);
975
+ await cleanupRemotePath(args.alias, tempRemotePath, args.timeout);
818
976
  }
819
977
  catch (cleanupError) {
820
978
  cleanupWarning = cleanupError instanceof Error ? cleanupError.message : String(cleanupError);
@@ -825,6 +983,7 @@ async function handleUpload(args) {
825
983
  ...sftpOperationOutcome(error),
826
984
  error: error instanceof Error ? error.message : String(error),
827
985
  cleanupWarning,
986
+ atomicReplaceSupported,
828
987
  finalRemotePath: args.remotePath,
829
988
  diagnostics: {
830
989
  local: summarizeLocalPathProbe(local),
@@ -838,6 +997,7 @@ async function handleUpload(args) {
838
997
  }
839
998
  async function handleDownload(args) {
840
999
  try {
1000
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
841
1001
  const downloadResult = await fileOps.downloadFile(args.alias, args.remotePath, args.localPath, undefined, undefined, undefined, args.timeout);
842
1002
  return formatResult({ ...downloadResult, message: `Downloaded to ${args.localPath}` });
843
1003
  }
@@ -856,11 +1016,14 @@ async function handleDownload(args) {
856
1016
  }
857
1017
  async function handleReadFile(args) {
858
1018
  try {
1019
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
859
1020
  const readResult = await fileOps.readFile(args.alias, args.remotePath, {
860
1021
  maxBytes: args.maxBytes,
861
1022
  offset: args.offset,
862
1023
  tail: args.tail,
863
1024
  lineRange: args.lineRange,
1025
+ encoding: args.encoding,
1026
+ binary: args.binary,
864
1027
  timeout: args.timeout,
865
1028
  });
866
1029
  return formatResult({ success: true, ...readResult });
@@ -871,6 +1034,7 @@ async function handleReadFile(args) {
871
1034
  }
872
1035
  async function handleWriteFile(args) {
873
1036
  try {
1037
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
874
1038
  const result = await fileOps.writeFile(args.alias, args.remotePath, args.content, args.append, args.timeout);
875
1039
  return formatResult(result);
876
1040
  }
@@ -880,13 +1044,69 @@ async function handleWriteFile(args) {
880
1044
  }
881
1045
  async function handleListDir(args) {
882
1046
  try {
883
- const files = await fileOps.listDir(args.alias, args.remotePath, args.showHidden, undefined, args.timeout);
884
- return formatResult({
1047
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
1048
+ const files = await fileOps.listDir(args.alias, args.remotePath, args.showHidden, undefined, args.timeout, sessionManager.getRemotePathStyle(args.alias));
1049
+ const bounded = [
1050
+ args.namePattern,
1051
+ args.modifiedAfter,
1052
+ args.modifiedBefore,
1053
+ args.offset,
1054
+ args.limit,
1055
+ args.maxBytes,
1056
+ ].some((value) => value !== undefined);
1057
+ if (!bounded) {
1058
+ return formatResult({ success: true, path: args.remotePath, count: files.length, files });
1059
+ }
1060
+ const patterns = args.namePattern === undefined ? undefined : [args.namePattern];
1061
+ const matching = files.filter((file) => (patterns === undefined || matchesDirectoryExclude(file.name, patterns)) &&
1062
+ (args.modifiedAfter === undefined ||
1063
+ compareDirectoryTimes(file.mtime.toISOString(), args.modifiedAfter) >= 0) &&
1064
+ (args.modifiedBefore === undefined ||
1065
+ compareDirectoryTimes(file.mtime.toISOString(), args.modifiedBefore) < 0));
1066
+ const offset = args.offset ?? 0;
1067
+ const limit = args.limit ?? 100;
1068
+ const maxBytes = args.maxBytes ?? 65536;
1069
+ const page = (count) => formatResult({
885
1070
  success: true,
886
1071
  path: args.remotePath,
887
- count: files.length,
888
- files,
1072
+ count,
1073
+ files: matching.slice(offset, offset + count),
1074
+ total_count: matching.length,
1075
+ offset,
1076
+ has_more: offset + count < matching.length,
1077
+ next_offset: offset + count,
889
1078
  });
1079
+ let lower = 0;
1080
+ let upper = Math.min(limit, Math.max(0, matching.length - offset));
1081
+ let response = page(0);
1082
+ while (lower < upper) {
1083
+ const count = Math.ceil((lower + upper) / 2);
1084
+ const candidate = page(count);
1085
+ if (Buffer.byteLength(candidate.content[0].text, 'utf8') <= maxBytes) {
1086
+ lower = count;
1087
+ response = candidate;
1088
+ }
1089
+ else {
1090
+ upper = count - 1;
1091
+ }
1092
+ }
1093
+ if (Buffer.byteLength(response.content[0].text, 'utf8') > maxBytes ||
1094
+ (lower === 0 && offset < matching.length)) {
1095
+ const minimum = page(offset < matching.length ? 1 : 0);
1096
+ return {
1097
+ ...formatResult({
1098
+ success: false,
1099
+ code: 'LIST_DIR_MAX_BYTES_TOO_SMALL',
1100
+ error: 'maxBytes is too small for directory page metadata and the next complete entry, if any',
1101
+ offset,
1102
+ next_offset: offset,
1103
+ maxBytes,
1104
+ requiredBytes: Buffer.byteLength(minimum.content[0].text, 'utf8'),
1105
+ }),
1106
+ isError: true,
1107
+ };
1108
+ }
1109
+ return response;
890
1110
  }
891
1111
  catch (error) {
892
1112
  return formatFileOperationError(error);
@@ -894,7 +1114,8 @@ async function handleListDir(args) {
894
1114
  }
895
1115
  async function handleFileInfo(args) {
896
1116
  try {
897
- const info = await fileOps.getFileInfo(args.alias, args.remotePath, args.timeout);
1117
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
1118
+ const info = await fileOps.getFileInfo(args.alias, args.remotePath, args.timeout, sessionManager.getRemotePathStyle(args.alias));
898
1119
  return formatResult({ success: true, ...info });
899
1120
  }
900
1121
  catch (error) {
@@ -903,7 +1124,8 @@ async function handleFileInfo(args) {
903
1124
  }
904
1125
  async function handleMkdir(args) {
905
1126
  try {
906
- const success = await fileOps.mkdir(args.alias, args.remotePath, args.recursive, undefined, args.timeout);
1127
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
1128
+ const success = await fileOps.mkdir(args.alias, args.remotePath, args.recursive, undefined, args.timeout, sessionManager.getRemotePathStyle(args.alias));
907
1129
  return formatResult({ success, path: args.remotePath });
908
1130
  }
909
1131
  catch (error) {
@@ -912,6 +1134,28 @@ async function handleMkdir(args) {
912
1134
  }
913
1135
  async function handleSync(args) {
914
1136
  const startedAt = Date.now();
1137
+ try {
1138
+ args.remotePath = normalizeRemotePath(args.alias, args.remotePath);
1139
+ const windows = sessionManager.getRemotePlatform(args.alias) === 'windows';
1140
+ if (windows &&
1141
+ (args.verifyOwner !== undefined || args.verifyMode !== undefined || args.verify?.owner || args.verify?.mode)) {
1142
+ return formatResult({
1143
+ success: false,
1144
+ code: 'unsupported_remote_platform',
1145
+ error: 'Windows SFTP owner/mode metadata cannot verify POSIX permissions; use verify.aclSddl',
1146
+ });
1147
+ }
1148
+ if (!windows && args.verify?.aclSddl) {
1149
+ return formatResult({
1150
+ success: false,
1151
+ code: 'unsupported_remote_platform',
1152
+ error: 'verify.aclSddl requires a Windows remote platform',
1153
+ });
1154
+ }
1155
+ }
1156
+ catch (error) {
1157
+ return formatError(error);
1158
+ }
915
1159
  if (args.verify?.deletions && args.delete !== true) {
916
1160
  return formatResult({
917
1161
  success: false,
@@ -944,6 +1188,33 @@ async function handleSync(args) {
944
1188
  remoteParent: await probeRemoteParent(args.alias, args.remotePath),
945
1189
  };
946
1190
  try {
1191
+ const remoteSource = args.direction === 'download'
1192
+ ? await fileOps.getFileInfo(args.alias, args.remotePath, remainingTimeout())
1193
+ : undefined;
1194
+ const sourceIsDirectory = args.direction === 'upload' ? localBefore.exists && localBefore.isDirectory : remoteSource.isDirectory;
1195
+ if (!sourceIsDirectory && (args.verify?.count || args.verify?.deletions || args.verify?.staleFiles)) {
1196
+ return formatResult({
1197
+ success: false,
1198
+ transferSuccess: false,
1199
+ code: 'DIRECTORY_VERIFICATION_REQUIRES_DIRECTORY',
1200
+ error: 'verify.count, verify.deletions and verify.staleFiles require a directory source',
1201
+ });
1202
+ }
1203
+ const sourceSize = args.direction === 'upload' && localBefore.exists ? localBefore.size : remoteSource?.size;
1204
+ const maxFileBytes = Math.min(args.verify?.maxFileBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_FILE_BYTES, args.verify?.maxTotalBytes ?? DIRECTORY_VERIFY_DEFAULT_MAX_TOTAL_BYTES);
1205
+ if (!sourceIsDirectory && args.verify?.sha256 && sourceSize !== undefined && sourceSize > maxFileBytes) {
1206
+ return formatResult({
1207
+ success: false,
1208
+ transferSuccess: false,
1209
+ verificationRequested: true,
1210
+ verificationSuccess: false,
1211
+ verificationStatus: 'skipped',
1212
+ code: 'VERIFICATION_BYTE_LIMIT',
1213
+ error: 'file verification byte budget exceeded before transfer',
1214
+ sourceSize,
1215
+ maxBytes: maxFileBytes,
1216
+ });
1217
+ }
947
1218
  let deletionBaseline;
948
1219
  try {
949
1220
  deletionBaseline = await captureDeletionBaseline(args, remainingTimeout);
@@ -989,17 +1260,23 @@ async function handleSync(args) {
989
1260
  preflightTimeout: args.preflightTimeout,
990
1261
  connectTimeout: args.connectTimeout,
991
1262
  operationTimeout: transferTimeout,
1263
+ remotePathStyle: sessionManager.getRemotePathStyle(args.alias),
992
1264
  });
993
1265
  const localAfter = fileOps.probeLocalPath(args.localPath, args.direction === 'upload' && args.followSymlinks === true);
994
1266
  diagnostics.localAfter = summarizeLocalPathProbe(localAfter);
1267
+ const transferredLocal = args.direction === 'download' && !sourceIsDirectory && localAfter.exists && localAfter.isDirectory
1268
+ ? fileOps.probeLocalPath(path.join(localAfter.expandedPath, remotePathModule(sessionManager.getRemotePathStyle(args.alias)).basename(args.remotePath)))
1269
+ : localAfter;
995
1270
  const verificationRequested = Boolean(args.verifyOwner !== undefined || args.verifyMode !== undefined || args.verify !== undefined);
996
1271
  let verification;
997
1272
  let verificationError;
998
1273
  if (verificationRequested && syncResult.success) {
999
1274
  try {
1000
1275
  const ownerModeVerification = await buildSyncUploadVerification(args, args.direction === 'upload' ? localBefore : localAfter, remainingTimeout());
1001
- const directoryVerification = await buildDirectorySyncVerification(args, args.direction === 'upload' ? localBefore : localAfter, remainingTimeout(), deletionBaseline);
1002
- verification = mergeSyncVerification(undefined, ownerModeVerification, directoryVerification);
1276
+ const contentVerification = sourceIsDirectory
1277
+ ? await buildDirectorySyncVerification(args, args.direction === 'upload' ? localBefore : localAfter, remainingTimeout(), deletionBaseline)
1278
+ : await buildSingleFileSyncVerification(args, args.direction === 'upload' ? localBefore : transferredLocal, remainingTimeout());
1279
+ verification = mergeSyncVerification(undefined, ownerModeVerification, contentVerification);
1003
1280
  }
1004
1281
  catch (error) {
1005
1282
  verificationError = error;
@@ -1037,7 +1314,7 @@ export function registerFileTools(server) {
1037
1314
  inputSchema: uploadSchema,
1038
1315
  }, (args) => handleUpload(args));
1039
1316
  server.registerTool('ssh_download', {
1040
- description: '从远程服务器下载文件。timeout 限制单个 SFTP 操作,超时后远端传输状态可能未知。',
1317
+ description: '从远程服务器原子下载文件。新文件使用 0600,替换普通文件时保留其 rwx 权限;symlink、目录和其他非普通目标会被拒绝。timeout 限制单个 SFTP 操作,超时后远端传输状态可能未知。',
1041
1318
  inputSchema: downloadSchema,
1042
1319
  }, (args) => handleDownload(args));
1043
1320
  server.registerTool('ssh_read_file', {
@@ -1049,11 +1326,11 @@ export function registerFileTools(server) {
1049
1326
  inputSchema: writeFileSchema,
1050
1327
  }, (args) => handleWriteFile(args));
1051
1328
  server.registerTool('ssh_list_dir', {
1052
- description: '列出远程目录内容',
1329
+ description: '列出远程目录内容,返回数值 mode 和 permissions 文本;名称与修改时间条件取交集,使用筛选或分页参数时默认最多 100 条、65536 UTF-8 字节,使用 next_offset 续查;完整 readdir 后分页,目录变化时不保证快照一致性',
1053
1330
  inputSchema: listDirSchema,
1054
1331
  }, (args) => handleListDir(args));
1055
1332
  server.registerTool('ssh_file_info', {
1056
- description: '获取远程文件信息(大小、权限、修改时间等)',
1333
+ description: '获取远程文件信息(大小、数值 mode、权限文本、修改时间等)',
1057
1334
  inputSchema: fileInfoSchema,
1058
1335
  }, (args) => handleFileInfo(args));
1059
1336
  server.registerTool('ssh_mkdir', {