@lousy-agents/cli 5.21.5 → 5.21.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3053,7 +3053,7 @@ exports.basename = (path, { windows } = {}) => {
3053
3053
 
3054
3054
 
3055
3055
  },
3056
- 8853(__unused_rspack_module, __unused_rspack___webpack_exports__, __webpack_require__) {
3056
+ 5694(__unused_rspack_module, __unused_rspack___webpack_exports__, __webpack_require__) {
3057
3057
  // NAMESPACE OBJECT: ../../node_modules/micromark/lib/constructs.js
3058
3058
  var constructs_namespaceObject = {};
3059
3059
  __webpack_require__.r(constructs_namespaceObject);
@@ -3111,7 +3111,7 @@ function byte_budget_normalizeMaxBytes(value, options = {}) {
3111
3111
  if (selected === undefined || selected === Number.POSITIVE_INFINITY)
3112
3112
  return selected;
3113
3113
  if (!Number.isSafeInteger(selected) || selected < 0) {
3114
- throw new RangeError(`${options.label ?? "maxBytes"} must be a non-negative safe integer or Infinity`);
3114
+ throw new RangeError("maxBytes must be a non-negative safe integer or Infinity");
3115
3115
  }
3116
3116
  return selected;
3117
3117
  }
@@ -3130,7 +3130,7 @@ function isStatValueProvablyDifferent(left, right, platform) {
3130
3130
  }
3131
3131
  return platform !== "win32" || (!isZero(left) && !isZero(right));
3132
3132
  }
3133
- function sha256Hex(data, encoding) {
3133
+ function file_identity_sha256Hex(data, encoding) {
3134
3134
  const buffer = typeof data === "string" ? Buffer.from(data, encoding ?? "utf8") : data;
3135
3135
  return (0,external_node_crypto_.createHash)("sha256").update(buffer).digest("hex");
3136
3136
  }
@@ -3141,7 +3141,7 @@ function file_identity_sameFileIdentity(left, right, platform = process.platform
3141
3141
  return (!isStatValueProvablyDifferent(left.dev, right.dev, platform) &&
3142
3142
  !isStatValueProvablyDifferent(left.ino, right.ino, platform));
3143
3143
  }
3144
- function sameFileIdentityForCleanup(left, right, platform = process.platform) {
3144
+ function file_identity_sameFileIdentityForCleanup(left, right, platform = process.platform) {
3145
3145
  // A zero Windows device or inode is unknown, not proof that a pathname still
3146
3146
  // names the object we created. Cleanup must fail closed rather than delete a
3147
3147
  // replacement that happens to share the known half of the identity.
@@ -3212,7 +3212,7 @@ function identityCheck(expected, platform) {
3212
3212
  }
3213
3213
  // Retry only unknown Windows identities, retaining every known component so a
3214
3214
  // later observation cannot erase a definite mismatch. Never reopen the file.
3215
- async function inspectFileIdentity(inspect, expected, platform = process.platform) {
3215
+ async function strict_file_identity_inspectFileIdentity(inspect, expected, platform = process.platform) {
3216
3216
  const check = identityCheck(expected, platform);
3217
3217
  for (let attempt = 0; attempt < 2; attempt++) {
3218
3218
  const stat = await inspect();
@@ -3221,7 +3221,7 @@ async function inspectFileIdentity(inspect, expected, platform = process.platfor
3221
3221
  }
3222
3222
  throw identityMismatch();
3223
3223
  }
3224
- function inspectFileIdentitySync(inspect, expected, platform = process.platform) {
3224
+ function strict_file_identity_inspectFileIdentitySync(inspect, expected, platform = process.platform) {
3225
3225
  const check = identityCheck(expected, platform);
3226
3226
  for (let attempt = 0; attempt < 2; attempt++) {
3227
3227
  const stat = inspect();
@@ -3252,11 +3252,11 @@ function normalizeWindowsPathForComparison(input) {
3252
3252
  // whitespace is part of the path and must not be trimmed away.
3253
3253
  return normalized.replaceAll("/", "\\").toLowerCase();
3254
3254
  }
3255
- function isNodeError(value) {
3255
+ function path_isNodeError(value) {
3256
3256
  return Boolean(value && typeof value === "object" && "code" in value);
3257
3257
  }
3258
3258
  function hasNodeErrorCode(value, code) {
3259
- return isNodeError(value) && value.code === code;
3259
+ return path_isNodeError(value) && value.code === code;
3260
3260
  }
3261
3261
  function path_assertNoNulPathInput(filePath, message = "path contains a NUL byte") {
3262
3262
  if (filePath.includes("\0")) {
@@ -3264,10 +3264,10 @@ function path_assertNoNulPathInput(filePath, message = "path contains a NUL byte
3264
3264
  }
3265
3265
  }
3266
3266
  function path_isNotFoundPathError(value) {
3267
- return isNodeError(value) && typeof value.code === "string" && NOT_FOUND_CODES.has(value.code);
3267
+ return path_isNodeError(value) && typeof value.code === "string" && NOT_FOUND_CODES.has(value.code);
3268
3268
  }
3269
3269
  function isSymlinkOpenError(value) {
3270
- return isNodeError(value) && typeof value.code === "string" && SYMLINK_OPEN_CODES.has(value.code);
3270
+ return path_isNodeError(value) && typeof value.code === "string" && SYMLINK_OPEN_CODES.has(value.code);
3271
3271
  }
3272
3272
  function path_isPathInside(root, target) {
3273
3273
  if (process.platform === "win32") {
@@ -3424,7 +3424,7 @@ function normalizeRemovePathError(error) {
3424
3424
  if (error instanceof errors_FsSafeError) {
3425
3425
  return error;
3426
3426
  }
3427
- if (!isNodeError(error) || typeof error.code !== "string") {
3427
+ if (!path_isNodeError(error) || typeof error.code !== "string") {
3428
3428
  return normalizePinnedPathError(error);
3429
3429
  }
3430
3430
  const cause = error instanceof Error ? error : undefined;
@@ -3436,6 +3436,15 @@ function normalizeRemovePathError(error) {
3436
3436
  }
3437
3437
  return new errors_FsSafeError("not-removable", "path could not be removed", { cause });
3438
3438
  }
3439
+ function throwFsSafeReadError(error, label) {
3440
+ if (error instanceof FsSafeError) {
3441
+ throw error;
3442
+ }
3443
+ if (isNodeError(error)) {
3444
+ throw new FsSafeError("read-failed", `${label} target could not be read`, { cause: error });
3445
+ }
3446
+ throw error;
3447
+ }
3439
3448
 
3440
3449
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/directory-guard.js
3441
3450
 
@@ -3445,20 +3454,21 @@ function normalizeRemovePathError(error) {
3445
3454
 
3446
3455
 
3447
3456
 
3448
-
3449
- async function directory_guard_createAsyncDirectoryGuard(dir) {
3450
- const stat = await promises_.lstat(dir);
3457
+ async function directory_guard_createAsyncDirectoryGuard(dir, options) {
3458
+ const stat = options?.bigint ? await inspectDirectoryIdentity(dir) : external_node_fs_.lstatSync(dir);
3451
3459
  if (stat.isSymbolicLink() || !stat.isDirectory()) {
3452
3460
  throw root_errors_directoryComponentNotDirectoryError();
3453
3461
  }
3454
- return { dir, realPath: await promises_.realpath(dir), stat };
3462
+ return { dir, realPath: external_node_fs_.realpathSync.native(dir), stat };
3455
3463
  }
3456
- async function assertAsyncDirectoryGuard(guard) {
3457
- const stat = await promises_.lstat(guard.dir);
3464
+ async function directory_guard_assertAsyncDirectoryGuard(guard) {
3465
+ const stat = typeof guard.stat.dev === "bigint" && typeof guard.stat.ino === "bigint"
3466
+ ? await inspectDirectoryIdentity(guard.dir, { dev: guard.stat.dev, ino: guard.stat.ino })
3467
+ : external_node_fs_.lstatSync(guard.dir);
3458
3468
  if (stat.isSymbolicLink() || !stat.isDirectory()) {
3459
3469
  throw root_errors_directoryComponentNotDirectoryError();
3460
3470
  }
3461
- if (!file_identity_sameFileIdentity(stat, guard.stat) || (await promises_.realpath(guard.dir)) !== guard.realPath) {
3471
+ if (!file_identity_sameFileIdentity(stat, guard.stat) || external_node_fs_.realpathSync.native(guard.dir) !== guard.realPath) {
3462
3472
  throw new errors_FsSafeError("path-mismatch", "directory changed during operation");
3463
3473
  }
3464
3474
  }
@@ -3478,12 +3488,12 @@ function directory_guard_assertSyncDirectoryGuard(guard) {
3478
3488
  throw new FsSafeError("path-mismatch", "directory changed during operation");
3479
3489
  }
3480
3490
  }
3481
- async function directory_guard_createNearestExistingDirectoryGuard(rootReal, targetPath) {
3491
+ async function directory_guard_createNearestExistingDirectoryGuard(rootReal, targetPath, options = { bigint: false }) {
3482
3492
  let current = external_node_path_.resolve(targetPath);
3483
3493
  const root = external_node_path_.resolve(rootReal);
3484
3494
  while (current !== root) {
3485
3495
  try {
3486
- return await directory_guard_createAsyncDirectoryGuard(current);
3496
+ return await directory_guard_createAsyncDirectoryGuard(current, options);
3487
3497
  }
3488
3498
  catch (error) {
3489
3499
  if (!path_isNotFoundPathError(error)) {
@@ -3492,7 +3502,7 @@ async function directory_guard_createNearestExistingDirectoryGuard(rootReal, tar
3492
3502
  current = external_node_path_.dirname(current);
3493
3503
  }
3494
3504
  }
3495
- return await directory_guard_createAsyncDirectoryGuard(root);
3505
+ return await directory_guard_createAsyncDirectoryGuard(root, options);
3496
3506
  }
3497
3507
  function directory_guard_createNearestExistingSyncDirectoryGuard(rootReal, targetPath) {
3498
3508
  let current = path.resolve(targetPath);
@@ -3512,8 +3522,8 @@ function directory_guard_createNearestExistingSyncDirectoryGuard(rootReal, targe
3512
3522
  }
3513
3523
  // Recovery receipts must retain every identity bit, including on Windows.
3514
3524
  async function inspectDirectoryIdentity(dir, expected) {
3515
- return await inspectFileIdentity(async () => {
3516
- const stat = await promises_.lstat(dir, { bigint: true });
3525
+ return await strict_file_identity_inspectFileIdentity(async () => {
3526
+ const stat = external_node_fs_.lstatSync(dir, { bigint: true });
3517
3527
  if (stat.isSymbolicLink() || !stat.isDirectory())
3518
3528
  throw root_errors_directoryComponentNotDirectoryError();
3519
3529
  return stat;
@@ -3566,11 +3576,11 @@ function assertDirectory(identity, pathname, label) {
3566
3576
  }
3567
3577
  async function createDirectoryReceipt(directoryPath, label) {
3568
3578
  const resolvedPath = external_node_path_.resolve(directoryPath);
3569
- const identity = await promises_.lstat(resolvedPath);
3579
+ const identity = external_node_fs_.lstatSync(resolvedPath);
3570
3580
  assertDirectory(identity, resolvedPath, label);
3571
3581
  return {
3572
3582
  path: resolvedPath,
3573
- realPath: await promises_.realpath(resolvedPath),
3583
+ realPath: external_node_fs_.realpathSync.native(resolvedPath),
3574
3584
  identity,
3575
3585
  };
3576
3586
  }
@@ -3585,10 +3595,10 @@ function createDirectoryReceiptSync(directoryPath, label) {
3585
3595
  };
3586
3596
  }
3587
3597
  async function assertDirectoryReceiptCurrent(receipt, label) {
3588
- const currentIdentity = await promises_.lstat(receipt.path);
3598
+ const currentIdentity = external_node_fs_.lstatSync(receipt.path);
3589
3599
  assertDirectory(currentIdentity, receipt.path, label);
3590
3600
  if (!file_identity_sameFileIdentity(receipt.identity, currentIdentity) ||
3591
- (await promises_.realpath(receipt.path)) !== receipt.realPath) {
3601
+ (external_node_fs_.realpathSync.native(receipt.path)) !== receipt.realPath) {
3592
3602
  throw new errors_FsSafeError("path-mismatch", `${label} changed during durable directory operation: ${receipt.path}`);
3593
3603
  }
3594
3604
  }
@@ -3601,7 +3611,7 @@ function assertDirectoryReceiptCurrentSync(receipt, label) {
3601
3611
  }
3602
3612
  }
3603
3613
  async function assertOpenDirectoryCurrent(handle, receipt, label) {
3604
- const openedIdentity = await handle.stat();
3614
+ const openedIdentity = external_node_fs_.fstatSync(handle.fd);
3605
3615
  assertDirectory(openedIdentity, receipt.path, label);
3606
3616
  if (!file_identity_sameFileIdentity(receipt.identity, openedIdentity)) {
3607
3617
  throw new errors_FsSafeError("path-mismatch", `${label} handle changed during directory sync: ${receipt.path}`);
@@ -3828,13 +3838,14 @@ async function ensureDurableDirectory(options) {
3828
3838
 
3829
3839
 
3830
3840
 
3841
+
3831
3842
  function isSameOrChildPath(candidate, parent) {
3832
3843
  const parentPrefix = parent.endsWith(external_node_path_.sep) ? parent : `${parent}${external_node_path_.sep}`;
3833
3844
  return candidate === parent || candidate.startsWith(parentPrefix);
3834
3845
  }
3835
3846
  async function realpathOrThrowNotFile(target) {
3836
3847
  try {
3837
- return external_node_path_.resolve(await promises_.realpath(target));
3848
+ return external_node_path_.resolve(external_node_fs_.realpathSync.native(target));
3838
3849
  }
3839
3850
  catch (error) {
3840
3851
  if (path_isNotFoundPathError(error)) {
@@ -3853,7 +3864,7 @@ async function realpathOrThrowNotFile(target) {
3853
3864
  */
3854
3865
  async function mkdirPathComponentsWithGuards(params) {
3855
3866
  const root = external_node_path_.resolve(params.rootReal);
3856
- const rootCanonical = external_node_path_.resolve(await promises_.realpath(root));
3867
+ const rootCanonical = external_node_path_.resolve(external_node_fs_.realpathSync.native(root));
3857
3868
  const target = external_node_path_.resolve(params.targetPath);
3858
3869
  const relative = external_node_path_.relative(root, target);
3859
3870
  if (isPathRelativeEscape(relative)) {
@@ -3863,18 +3874,18 @@ async function mkdirPathComponentsWithGuards(params) {
3863
3874
  for (const part of relative.split(external_node_path_.sep).filter(Boolean)) {
3864
3875
  const next = external_node_path_.join(current, part);
3865
3876
  const parentGuard = await directory_guard_createAsyncDirectoryGuard(current);
3866
- await assertAsyncDirectoryGuard(parentGuard);
3877
+ await directory_guard_assertAsyncDirectoryGuard(parentGuard);
3867
3878
  await params.beforeComponent?.(next);
3868
3879
  try {
3869
- await promises_.mkdir(next);
3880
+ await promises_.mkdir(next, { mode: params.mode });
3870
3881
  }
3871
3882
  catch (error) {
3872
3883
  if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST") {
3873
3884
  throw error;
3874
3885
  }
3875
3886
  }
3876
- const stat = await promises_.lstat(next);
3877
- if (!stat.isSymbolicLink() && !stat.isDirectory()) {
3887
+ const stat = external_node_fs_.lstatSync(next);
3888
+ if ((params.rejectSymlinks && stat.isSymbolicLink()) || (!stat.isSymbolicLink() && !stat.isDirectory())) {
3878
3889
  throw root_errors_directoryComponentNotDirectoryError();
3879
3890
  }
3880
3891
  // Node's recursive mkdir follows symlinks in missing components. Build one
@@ -3893,17 +3904,17 @@ async function mkdirPathComponentsWithGuards(params) {
3893
3904
  // every subsequent segment. Callers that need the final directory
3894
3905
  // (e.g. to guard it themselves after this function returns) must use
3895
3906
  // the returned resolved path, not their own lexical parent path.
3896
- const targetStat = await promises_.stat(nextReal);
3907
+ const targetStat = external_node_fs_.statSync(nextReal);
3897
3908
  if (!targetStat.isDirectory()) {
3898
3909
  throw root_errors_directoryComponentNotDirectoryError();
3899
3910
  }
3900
3911
  await directory_guard_createAsyncDirectoryGuard(nextReal);
3901
- await assertAsyncDirectoryGuard(parentGuard);
3912
+ await directory_guard_assertAsyncDirectoryGuard(parentGuard);
3902
3913
  current = nextReal;
3903
3914
  continue;
3904
3915
  }
3905
3916
  await directory_guard_createAsyncDirectoryGuard(next);
3906
- await assertAsyncDirectoryGuard(parentGuard);
3917
+ await directory_guard_assertAsyncDirectoryGuard(parentGuard);
3907
3918
  current = next;
3908
3919
  }
3909
3920
  return current;
@@ -3916,13 +3927,13 @@ async function mkdirPathComponentsWithGuards(params) {
3916
3927
 
3917
3928
  async function withAsyncDirectoryGuards(guards, mutate, options = {}) {
3918
3929
  for (const guard of guards) {
3919
- await assertAsyncDirectoryGuard(guard);
3930
+ await directory_guard_assertAsyncDirectoryGuard(guard);
3920
3931
  }
3921
3932
  const result = await mutate();
3922
3933
  if (options.verifyAfter !== false) {
3923
3934
  try {
3924
3935
  for (const guard of guards) {
3925
- await assertAsyncDirectoryGuard(guard);
3936
+ await directory_guard_assertAsyncDirectoryGuard(guard);
3926
3937
  }
3927
3938
  }
3928
3939
  catch (error) {
@@ -3960,9 +3971,13 @@ async function guardedRename(params) {
3960
3971
  ? await createNearestExistingDirectoryGuard(params.targetRoot, path.dirname(params.to))
3961
3972
  : await createAsyncDirectoryGuard(path.dirname(params.to));
3962
3973
  await withAsyncDirectoryGuards([sourceGuard, targetGuard], async () => {
3974
+ if (params.onSourceInspected) {
3975
+ params.onSourceInspected(fsSync.lstatSync(params.from, { bigint: true }));
3976
+ }
3963
3977
  // Authority must survive all awaited guards; do not yield before rename dispatch.
3964
3978
  params.assertBeforeRename?.();
3965
3979
  await fs.rename(params.from, params.to);
3980
+ params.onRenamed?.();
3966
3981
  }, { verifyAfter: params.verifyAfter });
3967
3982
  }
3968
3983
  function guardedRenameSync(params) {
@@ -3993,13 +4008,12 @@ function guardedRmSync(params) {
3993
4008
 
3994
4009
 
3995
4010
 
3996
-
3997
4011
  function isFilesystemRoot(candidate) {
3998
4012
  return external_node_path_.parse(candidate).root === candidate;
3999
4013
  }
4000
- async function pathExists(targetPath) {
4014
+ async function root_path_existing_pathExists(targetPath) {
4001
4015
  try {
4002
- await promises_.lstat(targetPath);
4016
+ external_node_fs_.lstatSync(targetPath);
4003
4017
  return true;
4004
4018
  }
4005
4019
  catch (error) {
@@ -4013,7 +4027,7 @@ async function resolvePathViaExistingAncestor(targetPath) {
4013
4027
  const normalized = external_node_path_.resolve(targetPath);
4014
4028
  let cursor = normalized;
4015
4029
  const missingSuffix = [];
4016
- while (!isFilesystemRoot(cursor) && !(await pathExists(cursor))) {
4030
+ while (!isFilesystemRoot(cursor) && !(await root_path_existing_pathExists(cursor))) {
4017
4031
  missingSuffix.unshift(external_node_path_.basename(cursor));
4018
4032
  const parent = external_node_path_.dirname(cursor);
4019
4033
  if (parent === cursor) {
@@ -4021,11 +4035,11 @@ async function resolvePathViaExistingAncestor(targetPath) {
4021
4035
  }
4022
4036
  cursor = parent;
4023
4037
  }
4024
- if (!(await pathExists(cursor))) {
4038
+ if (!(await root_path_existing_pathExists(cursor))) {
4025
4039
  return normalized;
4026
4040
  }
4027
4041
  try {
4028
- const resolvedAncestor = external_node_path_.resolve(await promises_.realpath(cursor));
4042
+ const resolvedAncestor = external_node_path_.resolve(external_node_fs_.realpathSync.native(cursor));
4029
4043
  return missingSuffix.length === 0
4030
4044
  ? resolvedAncestor
4031
4045
  : external_node_path_.resolve(resolvedAncestor, ...missingSuffix);
@@ -4135,10 +4149,15 @@ function mergeDenyMutationPolicies(defaultPolicy, callPolicy) {
4135
4149
 
4136
4150
 
4137
4151
 
4152
+
4138
4153
  function recordFileOpenFailure(error, filePath) {
4139
4154
  recordFileObservationFailure(error, `open:${filePath}`);
4140
4155
  throw error;
4141
4156
  }
4157
+ function recordExclusiveCreateFailure(error, filePath) {
4158
+ recordFileObservationFailure(error, `exclusive-create:${filePath}`);
4159
+ throw error;
4160
+ }
4142
4161
  function openedPathResolutionError(error = new errors_FsSafeError("path-mismatch", "unable to resolve opened file path")) {
4143
4162
  recordFileObservationFailure(error, "resolution");
4144
4163
  return error;
@@ -4148,8 +4167,8 @@ async function recordPreOpenFileChange(error, handle, filePath, before, opened)
4148
4167
  ![0n, 1n].includes(before.nlink) || ![0n, 1n].includes(opened.nlink))
4149
4168
  return;
4150
4169
  try {
4151
- await inspectFileIdentity(async () => before);
4152
- const current = await inspectFileIdentity(() => handle.stat({ bigint: true }), opened);
4170
+ await strict_file_identity_inspectFileIdentity(async () => before);
4171
+ const current = await strict_file_identity_inspectFileIdentity(() => external_node_fs_.fstatSync(handle.fd, { bigint: true }), opened);
4153
4172
  if (current.isFile() && [0n, 1n].includes(current.nlink) &&
4154
4173
  (before.dev !== current.dev || before.ino !== current.ino)) {
4155
4174
  // A stale pathname sample is not proof that its former inode was unlinked.
@@ -4165,7 +4184,7 @@ async function recordOpenedFileFailure(error, handle, filePath, identity) {
4165
4184
  !identity.isFile() || identity.nlink > 1n)
4166
4185
  return;
4167
4186
  try {
4168
- const current = await inspectFileIdentity(() => handle.stat({ bigint: true }), identity);
4187
+ const current = await strict_file_identity_inspectFileIdentity(() => external_node_fs_.fstatSync(handle.fd, { bigint: true }), identity);
4169
4188
  if (current.isFile() && current.nlink === 0n)
4170
4189
  recordFileObservationFailure(error, `unlinked:${filePath}`);
4171
4190
  }
@@ -4180,24 +4199,23 @@ async function recordOpenedFileFailure(error, handle, filePath, identity) {
4180
4199
 
4181
4200
 
4182
4201
 
4202
+
4183
4203
  async function resolveOpenedFileRealPathForHandle(handle, ioPath) {
4184
- const handleStat = await handle.stat();
4185
- return await resolveOpenedFileRealPathForFd(handle.fd, handleStat, ioPath);
4204
+ const handleStat = external_node_fs_.fstatSync(handle.fd);
4205
+ return (await resolveOpenedFileRealPathForFd(handle.fd, handleStat, ioPath)).realPath;
4186
4206
  }
4187
4207
  async function resolveOpenedFileRealPathForFd(fd, handleStat, ioPath) {
4188
4208
  const statOptions = typeof handleStat.dev === "bigint" || typeof handleStat.ino === "bigint"
4189
4209
  ? { bigint: true } : undefined;
4190
4210
  const fdCandidates = process.platform === "linux"
4191
4211
  ? [`/proc/self/fd/${fd}`, `/dev/fd/${fd}`]
4192
- : process.platform === "win32"
4193
- ? []
4194
- : [`/dev/fd/${fd}`];
4212
+ : [];
4195
4213
  for (const fdPath of fdCandidates) {
4196
4214
  try {
4197
- const fdRealPath = await promises_.realpath(fdPath);
4198
- const fdRealStat = statOptions ? await promises_.stat(fdRealPath, statOptions) : await promises_.stat(fdRealPath);
4215
+ const fdRealPath = external_node_fs_.realpathSync.native(fdPath);
4216
+ const fdRealStat = statOptions ? external_node_fs_.statSync(fdRealPath, statOptions) : external_node_fs_.statSync(fdRealPath);
4199
4217
  if (file_identity_sameFileIdentity(handleStat, fdRealStat)) {
4200
- return fdRealPath;
4218
+ return { realPath: fdRealPath, stat: fdRealStat };
4201
4219
  }
4202
4220
  }
4203
4221
  catch {
@@ -4205,10 +4223,10 @@ async function resolveOpenedFileRealPathForFd(fd, handleStat, ioPath) {
4205
4223
  }
4206
4224
  }
4207
4225
  try {
4208
- const ioRealPath = await promises_.realpath(ioPath);
4209
- const ioRealStat = statOptions ? await promises_.stat(ioRealPath, statOptions) : await promises_.stat(ioRealPath);
4226
+ const ioRealPath = external_node_fs_.realpathSync.native(ioPath);
4227
+ const ioRealStat = statOptions ? external_node_fs_.statSync(ioRealPath, statOptions) : external_node_fs_.statSync(ioRealPath);
4210
4228
  if (file_identity_sameFileIdentity(handleStat, ioRealStat)) {
4211
- return ioRealPath;
4229
+ return { realPath: ioRealPath, stat: ioRealStat };
4212
4230
  }
4213
4231
  }
4214
4232
  catch (err) {
@@ -4231,7 +4249,7 @@ async function resolveOpenedFileRealPathForFd(fd, handleStat, ioPath) {
4231
4249
  async function resolveOpenedFileRealPathFromParent(handleStat, ioPath, statOptions) {
4232
4250
  let parentReal;
4233
4251
  try {
4234
- parentReal = await promises_.realpath(external_node_path_.dirname(ioPath));
4252
+ parentReal = external_node_fs_.realpathSync.native(external_node_path_.dirname(ioPath));
4235
4253
  }
4236
4254
  catch (err) {
4237
4255
  if (path_isNotFoundPathError(err)) {
@@ -4252,9 +4270,12 @@ async function resolveOpenedFileRealPathFromParent(handleStat, ioPath, statOptio
4252
4270
  for (const entry of entries.toSorted()) {
4253
4271
  const candidatePath = external_node_path_.join(parentReal, entry);
4254
4272
  try {
4255
- const candidateStat = statOptions ? await promises_.lstat(candidatePath, statOptions) : await promises_.lstat(candidatePath);
4273
+ const candidateStat = statOptions ? external_node_fs_.lstatSync(candidatePath, statOptions) : external_node_fs_.lstatSync(candidatePath);
4256
4274
  if (candidateStat.isFile() && file_identity_sameFileIdentity(handleStat, candidateStat)) {
4257
- return await promises_.realpath(candidatePath);
4275
+ const realPath = external_node_fs_.realpathSync.native(candidatePath);
4276
+ const stat = statOptions ? external_node_fs_.statSync(realPath, statOptions) : external_node_fs_.statSync(realPath);
4277
+ if (file_identity_sameFileIdentity(handleStat, stat))
4278
+ return { realPath, stat };
4258
4279
  }
4259
4280
  }
4260
4281
  catch (err) {
@@ -4266,6 +4287,27 @@ async function resolveOpenedFileRealPathFromParent(handleStat, ioPath, statOptio
4266
4287
  return null;
4267
4288
  }
4268
4289
 
4290
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/file-sync.js
4291
+
4292
+ async function syncFileBestEffort(handle) {
4293
+ try {
4294
+ await handle.sync();
4295
+ }
4296
+ catch (error) {
4297
+ if (error?.code !== "EPERM")
4298
+ throw error;
4299
+ }
4300
+ }
4301
+ function syncFileBestEffortSync(fd, fsModule = external_node_fs_) {
4302
+ try {
4303
+ fsModule.fsyncSync(fd);
4304
+ }
4305
+ catch (error) {
4306
+ if (error?.code !== "EPERM")
4307
+ throw error;
4308
+ }
4309
+ }
4310
+
4269
4311
  // EXTERNAL MODULE: external "node:module"
4270
4312
  var external_node_module_ = __webpack_require__(8995);
4271
4313
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/native-config.js
@@ -4525,7 +4567,7 @@ function getNativeBinding() {
4525
4567
  }
4526
4568
  return undefined;
4527
4569
  }
4528
- function requireNativeBinding() {
4570
+ function native_requireNativeBinding() {
4529
4571
  const native = getNativeBinding();
4530
4572
  if (!native) {
4531
4573
  throw new FsSafeError("helper-unavailable", "native fs-safe helper is unavailable", {
@@ -4612,15 +4654,14 @@ function removeNativeCreatedFileIfStillPinned(params) {
4612
4654
  return;
4613
4655
  }
4614
4656
  try {
4615
- const parentPathStat = external_node_fs_.lstatSync(params.parentPath);
4616
- const parentFdStat = params.binding.fstatIdentity(params.parentFd);
4657
+ const parentPathStat = external_node_fs_.lstatSync(params.parentPath, { bigint: true });
4658
+ const parentFdStat = external_node_fs_.fstatSync(params.parentFd, { bigint: true });
4617
4659
  const targetPath = external_node_path_.join(params.parentPath, params.basename);
4618
- const target = external_node_fs_.lstatSync(targetPath);
4619
- if (!parentPathStat.isSymbolicLink() &&
4620
- parentPathStat.dev === parentFdStat.dev &&
4621
- parentPathStat.ino === parentFdStat.ino &&
4622
- !target.isSymbolicLink() &&
4623
- sameFileIdentityForCleanup(target, params.created)) {
4660
+ const target = external_node_fs_.lstatSync(targetPath, { bigint: true });
4661
+ if (!parentPathStat.isSymbolicLink() && parentPathStat.isDirectory() &&
4662
+ file_identity_sameFileIdentityForCleanup(parentPathStat, parentFdStat) &&
4663
+ !target.isSymbolicLink() && target.isFile() &&
4664
+ file_identity_sameFileIdentityForCleanup(target, params.created)) {
4624
4665
  external_node_fs_.rmSync(targetPath);
4625
4666
  }
4626
4667
  }
@@ -4657,7 +4698,7 @@ async function createNativeExclusiveFile(targetPath, mode) {
4657
4698
  }
4658
4699
  fd = opened.fd;
4659
4700
  external_node_fs_.fchmodSync(fd, mode);
4660
- created = external_node_fs_.fstatSync(fd);
4701
+ created = external_node_fs_.fstatSync(fd, { bigint: true });
4661
4702
  return wrapNativeFd(fd, opened.containment);
4662
4703
  }
4663
4704
  catch (error) {
@@ -4669,7 +4710,6 @@ async function createNativeExclusiveFile(targetPath, mode) {
4669
4710
  // Preserve the original error.
4670
4711
  }
4671
4712
  removeNativeCreatedFileIfStillPinned({
4672
- binding,
4673
4713
  parentPath,
4674
4714
  parentFd: parent.fd,
4675
4715
  basename,
@@ -4682,22 +4722,14 @@ async function createNativeExclusiveFile(targetPath, mode) {
4682
4722
  await parent.close().catch(() => undefined);
4683
4723
  }
4684
4724
  }
4685
- function syncNativeFileBestEffort(fd) {
4686
- try {
4687
- external_node_fs_.fsyncSync(fd);
4688
- }
4689
- catch (error) {
4690
- if (error.code !== "EPERM") {
4691
- throw error;
4692
- }
4693
- }
4694
- }
4695
4725
 
4696
4726
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/native-pinned-write-windows.js
4697
4727
 
4698
4728
 
4699
4729
 
4700
4730
 
4731
+
4732
+
4701
4733
  function sameNativeIdentity(left, right) {
4702
4734
  return left.dev === right.dev && left.ino === right.ino;
4703
4735
  }
@@ -4722,14 +4754,15 @@ async function runPinnedWriteWindows(binding, params, root, parentFd, parentGuar
4722
4754
  try {
4723
4755
  tempName = `.fs-safe-${(0,external_node_crypto_.randomUUID)()}.tmp`;
4724
4756
  tempFd = binding.openBeneath(parentFd, tempName, nativeOpenFlags(external_node_fs_.constants.O_WRONLY | external_node_fs_.constants.O_CREAT | external_node_fs_.constants.O_EXCL)).fd;
4725
- tempIdentity = external_node_fs_.fstatSync(tempFd);
4726
- const verificationIdentity = external_node_fs_.fstatSync(tempFd, { bigint: true });
4757
+ const verificationIdentity = strict_file_identity_inspectFileIdentitySync(() => external_node_fs_.fstatSync(tempFd, { bigint: true }));
4758
+ tempIdentity = verificationIdentity;
4727
4759
  // Creation is requested at 0600 in the binding, but a restrictive umask
4728
4760
  // can remove owner access. Keep the unpublished inode private and
4729
4761
  // reopenable until the published name has been identity-fenced.
4730
4762
  external_node_fs_.fchmodSync(tempFd, 0o600);
4731
4763
  await writeNativeInput(tempFd, params.input, params.maxBytes);
4732
- syncNativeFileBestEffort(tempFd);
4764
+ if (params.sync !== false)
4765
+ syncFileBestEffortSync(tempFd);
4733
4766
  if (params.overwrite === false) {
4734
4767
  binding.renameNoReplace(parentFd, tempName, parentFd, params.basename);
4735
4768
  }
@@ -4738,8 +4771,9 @@ async function runPinnedWriteWindows(binding, params, root, parentFd, parentGuar
4738
4771
  }
4739
4772
  renamed = true;
4740
4773
  targetFd = binding.openBeneath(parentFd, params.basename, nativeOpenFlags(external_node_fs_.constants.O_RDONLY)).fd;
4774
+ const targetStat = strict_file_identity_inspectFileIdentitySync(() => external_node_fs_.fstatSync(targetFd, { bigint: true }), verificationIdentity);
4741
4775
  const targetIdentity = binding.fstatIdentity(targetFd);
4742
- if (!targetIdentity.isFile || !sameNativeIdentity(tempIdentity, targetIdentity)) {
4776
+ if (!targetStat.isFile()) {
4743
4777
  throw new errors_FsSafeError("path-mismatch", "native write target changed after rename");
4744
4778
  }
4745
4779
  // Native exclusive creation starts at 0600. Apply the requested mode only
@@ -4747,13 +4781,13 @@ async function runPinnedWriteWindows(binding, params, root, parentFd, parentGuar
4747
4781
  // verifiable and so broader modes are never exposed before that fence.
4748
4782
  try {
4749
4783
  external_node_fs_.fchmodSync(targetFd, params.mode);
4750
- syncNativeFileBestEffort(targetFd);
4784
+ if (params.sync !== false)
4785
+ syncFileBestEffortSync(targetFd);
4751
4786
  }
4752
4787
  catch (error) {
4753
4788
  closeWriteFd(targetFd);
4754
4789
  targetFd = undefined;
4755
4790
  removeNativeCreatedFileIfStillPinned({
4756
- binding,
4757
4791
  parentPath,
4758
4792
  parentFd,
4759
4793
  basename: params.basename,
@@ -4761,7 +4795,8 @@ async function runPinnedWriteWindows(binding, params, root, parentFd, parentGuar
4761
4795
  });
4762
4796
  throw error;
4763
4797
  }
4764
- syncNativeFileBestEffort(parentFd);
4798
+ if (params.sync !== false)
4799
+ syncFileBestEffortSync(parentFd);
4765
4800
  // Verification follows publication and final chmod, outside rollback handling.
4766
4801
  await params.verifyPublished?.(targetFd, verificationIdentity, parentGuard);
4767
4802
  completed = true;
@@ -4772,7 +4807,6 @@ async function runPinnedWriteWindows(binding, params, root, parentFd, parentGuar
4772
4807
  const tempCloseError = closeWriteFd(tempFd);
4773
4808
  if (!renamed) {
4774
4809
  removeNativeCreatedFileIfStillPinned({
4775
- binding,
4776
4810
  parentPath,
4777
4811
  parentFd,
4778
4812
  basename: tempName,
@@ -4817,7 +4851,7 @@ function assertStagedDirectoryCurrent(receipt) {
4817
4851
  throw new errors_FsSafeError("path-mismatch", "staging directory pathname changed");
4818
4852
  }
4819
4853
  }
4820
- function openStagedDirectory(directory) {
4854
+ function staged_directory_openStagedDirectory(directory) {
4821
4855
  // Copy supplied facts before any asynchronous work; receipts are not authority.
4822
4856
  const pathname = path.resolve(typeof directory === "string" ? directory : directory.path);
4823
4857
  const expected = typeof directory === "string" ? undefined : {
@@ -4907,6 +4941,8 @@ var __disposeResources = (undefined && undefined.__disposeResources) || (functio
4907
4941
 
4908
4942
 
4909
4943
 
4944
+
4945
+
4910
4946
  function assertNativeStaging(binding) {
4911
4947
  if ([
4912
4948
  binding.createStagedFile,
@@ -4942,23 +4978,25 @@ class NativeStagedFile {
4942
4978
  #directory;
4943
4979
  #portableNames;
4944
4980
  #publishedMode;
4981
+ #sync;
4945
4982
  #name = `.fs-safe-${(0,external_node_crypto_.randomUUID)()}.tmp`;
4946
4983
  #state = { status: "open", publication: NOT_PUBLISHED };
4947
4984
  #receipt;
4948
- constructor(binding, parentFd, directory, portableNames, publishedMode) {
4985
+ constructor(binding, parentFd, directory, portableNames, publishedMode, sync) {
4949
4986
  this.#binding = binding;
4950
4987
  this.#parentFd = parentFd;
4951
4988
  this.#directory = directory;
4952
4989
  this.#portableNames = portableNames;
4953
4990
  this.#publishedMode = publishedMode;
4991
+ this.#sync = sync;
4954
4992
  }
4955
4993
  // Takes ownership of parentFd, including all construction and preparation failures.
4956
4994
  static async create(binding, parentFd, directory, input, mode, maxBytes,
4957
4995
  // Public staging uses portable names; existing POSIX writes accept literal names.
4958
- portableNames = true) {
4996
+ portableNames = true, sync = true) {
4959
4997
  let staged;
4960
4998
  try {
4961
- staged = new NativeStagedFile(binding, parentFd, directory, portableNames, mode);
4999
+ staged = new NativeStagedFile(binding, parentFd, directory, portableNames, mode, sync);
4962
5000
  }
4963
5001
  catch (error) {
4964
5002
  try {
@@ -4977,7 +5015,7 @@ class NativeStagedFile {
4977
5015
  try {
4978
5016
  // This owner never escapes. Only the internal verifier borrows its fd;
4979
5017
  // public descriptor methods remain await-free and cannot race disposal.
4980
- const staged = __addDisposableResource(env_1, await NativeStagedFile.create(binding, parentFd, directory, params.input, params.mode, params.maxBytes, false), true);
5018
+ const staged = __addDisposableResource(env_1, await NativeStagedFile.create(binding, parentFd, directory, params.input, params.mode, params.maxBytes, false, params.sync), true);
4981
5019
  const published = await staged.publish(params.basename, { overwrite: params.overwrite !== false });
4982
5020
  const identity = published.staged.identity;
4983
5021
  await params.verifyPublished?.(staged.#file(), identity, parentGuard);
@@ -5014,10 +5052,12 @@ class NativeStagedFile {
5014
5052
  }
5015
5053
  #assertNamed(name) {
5016
5054
  const fd = this.#file();
5017
- if (!this.#binding.stagedFileMatches(this.#parentFd, name, fd) ||
5018
- external_node_fs_.fstatSync(fd, { bigint: true }).nlink !== 1n) {
5055
+ const stat = this.#binding.stagedFileMatches(this.#parentFd, name, fd)
5056
+ ? external_node_fs_.fstatSync(fd, { bigint: true }) : undefined;
5057
+ if (!stat || stat.nlink !== 1n) {
5019
5058
  throw new errors_FsSafeError("path-mismatch", "staged entry no longer names the exclusive created file");
5020
5059
  }
5060
+ return Number(stat.mode & 4095n);
5021
5061
  }
5022
5062
  #assertCurrent() {
5023
5063
  if (this.#open().publication.status !== "not-published") {
@@ -5040,7 +5080,8 @@ class NativeStagedFile {
5040
5080
  const fd = state.fileFd;
5041
5081
  external_node_fs_.fchmodSync(fd, 0o600);
5042
5082
  await writeNativeInput(fd, input, maxBytes);
5043
- syncNativeFileBestEffort(fd);
5083
+ if (this.#sync)
5084
+ syncFileBestEffortSync(fd);
5044
5085
  const stat = external_node_fs_.fstatSync(fd, { bigint: true });
5045
5086
  this.#receipt = Object.freeze({
5046
5087
  directory: this.#directory,
@@ -5107,14 +5148,21 @@ class NativeStagedFile {
5107
5148
  overwrite,
5108
5149
  });
5109
5150
  state.publication = receipt;
5110
- this.#assertNamed(basename);
5151
+ const stagedMode = this.#assertNamed(basename);
5111
5152
  assertStagedDirectoryCurrent(this.#directory);
5112
5153
  // Keep contents private until the published name passes its identity
5113
5154
  // fence. Mode changes use the owned fd, including for final mode 000.
5114
5155
  const fd = this.#file();
5115
- external_node_fs_.fchmodSync(fd, this.#publishedMode);
5116
- syncNativeFileBestEffort(fd);
5117
- syncNativeFileBestEffort(this.#parentFd);
5156
+ if (this.#publishedMode !== 0o600 || stagedMode !== 0o600)
5157
+ external_node_fs_.fchmodSync(fd, this.#publishedMode);
5158
+ // With sync enabled, content was synced before rename. A lost chmod leaves staged 0600,
5159
+ // no wider than modes retaining owner rw. Restrictive modes and observed
5160
+ // widening of the stage still need the permission correction made durable.
5161
+ if (this.#sync && ((this.#publishedMode & 0o600) !== 0o600 || (stagedMode & ~this.#publishedMode) !== 0)) {
5162
+ syncFileBestEffortSync(fd);
5163
+ }
5164
+ if (this.#sync)
5165
+ syncFileBestEffortSync(this.#parentFd);
5118
5166
  this.#assertNamed(basename);
5119
5167
  assertStagedDirectoryCurrent(this.#directory);
5120
5168
  return receipt;
@@ -5187,6 +5235,17 @@ class NativeStagedFile {
5187
5235
  }
5188
5236
  const createNativeStage = NativeStagedFile.create;
5189
5237
  const writeNativeStage = NativeStagedFile.write;
5238
+ async function stageFileInDirectory(options) {
5239
+ if (process.platform !== "linux" && process.platform !== "darwin") {
5240
+ throw new FsSafeError("unsupported-platform", "retained-directory staging requires Linux or macOS");
5241
+ }
5242
+ const binding = requireNativeBinding();
5243
+ assertNativeStaging(binding);
5244
+ const input = { kind: "buffer", data: Buffer.from(options.content) };
5245
+ const mode = options.mode ?? 0o600;
5246
+ const parent = openStagedDirectory(options.directory);
5247
+ return await createNativeStage(binding, parent.fd, parent.receipt, input, mode);
5248
+ }
5190
5249
 
5191
5250
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/native-pinned-write.js
5192
5251
  var native_pinned_write_addDisposableResource = (undefined && undefined.__addDisposableResource) || function (env, value, async) {
@@ -5248,6 +5307,8 @@ var native_pinned_write_disposeResources = (undefined && undefined.__disposeReso
5248
5307
 
5249
5308
 
5250
5309
 
5310
+
5311
+
5251
5312
  async function runPinnedWriteNative(binding, params) {
5252
5313
  const env_1 = { stack: [], error: void 0, hasError: false };
5253
5314
  try {
@@ -5270,8 +5331,14 @@ async function runPinnedWriteNative(binding, params) {
5270
5331
  },
5271
5332
  }, false);
5272
5333
  try {
5334
+ const exactRoot = typeof params.rootIdentity?.dev === "bigint" && typeof params.rootIdentity.ino === "bigint"
5335
+ ? { dev: params.rootIdentity.dev, ino: params.rootIdentity.ino } : undefined;
5273
5336
  let rootMatches;
5274
- if (windows) {
5337
+ if (exactRoot) {
5338
+ strict_file_identity_inspectFileIdentitySync(() => external_node_fs_.fstatSync(root.fd, { bigint: true }), exactRoot);
5339
+ rootMatches = true;
5340
+ }
5341
+ else if (windows) {
5275
5342
  const identity = binding.fstatIdentity(root.fd);
5276
5343
  rootMatches = !params.rootIdentity || sameNativeIdentity(params.rootIdentity, identity);
5277
5344
  }
@@ -5286,24 +5353,26 @@ async function runPinnedWriteNative(binding, params) {
5286
5353
  binding.mkdirBeneath(root.fd, params.relativeParentPath, 0o777);
5287
5354
  }
5288
5355
  parentFd = binding.openBeneath(root.fd, params.relativeParentPath, directoryFlags).fd;
5289
- const parentPath = await promises_.realpath(params.relativeParentPath
5356
+ const parentPath = external_node_fs_.realpathSync.native(params.relativeParentPath
5290
5357
  ? external_node_path_.join(params.rootPath, ...params.relativeParentPath.split("/"))
5291
5358
  : params.rootPath);
5292
5359
  const directory = windows ? undefined : describeStagedDirectory(parentFd, parentPath);
5293
- const parentPathStat = await promises_.lstat(parentPath);
5294
- if (windows) {
5360
+ const parentPathStat = exactRoot
5361
+ ? await inspectDirectoryIdentity(parentPath, strict_file_identity_inspectFileIdentitySync(() => external_node_fs_.fstatSync(parentFd, { bigint: true })))
5362
+ : external_node_fs_.lstatSync(parentPath);
5363
+ if (windows && !exactRoot) {
5295
5364
  const parentIdentity = binding.fstatIdentity(parentFd);
5296
5365
  if (parentPathStat.isSymbolicLink() || !sameNativeIdentity(parentPathStat, parentIdentity)) {
5297
5366
  throw new errors_FsSafeError("path-mismatch", "native write parent changed during resolution");
5298
5367
  }
5299
5368
  }
5300
- else if (parentPathStat.isSymbolicLink() || !exactIdentityMatches(parentPathStat, directory.identity)) {
5369
+ else if (!windows && (parentPathStat.isSymbolicLink() || !exactIdentityMatches(parentPathStat, directory.identity))) {
5301
5370
  throw new errors_FsSafeError("path-mismatch", "native write parent changed during resolution");
5302
5371
  }
5303
5372
  const verificationGuard = { dir: parentPath, realPath: parentPath, stat: parentPathStat };
5304
5373
  if (params.overwrite === false) {
5305
5374
  try {
5306
- await promises_.lstat(external_node_path_.join(parentPath, params.basename));
5375
+ external_node_fs_.lstatSync(external_node_path_.join(parentPath, params.basename));
5307
5376
  throw Object.assign(new Error("destination already exists"), { code: "EEXIST" });
5308
5377
  }
5309
5378
  catch (error) {
@@ -5393,6 +5462,384 @@ function read_open_flags_resolveReadOpenFlags(options) {
5393
5462
  return constants.O_RDONLY | noFollow | nonBlocking;
5394
5463
  }
5395
5464
 
5465
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/replace-file-temp-owner.js
5466
+
5467
+
5468
+
5469
+
5470
+
5471
+
5472
+
5473
+
5474
+ const PUBLISHED_READ_FLAGS = read_open_flags_resolveReadOpenFlags();
5475
+ function assertOwnedFile(stat, pathname, pathnameEntry) {
5476
+ if (stat.isSymbolicLink()) {
5477
+ throw new FsSafeError("symlink", `Atomic replace owned file became a symlink: ${pathname}`);
5478
+ }
5479
+ if (!stat.isFile()) {
5480
+ throw new FsSafeError("not-file", `Atomic replace owned file must remain regular: ${pathname}`);
5481
+ }
5482
+ if (stat.nlink > 1n || (pathnameEntry && stat.nlink !== 1n)) {
5483
+ throw new FsSafeError("hardlink", `Atomic replace owned file must retain one link: ${pathname}`);
5484
+ }
5485
+ }
5486
+ function missingOwnedFile(pathname, cause) {
5487
+ return new FsSafeError("path-mismatch", `Atomic replace owned file disappeared: ${pathname}`, {
5488
+ cause,
5489
+ });
5490
+ }
5491
+ function cleanupFailure(originalError, cleanupError) {
5492
+ if (originalError !== undefined) {
5493
+ return new Error(`Atomic file replace failed (${String(originalError)}); cleanup also failed (${String(cleanupError)})`, { cause: originalError });
5494
+ }
5495
+ return cleanupError instanceof Error ? cleanupError : new Error(String(cleanupError));
5496
+ }
5497
+ async function cleanupOwnedPath(params) {
5498
+ if (!params.identity)
5499
+ return true;
5500
+ try {
5501
+ const current = params.fsModule === promises_
5502
+ ? external_node_fs_.lstatSync(params.pathname, { bigint: true })
5503
+ : await params.fsModule.lstat(params.pathname, { bigint: true });
5504
+ if (current.isSymbolicLink() ||
5505
+ !current.isFile() ||
5506
+ current.nlink !== 1n ||
5507
+ !file_identity_sameFileIdentityForCleanup(current, params.identity)) {
5508
+ return true;
5509
+ }
5510
+ await params.fsModule.unlink(params.pathname);
5511
+ return true;
5512
+ }
5513
+ catch (cleanupError) {
5514
+ if (cleanupError.code === "ENOENT")
5515
+ return true;
5516
+ if (params.throwOnCleanupError) {
5517
+ throw cleanupFailure(params.originalError, cleanupError);
5518
+ }
5519
+ return false;
5520
+ }
5521
+ }
5522
+ // Borrowed handle: the caller retains it until this best-effort cleanup finishes.
5523
+ async function cleanupPinnedFilePath(params) {
5524
+ if (!params.identity)
5525
+ return;
5526
+ try {
5527
+ const guard = params.parentGuard;
5528
+ if ([guard.stat.dev, guard.stat.ino].some((value) => typeof value === "number" && !Number.isSafeInteger(value)))
5529
+ return;
5530
+ await directory_guard_assertAsyncDirectoryGuard(guard);
5531
+ const parent = external_node_fs_.lstatSync(guard.dir, { bigint: true });
5532
+ if (parent.isSymbolicLink() || !parent.isDirectory() ||
5533
+ !file_identity_sameFileIdentityForCleanup(parent, guard.stat))
5534
+ return;
5535
+ const opened = external_node_fs_.fstatSync(params.handle.fd, { bigint: true });
5536
+ if (!opened.isFile() || opened.nlink !== 1n ||
5537
+ !file_identity_sameFileIdentityForCleanup(opened, params.identity))
5538
+ return;
5539
+ await cleanupOwnedPath({
5540
+ fsModule: promises_,
5541
+ pathname: params.pathname,
5542
+ identity: params.identity,
5543
+ throwOnCleanupError: false,
5544
+ });
5545
+ }
5546
+ catch {
5547
+ // Unverifiable authority must preserve the path and the original write failure.
5548
+ }
5549
+ }
5550
+ function cleanupOwnedPathSync(params) {
5551
+ if (!params.identity)
5552
+ return true;
5553
+ try {
5554
+ const current = params.fsModule.lstatSync(params.pathname, { bigint: true });
5555
+ if (current.isSymbolicLink() ||
5556
+ !current.isFile() ||
5557
+ current.nlink !== 1n ||
5558
+ !sameFileIdentityForCleanup(current, params.identity)) {
5559
+ return true;
5560
+ }
5561
+ params.fsModule.unlinkSync(params.pathname);
5562
+ return true;
5563
+ }
5564
+ catch (cleanupError) {
5565
+ if (cleanupError.code === "ENOENT")
5566
+ return true;
5567
+ if (params.throwOnCleanupError) {
5568
+ throw cleanupFailure(params.originalError, cleanupError);
5569
+ }
5570
+ return false;
5571
+ }
5572
+ }
5573
+ class AsyncAtomicTempOwner {
5574
+ pathname;
5575
+ #handle;
5576
+ #identity;
5577
+ #exists = false;
5578
+ #unregister;
5579
+ constructor(pathname) {
5580
+ this.pathname = pathname;
5581
+ this.#unregister = registerTempPathForExit(pathname, { singleLinkFile: true });
5582
+ }
5583
+ start() {
5584
+ this.#exists = true;
5585
+ }
5586
+ onIdentity = (identity) => {
5587
+ this.#identity = identity;
5588
+ this.#unregister.setIdentity(identity);
5589
+ };
5590
+ adopt(temp) {
5591
+ this.#handle = temp.handle;
5592
+ this.onIdentity(temp.identity);
5593
+ }
5594
+ get identity() {
5595
+ if (!this.#identity)
5596
+ throw new Error("Atomic temp owner has no identity");
5597
+ return this.#identity;
5598
+ }
5599
+ async assertCurrent(fsModule, pathname = this.pathname) {
5600
+ const opened = await inspectFileIdentity(async () => {
5601
+ const stat = fsModule === fs ? syncFs.fstatSync(this.#handle.fd, { bigint: true })
5602
+ : await this.#handle.stat({ bigint: true });
5603
+ assertOwnedFile(stat, pathname, false);
5604
+ return stat;
5605
+ }, this.identity);
5606
+ try {
5607
+ await inspectFileIdentity(async () => {
5608
+ const stat = fsModule === fs ? syncFs.lstatSync(pathname, { bigint: true })
5609
+ : await fsModule.lstat(pathname, { bigint: true });
5610
+ assertOwnedFile(stat, pathname, true);
5611
+ return stat;
5612
+ }, opened);
5613
+ }
5614
+ catch (error) {
5615
+ if (error.code === "ENOENT") {
5616
+ throw missingOwnedFile(pathname, error);
5617
+ }
5618
+ throw error;
5619
+ }
5620
+ }
5621
+ async assertPublished(fsModule, pathname, expectedHash) {
5622
+ try {
5623
+ await this.assertCurrent(fsModule, pathname);
5624
+ return;
5625
+ }
5626
+ catch (error) {
5627
+ if (!(error instanceof FsSafeError) || error.code !== "path-mismatch" || !expectedHash) {
5628
+ throw error;
5629
+ }
5630
+ }
5631
+ let published;
5632
+ try {
5633
+ try {
5634
+ published = await fsModule.open(pathname, PUBLISHED_READ_FLAGS);
5635
+ }
5636
+ catch (error) {
5637
+ if (error.code === "ELOOP") {
5638
+ throw new FsSafeError("symlink", `Atomic replace published file became a symlink: ${pathname}`, {
5639
+ cause: error,
5640
+ });
5641
+ }
5642
+ throw error;
5643
+ }
5644
+ const identity = await inspectFileIdentity(async () => {
5645
+ const stat = fsModule === fs ? syncFs.fstatSync(published.fd, { bigint: true })
5646
+ : await published.stat({ bigint: true });
5647
+ assertOwnedFile(stat, pathname, false);
5648
+ return stat;
5649
+ });
5650
+ await inspectFileIdentity(async () => {
5651
+ const stat = fsModule === fs ? syncFs.lstatSync(pathname, { bigint: true })
5652
+ : await fsModule.lstat(pathname, { bigint: true });
5653
+ assertOwnedFile(stat, pathname, true);
5654
+ return stat;
5655
+ }, identity);
5656
+ if (sha256Hex(await published.readFile()) !== expectedHash) {
5657
+ throw new FsSafeError("path-mismatch", `Atomic replace published content changed: ${pathname}`);
5658
+ }
5659
+ await this.#handle?.close();
5660
+ this.#handle = published;
5661
+ this.#identity = identity;
5662
+ published = undefined;
5663
+ }
5664
+ finally {
5665
+ await published?.close().catch(() => undefined);
5666
+ }
5667
+ }
5668
+ markRenamed() {
5669
+ this.#exists = false;
5670
+ this.#unregister();
5671
+ }
5672
+ async finish(params) {
5673
+ let deferredError;
5674
+ let cleanupComplete = !this.#exists;
5675
+ if (this.#exists) {
5676
+ try {
5677
+ cleanupComplete = await cleanupOwnedPath({
5678
+ fsModule: params.fsModule,
5679
+ pathname: this.pathname,
5680
+ identity: this.#identity,
5681
+ originalError: params.originalError,
5682
+ throwOnCleanupError: params.throwOnCleanupError,
5683
+ });
5684
+ }
5685
+ catch (error) {
5686
+ deferredError = error;
5687
+ }
5688
+ }
5689
+ if (cleanupComplete)
5690
+ this.#unregister();
5691
+ try {
5692
+ await this.#handle?.close();
5693
+ }
5694
+ catch (closeError) {
5695
+ deferredError = deferredError
5696
+ ? new AggregateError([deferredError, closeError], "Atomic temp cleanup and close failed")
5697
+ : params.originalError !== undefined
5698
+ ? new AggregateError([params.originalError, closeError], "Atomic file replace and close failed")
5699
+ : closeError;
5700
+ }
5701
+ if (deferredError)
5702
+ throw deferredError;
5703
+ }
5704
+ }
5705
+ class SyncAtomicTempOwner {
5706
+ pathname;
5707
+ #fd;
5708
+ #identity;
5709
+ #exists = false;
5710
+ #unregister;
5711
+ constructor(pathname) {
5712
+ this.pathname = pathname;
5713
+ this.#unregister = registerTempPathForExit(pathname, { singleLinkFile: true });
5714
+ }
5715
+ start() {
5716
+ this.#exists = true;
5717
+ }
5718
+ onIdentity = (identity) => {
5719
+ this.#identity = identity;
5720
+ this.#unregister.setIdentity(identity);
5721
+ };
5722
+ adopt(temp) {
5723
+ this.#fd = temp.fd;
5724
+ this.onIdentity(temp.identity);
5725
+ }
5726
+ get identity() {
5727
+ if (!this.#identity)
5728
+ throw new Error("Atomic temp owner has no identity");
5729
+ return this.#identity;
5730
+ }
5731
+ assertCurrent(fsModule, pathname = this.pathname) {
5732
+ const opened = inspectFileIdentitySync(() => {
5733
+ const stat = fsModule.fstatSync(this.#fd, { bigint: true });
5734
+ assertOwnedFile(stat, pathname, false);
5735
+ return stat;
5736
+ }, this.identity);
5737
+ try {
5738
+ inspectFileIdentitySync(() => {
5739
+ const stat = fsModule.lstatSync(pathname, { bigint: true });
5740
+ assertOwnedFile(stat, pathname, true);
5741
+ return stat;
5742
+ }, opened);
5743
+ }
5744
+ catch (error) {
5745
+ if (error.code === "ENOENT") {
5746
+ throw missingOwnedFile(pathname, error);
5747
+ }
5748
+ throw error;
5749
+ }
5750
+ }
5751
+ assertPublished(fsModule, pathname, expectedHash) {
5752
+ try {
5753
+ this.assertCurrent(fsModule, pathname);
5754
+ return;
5755
+ }
5756
+ catch (error) {
5757
+ if (!(error instanceof FsSafeError) || error.code !== "path-mismatch" || !expectedHash) {
5758
+ throw error;
5759
+ }
5760
+ }
5761
+ let publishedFd;
5762
+ try {
5763
+ try {
5764
+ publishedFd = fsModule.openSync(pathname, PUBLISHED_READ_FLAGS);
5765
+ }
5766
+ catch (error) {
5767
+ if (error.code === "ELOOP") {
5768
+ throw new FsSafeError("symlink", `Atomic replace published file became a symlink: ${pathname}`, {
5769
+ cause: error,
5770
+ });
5771
+ }
5772
+ throw error;
5773
+ }
5774
+ const identity = inspectFileIdentitySync(() => {
5775
+ const stat = fsModule.fstatSync(publishedFd, { bigint: true });
5776
+ assertOwnedFile(stat, pathname, false);
5777
+ return stat;
5778
+ });
5779
+ inspectFileIdentitySync(() => {
5780
+ const stat = fsModule.lstatSync(pathname, { bigint: true });
5781
+ assertOwnedFile(stat, pathname, true);
5782
+ return stat;
5783
+ }, identity);
5784
+ if (sha256Hex(fsModule.readFileSync(publishedFd)) !== expectedHash) {
5785
+ throw new FsSafeError("path-mismatch", `Atomic replace published content changed: ${pathname}`);
5786
+ }
5787
+ fsModule.closeSync(this.#fd);
5788
+ this.#fd = publishedFd;
5789
+ this.#identity = identity;
5790
+ publishedFd = undefined;
5791
+ }
5792
+ finally {
5793
+ if (publishedFd !== undefined) {
5794
+ try {
5795
+ fsModule.closeSync(publishedFd);
5796
+ }
5797
+ catch {
5798
+ // Best-effort close after a rejected content verification.
5799
+ }
5800
+ }
5801
+ }
5802
+ }
5803
+ markRenamed() {
5804
+ this.#exists = false;
5805
+ this.#unregister();
5806
+ }
5807
+ finish(params) {
5808
+ let deferredError;
5809
+ let cleanupComplete = !this.#exists;
5810
+ if (this.#exists) {
5811
+ try {
5812
+ cleanupComplete = cleanupOwnedPathSync({
5813
+ fsModule: params.fsModule,
5814
+ pathname: this.pathname,
5815
+ identity: this.#identity,
5816
+ originalError: params.originalError,
5817
+ throwOnCleanupError: params.throwOnCleanupError,
5818
+ });
5819
+ }
5820
+ catch (error) {
5821
+ deferredError = error;
5822
+ }
5823
+ }
5824
+ if (cleanupComplete)
5825
+ this.#unregister();
5826
+ if (this.#fd !== undefined) {
5827
+ try {
5828
+ params.fsModule.closeSync(this.#fd);
5829
+ }
5830
+ catch (closeError) {
5831
+ deferredError = deferredError
5832
+ ? new AggregateError([deferredError, closeError], "Atomic temp cleanup and close failed")
5833
+ : params.originalError !== undefined
5834
+ ? new AggregateError([params.originalError, closeError], "Atomic file replace and close failed")
5835
+ : closeError;
5836
+ }
5837
+ }
5838
+ if (deferredError)
5839
+ throw deferredError;
5840
+ }
5841
+ }
5842
+
5396
5843
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/bounded-read.js
5397
5844
 
5398
5845
 
@@ -5417,11 +5864,24 @@ function appendChunk(params) {
5417
5864
  params.chunks.push(Buffer.from(params.scratch.subarray(0, params.bytesRead)));
5418
5865
  return total;
5419
5866
  }
5420
- async function readBoundedAsync(maxBytes, readChunk) {
5867
+ async function readBoundedAsync(maxBytes, readChunk, observeRegularFileSize) {
5421
5868
  byte_budget_normalizeMaxBytes(maxBytes);
5422
5869
  const chunks = [];
5423
- const scratch = createScratchBuffer(maxBytes);
5424
5870
  let total = 0;
5871
+ const size = observeRegularFileSize?.();
5872
+ if (size !== undefined) {
5873
+ const first = Buffer.allocUnsafe(Math.min(maxBytes, size) + 1);
5874
+ const bytesRead = await readChunk(first, first.length);
5875
+ if (bytesRead === 0)
5876
+ return first.subarray(0, 0);
5877
+ // Short reads can occur before EOF. Only accept one when a fresh fd size
5878
+ // observation proves we consumed at least the entire current file size.
5879
+ const currentSize = bytesRead < first.length ? observeRegularFileSize?.() : undefined;
5880
+ if (currentSize !== undefined && bytesRead >= currentSize)
5881
+ return first.subarray(0, bytesRead);
5882
+ total = appendChunk({ chunks, scratch: first, bytesRead, total, maxBytes });
5883
+ }
5884
+ const scratch = createScratchBuffer(maxBytes);
5425
5885
  while (true) {
5426
5886
  const length = nextReadLength(total, maxBytes, scratch.length);
5427
5887
  const bytesRead = await readChunk(scratch, length);
@@ -5437,9 +5897,22 @@ async function readBoundedAsync(maxBytes, readChunk) {
5437
5897
  * force an unbounded allocation.
5438
5898
  */
5439
5899
  async function readFileHandleBounded(handle, maxBytes) {
5900
+ byte_budget_normalizeMaxBytes(maxBytes);
5901
+ const fd = "fd" in handle && typeof handle.fd === "number" ? handle.fd : undefined;
5440
5902
  return await readBoundedAsync(maxBytes, async (scratch, length) => {
5441
5903
  return (await handle.read(scratch, 0, length, null)).bytesRead;
5442
- });
5904
+ }, fd === undefined ? undefined : () => regularFileSize(fd));
5905
+ }
5906
+ function regularFileSize(fd) {
5907
+ try {
5908
+ const stat = external_node_fs_.fstatSync(fd);
5909
+ return stat.isFile() && Number.isSafeInteger(stat.size) && stat.size >= 0
5910
+ ? stat.size : undefined;
5911
+ }
5912
+ catch {
5913
+ // Size is only an optimization hint; retain the reader's original errors.
5914
+ return undefined;
5915
+ }
5443
5916
  }
5444
5917
  function readDescriptorChunk(fd, scratch, length) {
5445
5918
  return new Promise((resolve, reject) => {
@@ -5454,9 +5927,10 @@ function readDescriptorChunk(fd, scratch, length) {
5454
5927
  }
5455
5928
  /** Async bounded read from a numeric descriptor. The caller owns the descriptor. */
5456
5929
  async function readFileDescriptorBounded(fd, maxBytes) {
5930
+ normalizeMaxBytes(maxBytes);
5457
5931
  return await readBoundedAsync(maxBytes, async (scratch, length) => {
5458
5932
  return await readDescriptorChunk(fd, scratch, length);
5459
- });
5933
+ }, () => regularFileSize(fd));
5460
5934
  }
5461
5935
  /** Sync bounded read from a numeric descriptor. The caller owns the descriptor. */
5462
5936
  function bounded_read_readFileDescriptorBoundedSync(fd, maxBytes) {
@@ -5474,11 +5948,19 @@ function bounded_read_readFileDescriptorBoundedSync(fd, maxBytes) {
5474
5948
  }
5475
5949
  }
5476
5950
 
5951
+ // EXTERNAL MODULE: external "node:os"
5952
+ var external_node_os_ = __webpack_require__(8161);
5477
5953
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/error-detail.js
5954
+
5478
5955
  const UNSAFE_ERROR_DETAIL_CHARACTERS = /[\u0000-\u001f\u007f-\u009f\u2028\u2029]/gu;
5479
5956
  function formatErrorDetail(value) {
5480
5957
  return value.replace(UNSAFE_ERROR_DETAIL_CHARACTERS, (character) => `\\u${character.charCodeAt(0).toString(16).padStart(4, "0")}`);
5481
5958
  }
5959
+ function shortPath(value) {
5960
+ const home = external_node_os_.homedir();
5961
+ const shortened = value.startsWith(home) ? `~${value.slice(home.length)}` : value;
5962
+ return formatErrorDetail(shortened);
5963
+ }
5482
5964
 
5483
5965
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-path-symlink.js
5484
5966
 
@@ -5486,9 +5968,9 @@ function formatErrorDetail(value) {
5486
5968
 
5487
5969
 
5488
5970
 
5489
-
5490
- function normalizeSymlinkResolutionError(error) {
5491
- if (isSymlinkOpenError(error)) {
5971
+ function normalizeSymlinkResolutionError(error, options) {
5972
+ if (isSymlinkOpenError(error) ||
5973
+ (options.rejectUnresolved && path_isNotFoundPathError(error))) {
5492
5974
  throw new errors_FsSafeError("symlink", "symlink path could not be resolved", {
5493
5975
  cause: error instanceof Error ? error : undefined,
5494
5976
  });
@@ -5496,22 +5978,22 @@ function normalizeSymlinkResolutionError(error) {
5496
5978
  if (!path_isNotFoundPathError(error))
5497
5979
  throw error;
5498
5980
  }
5499
- async function resolveSymlinkHopPath(symlinkPath) {
5981
+ async function resolveSymlinkHopPath(symlinkPath, options = {}) {
5500
5982
  try {
5501
- return external_node_path_.resolve(await promises_.realpath(symlinkPath));
5983
+ return external_node_path_.resolve(external_node_fs_.realpathSync.native(symlinkPath));
5502
5984
  }
5503
5985
  catch (error) {
5504
- normalizeSymlinkResolutionError(error);
5505
- const linkTarget = await promises_.readlink(symlinkPath);
5986
+ normalizeSymlinkResolutionError(error, options);
5987
+ const linkTarget = external_node_fs_.readlinkSync(symlinkPath);
5506
5988
  return resolvePathViaExistingAncestor(external_node_path_.resolve(external_node_path_.dirname(symlinkPath), linkTarget));
5507
5989
  }
5508
5990
  }
5509
- function root_path_symlink_resolveSymlinkHopPathSync(symlinkPath) {
5991
+ function root_path_symlink_resolveSymlinkHopPathSync(symlinkPath, options = {}) {
5510
5992
  try {
5511
5993
  return path.resolve(fs.realpathSync(symlinkPath));
5512
5994
  }
5513
5995
  catch (error) {
5514
- normalizeSymlinkResolutionError(error);
5996
+ normalizeSymlinkResolutionError(error, options);
5515
5997
  const linkTarget = fs.readlinkSync(symlinkPath);
5516
5998
  return resolvePathViaExistingAncestorSync(path.resolve(path.dirname(symlinkPath), linkTarget));
5517
5999
  }
@@ -5594,17 +6076,6 @@ function assertSafePathPrefix(prefix, options = {}) {
5594
6076
  });
5595
6077
  }
5596
6078
 
5597
- // EXTERNAL MODULE: external "node:os"
5598
- var external_node_os_ = __webpack_require__(8161);
5599
- ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/short-path.js
5600
-
5601
-
5602
- function shortPath(value) {
5603
- const home = external_node_os_.homedir();
5604
- const shortened = value.startsWith(home) ? `~${value.slice(home.length)}` : value;
5605
- return formatErrorDetail(shortened);
5606
- }
5607
-
5608
6079
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-path.js
5609
6080
 
5610
6081
 
@@ -5615,8 +6086,6 @@ function shortPath(value) {
5615
6086
 
5616
6087
 
5617
6088
 
5618
-
5619
-
5620
6089
  const ROOT_PATH_ALIAS_POLICIES = {
5621
6090
  strict: Object.freeze({
5622
6091
  allowFinalSymlinkForUnlink: false,
@@ -5627,7 +6096,7 @@ const ROOT_PATH_ALIAS_POLICIES = {
5627
6096
  allowFinalHardlinkForUnlink: true,
5628
6097
  }),
5629
6098
  };
5630
- async function resolveRootPath(params) {
6099
+ async function root_path_resolveRootPath(params) {
5631
6100
  try {
5632
6101
  return await resolveRootPathInternal(params);
5633
6102
  }
@@ -5728,12 +6197,6 @@ function assertNoEmbeddedDriveRelativeSegment(filePath, label) {
5728
6197
  const root = external_node_path_.parse(filePath).root;
5729
6198
  assertNoDriveRelativePathSegments(filePath.slice(root.length).replaceAll("\\", "/"), label);
5730
6199
  }
5731
- function isPromiseLike(value) {
5732
- return Boolean(value &&
5733
- (typeof value === "object" || typeof value === "function") &&
5734
- "then" in value &&
5735
- typeof value.then === "function");
5736
- }
5737
6200
  function createLexicalTraversalState(params) {
5738
6201
  const rawAbsolutePath = params.params.absolutePath;
5739
6202
  const rawRelativePath = rawPathRelativeToRoot(params.rootPath, rawAbsolutePath);
@@ -5813,26 +6276,13 @@ function handleLexicalLstatFailure(context, error, missingFromIndex) {
5813
6276
  applyMissingSuffixToCanonicalCursor(context, missingFromIndex);
5814
6277
  return true;
5815
6278
  }
5816
- function handleLexicalStatReadFailure(context, error, missingFromIndex) {
5817
- if (handleLexicalLstatFailure(context, error, missingFromIndex)) {
5818
- return null;
5819
- }
5820
- throw error;
5821
- }
5822
- function handleLexicalStatDisposition(context, params) {
5823
- if (!params.isSymbolicLink) {
5824
- advanceCanonicalCursorForSegment(context, params.segment);
6279
+ function lexicalStatDisposition(params) {
6280
+ if (!params.isSymbolicLink)
5825
6281
  return "continue";
5826
- }
5827
- if (context.resolveParams.rejectSymlinks === true && params.isLast) {
6282
+ if (params.rejectSymlinks === true && params.isLast) {
5828
6283
  throw new errors_FsSafeError("symlink", "symlink path component not allowed");
5829
6284
  }
5830
- if (context.state.allowFinalSymlink && params.isLast) {
5831
- context.state.preserveFinalSymlink = true;
5832
- advanceCanonicalCursorForSegment(context, params.segment);
5833
- return "break";
5834
- }
5835
- return "resolve-link";
6285
+ return params.allowFinalSymlink && params.isLast ? "break" : "resolve-link";
5836
6286
  }
5837
6287
  function applyResolvedSymlinkHop(context, linkCanonical) {
5838
6288
  if (!path_isPathInside(context.rootCanonicalPath, linkCanonical)) {
@@ -5845,68 +6295,48 @@ function applyResolvedSymlinkHop(context, linkCanonical) {
5845
6295
  context.state.canonicalCursor = linkCanonical;
5846
6296
  context.state.lexicalCursor = linkCanonical;
5847
6297
  }
5848
- function readLexicalStat(context, params) {
5849
- try {
5850
- const stat = params.read(context.state.lexicalCursor);
5851
- if (isPromiseLike(stat)) {
5852
- return Promise.resolve(stat).catch((error) => handleLexicalStatReadFailure(context, error, params.missingFromIndex));
5853
- }
5854
- return stat;
5855
- }
5856
- catch (error) {
5857
- return handleLexicalStatReadFailure(context, error, params.missingFromIndex);
5858
- }
5859
- }
5860
- function resolveAndApplySymlinkHop(context, params) {
5861
- const linkCanonical = params.resolveLinkCanonical(context.state.lexicalCursor);
5862
- if (isPromiseLike(linkCanonical)) {
5863
- return Promise.resolve(linkCanonical).then((value) => {
5864
- applyResolvedSymlinkHop(context, value);
5865
- });
5866
- }
5867
- applyResolvedSymlinkHop(context, linkCanonical);
5868
- }
5869
6298
  function applyParentTraversalStep(context) {
5870
6299
  context.state.lexicalCursor = external_node_path_.resolve(context.state.lexicalCursor, "..");
5871
6300
  advanceCanonicalCursorForSegment(context, "..");
5872
6301
  }
5873
- function* iterateLexicalTraversal(state) {
5874
- for (let idx = 0; idx < state.segments.length; idx += 1) {
5875
- const segment = state.segments[idx] ?? "";
5876
- const isLast = idx === state.segments.length - 1;
5877
- yield { idx, segment, isLast };
5878
- }
5879
- }
5880
6302
  async function resolveRootPathLexicalAsync(params) {
5881
6303
  const context = createLexicalTraversalContext(params);
5882
6304
  const { state } = context;
5883
- for (const { idx, segment, isLast } of iterateLexicalTraversal(state)) {
6305
+ for (let idx = 0; idx < state.segments.length; idx += 1) {
6306
+ const segment = state.segments[idx] ?? "";
6307
+ const isLast = idx === state.segments.length - 1;
5884
6308
  if (segment === "..") {
5885
6309
  applyParentTraversalStep(context);
5886
6310
  continue;
5887
6311
  }
5888
6312
  state.lexicalCursor = external_node_path_.join(state.lexicalCursor, segment);
5889
- const stat = await readLexicalStat(context, {
5890
- missingFromIndex: idx,
5891
- read: (cursor) => promises_.lstat(cursor),
5892
- });
5893
- if (!stat) {
5894
- break;
6313
+ let stat;
6314
+ try {
6315
+ stat = external_node_fs_.lstatSync(state.lexicalCursor);
5895
6316
  }
5896
- const disposition = handleLexicalStatDisposition(context, {
5897
- isSymbolicLink: stat.isSymbolicLink(),
5898
- segment,
6317
+ catch (error) {
6318
+ if (handleLexicalLstatFailure(context, error, idx))
6319
+ break;
6320
+ throw error;
6321
+ }
6322
+ const isSymbolicLink = stat.isSymbolicLink();
6323
+ const disposition = lexicalStatDisposition({
6324
+ isSymbolicLink,
5899
6325
  isLast,
6326
+ rejectSymlinks: isSymbolicLink ? context.resolveParams.rejectSymlinks : undefined,
6327
+ allowFinalSymlink: state.allowFinalSymlink,
5900
6328
  });
5901
- if (disposition === "continue") {
6329
+ if (disposition !== "resolve-link") {
6330
+ state.preserveFinalSymlink = disposition === "break";
6331
+ advanceCanonicalCursorForSegment(context, segment);
6332
+ if (state.preserveFinalSymlink)
6333
+ break;
5902
6334
  continue;
5903
6335
  }
5904
- if (disposition === "break") {
5905
- break;
5906
- }
5907
- await resolveAndApplySymlinkHop(context, {
5908
- resolveLinkCanonical: (cursor) => resolveSymlinkHopPath(cursor),
6336
+ const linkCanonical = await resolveSymlinkHopPath(state.lexicalCursor, {
6337
+ rejectUnresolved: context.resolveParams.rejectUnresolvedSymlinks,
5909
6338
  });
6339
+ applyResolvedSymlinkHop(context, linkCanonical);
5910
6340
  if (context.resolveParams.rejectSymlinks === true) {
5911
6341
  throw new errors_FsSafeError("symlink", "symlink path component not allowed");
5912
6342
  }
@@ -5925,34 +6355,33 @@ function resolveRootPathLexicalSync(params) {
5925
6355
  continue;
5926
6356
  }
5927
6357
  state.lexicalCursor = path.join(state.lexicalCursor, segment);
5928
- const maybeStat = readLexicalStat(context, {
5929
- missingFromIndex: idx,
5930
- read: (cursor) => fs.lstatSync(cursor),
5931
- });
5932
- if (isPromiseLike(maybeStat)) {
5933
- throw new Error("Unexpected async lexical stat");
6358
+ let stat;
6359
+ try {
6360
+ stat = fs.lstatSync(state.lexicalCursor);
5934
6361
  }
5935
- const stat = maybeStat;
5936
- if (!stat) {
5937
- break;
6362
+ catch (error) {
6363
+ if (handleLexicalLstatFailure(context, error, idx))
6364
+ break;
6365
+ throw error;
5938
6366
  }
5939
- const disposition = handleLexicalStatDisposition(context, {
5940
- isSymbolicLink: stat.isSymbolicLink(),
5941
- segment,
6367
+ const isSymbolicLink = stat.isSymbolicLink();
6368
+ const disposition = lexicalStatDisposition({
6369
+ isSymbolicLink,
5942
6370
  isLast,
6371
+ rejectSymlinks: isSymbolicLink ? context.resolveParams.rejectSymlinks : undefined,
6372
+ allowFinalSymlink: state.allowFinalSymlink,
5943
6373
  });
5944
- if (disposition === "continue") {
6374
+ if (disposition !== "resolve-link") {
6375
+ state.preserveFinalSymlink = disposition === "break";
6376
+ advanceCanonicalCursorForSegment(context, segment);
6377
+ if (state.preserveFinalSymlink)
6378
+ break;
5945
6379
  continue;
5946
6380
  }
5947
- if (disposition === "break") {
5948
- break;
5949
- }
5950
- const maybeApplied = resolveAndApplySymlinkHop(context, {
5951
- resolveLinkCanonical: (cursor) => resolveSymlinkHopPathSync(cursor),
6381
+ const linkCanonical = resolveSymlinkHopPathSync(state.lexicalCursor, {
6382
+ rejectUnresolved: context.resolveParams.rejectUnresolvedSymlinks,
5952
6383
  });
5953
- if (isPromiseLike(maybeApplied)) {
5954
- throw new Error("Unexpected async symlink resolution");
5955
- }
6384
+ applyResolvedSymlinkHop(context, linkCanonical);
5956
6385
  if (context.resolveParams.rejectSymlinks === true) {
5957
6386
  throw new FsSafeError("symlink", "symlink path component not allowed");
5958
6387
  }
@@ -6072,8 +6501,8 @@ function buildResolvedRootPath(params) {
6072
6501
  async function getPathKind(absolutePath, preserveFinalSymlink) {
6073
6502
  try {
6074
6503
  const stat = preserveFinalSymlink
6075
- ? await promises_.lstat(absolutePath)
6076
- : await promises_.stat(absolutePath);
6504
+ ? external_node_fs_.lstatSync(absolutePath)
6505
+ : external_node_fs_.statSync(absolutePath);
6077
6506
  return { exists: true, kind: toResolvedKind(stat) };
6078
6507
  }
6079
6508
  catch (error) {
@@ -6139,7 +6568,7 @@ function symlinkEscapeError(params) {
6139
6568
 
6140
6569
  async function openSidecarRoot(lockRoot, relative, discardObservation, onOpenFailure) {
6141
6570
  const resolved = await lockRoot.resolve(relative);
6142
- const canonicalPath = async () => (await resolveRootPath({
6571
+ const canonicalPath = async () => (await root_path_resolveRootPath({
6143
6572
  absolutePath: resolved,
6144
6573
  rootPath: lockRoot.rootReal,
6145
6574
  rootCanonicalPath: lockRoot.rootReal,
@@ -6256,10 +6685,12 @@ function readSidecarLockOwnershipToken(raw) {
6256
6685
  }
6257
6686
  function serializeSidecarLockPayload(payload) {
6258
6687
  const ownershipToken = createSidecarLockOwnershipToken();
6259
- return {
6260
- raw: `${JSON.stringify(payload, null, 2)}\n${ownershipToken}\n`,
6261
- ownershipToken,
6262
- };
6688
+ const raw = `${JSON.stringify(payload, null, 2)}\n${ownershipToken}\n`;
6689
+ const bytes = Buffer.byteLength(raw, "utf8");
6690
+ if (bytes > MAX_LOCK_PAYLOAD_BYTES) {
6691
+ throw new errors_FsSafeError("too-large", `sidecar lock payload exceeds limit of ${MAX_LOCK_PAYLOAD_BYTES} bytes (got ${bytes})`);
6692
+ }
6693
+ return { raw, ownershipToken };
6263
6694
  }
6264
6695
  function relativeSidecarLockPath(lockRoot, lockPath) {
6265
6696
  const resolved = external_node_path_.resolve(lockPath);
@@ -6314,7 +6745,13 @@ async function readSidecarLockRawSnapshot(lockPath, options = {}) {
6314
6745
  await opened.handle.close().catch(() => undefined);
6315
6746
  }
6316
6747
  }
6317
- const before = await promises_.lstat(lockPath).catch(missingSnapshotPath);
6748
+ let before;
6749
+ try {
6750
+ before = external_node_fs_.lstatSync(lockPath);
6751
+ }
6752
+ catch (error) {
6753
+ before = missingSnapshotPath(error);
6754
+ }
6318
6755
  if (!before)
6319
6756
  return null;
6320
6757
  if (!before.isFile() || before.isSymbolicLink()) {
@@ -6343,7 +6780,7 @@ async function readSidecarLockRawSnapshot(lockPath, options = {}) {
6343
6780
  options.onOpenFailure?.(error);
6344
6781
  throw error;
6345
6782
  }
6346
- const opened = await handle.stat();
6783
+ const opened = external_node_fs_.fstatSync(handle.fd);
6347
6784
  if (!opened.isFile()) {
6348
6785
  if (options.rejectNonFile) {
6349
6786
  throw new errors_FsSafeError("not-file", `sidecar lock is not a regular file: ${lockPath}`);
@@ -6353,7 +6790,13 @@ async function readSidecarLockRawSnapshot(lockPath, options = {}) {
6353
6790
  if (!options.allowDescriptorIdentityDrift && !file_identity_sameFileIdentity(before, opened))
6354
6791
  return null;
6355
6792
  const raw = (await readFileHandleBounded(handle, MAX_LOCK_PAYLOAD_BYTES)).toString("utf8");
6356
- const after = await promises_.lstat(lockPath).catch(missingSnapshotPath);
6793
+ let after;
6794
+ try {
6795
+ after = external_node_fs_.lstatSync(lockPath);
6796
+ }
6797
+ catch (error) {
6798
+ after = missingSnapshotPath(error);
6799
+ }
6357
6800
  if (!after || !after.isFile() || !file_identity_sameFileIdentity(before, after))
6358
6801
  return null;
6359
6802
  return { raw, stat: after };
@@ -6465,7 +6908,7 @@ async function sidecarLockSnapshotStillPresent(lockPath, observed, options = {})
6465
6908
  }
6466
6909
  async function sidecarReclaimGuardExists(pathname) {
6467
6910
  try {
6468
- await promises_.lstat(pathname);
6911
+ external_node_fs_.lstatSync(pathname);
6469
6912
  return true;
6470
6913
  }
6471
6914
  catch (err) {
@@ -6528,6 +6971,315 @@ async function removeStaleSidecarLockIfAllowed(params) {
6528
6971
  }
6529
6972
  }
6530
6973
 
6974
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/absolute-path.js
6975
+
6976
+
6977
+
6978
+
6979
+
6980
+
6981
+
6982
+ function resolveSymlinkPolicy(policy) {
6983
+ if (policy === undefined)
6984
+ return "reject";
6985
+ if (policy !== "reject" && policy !== "follow") {
6986
+ throw new TypeError(`invalid absolute path symlink policy: ${String(policy)}`);
6987
+ }
6988
+ return policy;
6989
+ }
6990
+ function ensureDirectoryFailure(code, message, cause) {
6991
+ return {
6992
+ ok: false,
6993
+ code,
6994
+ error: new FsSafeError(code, message, { cause }),
6995
+ };
6996
+ }
6997
+ async function assertGuardResult(guard, scopeLabel) {
6998
+ try {
6999
+ await assertAsyncDirectoryGuard(guard);
7000
+ return { ok: true };
7001
+ }
7002
+ catch (err) {
7003
+ if (err instanceof FsSafeError) {
7004
+ return await directoryGuardFailure(err, guard.dir, scopeLabel);
7005
+ }
7006
+ throw err;
7007
+ }
7008
+ }
7009
+ async function createDirectoryGuardResult(dir, scopeLabel) {
7010
+ try {
7011
+ return { ok: true, guard: await createAsyncDirectoryGuard(dir) };
7012
+ }
7013
+ catch (err) {
7014
+ if (err instanceof FsSafeError) {
7015
+ return await directoryGuardFailure(err, dir, scopeLabel);
7016
+ }
7017
+ throw err;
7018
+ }
7019
+ }
7020
+ function classifyDirectoryLookupError(err, scopeLabel) {
7021
+ const code = err.code;
7022
+ if (code === "ENOENT") {
7023
+ return ensureDirectoryFailure("not-found", `directory path must have a real existing ancestor within ${scopeLabel}`, err);
7024
+ }
7025
+ if (code === "ENOTDIR") {
7026
+ return ensureDirectoryFailure("not-file", `path must be a real directory within ${scopeLabel}`, err);
7027
+ }
7028
+ return null;
7029
+ }
7030
+ function classifyExistingDirectorySegment(stat, scopeLabel) {
7031
+ if (stat.isSymbolicLink()) {
7032
+ return ensureDirectoryFailure("symlink", `directory path traverses a symlink within ${scopeLabel}`);
7033
+ }
7034
+ if (!stat.isDirectory()) {
7035
+ return ensureDirectoryFailure("not-file", `path must be a real directory within ${scopeLabel}`);
7036
+ }
7037
+ return null;
7038
+ }
7039
+ async function directoryGuardFailure(err, dir, scopeLabel) {
7040
+ if (err.code !== "not-file") {
7041
+ return { ok: false, code: err.code, error: err };
7042
+ }
7043
+ try {
7044
+ const stat = fsSync.lstatSync(dir);
7045
+ const failure = classifyExistingDirectorySegment(stat, scopeLabel);
7046
+ if (failure) {
7047
+ return failure;
7048
+ }
7049
+ }
7050
+ catch (lookupErr) {
7051
+ const failure = classifyDirectoryLookupError(lookupErr, scopeLabel);
7052
+ if (failure) {
7053
+ return failure;
7054
+ }
7055
+ throw lookupErr;
7056
+ }
7057
+ return { ok: false, code: err.code, error: err };
7058
+ }
7059
+ async function resolveTrustedDirectoryPrefix(targetPath, scopeLabel) {
7060
+ const root = path.parse(targetPath).root;
7061
+ let current = root;
7062
+ let currentStat;
7063
+ try {
7064
+ currentStat = fsSync.lstatSync(current);
7065
+ }
7066
+ catch (err) {
7067
+ const failure = classifyDirectoryLookupError(err, scopeLabel);
7068
+ if (failure) {
7069
+ return failure;
7070
+ }
7071
+ throw err;
7072
+ }
7073
+ const rootFailure = classifyExistingDirectorySegment(currentStat, scopeLabel);
7074
+ if (rootFailure) {
7075
+ return rootFailure;
7076
+ }
7077
+ // Walk forward with lstat. Looking backward for the "nearest existing
7078
+ // ancestor" can cross an existing suffix through a symlinked parent before
7079
+ // this helper gets a chance to reject that parent.
7080
+ const segments = path.relative(root, targetPath).split(path.sep).filter(Boolean);
7081
+ for (let index = 0; index < segments.length; index += 1) {
7082
+ const segment = segments[index];
7083
+ if (!segment) {
7084
+ continue;
7085
+ }
7086
+ const next = path.join(current, segment);
7087
+ try {
7088
+ const nextStat = fsSync.lstatSync(next);
7089
+ const segmentFailure = classifyExistingDirectorySegment(nextStat, scopeLabel);
7090
+ if (segmentFailure) {
7091
+ return segmentFailure;
7092
+ }
7093
+ current = next;
7094
+ currentStat = nextStat;
7095
+ }
7096
+ catch (err) {
7097
+ const code = err.code;
7098
+ if (code === "ENOENT") {
7099
+ return {
7100
+ ok: true,
7101
+ ancestorPath: current,
7102
+ missingSegments: segments.slice(index),
7103
+ };
7104
+ }
7105
+ const failure = classifyDirectoryLookupError(err, scopeLabel);
7106
+ if (failure) {
7107
+ return failure;
7108
+ }
7109
+ throw err;
7110
+ }
7111
+ }
7112
+ return { ok: true, ancestorPath: current, missingSegments: [] };
7113
+ }
7114
+ function assertAbsolutePathInput(filePath) {
7115
+ if (!filePath) {
7116
+ throw new FsSafeError("invalid-path", "path is required");
7117
+ }
7118
+ if (filePath.includes("\0")) {
7119
+ throw new FsSafeError("invalid-path", "path must not contain NUL bytes");
7120
+ }
7121
+ if (!path.isAbsolute(filePath)) {
7122
+ throw new FsSafeError("invalid-path", "path must be absolute");
7123
+ }
7124
+ return path.normalize(filePath);
7125
+ }
7126
+ async function findExistingAncestor(filePath) {
7127
+ return (await findExistingAncestorWithStat(filePath))?.path ?? null;
7128
+ }
7129
+ async function findExistingAncestorWithStat(filePath) {
7130
+ let current = external_node_path_.resolve(filePath);
7131
+ while (true) {
7132
+ try {
7133
+ return { path: current, stat: external_node_fs_.lstatSync(current) };
7134
+ }
7135
+ catch (err) {
7136
+ if (err.code !== "ENOENT") {
7137
+ throw err;
7138
+ }
7139
+ }
7140
+ const parent = external_node_path_.dirname(current);
7141
+ if (parent === current) {
7142
+ return null;
7143
+ }
7144
+ current = parent;
7145
+ }
7146
+ }
7147
+ async function absolute_path_ensureAbsoluteDirectory(dirPath, options = {}) {
7148
+ const scopeLabel = options.scopeLabel ?? "directory";
7149
+ let targetPath;
7150
+ try {
7151
+ targetPath = assertAbsolutePathInput(dirPath);
7152
+ }
7153
+ catch (err) {
7154
+ if (err instanceof FsSafeError) {
7155
+ return { ok: false, code: err.code, error: err };
7156
+ }
7157
+ throw err;
7158
+ }
7159
+ const prefix = await resolveTrustedDirectoryPrefix(targetPath, scopeLabel);
7160
+ if (!prefix.ok) {
7161
+ return prefix;
7162
+ }
7163
+ let current = prefix.ancestorPath;
7164
+ const initialGuard = await createDirectoryGuardResult(prefix.ancestorPath, scopeLabel);
7165
+ if (!initialGuard.ok) {
7166
+ return initialGuard;
7167
+ }
7168
+ let currentGuard = initialGuard.guard;
7169
+ for (const segment of prefix.missingSegments) {
7170
+ current = path.join(current, segment);
7171
+ while (true) {
7172
+ const guardResult = await assertGuardResult(currentGuard, scopeLabel);
7173
+ if (!guardResult.ok) {
7174
+ return guardResult;
7175
+ }
7176
+ try {
7177
+ const stat = fsSync.lstatSync(current);
7178
+ if (stat.isSymbolicLink()) {
7179
+ return ensureDirectoryFailure("symlink", `directory path traverses a symlink within ${scopeLabel}`);
7180
+ }
7181
+ if (!stat.isDirectory()) {
7182
+ return ensureDirectoryFailure("not-file", `path must be a real directory within ${scopeLabel}`);
7183
+ }
7184
+ break;
7185
+ }
7186
+ catch (err) {
7187
+ if (err.code !== "ENOENT") {
7188
+ throw err;
7189
+ }
7190
+ const parentStillValid = await assertGuardResult(currentGuard, scopeLabel);
7191
+ if (!parentStillValid.ok) {
7192
+ return parentStillValid;
7193
+ }
7194
+ try {
7195
+ await fs.mkdir(current, { mode: options.mode });
7196
+ }
7197
+ catch (mkdirErr) {
7198
+ if (mkdirErr.code === "EEXIST") {
7199
+ continue;
7200
+ }
7201
+ throw mkdirErr;
7202
+ }
7203
+ }
7204
+ }
7205
+ const nextGuard = await createDirectoryGuardResult(current, scopeLabel);
7206
+ if (!nextGuard.ok) {
7207
+ return nextGuard;
7208
+ }
7209
+ const previousGuardStillValid = await assertGuardResult(currentGuard, scopeLabel);
7210
+ if (!previousGuardStillValid.ok) {
7211
+ return previousGuardStillValid;
7212
+ }
7213
+ currentGuard = nextGuard.guard;
7214
+ }
7215
+ const finalGuardResult = await assertGuardResult(currentGuard, scopeLabel);
7216
+ if (!finalGuardResult.ok) {
7217
+ return finalGuardResult;
7218
+ }
7219
+ return { ok: true, path: targetPath };
7220
+ }
7221
+ async function canonicalPathFromExistingAncestor(filePath) {
7222
+ const ancestor = await findExistingAncestor(filePath);
7223
+ if (!ancestor) {
7224
+ return external_node_path_.resolve(filePath);
7225
+ }
7226
+ let canonicalAncestor = ancestor;
7227
+ try {
7228
+ canonicalAncestor = external_node_fs_.realpathSync.native(ancestor);
7229
+ }
7230
+ catch {
7231
+ // Keep lexical path when the existing ancestor cannot be canonicalized.
7232
+ }
7233
+ const relative = external_node_path_.relative(ancestor, filePath);
7234
+ return relative ? external_node_path_.join(canonicalAncestor, relative) : canonicalAncestor;
7235
+ }
7236
+ async function resolveAbsolutePathForRead(filePath, options = {}) {
7237
+ const symlinks = resolveSymlinkPolicy(options.symlinks);
7238
+ const normalized = assertAbsolutePathInput(filePath);
7239
+ let canonicalPath;
7240
+ try {
7241
+ canonicalPath = fsSync.realpathSync.native(normalized);
7242
+ }
7243
+ catch (err) {
7244
+ if (err.code === "ENOENT") {
7245
+ throw new FsSafeError("not-found", "path not found", { cause: err });
7246
+ }
7247
+ throw err;
7248
+ }
7249
+ if (symlinks === "reject" && canonicalPath !== normalized) {
7250
+ throw new FsSafeError("symlink", "path traverses a symlink", { cause: { canonicalPath } });
7251
+ }
7252
+ return { path: normalized, canonicalPath };
7253
+ }
7254
+ async function resolveAbsolutePathForWrite(filePath, options = {}) {
7255
+ const symlinks = resolveSymlinkPolicy(options.symlinks);
7256
+ const normalized = assertAbsolutePathInput(filePath);
7257
+ const parentDir = path.dirname(normalized);
7258
+ const parentExists = await pathExists(parentDir);
7259
+ if (symlinks === "reject") {
7260
+ const filesystemRoot = path.parse(normalized).root;
7261
+ await resolveRootPath({
7262
+ absolutePath: normalized,
7263
+ rootPath: filesystemRoot,
7264
+ rootCanonicalPath: filesystemRoot,
7265
+ boundaryLabel: "absolute path",
7266
+ rejectSymlinks: true,
7267
+ });
7268
+ }
7269
+ const canonicalPath = await canonicalPathFromExistingAncestor(normalized);
7270
+ if (symlinks === "reject" && canonicalPath !== normalized) {
7271
+ throw new FsSafeError("symlink", "path traverses a symlink", {
7272
+ cause: { canonicalPath },
7273
+ });
7274
+ }
7275
+ return {
7276
+ path: normalized,
7277
+ canonicalPath,
7278
+ parentDir,
7279
+ parentExists,
7280
+ };
7281
+ }
7282
+
6531
7283
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/sidecar-lock-policy.js
6532
7284
 
6533
7285
  function assertFiniteNonNegative(value, label) {
@@ -6579,10 +7331,6 @@ function isTransientLockFileDenial(error, lockPath) {
6579
7331
  const denial = error;
6580
7332
  return process.platform === "win32" && denial?.code === "EPERM" && denial.path === lockPath;
6581
7333
  }
6582
- function sidecarLockPayloadIsStale(payload, staleMs, nowMs) {
6583
- const createdAtMs = sidecarLockPayloadCreatedAtMs(payload);
6584
- return createdAtMs !== null && nowMs - createdAtMs > staleMs;
6585
- }
6586
7334
  function sidecarLockPayloadCreatedAtMs(payload) {
6587
7335
  const createdAt = payload &&
6588
7336
  typeof payload === "object" &&
@@ -6598,7 +7346,7 @@ async function defaultSidecarLockShouldReclaim(params) {
6598
7346
  if (createdAtMs !== null)
6599
7347
  return params.nowMs - createdAtMs > params.staleMs;
6600
7348
  try {
6601
- return params.nowMs - (await promises_.stat(params.lockPath)).mtimeMs > params.staleMs;
7349
+ return params.nowMs - external_node_fs_.statSync(params.lockPath).mtimeMs > params.staleMs;
6602
7350
  }
6603
7351
  catch {
6604
7352
  return true;
@@ -6632,12 +7380,23 @@ function createSuppressedError(error, suppressed, message) {
6632
7380
 
6633
7381
 
6634
7382
 
6635
- async function resolveNormalizedTargetPath(targetPath) {
7383
+
7384
+
7385
+
7386
+ async function resolveNormalizedTargetPath(targetPath, lockRoot) {
6636
7387
  const resolved = external_node_path_.resolve(targetPath);
6637
7388
  const dir = external_node_path_.dirname(resolved);
7389
+ if (lockRoot) {
7390
+ // The target is an arbitration key, not necessarily inside the lock Root.
7391
+ // Leave parent creation to the Root-backed sidecar write.
7392
+ await lockRoot.resolve(".");
7393
+ const parent = await canonicalPathFromExistingAncestor(dir);
7394
+ await lockRoot.resolve(".");
7395
+ return external_node_path_.join(parent, external_node_path_.basename(resolved));
7396
+ }
6638
7397
  await promises_.mkdir(dir, { recursive: true });
6639
7398
  try {
6640
- return external_node_path_.join(await promises_.realpath(dir), external_node_path_.basename(resolved));
7399
+ return external_node_path_.join(external_node_fs_.realpathSync.native(dir), external_node_path_.basename(resolved));
6641
7400
  }
6642
7401
  catch {
6643
7402
  return resolved;
@@ -6648,7 +7407,7 @@ async function acquireSidecarLock(options, context) {
6648
7407
  validateSidecarLockRetryOptions(retry);
6649
7408
  validateSidecarLockTimeoutMs(options.timeoutMs);
6650
7409
  context.ensureExitCleanupRegistered();
6651
- const normalizedTargetPath = await resolveNormalizedTargetPath(options.targetPath);
7410
+ const normalizedTargetPath = await resolveNormalizedTargetPath(options.targetPath, options.lockRoot);
6652
7411
  const lockPath = options.lockPath ?? `${normalizedTargetPath}.lock`;
6653
7412
  let held = context.held.get(normalizedTargetPath);
6654
7413
  if (held &&
@@ -6668,11 +7427,15 @@ async function acquireSidecarLock(options, context) {
6668
7427
  held.reentrantOwner !== undefined &&
6669
7428
  options.reentrantOwner === held.reentrantOwner) {
6670
7429
  held.refCount += 1;
7430
+ // Retention is monotonic: any same-owner request to keep the sidecar on
7431
+ // exit upgrades the held lock; a later default acquisition never revokes it.
7432
+ if (options.retainOnExit === true) {
7433
+ held.retainOnExit = true;
7434
+ }
6671
7435
  return context.handleForHeldLock(normalizedTargetPath, held);
6672
7436
  }
6673
7437
  }
6674
7438
  const startedAt = Date.now();
6675
- const maxRetries = options.timeoutMs === Number.POSITIVE_INFINITY ? undefined : retry.retries;
6676
7439
  const reclaimGuardPath = `${lockPath}.reclaim`;
6677
7440
  let ownsReclaimGuard = false;
6678
7441
  let attempt = 0;
@@ -6684,7 +7447,7 @@ async function acquireSidecarLock(options, context) {
6684
7447
  if ((options.timeoutMs !== undefined &&
6685
7448
  options.timeoutMs !== Number.POSITIVE_INFINITY &&
6686
7449
  elapsed >= options.timeoutMs) ||
6687
- (maxRetries !== undefined && attempt >= maxRetries)) {
7450
+ (retry.retries !== undefined && attempt >= retry.retries)) {
6688
7451
  throw Object.assign(new Error(`file lock timeout for ${normalizedTargetPath}`), {
6689
7452
  code: "file_lock_timeout",
6690
7453
  lockPath,
@@ -6726,10 +7489,14 @@ async function acquireSidecarLock(options, context) {
6726
7489
  if (options.lockRoot) {
6727
7490
  const lockRoot = options.lockRoot;
6728
7491
  const relativeLockPath = relativeSidecarLockPath(lockRoot, lockPath);
7492
+ const observation = fileObservation();
6729
7493
  try {
6730
- await lockRoot.create(relativeLockPath, raw, { mkdir: true, mode: 0o600 });
7494
+ await observation.run(() => lockRoot.create(relativeLockPath, raw, { mkdir: true, mode: 0o600 }));
6731
7495
  }
6732
7496
  catch (error) {
7497
+ // Only this invocation's failed exclusive open grants denial retry authority.
7498
+ lockFileCreateDenied = observation.has(error, `exclusive-create:${lockPath}`) &&
7499
+ isTransientLockFileDenial(error, lockPath);
6733
7500
  if (error instanceof errors_FsSafeError && error.code === "already-exists") {
6734
7501
  throw Object.assign(new Error("sidecar lock exists"), { code: "EEXIST" });
6735
7502
  }
@@ -6766,7 +7533,7 @@ async function acquireSidecarLock(options, context) {
6766
7533
  }
6767
7534
  await handle.writeFile(raw, "utf8");
6768
7535
  }
6769
- const snapshot = { raw, payload, stat: await handle.stat(), ownershipToken };
7536
+ const snapshot = { raw, payload, stat: external_node_fs_.fstatSync(handle.fd), ownershipToken };
6770
7537
  if (snapshot.stat.nlink === 0) {
6771
7538
  await handle.close();
6772
7539
  handle = null;
@@ -6782,6 +7549,7 @@ async function acquireSidecarLock(options, context) {
6782
7549
  acquiredAt: Date.now(),
6783
7550
  metadata: options.metadata ?? {},
6784
7551
  lockRoot: options.lockRoot,
7552
+ retainOnExit: options.retainOnExit,
6785
7553
  parsePayload: options.parsePayload,
6786
7554
  };
6787
7555
  context.held.set(normalizedTargetPath, createdHeld);
@@ -6819,7 +7587,7 @@ async function acquireSidecarLock(options, context) {
6819
7587
  if (handle) {
6820
7588
  const failedSnapshot = createdSnapshot ?? { payload: null };
6821
7589
  try {
6822
- failedSnapshot.stat = await handle.stat();
7590
+ failedSnapshot.stat = external_node_fs_.fstatSync(handle.fd);
6823
7591
  }
6824
7592
  catch {
6825
7593
  // Best-effort cleanup of a failed exclusive create.
@@ -6992,9 +7760,15 @@ function createHeldSidecarLockHandle(params) {
6992
7760
 
6993
7761
 
6994
7762
 
7763
+
6995
7764
  const GLOBAL_STATE_KEY = Symbol.for("fsSafe.sidecarLockManagers");
6996
7765
  const GLOBAL_CLEANUP_KEY = Symbol.for("fsSafe.sidecarLockCleanupRegistered");
6997
7766
  const GLOBAL_CLEANUP_HANDLER_KEY = Symbol.for("fsSafe.sidecarLockCleanupHandler");
7767
+ const GLOBAL_BEFORE_EXIT_KEY = Symbol.for("fsSafe.sidecarLockBeforeExitCleanup");
7768
+ // Set by copies whose exit handlers honor retainOnExit. When an older package
7769
+ // copy registered the handlers first, this marker stays absent and retained
7770
+ // acquisitions must fail closed rather than silently lose the guarantee.
7771
+ const GLOBAL_RETAIN_AWARE_KEY = Symbol.for("fsSafe.sidecarLockRetainAwareCleanup");
6998
7772
  function getGlobalManagers() {
6999
7773
  const globalWithState = globalThis;
7000
7774
  if (!globalWithState[GLOBAL_STATE_KEY]) {
@@ -7067,7 +7841,8 @@ function snapshotMatchesSync(lockPath, observed) {
7067
7841
  }
7068
7842
  }
7069
7843
  function releaseAllReclaimGuardsSync(state) {
7070
- for (const reclaimGuardPath of state.reclaimGuards) {
7844
+ // Exit cleanup also visits managers created by older copies and never reopened here.
7845
+ for (const reclaimGuardPath of state.reclaimGuards ?? []) {
7071
7846
  try {
7072
7847
  external_node_fs_.rmdirSync(reclaimGuardPath);
7073
7848
  state.reclaimGuards.delete(reclaimGuardPath);
@@ -7077,11 +7852,12 @@ function releaseAllReclaimGuardsSync(state) {
7077
7852
  }
7078
7853
  }
7079
7854
  }
7080
- function releaseAllLocksSync(state) {
7855
+ function releaseAllLocksSync(state, options) {
7081
7856
  for (const [normalizedTargetPath, held] of state.held) {
7082
7857
  void held.handle.close().catch(() => undefined);
7083
7858
  try {
7084
- if (!held.lockRoot && snapshotMatchesSync(held.lockPath, held.snapshot)) {
7859
+ const retained = options?.preserveRetained === true && held.retainOnExit;
7860
+ if (!retained && !held.lockRoot && snapshotMatchesSync(held.lockPath, held.snapshot)) {
7085
7861
  external_node_fs_.rmSync(held.lockPath, { force: true });
7086
7862
  }
7087
7863
  }
@@ -7097,14 +7873,43 @@ function ensureGlobalExitCleanupRegistered() {
7097
7873
  if (globalWithCleanup[GLOBAL_CLEANUP_KEY])
7098
7874
  return;
7099
7875
  globalWithCleanup[GLOBAL_CLEANUP_KEY] = true;
7876
+ globalWithCleanup[GLOBAL_RETAIN_AWARE_KEY] = true;
7100
7877
  const cleanup = () => {
7101
7878
  for (const state of getGlobalManagers().values()) {
7102
- releaseAllLocksSync(state);
7879
+ releaseAllLocksSync(state, { preserveRetained: true });
7103
7880
  }
7104
7881
  };
7105
7882
  globalWithCleanup[GLOBAL_CLEANUP_HANDLER_KEY] = cleanup;
7106
7883
  process.on("exit", cleanup);
7107
7884
  }
7885
+ /** True when a retain-unaware package copy registered the process-exit handlers first. */
7886
+ function exitCleanupCannotRetain() {
7887
+ const globalWithCleanup = globalThis;
7888
+ return globalWithCleanup[GLOBAL_CLEANUP_KEY] === true && globalWithCleanup[GLOBAL_RETAIN_AWARE_KEY] !== true;
7889
+ }
7890
+ function ensureGlobalBeforeExitCleanupRegistered() {
7891
+ const globalWithCleanup = globalThis;
7892
+ if (globalWithCleanup[GLOBAL_BEFORE_EXIT_KEY]) {
7893
+ return globalWithCleanup[GLOBAL_BEFORE_EXIT_KEY];
7894
+ }
7895
+ // Independent of the exit registration, which an older package copy may own.
7896
+ const lifecycle = { armed: false };
7897
+ globalWithCleanup[GLOBAL_BEFORE_EXIT_KEY] = lifecycle;
7898
+ process.on("beforeExit", () => {
7899
+ if (!lifecycle.armed)
7900
+ return;
7901
+ // Cleanup itself schedules I/O; retry only after another acquisition.
7902
+ lifecycle.armed = false;
7903
+ for (const state of getGlobalManagers().values()) {
7904
+ for (const [normalizedTargetPath, held] of Array.from(state.held.entries())) {
7905
+ if (held.lockRoot && !held.retainOnExit) {
7906
+ void releaseHeldLock(state, normalizedTargetPath, held, { force: true }).catch(() => undefined);
7907
+ }
7908
+ }
7909
+ }
7910
+ });
7911
+ return lifecycle;
7912
+ }
7108
7913
  async function releaseHeldLock(state, normalizedTargetPath, held, options = {}) {
7109
7914
  const current = state.held.get(normalizedTargetPath);
7110
7915
  if (current !== held) {
@@ -7146,6 +7951,7 @@ async function releaseHeldLock(state, normalizedTargetPath, held, options = {})
7146
7951
  }
7147
7952
  }
7148
7953
  function handleForHeldLock(state, normalizedTargetPath, held) {
7954
+ ensureGlobalBeforeExitCleanupRegistered().armed = true;
7149
7955
  return createHeldSidecarLockHandle({
7150
7956
  normalizedTargetPath,
7151
7957
  held,
@@ -7158,8 +7964,12 @@ function createSidecarLockManager(key) {
7158
7964
  state.cleanupRegistered = true;
7159
7965
  state.reclaimCleanupRegistered = true;
7160
7966
  ensureGlobalExitCleanupRegistered();
7967
+ ensureGlobalBeforeExitCleanupRegistered().armed = true;
7161
7968
  }
7162
7969
  async function acquire(options) {
7970
+ if (options.retainOnExit === true && exitCleanupCannotRetain()) {
7971
+ throw new errors_FsSafeError("helper-unavailable", "retainOnExit requires this process's exit handlers to be retain-aware; an older package copy registered them first");
7972
+ }
7163
7973
  return await acquireSidecarLock(options, {
7164
7974
  held: state.held,
7165
7975
  reclaimGuards: state.reclaimGuards,
@@ -7229,6 +8039,8 @@ async function withSidecarLock(targetPath, options, fn) {
7229
8039
 
7230
8040
 
7231
8041
 
8042
+
8043
+
7232
8044
  function pinned_write_byteLength(input, encoding) {
7233
8045
  return typeof input === "string"
7234
8046
  ? Buffer.byteLength(input, encoding ?? "utf8")
@@ -7248,16 +8060,6 @@ function assertWithinMaxBytes(bytes, maxBytes) {
7248
8060
  throw new errors_FsSafeError("too-large", `file exceeds limit of ${maxBytes} bytes (got at least ${bytes})`);
7249
8061
  }
7250
8062
  }
7251
- async function syncFileBestEffort(handle) {
7252
- try {
7253
- await handle.sync();
7254
- }
7255
- catch (error) {
7256
- if (error?.code !== "EPERM") {
7257
- throw error;
7258
- }
7259
- }
7260
- }
7261
8063
  async function writeStreamToHandle(stream, handle, maxBytes) {
7262
8064
  let bytes = 0;
7263
8065
  for await (const chunk of stream) {
@@ -7299,7 +8101,7 @@ async function runPinnedWriteWithRenamePolicy(params) {
7299
8101
  const relativeTargetPath = writeParams.relativeParentPath
7300
8102
  ? `${writeParams.relativeParentPath}/${writeParams.basename}`
7301
8103
  : writeParams.basename;
7302
- const lockPath = external_node_path_.join(writeParams.rootPath, `.fs-safe-write-${sha256Hex(relativeTargetPath)}.lock`);
8104
+ const lockPath = external_node_path_.join(writeParams.rootPath, `.fs-safe-write-${file_identity_sha256Hex(relativeTargetPath)}.lock`);
7303
8105
  return await withSidecarLock(writeParams.rootPath, {
7304
8106
  managerKey: `fs-safe.write:${targetPath}`,
7305
8107
  lockPath,
@@ -7313,6 +8115,11 @@ async function runPinnedWriteWithRenamePolicy(params) {
7313
8115
  }));
7314
8116
  }
7315
8117
  async function runPinnedWriteFallback(params) {
8118
+ const exactRoot = typeof params.rootIdentity?.dev === "bigint" && typeof params.rootIdentity.ino === "bigint"
8119
+ ? { dev: params.rootIdentity.dev, ino: params.rootIdentity.ino } : undefined;
8120
+ if (exactRoot)
8121
+ await inspectDirectoryIdentity(params.rootPath, exactRoot);
8122
+ const guardOptions = { bigint: exactRoot !== undefined };
7316
8123
  let parentPath = params.relativeParentPath
7317
8124
  ? external_node_path_.join(params.rootPath, ...params.relativeParentPath.split("/"))
7318
8125
  : params.rootPath;
@@ -7328,8 +8135,8 @@ async function runPinnedWriteFallback(params) {
7328
8135
  });
7329
8136
  }
7330
8137
  const parentGuard = params.mkdir
7331
- ? await directory_guard_createAsyncDirectoryGuard(parentPath)
7332
- : await directory_guard_createNearestExistingDirectoryGuard(params.rootPath, parentPath);
8138
+ ? await directory_guard_createAsyncDirectoryGuard(parentPath, guardOptions)
8139
+ : await directory_guard_createNearestExistingDirectoryGuard(params.rootPath, parentPath, guardOptions);
7333
8140
  const targetPath = external_node_path_.join(parentPath, params.basename);
7334
8141
  if (params.overwrite === false) {
7335
8142
  const handle = await withAsyncDirectoryGuards([parentGuard], async () => await promises_.open(targetPath, external_node_fs_.constants.O_WRONLY | external_node_fs_.constants.O_CREAT | external_node_fs_.constants.O_EXCL, params.mode), {
@@ -7340,9 +8147,10 @@ async function runPinnedWriteFallback(params) {
7340
8147
  },
7341
8148
  });
7342
8149
  let created = true;
8150
+ let createdIdentity;
7343
8151
  try {
7344
- const verificationIdentity = await handle.stat({ bigint: true });
7345
- await handle.chmod(params.mode);
8152
+ const verificationIdentity = external_node_fs_.fstatSync(handle.fd, { bigint: true });
8153
+ createdIdentity = verificationIdentity;
7346
8154
  if (params.input.kind === "buffer") {
7347
8155
  assertWithinMaxBytes(pinned_write_byteLength(params.input.data, params.input.encoding), params.maxBytes);
7348
8156
  if (typeof params.input.data === "string") {
@@ -7355,18 +8163,26 @@ async function runPinnedWriteFallback(params) {
7355
8163
  else {
7356
8164
  await writeStreamToHandle(params.input.stream, handle, params.maxBytes);
7357
8165
  }
7358
- await syncFileBestEffort(handle);
7359
- const stat = await handle.stat();
7360
- await syncDirectoryBestEffort(parentPath);
8166
+ // Content writes may clear set-ID bits; finalize them through the owned fd.
8167
+ await handle.chmod(params.mode);
8168
+ if (params.sync !== false)
8169
+ await syncFileBestEffort(handle);
8170
+ const stat = external_node_fs_.fstatSync(handle.fd);
8171
+ if (params.sync !== false)
8172
+ await syncDirectoryBestEffort(parentPath);
7361
8173
  // Publication is complete. A failed outer check must not remove its target.
7362
8174
  created = false;
7363
8175
  await params.verifyPublished?.(handle.fd, verificationIdentity, parentGuard);
7364
8176
  return { dev: stat.dev, ino: stat.ino };
7365
8177
  }
7366
8178
  finally {
7367
- await handle.close().catch(() => undefined);
7368
- if (created) {
7369
- await promises_.rm(targetPath, { force: true }).catch(() => undefined);
8179
+ try {
8180
+ if (created) {
8181
+ await cleanupPinnedFilePath({ pathname: targetPath, handle, identity: createdIdentity, parentGuard });
8182
+ }
8183
+ }
8184
+ finally {
8185
+ await handle.close().catch(() => undefined);
7370
8186
  }
7371
8187
  }
7372
8188
  }
@@ -7380,12 +8196,13 @@ async function runPinnedWriteFallback(params) {
7380
8196
  : 0);
7381
8197
  let handle;
7382
8198
  let tempStat;
8199
+ let tempIdentity;
7383
8200
  let readHandle;
7384
8201
  let renamed = false;
7385
8202
  try {
7386
8203
  handle = await promises_.open(tempPath, tempFlags, params.mode);
7387
- let verificationIdentity = await handle.stat({ bigint: true });
7388
- await handle.chmod(params.mode);
8204
+ let verificationIdentity = external_node_fs_.fstatSync(handle.fd, { bigint: true });
8205
+ tempIdentity = verificationIdentity;
7389
8206
  if (params.input.kind === "buffer") {
7390
8207
  assertWithinMaxBytes(pinned_write_byteLength(params.input.data, params.input.encoding), params.maxBytes);
7391
8208
  if (typeof params.input.data === "string") {
@@ -7398,20 +8215,23 @@ async function runPinnedWriteFallback(params) {
7398
8215
  else {
7399
8216
  await writeStreamToHandle(params.input.stream, handle, params.maxBytes);
7400
8217
  }
7401
- tempStat = await handle.stat();
7402
- const tempPathStat = await promises_.lstat(tempPath);
8218
+ tempStat = external_node_fs_.fstatSync(handle.fd);
8219
+ const tempPathStat = external_node_fs_.lstatSync(tempPath);
7403
8220
  if (tempPathStat.isSymbolicLink() || !file_identity_sameFileIdentity(tempPathStat, tempStat)) {
7404
8221
  throw new errors_FsSafeError("path-mismatch", "fallback temp path changed during write");
7405
8222
  }
7406
8223
  const expectedTempStat = tempStat;
7407
- await syncFileBestEffort(handle);
8224
+ await handle.chmod(params.mode);
8225
+ if (params.sync !== false)
8226
+ await syncFileBestEffort(handle);
7408
8227
  let verifiedIdentity = expectedTempStat;
7409
8228
  await withAsyncDirectoryGuards([parentGuard], async () => {
7410
8229
  await promises_.rename(tempPath, targetPath);
7411
8230
  renamed = true;
7412
8231
  await getFsSafeTestHooks()?.afterPinnedWriteFallbackRename?.(targetPath);
7413
- await syncDirectoryBestEffort(parentPath);
7414
- const targetStat = await promises_.lstat(targetPath);
8232
+ if (params.sync !== false)
8233
+ await syncDirectoryBestEffort(parentPath);
8234
+ const targetStat = external_node_fs_.lstatSync(targetPath);
7415
8235
  if (targetStat.isSymbolicLink()) {
7416
8236
  throw new errors_FsSafeError("path-mismatch", "fallback target changed during write");
7417
8237
  }
@@ -7426,10 +8246,10 @@ async function runPinnedWriteFallback(params) {
7426
8246
  if (params.input.kind !== "buffer") {
7427
8247
  throw new errors_FsSafeError("path-mismatch", "fallback target changed during write");
7428
8248
  }
7429
- const expectedHash = sha256Hex(params.input.data, params.input.encoding);
8249
+ const expectedHash = file_identity_sha256Hex(params.input.data, params.input.encoding);
7430
8250
  readHandle = await promises_.open(targetPath, read_open_flags_resolveReadOpenFlags());
7431
- const readHandleStat = await readHandle.stat({ bigint: true });
7432
- const actualHash = sha256Hex(await readHandle.readFile());
8251
+ const readHandleStat = external_node_fs_.fstatSync(readHandle.fd, { bigint: true });
8252
+ const actualHash = file_identity_sha256Hex(await readHandle.readFile());
7433
8253
  if (actualHash !== expectedHash) {
7434
8254
  throw new errors_FsSafeError("path-mismatch", "fallback target changed during write");
7435
8255
  }
@@ -7443,10 +8263,14 @@ async function runPinnedWriteFallback(params) {
7443
8263
  return { dev: verifiedIdentity.dev, ino: verifiedIdentity.ino };
7444
8264
  }
7445
8265
  finally {
7446
- await readHandle?.close().catch(() => undefined);
7447
- await handle?.close().catch(() => undefined);
7448
- if (!renamed) {
7449
- await promises_.rm(tempPath, { force: true }).catch(() => undefined);
8266
+ try {
8267
+ if (!renamed && handle) {
8268
+ await cleanupPinnedFilePath({ pathname: tempPath, handle, identity: tempIdentity, parentGuard });
8269
+ }
8270
+ }
8271
+ finally {
8272
+ await readHandle?.close().catch(() => undefined);
8273
+ await handle?.close().catch(() => undefined);
7450
8274
  }
7451
8275
  }
7452
8276
  }
@@ -7458,7 +8282,7 @@ async function runPinnedWriteFallback(params) {
7458
8282
 
7459
8283
  const PATH_ALIAS_POLICIES = ROOT_PATH_ALIAS_POLICIES;
7460
8284
  async function assertNoPathAliasEscape(params) {
7461
- const resolved = await resolveRootPath({
8285
+ const resolved = await root_path_resolveRootPath({
7462
8286
  absolutePath: params.absolutePath,
7463
8287
  rootPath: params.rootPath,
7464
8288
  boundaryLabel: params.boundaryLabel,
@@ -7481,7 +8305,7 @@ async function assertNoHardlinkedFinalPath(params) {
7481
8305
  }
7482
8306
  let stat;
7483
8307
  try {
7484
- stat = await promises_.stat(params.filePath);
8308
+ stat = external_node_fs_.statSync(params.filePath);
7485
8309
  }
7486
8310
  catch (err) {
7487
8311
  if (path_isNotFoundPathError(err)) {
@@ -7500,9 +8324,6 @@ async function assertNoHardlinkedFinalPath(params) {
7500
8324
  // EXTERNAL MODULE: external "node:url"
7501
8325
  var external_node_url_ = __webpack_require__(3136);
7502
8326
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/string-coerce.js
7503
- function readStringValue(value) {
7504
- return typeof value === "string" ? value : undefined;
7505
- }
7506
8327
  function normalizeNullableString(value) {
7507
8328
  if (typeof value !== "string") {
7508
8329
  return null;
@@ -7513,65 +8334,12 @@ function normalizeNullableString(value) {
7513
8334
  function normalizeOptionalString(value) {
7514
8335
  return normalizeNullableString(value) ?? undefined;
7515
8336
  }
7516
- function normalizeStringifiedOptionalString(value) {
7517
- if (typeof value === "string") {
7518
- return normalizeOptionalString(value);
7519
- }
7520
- if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
7521
- return normalizeOptionalString(String(value));
7522
- }
7523
- return undefined;
7524
- }
7525
8337
  function normalizeOptionalLowercaseString(value) {
7526
8338
  return normalizeOptionalString(value)?.toLowerCase();
7527
8339
  }
7528
8340
  function normalizeLowercaseStringOrEmpty(value) {
7529
8341
  return normalizeOptionalLowercaseString(value) ?? "";
7530
8342
  }
7531
- function normalizeFastMode(raw) {
7532
- if (typeof raw === "boolean") {
7533
- return raw;
7534
- }
7535
- if (!raw) {
7536
- return undefined;
7537
- }
7538
- const key = normalizeLowercaseStringOrEmpty(raw);
7539
- if (["off", "false", "no", "0", "disable", "disabled", "normal"].includes(key)) {
7540
- return false;
7541
- }
7542
- if (["on", "true", "yes", "1", "enable", "enabled", "fast"].includes(key)) {
7543
- return true;
7544
- }
7545
- return undefined;
7546
- }
7547
- function lowercasePreservingWhitespace(value) {
7548
- return value.toLowerCase();
7549
- }
7550
- function localeLowercasePreservingWhitespace(value) {
7551
- return value.toLocaleLowerCase();
7552
- }
7553
- function resolvePrimaryStringValue(value) {
7554
- if (typeof value === "string") {
7555
- return normalizeOptionalString(value);
7556
- }
7557
- if (!value || typeof value !== "object") {
7558
- return undefined;
7559
- }
7560
- return normalizeOptionalString(value.primary);
7561
- }
7562
- function normalizeOptionalThreadValue(value) {
7563
- if (typeof value === "number") {
7564
- return Number.isFinite(value) ? Math.trunc(value) : undefined;
7565
- }
7566
- return normalizeOptionalString(value);
7567
- }
7568
- function normalizeOptionalStringifiedId(value) {
7569
- const normalized = normalizeOptionalThreadValue(value);
7570
- return normalized == null ? undefined : String(normalized);
7571
- }
7572
- function hasNonEmptyString(value) {
7573
- return normalizeOptionalString(value) !== undefined;
7574
- }
7575
8343
 
7576
8344
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/local-file-access.js
7577
8345
 
@@ -7763,8 +8531,11 @@ function normalizeWindowsDeviceBaseName(filePath) {
7763
8531
  const normalized = trimTrailingWindowsSeparators(filePath.replace(/\//g, "\\"));
7764
8532
  const lastSegment = normalized.split("\\").filter(Boolean).at(-1) ?? normalized;
7765
8533
  const withoutStream = lastSegment.split(":")[0] ?? lastSegment;
7766
- const withoutTrailingIgnoredChars = trimTrailingWindowsIgnoredChars(withoutStream);
7767
- return (withoutTrailingIgnoredChars.split(".")[0] ?? withoutTrailingIgnoredChars).toUpperCase();
8534
+ const stem = withoutStream.split(".")[0] ?? withoutStream;
8535
+ return trimTrailingWindowsIgnoredChars(stem).toUpperCase();
8536
+ }
8537
+ function isWindowsReservedDeviceName(name) {
8538
+ return name.length > 0 && WINDOWS_RESERVED_DEVICE_NAMES.has(normalizeWindowsDeviceBaseName(name));
7768
8539
  }
7769
8540
  function matchWindowsDeviceReadPath(filePath) {
7770
8541
  const normalized = filePath.replace(/\//g, "\\");
@@ -7818,6 +8589,42 @@ async function read_opened_file_readOpenedFileSafely(params) {
7818
8589
  };
7819
8590
  }
7820
8591
 
8592
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/write-open-flags.js
8593
+
8594
+
8595
+ function resolveNonblockingWriteFlag(constants = external_node_fs_.constants) {
8596
+ return process.platform !== "win32" && typeof constants.O_NONBLOCK === "number"
8597
+ ? constants.O_NONBLOCK
8598
+ : 0;
8599
+ }
8600
+ function isNonblockingWriteEnxio(error, flags) {
8601
+ return hasNodeErrorCode(error, "ENXIO") &&
8602
+ (flags & (external_node_fs_.constants.O_WRONLY | external_node_fs_.constants.O_RDWR)) === external_node_fs_.constants.O_WRONLY &&
8603
+ (flags & resolveNonblockingWriteFlag()) !== 0;
8604
+ }
8605
+ // A no-reader FIFO rejects a nonblocking write-only open before fstat is possible.
8606
+ // Reclassify only a confirmed non-regular path; inconclusive races keep the errno.
8607
+ async function isNonRegularWriteOpenError(error, filePath, flags) {
8608
+ if (!isNonblockingWriteEnxio(error, flags))
8609
+ return false;
8610
+ try {
8611
+ return !external_node_fs_.lstatSync(filePath).isFile();
8612
+ }
8613
+ catch {
8614
+ return false;
8615
+ }
8616
+ }
8617
+ function isNonRegularWriteOpenErrorSync(error, filePath, flags) {
8618
+ if (!isNonblockingWriteEnxio(error, flags))
8619
+ return false;
8620
+ try {
8621
+ return !fsSync.lstatSync(filePath).isFile();
8622
+ }
8623
+ catch {
8624
+ return false;
8625
+ }
8626
+ }
8627
+
7821
8628
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/home-dir.js
7822
8629
 
7823
8630
 
@@ -7836,10 +8643,6 @@ function resolveEffectiveHomeDir(env = process.env, homedir = external_node_os_.
7836
8643
  const raw = resolveRawHomeDir(env, homedir);
7837
8644
  return raw ? external_node_path_.resolve(raw) : undefined;
7838
8645
  }
7839
- function resolveOsHomeDir(env = process.env, homedir = os.homedir) {
7840
- const raw = resolveRawOsHomeDir(env, homedir);
7841
- return raw ? path.resolve(raw) : undefined;
7842
- }
7843
8646
  function resolveRawHomeDir(env, homedir) {
7844
8647
  const explicitHome = normalize(env.OPENCLAW_HOME);
7845
8648
  if (!explicitHome) {
@@ -7880,9 +8683,6 @@ function normalizeSafe(homedir) {
7880
8683
  function resolveRequiredHomeDir(env = process.env, homedir = os.homedir) {
7881
8684
  return resolveEffectiveHomeDir(env, homedir) ?? path.resolve(process.cwd());
7882
8685
  }
7883
- function resolveRequiredOsHomeDir(env = process.env, homedir = os.homedir) {
7884
- return resolveOsHomeDir(env, homedir) ?? path.resolve(process.cwd());
7885
- }
7886
8686
  function expandHomePrefix(input, opts) {
7887
8687
  const segments = external_node_path_.normalize(input).split(external_node_path_.sep);
7888
8688
  if (segments[0] !== "~") {
@@ -7910,27 +8710,6 @@ function resolveHomeRelativePath(input, opts) {
7910
8710
  });
7911
8711
  return path.resolve(expanded);
7912
8712
  }
7913
- function resolveUserPath(input, optsOrEnv, homedir) {
7914
- const opts = optsOrEnv && ("env" in optsOrEnv || "homedir" in optsOrEnv)
7915
- ? optsOrEnv
7916
- : { env: optsOrEnv, homedir };
7917
- return resolveHomeRelativePath(input, opts);
7918
- }
7919
- function resolveOsHomeRelativePath(input, opts) {
7920
- if (!input) {
7921
- return input;
7922
- }
7923
- const segments = path.normalize(input).split(path.sep);
7924
- if (segments[0] !== "~") {
7925
- return path.resolve(input);
7926
- }
7927
- const expanded = expandHomePrefix(input, {
7928
- home: resolveRequiredOsHomeDir(opts?.env ?? process.env, opts?.homedir ?? os.homedir),
7929
- env: opts?.env,
7930
- homedir: opts?.homedir,
7931
- });
7932
- return path.resolve(expanded);
7933
- }
7934
8713
 
7935
8714
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-context.js
7936
8715
 
@@ -7943,6 +8722,7 @@ function resolveOsHomeRelativePath(input, opts) {
7943
8722
 
7944
8723
 
7945
8724
 
8725
+
7946
8726
  const ensureTrailingSep = (value) => value.endsWith(external_node_path_.sep) ? value : value + external_node_path_.sep;
7947
8727
  function assertValidRootRelativePath(relativePath) {
7948
8728
  path_assertNoNulPathInput(relativePath, "relative path contains a NUL byte");
@@ -7959,7 +8739,7 @@ async function expandRelativePathWithHome(relativePath) {
7959
8739
  if (cachedHomePath?.raw !== rawHome) {
7960
8740
  let realHome = rawHome;
7961
8741
  try {
7962
- realHome = await promises_.realpath(rawHome);
8742
+ realHome = external_node_fs_.realpathSync.native(rawHome);
7963
8743
  }
7964
8744
  catch {
7965
8745
  // If the home dir cannot be canonicalized, keep lexical expansion behavior.
@@ -7973,8 +8753,8 @@ async function resolveRootContext(rootDir) {
7973
8753
  let rootReal;
7974
8754
  let rootIdentity;
7975
8755
  try {
7976
- rootReal = await promises_.realpath(rootDir);
7977
- const rootStat = await promises_.stat(rootReal);
8756
+ rootReal = external_node_fs_.realpathSync.native(rootDir);
8757
+ const rootStat = external_node_fs_.statSync(rootReal);
7978
8758
  if (!rootStat.isDirectory()) {
7979
8759
  throw new errors_FsSafeError("invalid-path", "root dir is not a directory");
7980
8760
  }
@@ -7996,10 +8776,28 @@ async function resolveRootContext(rootDir) {
7996
8776
  rootWithSep: ensureTrailingSep(rootReal),
7997
8777
  };
7998
8778
  }
8779
+ function rootRelativeReadPath(root, filePath) {
8780
+ const absoluteInput = external_node_path_.isAbsolute(filePath);
8781
+ const candidatePath = absoluteInput
8782
+ ? external_node_path_.resolve(filePath)
8783
+ : external_node_path_.resolve(root.rootDir, filePath);
8784
+ let relativeBase = root.rootDir;
8785
+ if (absoluteInput &&
8786
+ !path_isPathInside(root.rootDir, candidatePath) &&
8787
+ path_isPathInside(root.rootReal, candidatePath)) {
8788
+ // A Root created through an alias has two valid in-root absolute spellings.
8789
+ relativeBase = root.rootReal;
8790
+ }
8791
+ return external_node_path_.relative(relativeBase, candidatePath);
8792
+ }
7999
8793
  async function assertRootIdentityCurrent(root) {
8000
8794
  let current;
8001
8795
  try {
8002
- current = await promises_.lstat(root.rootReal);
8796
+ if (typeof root.rootIdentity.dev === "bigint" && typeof root.rootIdentity.ino === "bigint") {
8797
+ await inspectDirectoryIdentity(root.rootReal, { dev: root.rootIdentity.dev, ino: root.rootIdentity.ino });
8798
+ return;
8799
+ }
8800
+ current = external_node_fs_.lstatSync(root.rootReal);
8003
8801
  }
8004
8802
  catch (error) {
8005
8803
  throw new errors_FsSafeError("path-mismatch", "root path changed during operation", {
@@ -8027,7 +8825,7 @@ async function resolvePathInRoot(root, relativePath, options) {
8027
8825
  ? expanded
8028
8826
  : `${root.rootWithSep}${expanded}`;
8029
8827
  try {
8030
- await resolveRootPath({
8828
+ await root_path_resolveRootPath({
8031
8829
  absolutePath: rawAbsolutePath,
8032
8830
  rootPath: root.rootReal,
8033
8831
  rootCanonicalPath: root.rootReal,
@@ -8105,17 +8903,19 @@ async function* walkRoot(root, relativePath, options) {
8105
8903
  const maxEntries = validateBudget("maxEntries", options.maxEntries);
8106
8904
  const visitedDirectories = new Set();
8107
8905
  let examined = 0;
8906
+ let truncated = false;
8108
8907
  const onLimit = (atPath) => {
8109
8908
  if ((options.limitBehavior ?? "truncate") === "throw") {
8110
8909
  throw new errors_FsSafeError("too-large", `root walk budget exceeded at ${atPath || "."}`);
8111
8910
  }
8911
+ truncated = true;
8112
8912
  return limitEntry(atPath);
8113
8913
  };
8114
8914
  async function* visit(directory, depth) {
8115
8915
  options.signal?.throwIfAborted();
8116
8916
  let entries;
8117
8917
  try {
8118
- const resolvedDirectory = await resolveRootPath({
8918
+ const resolvedDirectory = await root_path_resolveRootPath({
8119
8919
  absolutePath: external_node_path_.resolve(root.rootReal, directory),
8120
8920
  rootPath: root.rootReal,
8121
8921
  rootCanonicalPath: root.rootReal,
@@ -8159,7 +8959,7 @@ async function* walkRoot(root, relativePath, options) {
8159
8959
  if (options.symlinkPolicy === "skip") {
8160
8960
  continue;
8161
8961
  }
8162
- const resolved = await resolveRootPath({
8962
+ const resolved = await root_path_resolveRootPath({
8163
8963
  absolutePath: external_node_path_.resolve(root.rootReal, child),
8164
8964
  rootPath: root.rootReal,
8165
8965
  rootCanonicalPath: root.rootReal,
@@ -8190,6 +8990,8 @@ async function* walkRoot(root, relativePath, options) {
8190
8990
  return;
8191
8991
  }
8192
8992
  yield* visit(child, depth + 1);
8993
+ if (truncated)
8994
+ return;
8193
8995
  }
8194
8996
  }
8195
8997
  yield* visit(relativePath, 0);
@@ -8207,7 +9009,7 @@ function pathStillMatchesReceipt(entry) {
8207
9009
  try {
8208
9010
  const current = external_node_fs_.lstatSync(entry.path, { bigint: true });
8209
9011
  return (!entry.singleLinkFile || (current.isFile() && current.nlink === 1n)) &&
8210
- sameFileIdentityForCleanup(current, entry.identity);
9012
+ file_identity_sameFileIdentityForCleanup(current, entry.identity);
8211
9013
  }
8212
9014
  catch (error) {
8213
9015
  return !entry.singleLinkFile && error.code === "ENOENT";
@@ -8238,7 +9040,7 @@ function cleanupRegisteredTempPathsSync() {
8238
9040
  }
8239
9041
  tempCleanupEntries.clear();
8240
9042
  }
8241
- function registerTempPathForExit(tempPath, options) {
9043
+ function temp_cleanup_registerTempPathForExit(tempPath, options) {
8242
9044
  if (!cleanupRegistered) {
8243
9045
  cleanupRegistered = true;
8244
9046
  process.once("exit", cleanupRegisteredTempPathsSync);
@@ -8342,21 +9144,27 @@ async function verifyAtomicWriteResult(params) {
8342
9144
  throw new errors_FsSafeError("path-mismatch", "descriptor changed during write");
8343
9145
  }
8344
9146
  assertFile(stat);
9147
+ if (process.platform !== "win32" && params.expectedMode !== undefined) {
9148
+ const actualMode = Number(stat.mode & 4095n);
9149
+ if (actualMode !== params.expectedMode) {
9150
+ throw new Error(`Private secret file ${params.targetPath} has insecure permissions ${actualMode.toString(8)}.`);
9151
+ }
9152
+ }
8345
9153
  return stat;
8346
9154
  };
8347
9155
  try {
8348
9156
  // This descriptor remains owned by the writer, even when final mode forbids opens.
8349
9157
  const stat = assertDescriptor();
8350
- assertPath(await promises_.lstat(params.targetPath, { bigint: true }));
8351
- const realPath = await resolveOpenedFileRealPathForFd(params.fd, stat, params.targetPath);
8352
- assertPath(await promises_.stat(realPath, { bigint: true }));
9158
+ assertPath(external_node_fs_.lstatSync(params.targetPath, { bigint: true }));
9159
+ const { realPath } = await resolveOpenedFileRealPathForFd(params.fd, stat, params.targetPath);
9160
+ assertPath(external_node_fs_.statSync(realPath, { bigint: true }));
8353
9161
  if (!path_isPathInside(params.root.rootWithSep, realPath)) {
8354
9162
  throw outsideWorkspaceError();
8355
9163
  }
8356
- await assertAsyncDirectoryGuard(params.parentGuard);
9164
+ await directory_guard_assertAsyncDirectoryGuard(params.parentGuard);
8357
9165
  await assertRootIdentityCurrent(params.root);
8358
9166
  // Recheck after canonical resolution and directory checks, including late links.
8359
- assertPath(await promises_.lstat(params.targetPath, { bigint: true }));
9167
+ assertPath(external_node_fs_.lstatSync(params.targetPath, { bigint: true }));
8360
9168
  assertDescriptor();
8361
9169
  if (needsPathOpen) {
8362
9170
  // A retained fd cannot prove that an opaque Windows pathname still names it.
@@ -8374,15 +9182,15 @@ async function verifyAtomicWriteResult(params) {
8374
9182
  });
8375
9183
  try {
8376
9184
  const reopenedStat = assertDescriptor(opened.fd);
8377
- assertPath(await promises_.lstat(params.targetPath, { bigint: true }));
8378
- const reopenedPath = await resolveOpenedFileRealPathForFd(opened.fd, reopenedStat, params.targetPath);
8379
- assertPath(await promises_.stat(reopenedPath, { bigint: true }));
9185
+ assertPath(external_node_fs_.lstatSync(params.targetPath, { bigint: true }));
9186
+ const { realPath: reopenedPath } = await resolveOpenedFileRealPathForFd(opened.fd, reopenedStat, params.targetPath);
9187
+ assertPath(external_node_fs_.statSync(reopenedPath, { bigint: true }));
8380
9188
  if (!path_isPathInside(params.root.rootWithSep, reopenedPath)) {
8381
9189
  throw outsideWorkspaceError();
8382
9190
  }
8383
- await assertAsyncDirectoryGuard(params.parentGuard);
9191
+ await directory_guard_assertAsyncDirectoryGuard(params.parentGuard);
8384
9192
  await assertRootIdentityCurrent(params.root);
8385
- assertPath(await promises_.lstat(params.targetPath, { bigint: true }));
9193
+ assertPath(external_node_fs_.lstatSync(params.targetPath, { bigint: true }));
8386
9194
  assertDescriptor(opened.fd);
8387
9195
  }
8388
9196
  finally {
@@ -8397,6 +9205,74 @@ async function verifyAtomicWriteResult(params) {
8397
9205
  }
8398
9206
  }
8399
9207
 
9208
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-write-mode.js
9209
+
9210
+
9211
+
9212
+
9213
+
9214
+
9215
+
9216
+
9217
+ // The caller has already resolved and guarded this write target.
9218
+ async function inheritWriteTargetMode(params) {
9219
+ try {
9220
+ const existing = await strict_file_identity_inspectFileIdentity(() => external_node_fs_.lstatSync(params.targetPath, { bigint: true }));
9221
+ if (existing.isSymbolicLink())
9222
+ throw new errors_FsSafeError("path-alias", "path alias escape blocked");
9223
+ if (!existing.isFile())
9224
+ throw new errors_FsSafeError("not-file", "not a file");
9225
+ if (existing.nlink > 1n)
9226
+ throw hardlinkedPathNotAllowedError();
9227
+ if (!path_isPathInside(params.rootWithSep, params.targetPath))
9228
+ throw outsideWorkspaceError();
9229
+ // Preserve read-open admission of the pre-existing destination. access(2)
9230
+ // is not equivalent: it ignores ACLs on Windows and capabilities on Linux.
9231
+ const handle = await promises_.open(params.targetPath, read_open_flags_resolveReadOpenFlags());
9232
+ try {
9233
+ // Bind admission to the inode whose metadata is inherited.
9234
+ if (!file_identity_sameFileIdentity(external_node_fs_.fstatSync(handle.fd, { bigint: true }), existing)) {
9235
+ throw new errors_FsSafeError("path-mismatch", "write target changed during mode inheritance");
9236
+ }
9237
+ }
9238
+ finally {
9239
+ await handle.close().catch(() => undefined);
9240
+ }
9241
+ try {
9242
+ // A parent can change after guarded resolution. Do not inherit metadata
9243
+ // from an outside inode, even if the parent is restored before publication.
9244
+ const realPath = external_node_fs_.realpathSync.native(params.targetPath);
9245
+ if (!path_isPathInside(params.rootWithSep, realPath))
9246
+ throw outsideWorkspaceError();
9247
+ await strict_file_identity_inspectFileIdentity(async () => {
9248
+ const current = external_node_fs_.statSync(realPath, { bigint: true });
9249
+ if (!current.isFile())
9250
+ throw new errors_FsSafeError("not-file", "not a file");
9251
+ if (current.nlink > 1n)
9252
+ throw hardlinkedPathNotAllowedError();
9253
+ return current;
9254
+ }, existing);
9255
+ }
9256
+ catch (error) {
9257
+ if (path_isNotFoundPathError(error)) {
9258
+ throw new errors_FsSafeError("path-mismatch", "write target changed during mode inheritance", { cause: error });
9259
+ }
9260
+ throw error;
9261
+ }
9262
+ return params.requestedMode ?? Number(existing.mode & 511n);
9263
+ }
9264
+ catch (error) {
9265
+ if (!path_isNotFoundPathError(error))
9266
+ throw error;
9267
+ return params.requestedMode ?? 0o600;
9268
+ }
9269
+ }
9270
+
9271
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/copy-publication.js
9272
+ // Internal composition hook; the descriptor is borrowed until the callback returns.
9273
+ // Kept off RootCopyOptions and all public package exports.
9274
+ const onCopyPublication = Symbol("onCopyPublication");
9275
+
8400
9276
  ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-impl.js
8401
9277
 
8402
9278
 
@@ -8426,6 +9302,9 @@ async function verifyAtomicWriteResult(params) {
8426
9302
 
8427
9303
 
8428
9304
 
9305
+
9306
+
9307
+
8429
9308
 
8430
9309
 
8431
9310
 
@@ -8438,12 +9317,14 @@ function logWarn(message) {
8438
9317
  const SUPPORTS_NOFOLLOW = process.platform !== "win32" && "O_NOFOLLOW" in external_node_fs_.constants;
8439
9318
  const OPEN_READ_FLAGS = read_open_flags_resolveReadOpenFlags();
8440
9319
  const OPEN_READ_FOLLOW_FLAGS = read_open_flags_resolveReadOpenFlags({ followSymlinks: true });
8441
- const OPEN_WRITE_EXISTING_FLAGS = external_node_fs_.constants.O_WRONLY | (SUPPORTS_NOFOLLOW ? external_node_fs_.constants.O_NOFOLLOW : 0);
9320
+ const OPEN_WRITE_EXISTING_FLAGS = external_node_fs_.constants.O_WRONLY | (SUPPORTS_NOFOLLOW ? external_node_fs_.constants.O_NOFOLLOW : 0) |
9321
+ resolveNonblockingWriteFlag();
8442
9322
  const OPEN_WRITE_CREATE_FLAGS = external_node_fs_.constants.O_WRONLY |
8443
9323
  external_node_fs_.constants.O_CREAT |
8444
9324
  external_node_fs_.constants.O_EXCL |
8445
9325
  (SUPPORTS_NOFOLLOW ? external_node_fs_.constants.O_NOFOLLOW : 0);
8446
- const OPEN_APPEND_EXISTING_FLAGS = external_node_fs_.constants.O_RDWR | external_node_fs_.constants.O_APPEND | (SUPPORTS_NOFOLLOW ? external_node_fs_.constants.O_NOFOLLOW : 0);
9326
+ const OPEN_APPEND_EXISTING_FLAGS = external_node_fs_.constants.O_RDWR | external_node_fs_.constants.O_APPEND | (SUPPORTS_NOFOLLOW ? external_node_fs_.constants.O_NOFOLLOW : 0) |
9327
+ resolveNonblockingWriteFlag();
8447
9328
  const OPEN_APPEND_CREATE_FLAGS = external_node_fs_.constants.O_RDWR |
8448
9329
  external_node_fs_.constants.O_APPEND |
8449
9330
  external_node_fs_.constants.O_CREAT |
@@ -8482,8 +9363,8 @@ async function openVerifiedLocalFile(filePath, options) {
8482
9363
  // Reject directories before opening so we never surface EISDIR to callers (e.g. tool
8483
9364
  // results that get sent to messaging channels). See openclaw/openclaw#31186.
8484
9365
  try {
8485
- preOpenStat = await inspectFileIdentity(async () => {
8486
- const stat = await promises_.lstat(filePath, { bigint: true });
9366
+ preOpenStat = await strict_file_identity_inspectFileIdentity(async () => {
9367
+ const stat = external_node_fs_.lstatSync(filePath, { bigint: true });
8487
9368
  observedBeforeOpen = true;
8488
9369
  if (stat.isSymbolicLink() && options?.symlinks !== "follow-within-root") {
8489
9370
  throw new errors_FsSafeError("symlink", "symlink not allowed");
@@ -8523,13 +9404,13 @@ async function openVerifiedLocalFile(filePath, options) {
8523
9404
  }
8524
9405
  try {
8525
9406
  await fsSafeTestHooks?.afterOpen?.(filePath, handle);
8526
- const stat = await handle.stat();
9407
+ const stat = external_node_fs_.fstatSync(handle.fd);
8527
9408
  if (!stat.isFile()) {
8528
9409
  throw new errors_FsSafeError("not-file", "not a file");
8529
9410
  }
8530
9411
  // Keep numeric Stats for the public receipt, never for identity verification.
8531
9412
  let openedIdentity;
8532
- const identity = await inspectFileIdentity(async () => (openedIdentity = await handle.stat({ bigint: true })), preOpenStat && !preOpenStat.isSymbolicLink() ? preOpenStat : undefined).catch(async (error) => {
9413
+ const identity = await strict_file_identity_inspectFileIdentity(async () => (openedIdentity = external_node_fs_.fstatSync(handle.fd, { bigint: true })), preOpenStat && !preOpenStat.isSymbolicLink() ? preOpenStat : undefined).catch(async (error) => {
8533
9414
  if ([0, 1].includes(stat.nlink)) {
8534
9415
  await recordPreOpenFileChange(error, handle, filePath, preOpenStat, openedIdentity);
8535
9416
  }
@@ -8540,7 +9421,7 @@ async function openVerifiedLocalFile(filePath, options) {
8540
9421
  }
8541
9422
  const inspectPathIdentity = async (inspect) => {
8542
9423
  try {
8543
- return await inspectFileIdentity(inspect, identity);
9424
+ return await strict_file_identity_inspectFileIdentity(inspect, identity);
8544
9425
  }
8545
9426
  catch (error) {
8546
9427
  const failure = path_isNotFoundPathError(error) ? openedPathResolutionError(fileNotFoundError()) : error;
@@ -8552,23 +9433,28 @@ async function openVerifiedLocalFile(filePath, options) {
8552
9433
  };
8553
9434
  await inspectPathIdentity(async () => {
8554
9435
  const pathStat = options?.symlinks === "follow-within-root"
8555
- ? await promises_.stat(filePath, { bigint: true })
8556
- : await promises_.lstat(filePath, { bigint: true });
9436
+ ? external_node_fs_.statSync(filePath, { bigint: true })
9437
+ : external_node_fs_.lstatSync(filePath, { bigint: true });
8557
9438
  if (pathStat.isSymbolicLink() && options?.symlinks !== "follow-within-root") {
8558
9439
  throw new errors_FsSafeError("symlink", "symlink not allowed");
8559
9440
  }
8560
9441
  return pathStat;
8561
9442
  });
8562
9443
  await fsSafeTestHooks?.afterOpenedPathIdentityCheck?.(filePath, handle);
8563
- const realPath = await resolveOpenedFileRealPathForFd(handle.fd, identity, filePath)
9444
+ const resolved = await resolveOpenedFileRealPathForFd(handle.fd, identity, filePath)
8564
9445
  .catch(async (error) => {
8565
9446
  if (stat.nlink <= 1 && (!preOpenStat || preOpenStat.nlink <= 1n)) {
8566
9447
  await recordOpenedFileFailure(error, handle, filePath, identity);
8567
9448
  }
8568
9449
  throw error;
8569
9450
  });
9451
+ const { realPath } = resolved;
9452
+ let resolvedStat = resolved.stat;
8570
9453
  await inspectPathIdentity(async () => {
8571
- const realStat = await promises_.stat(realPath, { bigint: true });
9454
+ // Reuse the post-realpath observation; unknown Windows identities still
9455
+ // get a fresh observation on inspectFileIdentity's retry.
9456
+ const realStat = resolvedStat ?? external_node_fs_.statSync(realPath, { bigint: true });
9457
+ resolvedStat = undefined;
8572
9458
  if (options?.hardlinks === "reject" && realStat.nlink > 1n) {
8573
9459
  throw hardlinkedPathNotAllowedError();
8574
9460
  }
@@ -8666,6 +9552,7 @@ class RootHandle {
8666
9552
  mkdir: this.defaults.mkdir,
8667
9553
  mode: this.defaults.mode,
8668
9554
  ...this.mutationOptions(options),
9555
+ durable: options.durable ?? this.defaults.durable ?? true,
8669
9556
  });
8670
9557
  }
8671
9558
  async remove(relativePath, options = {}) {
@@ -8698,6 +9585,7 @@ class RootHandle {
8698
9585
  mode: this.defaults.mode,
8699
9586
  renameIdentity: this.defaults.renameIdentity,
8700
9587
  ...this.mutationOptions(options),
9588
+ durable: options.durable ?? this.defaults.durable ?? true,
8701
9589
  });
8702
9590
  }
8703
9591
  async create(relativePath, data, options = {}) {
@@ -8708,6 +9596,7 @@ class RootHandle {
8708
9596
  mkdir: this.defaults.mkdir,
8709
9597
  mode: this.defaults.mode,
8710
9598
  ...this.mutationOptions(options),
9599
+ durable: options.durable ?? this.defaults.durable ?? true,
8711
9600
  overwrite: false,
8712
9601
  });
8713
9602
  }
@@ -8731,6 +9620,8 @@ class RootHandle {
8731
9620
  mkdir: this.defaults.mkdir,
8732
9621
  mode: this.defaults.mode,
8733
9622
  ...copyOptions,
9623
+ durable: options.durable ?? this.defaults.durable ?? true,
9624
+ verifyPublished: options[onCopyPublication],
8734
9625
  });
8735
9626
  }
8736
9627
  async exists(relativePath) {
@@ -8781,7 +9672,6 @@ function readDefaults(defaults) {
8781
9672
  return {
8782
9673
  hardlinks: defaults.hardlinks,
8783
9674
  maxBytes: byte_budget_normalizeMaxBytes(defaults.maxBytes, { defaultValue: DEFAULT_ROOT_MAX_BYTES }),
8784
- nonBlockingRead: defaults.nonBlockingRead,
8785
9675
  symlinks: defaults.symlinks,
8786
9676
  };
8787
9677
  }
@@ -8790,8 +9680,6 @@ function mergeReadOptions(defaults, options) {
8790
9680
  if (options.hardlinks !== undefined)
8791
9681
  merged.hardlinks = options.hardlinks;
8792
9682
  merged.maxBytes = byte_budget_normalizeMaxBytes(options.maxBytes, { defaultValue: merged.maxBytes });
8793
- if (options.nonBlockingRead !== undefined)
8794
- merged.nonBlockingRead = options.nonBlockingRead;
8795
9683
  if (options.symlinks !== undefined)
8796
9684
  merged.symlinks = options.symlinks;
8797
9685
  return merged;
@@ -8807,7 +9695,6 @@ async function openFileInRoot(root, params) {
8807
9695
  rejectSymlinks: params.symlinks !== "follow-within-root",
8808
9696
  });
8809
9697
  const { opened } = await openVerifiedLocalFile(resolved, {
8810
- nonBlockingRead: params.nonBlockingRead,
8811
9698
  symlinks: params.symlinks,
8812
9699
  });
8813
9700
  if (params.hardlinks !== "allow" && opened.stat.nlink > 1) {
@@ -8830,16 +9717,11 @@ async function readFileInRoot(root, params) {
8830
9717
  }
8831
9718
  }
8832
9719
  async function readPathInRoot(root, params) {
8833
- const rootDir = root.rootDir;
8834
- const candidatePath = external_node_path_.isAbsolute(params.filePath)
8835
- ? external_node_path_.resolve(params.filePath)
8836
- : external_node_path_.resolve(rootDir, params.filePath);
8837
- const relativePath = external_node_path_.relative(rootDir, candidatePath);
9720
+ const relativePath = rootRelativeReadPath(root, params.filePath);
8838
9721
  return await readFileInRoot(root, {
8839
9722
  relativePath,
8840
9723
  hardlinks: params.hardlinks,
8841
9724
  maxBytes: params.maxBytes,
8842
- nonBlockingRead: params.nonBlockingRead,
8843
9725
  symlinks: params.symlinks,
8844
9726
  });
8845
9727
  }
@@ -8886,7 +9768,7 @@ async function writeTempFileForAtomicReplace(params) {
8886
9768
  }
8887
9769
  return {
8888
9770
  handle: tempHandle,
8889
- identity: await tempHandle.stat({ bigint: true }),
9771
+ identity: external_node_fs_.fstatSync(tempHandle.fd, { bigint: true }),
8890
9772
  };
8891
9773
  }
8892
9774
  catch (error) {
@@ -8925,7 +9807,7 @@ async function openWritableFileInRoot(root, params) {
8925
9807
  ? resolved
8926
9808
  : await prepareRootWriteTarget(rootReal, resolved);
8927
9809
  try {
8928
- const resolvedRealPath = await promises_.realpath(ioPath);
9810
+ const resolvedRealPath = external_node_fs_.realpathSync.native(ioPath);
8929
9811
  if (!path_isPathInside(rootWithSep, resolvedRealPath)) {
8930
9812
  throw outsideWorkspaceError();
8931
9813
  }
@@ -8949,6 +9831,9 @@ async function openWritableFileInRoot(root, params) {
8949
9831
  handle = await promises_.open(ioPath, existingFlags, mode);
8950
9832
  }
8951
9833
  catch (err) {
9834
+ if (await isNonRegularWriteOpenError(err, ioPath, existingFlags)) {
9835
+ throw new errors_FsSafeError("not-file", "path is not a regular file under root");
9836
+ }
8952
9837
  if (!path_isNotFoundPathError(err)) {
8953
9838
  throw err;
8954
9839
  }
@@ -8971,7 +9856,7 @@ async function openWritableFileInRoot(root, params) {
8971
9856
  let realPathForCleanup = null;
8972
9857
  let createdIdentity = null;
8973
9858
  try {
8974
- const stat = await handle.stat();
9859
+ const stat = external_node_fs_.fstatSync(handle.fd);
8975
9860
  if (createdForWrite) {
8976
9861
  createdIdentity = stat;
8977
9862
  }
@@ -8982,7 +9867,7 @@ async function openWritableFileInRoot(root, params) {
8982
9867
  throw hardlinkedPathNotAllowedError();
8983
9868
  }
8984
9869
  try {
8985
- const lstat = await promises_.lstat(ioPath);
9870
+ const lstat = external_node_fs_.lstatSync(ioPath);
8986
9871
  if (lstat.isSymbolicLink() || !lstat.isFile()) {
8987
9872
  throw new errors_FsSafeError(lstat.isSymbolicLink() ? "symlink" : "not-file", "path is not a regular file under root");
8988
9873
  }
@@ -8997,7 +9882,7 @@ async function openWritableFileInRoot(root, params) {
8997
9882
  }
8998
9883
  const realPath = await resolveOpenedFileRealPathForHandle(handle, ioPath);
8999
9884
  realPathForCleanup = realPath;
9000
- const realStat = await promises_.stat(realPath);
9885
+ const realStat = external_node_fs_.statSync(realPath);
9001
9886
  if (!file_identity_sameFileIdentity(stat, realStat)) {
9002
9887
  throw new errors_FsSafeError("path-mismatch", "path mismatch");
9003
9888
  }
@@ -9060,8 +9945,9 @@ async function appendFileInRoot(root, params) {
9060
9945
  const payload = prefix.length > 0 ? Buffer.concat([Buffer.from(prefix, "utf8"), params.data]) : params.data;
9061
9946
  await target.handle.appendFile(payload);
9062
9947
  }
9063
- await target.handle.sync();
9064
- if (target.createdForWrite) {
9948
+ if (params.durable !== false)
9949
+ await target.handle.sync();
9950
+ if (params.durable !== false && target.createdForWrite) {
9065
9951
  await syncDirectoryBestEffort(external_node_path_.dirname(target.realPath));
9066
9952
  }
9067
9953
  }
@@ -9117,6 +10003,7 @@ async function commitPinnedWriteInRoot(root, pinned, params) {
9117
10003
  renameIdentity: params.renameIdentity,
9118
10004
  mkdir: params.mkdir !== false,
9119
10005
  mode: params.mode ?? pinned.mode,
10006
+ sync: params.durable !== false,
9120
10007
  overwrite: params.overwrite,
9121
10008
  input: { kind: "buffer", data: params.data, encoding: params.encoding },
9122
10009
  rootIdentity: root.rootIdentity,
@@ -9178,6 +10065,8 @@ async function copyFileInRoot(root, params) {
9178
10065
  mode: pinned.mode,
9179
10066
  overwrite: true,
9180
10067
  maxBytes: params.maxBytes,
10068
+ sync: params.durable !== false,
10069
+ verifyPublished: params.verifyPublished,
9181
10070
  input: { kind: "stream", stream: source.handle.createReadStream() },
9182
10071
  rootIdentity: root.rootIdentity,
9183
10072
  });
@@ -9200,12 +10089,12 @@ async function copyFileInRoot(root, params) {
9200
10089
  }
9201
10090
  }
9202
10091
  async function assertCopySourceCurrent(source, identity) {
9203
- await inspectFileIdentity(() => source.handle.stat({ bigint: true }), identity);
10092
+ await strict_file_identity_inspectFileIdentity(() => external_node_fs_.fstatSync(source.handle.fd, { bigint: true }), identity);
9204
10093
  await assertCopySourcePathCurrent(source, identity);
9205
10094
  }
9206
10095
  async function assertCopySourcePathCurrent(source, identity) {
9207
- await inspectFileIdentity(async () => {
9208
- const current = await promises_.lstat(source.realPath, { bigint: true });
10096
+ await strict_file_identity_inspectFileIdentity(async () => {
10097
+ const current = external_node_fs_.lstatSync(source.realPath, { bigint: true });
9209
10098
  if (current.isSymbolicLink() || !current.isFile()) {
9210
10099
  throw new errors_FsSafeError("path-mismatch", "copy source path changed");
9211
10100
  }
@@ -9214,8 +10103,8 @@ async function assertCopySourcePathCurrent(source, identity) {
9214
10103
  }
9215
10104
  async function removePathIfIdentityUnchanged(targetPath, identity) {
9216
10105
  const parentGuard = await directory_guard_createAsyncDirectoryGuard(external_node_path_.dirname(targetPath));
9217
- const current = await promises_.lstat(targetPath);
9218
- if (current.isSymbolicLink() || !sameFileIdentityForCleanup(current, identity)) {
10106
+ const current = external_node_fs_.lstatSync(targetPath);
10107
+ if (current.isSymbolicLink() || !file_identity_sameFileIdentityForCleanup(current, identity)) {
9219
10108
  return;
9220
10109
  }
9221
10110
  await withAsyncDirectoryGuards([parentGuard], async () => {
@@ -9244,7 +10133,7 @@ async function resolvePinnedWriteTargetInRoot(root, relativePath, requestedMode,
9244
10133
  // and alias checks, but never open a competing owner's record just to reject it.
9245
10134
  if (!overwrite) {
9246
10135
  try {
9247
- const existing = await promises_.stat(resolved);
10136
+ const existing = external_node_fs_.statSync(resolved);
9248
10137
  if (!existing.isFile())
9249
10138
  throw new errors_FsSafeError("not-file", "not a file");
9250
10139
  if (existing.nlink > 1)
@@ -9256,31 +10145,9 @@ async function resolvePinnedWriteTargetInRoot(root, relativePath, requestedMode,
9256
10145
  throw error;
9257
10146
  }
9258
10147
  }
9259
- let mode = requestedMode ?? 0o600;
9260
- try {
9261
- if (overwrite) {
9262
- const opened = await openFileInRoot(root, {
9263
- relativePath,
9264
- hardlinks: "reject",
9265
- nonBlockingRead: true,
9266
- symlinks: "follow-within-root",
9267
- });
9268
- try {
9269
- mode = requestedMode ?? (opened.stat.mode & 0o777);
9270
- if (!path_isPathInside(rootWithSep, opened.realPath)) {
9271
- throw outsideWorkspaceError();
9272
- }
9273
- }
9274
- finally {
9275
- await opened.handle.close().catch(() => { });
9276
- }
9277
- }
9278
- }
9279
- catch (err) {
9280
- if (!(err instanceof errors_FsSafeError) || err.code !== "not-found") {
9281
- throw err;
9282
- }
9283
- }
10148
+ const mode = overwrite
10149
+ ? await inheritWriteTargetMode({ targetPath: resolved, rootWithSep, requestedMode })
10150
+ : requestedMode ?? 0o600;
9284
10151
  return {
9285
10152
  rootReal,
9286
10153
  targetPath: resolved,
@@ -9330,7 +10197,7 @@ async function resolvePinnedRootPathInRoot(root, params) {
9330
10197
  let resolved;
9331
10198
  try {
9332
10199
  const expandedPath = await expandRelativePathWithHome(params.relativePath);
9333
- resolved = await resolveRootPath({
10200
+ resolved = await root_path_resolveRootPath({
9334
10201
  absolutePath: external_node_path_.isAbsolute(expandedPath)
9335
10202
  ? expandedPath
9336
10203
  : `${ensureTrailingSep(rootReal)}${expandedPath}`,
@@ -9354,7 +10221,7 @@ async function prepareRemoveGuard(targetPath) {
9354
10221
  try {
9355
10222
  const guard = await directory_guard_createAsyncDirectoryGuard(external_node_path_.dirname(targetPath));
9356
10223
  await getFsSafeTestHooks()?.beforeRootFallbackMutation?.("remove", targetPath);
9357
- await assertAsyncDirectoryGuard(guard);
10224
+ await directory_guard_assertAsyncDirectoryGuard(guard);
9358
10225
  return guard;
9359
10226
  }
9360
10227
  catch (error) {
@@ -9364,12 +10231,12 @@ async function prepareRemoveGuard(targetPath) {
9364
10231
  async function removePathFallback(resolved) {
9365
10232
  const guard = await prepareRemoveGuard(resolved.resolved);
9366
10233
  try {
9367
- await ((await promises_.lstat(resolved.resolved)).isDirectory() ? promises_.rmdir(resolved.resolved) : promises_.rm(resolved.resolved));
10234
+ await (external_node_fs_.lstatSync(resolved.resolved).isDirectory() ? promises_.rmdir(resolved.resolved) : promises_.rm(resolved.resolved));
9368
10235
  }
9369
10236
  catch (error) {
9370
10237
  throw normalizeRemovePathError(error);
9371
10238
  }
9372
- await assertAsyncDirectoryGuard(guard).catch(() => undefined);
10239
+ await directory_guard_assertAsyncDirectoryGuard(guard).catch(() => undefined);
9373
10240
  }
9374
10241
  async function mkdirPathFallback(resolved) {
9375
10242
  await mkdirPathComponentsWithGuards({
@@ -9380,7 +10247,7 @@ async function mkdirPathFallback(resolved) {
9380
10247
  async function statPathFallback(root, relativePath) {
9381
10248
  const resolved = await resolvePinnedPathInRoot(root, { relativePath, allowRoot: true });
9382
10249
  try {
9383
- const stat = pathStatFromStats(await promises_.lstat(resolved.resolved));
10250
+ const stat = pathStatFromStats(external_node_fs_.lstatSync(resolved.resolved));
9384
10251
  await assertRootIdentityCurrent(root);
9385
10252
  return stat;
9386
10253
  }
@@ -9404,7 +10271,7 @@ async function listPathFallback(root, relativePath, withFileTypes) {
9404
10271
  for (const name of sortedNames) {
9405
10272
  entries.push({
9406
10273
  name,
9407
- ...pathStatFromStats(await promises_.lstat(external_node_path_.join(resolved.resolved, name))),
10274
+ ...pathStatFromStats(external_node_fs_.lstatSync(external_node_path_.join(resolved.resolved, name))),
9408
10275
  });
9409
10276
  }
9410
10277
  await assertRootIdentityCurrent(root);
@@ -9453,7 +10320,11 @@ async function movePathFallback(root, params) {
9453
10320
  relativePath: params.toRelative,
9454
10321
  policy: PATH_ALIAS_POLICIES.unlinkTarget,
9455
10322
  });
9456
- const targetStat = await promises_.lstat(resolvedTarget.resolved).catch(() => undefined);
10323
+ let targetStat;
10324
+ try {
10325
+ targetStat = external_node_fs_.lstatSync(resolvedTarget.resolved);
10326
+ }
10327
+ catch { /* Advisory lookup. */ }
9457
10328
  return !(process.platform !== "win32" &&
9458
10329
  params.overwrite &&
9459
10330
  targetStat?.isSymbolicLink() === true);
@@ -9461,7 +10332,7 @@ async function movePathFallback(root, params) {
9461
10332
  });
9462
10333
  let sourceStat;
9463
10334
  try {
9464
- sourceStat = await promises_.lstat(source.resolved);
10335
+ sourceStat = external_node_fs_.lstatSync(source.resolved);
9465
10336
  }
9466
10337
  catch (error) {
9467
10338
  if (path_isNotFoundPathError(error)) {
@@ -9480,7 +10351,7 @@ async function movePathFallback(root, params) {
9480
10351
  }
9481
10352
  if (!params.overwrite) {
9482
10353
  try {
9483
- await promises_.lstat(target.resolved);
10354
+ external_node_fs_.lstatSync(target.resolved);
9484
10355
  throw new errors_FsSafeError("already-exists", "destination exists");
9485
10356
  }
9486
10357
  catch (error) {
@@ -9495,8 +10366,8 @@ async function movePathFallback(root, params) {
9495
10366
  const sourceParentGuard = await directory_guard_createAsyncDirectoryGuard(external_node_path_.dirname(source.resolved));
9496
10367
  const targetParentGuard = await directory_guard_createNearestExistingDirectoryGuard(target.rootReal, external_node_path_.dirname(target.resolved));
9497
10368
  await getFsSafeTestHooks()?.beforeRootFallbackMutation?.("move", target.resolved);
9498
- await assertAsyncDirectoryGuard(sourceParentGuard);
9499
- await assertAsyncDirectoryGuard(targetParentGuard);
10369
+ await directory_guard_assertAsyncDirectoryGuard(sourceParentGuard);
10370
+ await directory_guard_assertAsyncDirectoryGuard(targetParentGuard);
9500
10371
  try {
9501
10372
  await promises_.rename(source.resolved, target.resolved);
9502
10373
  }
@@ -9511,7 +10382,7 @@ async function movePathFallback(root, params) {
9511
10382
  }
9512
10383
  throw error;
9513
10384
  }
9514
- await assertAsyncDirectoryGuard(targetParentGuard).catch(() => undefined);
10385
+ await directory_guard_assertAsyncDirectoryGuard(targetParentGuard).catch(() => undefined);
9515
10386
  }
9516
10387
  async function writeFileFallback(root, params) {
9517
10388
  if (params.overwrite === false) {
@@ -9521,7 +10392,8 @@ async function writeFileFallback(root, params) {
9521
10392
  const target = await openWritableFileInRoot(root, {
9522
10393
  relativePath: params.relativePath,
9523
10394
  mkdir: params.mkdir,
9524
- mode: params.mode,
10395
+ // Private, writable placeholder: Windows cannot rename over a read-only file.
10396
+ mode: 0o600,
9525
10397
  denyMutations: params.denyMutations,
9526
10398
  truncateExisting: false,
9527
10399
  });
@@ -9534,12 +10406,12 @@ async function writeFileFallback(root, params) {
9534
10406
  let writtenHandle;
9535
10407
  try {
9536
10408
  tempPath = buildAtomicWriteTempPath(destinationPath);
9537
- unregisterTempPath = registerTempPathForExit(tempPath);
10409
+ unregisterTempPath = temp_cleanup_registerTempPathForExit(tempPath);
9538
10410
  const written = await writeTempFileForAtomicReplace({
9539
10411
  tempPath,
9540
10412
  data: params.data,
9541
10413
  encoding: params.encoding,
9542
- mode,
10414
+ mode: 0o600,
9543
10415
  });
9544
10416
  writtenHandle = written.handle;
9545
10417
  unregisterTempPath.setIdentity(written.identity);
@@ -9550,6 +10422,14 @@ async function writeFileFallback(root, params) {
9550
10422
  });
9551
10423
  unregisterTempPath();
9552
10424
  unregisterTempPath = null;
10425
+ // Final mode via the retained handle after publication, as the native writer does.
10426
+ try {
10427
+ await written.handle.chmod(mode);
10428
+ }
10429
+ catch (error) {
10430
+ await removePathIfIdentityUnchanged(destinationPath, written.identity).catch(() => { });
10431
+ throw error;
10432
+ }
9553
10433
  try {
9554
10434
  await verifyAtomicWriteResult({
9555
10435
  root,
@@ -9587,11 +10467,11 @@ async function writeMissingFileFallback(root, params) {
9587
10467
  let verifyingPublication = false;
9588
10468
  try {
9589
10469
  const { handle, writtenStat } = await withAsyncDirectoryGuards([parentGuard], async () => {
9590
- const handle = await promises_.open(targetPath, OPEN_WRITE_CREATE_FLAGS, params.mode ?? 0o600);
10470
+ const handle = await promises_.open(targetPath, OPEN_WRITE_CREATE_FLAGS, params.mode ?? 0o600).catch((error) => recordExclusiveCreateFailure(error, targetPath));
9591
10471
  created = true;
9592
10472
  try {
9593
- createdIdentity = await handle.stat();
9594
- const writtenStat = await handle.stat({ bigint: true });
10473
+ createdIdentity = external_node_fs_.fstatSync(handle.fd);
10474
+ const writtenStat = external_node_fs_.fstatSync(handle.fd, { bigint: true });
9595
10475
  if (typeof params.data === "string") {
9596
10476
  await handle.writeFile(params.data, params.encoding ?? "utf8");
9597
10477
  }
@@ -94268,4 +95148,4 @@ if (installedChunkData !== 0) { // 0 means "already installed".'
94268
95148
  // module factories are used so entry inlining is disabled
94269
95149
  // startup
94270
95150
  // Load entry module and return exports
94271
- var __webpack_exports__ = __webpack_require__(8853);
95151
+ var __webpack_exports__ = __webpack_require__(5694);