@lousy-agents/agent-shell 5.14.1 → 5.14.3

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.
Files changed (2) hide show
  1. package/dist/index.js +3803 -54
  2. package/package.json +2 -1
package/dist/index.js CHANGED
@@ -2,7 +2,7 @@
2
2
  import { createRequire as __rspack_createRequire } from "node:module";
3
3
  const __rspack_createRequire_require = __rspack_createRequire(import.meta.url);
4
4
  var __webpack_modules__ = ({
5
- 176(__unused_rspack_module, __unused_rspack___webpack_exports__, __webpack_require__) {
5
+ 391(__unused_rspack_module, __unused_rspack___webpack_exports__, __webpack_require__) {
6
6
 
7
7
  ;// CONCATENATED MODULE: external "node:child_process"
8
8
  const external_node_child_process_namespaceObject = __rspack_createRequire_require("node:child_process");
@@ -77,6 +77,3705 @@ function defaultExecutor(env) {
77
77
  }
78
78
  /** Process-scoped singleton for production use. */ const git_utils_getRepositoryRoot = createGetRepositoryRoot();
79
79
 
80
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/errors.js
81
+ const OPERATIONAL_CODES = new Set([
82
+ "helper-failed",
83
+ "helper-unavailable",
84
+ "permission-unverified",
85
+ "timeout",
86
+ "unsupported-platform",
87
+ ]);
88
+ function categorizeFsSafeError(code) {
89
+ return OPERATIONAL_CODES.has(code) ? "operational" : "policy";
90
+ }
91
+ class errors_FsSafeError extends Error {
92
+ code;
93
+ category;
94
+ constructor(code, message, options = {}) {
95
+ super(message, options);
96
+ this.name = "FsSafeError";
97
+ this.code = code;
98
+ this.category = categorizeFsSafeError(code);
99
+ }
100
+ }
101
+
102
+ ;// CONCATENATED MODULE: external "node:fs"
103
+ const external_node_fs_namespaceObject = __rspack_createRequire_require("node:fs");
104
+ ;// CONCATENATED MODULE: external "node:stream/promises"
105
+ const external_node_stream_promises_namespaceObject = __rspack_createRequire_require("node:stream/promises");
106
+ ;// CONCATENATED MODULE: external "node:stream"
107
+ const external_node_stream_namespaceObject = __rspack_createRequire_require("node:stream");
108
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/bounded-read-stream.js
109
+
110
+
111
+ function createMaxBytesTransform(maxBytes) {
112
+ let bytes = 0;
113
+ return new external_node_stream_namespaceObject.Transform({
114
+ transform(chunk, _encoding, callback) {
115
+ const buffer = chunk instanceof Buffer ? chunk : Buffer.from(chunk);
116
+ bytes += buffer.byteLength;
117
+ if (bytes > maxBytes) {
118
+ callback(new errors_FsSafeError("too-large", `file exceeds limit of ${maxBytes} bytes (got at least ${bytes})`));
119
+ return;
120
+ }
121
+ callback(null, buffer);
122
+ },
123
+ });
124
+ }
125
+ function createBoundedReadStream(opened, maxBytes) {
126
+ const stream = opened.handle.createReadStream();
127
+ return maxBytes === undefined ? stream : stream.pipe(createMaxBytesTransform(maxBytes));
128
+ }
129
+
130
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/file-identity.js
131
+ function isZero(value) {
132
+ return value === 0 || value === 0n;
133
+ }
134
+ function file_identity_sameFileIdentity(left, right, platform = process.platform) {
135
+ if (left.ino !== right.ino) {
136
+ return false;
137
+ }
138
+ // On Windows, path-based stat calls can report dev=0 while fd-based stat
139
+ // reports a real volume serial; treat either-side dev=0 as "unknown device".
140
+ if (left.dev === right.dev) {
141
+ return true;
142
+ }
143
+ return platform === "win32" && (isZero(left.dev) || isZero(right.dev));
144
+ }
145
+
146
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/string-coerce.js
147
+ function readStringValue(value) {
148
+ return typeof value === "string" ? value : undefined;
149
+ }
150
+ function normalizeNullableString(value) {
151
+ if (typeof value !== "string") {
152
+ return null;
153
+ }
154
+ const trimmed = value.trim();
155
+ return trimmed ? trimmed : null;
156
+ }
157
+ function normalizeOptionalString(value) {
158
+ return normalizeNullableString(value) ?? undefined;
159
+ }
160
+ function normalizeStringifiedOptionalString(value) {
161
+ if (typeof value === "string") {
162
+ return normalizeOptionalString(value);
163
+ }
164
+ if (typeof value === "number" || typeof value === "boolean" || typeof value === "bigint") {
165
+ return normalizeOptionalString(String(value));
166
+ }
167
+ return undefined;
168
+ }
169
+ function normalizeOptionalLowercaseString(value) {
170
+ return normalizeOptionalString(value)?.toLowerCase();
171
+ }
172
+ function normalizeLowercaseStringOrEmpty(value) {
173
+ return normalizeOptionalLowercaseString(value) ?? "";
174
+ }
175
+ function normalizeFastMode(raw) {
176
+ if (typeof raw === "boolean") {
177
+ return raw;
178
+ }
179
+ if (!raw) {
180
+ return undefined;
181
+ }
182
+ const key = normalizeLowercaseStringOrEmpty(raw);
183
+ if (["off", "false", "no", "0", "disable", "disabled", "normal"].includes(key)) {
184
+ return false;
185
+ }
186
+ if (["on", "true", "yes", "1", "enable", "enabled", "fast"].includes(key)) {
187
+ return true;
188
+ }
189
+ return undefined;
190
+ }
191
+ function lowercasePreservingWhitespace(value) {
192
+ return value.toLowerCase();
193
+ }
194
+ function localeLowercasePreservingWhitespace(value) {
195
+ return value.toLocaleLowerCase();
196
+ }
197
+ function resolvePrimaryStringValue(value) {
198
+ if (typeof value === "string") {
199
+ return normalizeOptionalString(value);
200
+ }
201
+ if (!value || typeof value !== "object") {
202
+ return undefined;
203
+ }
204
+ return normalizeOptionalString(value.primary);
205
+ }
206
+ function normalizeOptionalThreadValue(value) {
207
+ if (typeof value === "number") {
208
+ return Number.isFinite(value) ? Math.trunc(value) : undefined;
209
+ }
210
+ return normalizeOptionalString(value);
211
+ }
212
+ function normalizeOptionalStringifiedId(value) {
213
+ const normalized = normalizeOptionalThreadValue(value);
214
+ return normalized == null ? undefined : String(normalized);
215
+ }
216
+ function hasNonEmptyString(value) {
217
+ return normalizeOptionalString(value) !== undefined;
218
+ }
219
+
220
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/path.js
221
+
222
+
223
+
224
+
225
+ const NOT_FOUND_CODES = new Set(["ENOENT", "ENOTDIR"]);
226
+ const SYMLINK_OPEN_CODES = new Set(["ELOOP", "EINVAL", "ENOTSUP"]);
227
+ const POSIX_SEPARATOR_CHAR_CODE = 0x2f;
228
+ function normalizeWindowsPathForComparison(input) {
229
+ let normalized = external_node_path_namespaceObject.win32.normalize(input);
230
+ if (normalized.startsWith("\\\\?\\")) {
231
+ normalized = normalized.slice(4);
232
+ if (normalized.toUpperCase().startsWith("UNC\\")) {
233
+ normalized = `\\\\${normalized.slice(4)}`;
234
+ }
235
+ }
236
+ return normalizeLowercaseStringOrEmpty(normalized.replaceAll("/", "\\"));
237
+ }
238
+ function isNodeError(value) {
239
+ return Boolean(value && typeof value === "object" && "code" in value);
240
+ }
241
+ function hasNodeErrorCode(value, code) {
242
+ return isNodeError(value) && value.code === code;
243
+ }
244
+ function path_assertNoNulPathInput(filePath, message = "path contains a NUL byte") {
245
+ if (filePath.includes("\0")) {
246
+ throw new errors_FsSafeError("invalid-path", message);
247
+ }
248
+ }
249
+ function path_isNotFoundPathError(value) {
250
+ return isNodeError(value) && typeof value.code === "string" && NOT_FOUND_CODES.has(value.code);
251
+ }
252
+ function isSymlinkOpenError(value) {
253
+ return isNodeError(value) && typeof value.code === "string" && SYMLINK_OPEN_CODES.has(value.code);
254
+ }
255
+ function path_isPathInside(root, target) {
256
+ if (process.platform === "win32") {
257
+ const rootForCompare = normalizeWindowsPathForComparison(external_node_path_namespaceObject.win32.resolve(root));
258
+ const targetForCompare = normalizeWindowsPathForComparison(external_node_path_namespaceObject.win32.resolve(target));
259
+ const relative = external_node_path_namespaceObject.win32.relative(rootForCompare, targetForCompare);
260
+ const firstSegment = relative.split(external_node_path_namespaceObject.win32.sep)[0];
261
+ return (relative === "" || (firstSegment !== ".." && !external_node_path_namespaceObject.win32.isAbsolute(relative)));
262
+ }
263
+ if (root.length > 0 &&
264
+ root.charCodeAt(0) === POSIX_SEPARATOR_CHAR_CODE &&
265
+ target.length >= root.length &&
266
+ target.charCodeAt(0) === POSIX_SEPARATOR_CHAR_CODE &&
267
+ !target.includes("/..") &&
268
+ (target === root ||
269
+ (target.startsWith(root) && target.charCodeAt(root.length) === POSIX_SEPARATOR_CHAR_CODE))) {
270
+ return true;
271
+ }
272
+ const resolvedRoot = external_node_path_namespaceObject.resolve(root);
273
+ const resolvedTarget = external_node_path_namespaceObject.resolve(target);
274
+ const relative = external_node_path_namespaceObject.relative(resolvedRoot, resolvedTarget);
275
+ const firstSegment = relative.split(external_node_path_namespaceObject.posix.sep)[0];
276
+ return relative === "" || (firstSegment !== ".." && !external_node_path_namespaceObject.isAbsolute(relative));
277
+ }
278
+ function resolveSafeBaseDir(rootDir) {
279
+ const resolved = path.resolve(rootDir);
280
+ return resolved.endsWith(path.sep) ? resolved : `${resolved}${path.sep}`;
281
+ }
282
+ function isWithinDir(rootDir, targetPath) {
283
+ return path_isPathInside(rootDir, targetPath);
284
+ }
285
+ function safeRealpathSync(targetPath, cache) {
286
+ const cached = cache?.get(targetPath);
287
+ if (cached) {
288
+ return cached;
289
+ }
290
+ try {
291
+ const resolved = fs.realpathSync(targetPath);
292
+ cache?.set(targetPath, resolved);
293
+ cache?.set(resolved, resolved);
294
+ return resolved;
295
+ }
296
+ catch {
297
+ return null;
298
+ }
299
+ }
300
+ function isPathInsideWithRealpath(basePath, candidatePath, opts) {
301
+ if (!path_isPathInside(basePath, candidatePath)) {
302
+ return false;
303
+ }
304
+ const baseReal = safeRealpathSync(basePath, opts?.cache);
305
+ const candidateReal = safeRealpathSync(candidatePath, opts?.cache);
306
+ if (!baseReal || !candidateReal) {
307
+ return opts?.requireRealpath === false;
308
+ }
309
+ return path_isPathInside(baseReal, candidateReal);
310
+ }
311
+ function safeStatSync(targetPath) {
312
+ try {
313
+ return fs.statSync(targetPath);
314
+ }
315
+ catch {
316
+ return null;
317
+ }
318
+ }
319
+ function splitSafeRelativePath(relativePath) {
320
+ if (relativePath.length === 0 || relativePath === ".") {
321
+ return [];
322
+ }
323
+ path_assertNoNulPathInput(relativePath, "relative path contains a NUL byte");
324
+ if (relativePath.includes("\\")) {
325
+ throw new FsSafeError("invalid-path", "relative path must use forward slashes");
326
+ }
327
+ if (path.posix.isAbsolute(relativePath) ||
328
+ path.win32.isAbsolute(relativePath) ||
329
+ relativePath.startsWith("//")) {
330
+ throw new FsSafeError("invalid-path", "relative path must not be absolute");
331
+ }
332
+ const segments = relativePath.split("/").filter((segment) => segment.length > 0 && segment !== ".");
333
+ for (const segment of segments) {
334
+ if (segment === "..") {
335
+ throw new FsSafeError("invalid-path", "relative path must not contain '..'");
336
+ }
337
+ }
338
+ return segments;
339
+ }
340
+ function resolveSafeRelativePath(rootDir, relativePath) {
341
+ const root = path.resolve(rootDir);
342
+ const target = path.resolve(root, ...splitSafeRelativePath(relativePath));
343
+ if (target !== root && !target.startsWith(root + path.sep)) {
344
+ throw new FsSafeError("outside-workspace", "relative path escapes root");
345
+ }
346
+ return target;
347
+ }
348
+
349
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/directory-guard.js
350
+
351
+
352
+
353
+
354
+
355
+
356
+ async function directory_guard_createAsyncDirectoryGuard(dir) {
357
+ const stat = await promises_namespaceObject.lstat(dir);
358
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
359
+ throw new errors_FsSafeError("not-file", "directory component must be a directory");
360
+ }
361
+ return { dir, realPath: await promises_namespaceObject.realpath(dir), stat };
362
+ }
363
+ async function assertAsyncDirectoryGuard(guard) {
364
+ const stat = await promises_namespaceObject.lstat(guard.dir);
365
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
366
+ throw new errors_FsSafeError("not-file", "directory component must be a directory");
367
+ }
368
+ if (!file_identity_sameFileIdentity(stat, guard.stat) || (await promises_namespaceObject.realpath(guard.dir)) !== guard.realPath) {
369
+ throw new errors_FsSafeError("path-mismatch", "directory changed during operation");
370
+ }
371
+ }
372
+ function directory_guard_createSyncDirectoryGuard(dir) {
373
+ const stat = fsSync.lstatSync(dir);
374
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
375
+ throw new FsSafeError("not-file", "directory component must be a directory");
376
+ }
377
+ return { dir, realPath: fsSync.realpathSync(dir), stat };
378
+ }
379
+ function directory_guard_assertSyncDirectoryGuard(guard) {
380
+ const stat = fsSync.lstatSync(guard.dir);
381
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
382
+ throw new FsSafeError("not-file", "directory component must be a directory");
383
+ }
384
+ if (!sameFileIdentity(stat, guard.stat) || fsSync.realpathSync(guard.dir) !== guard.realPath) {
385
+ throw new FsSafeError("path-mismatch", "directory changed during operation");
386
+ }
387
+ }
388
+ async function directory_guard_createNearestExistingDirectoryGuard(rootReal, targetPath) {
389
+ let current = external_node_path_namespaceObject.resolve(targetPath);
390
+ const root = external_node_path_namespaceObject.resolve(rootReal);
391
+ while (current !== root) {
392
+ try {
393
+ return await directory_guard_createAsyncDirectoryGuard(current);
394
+ }
395
+ catch (error) {
396
+ if (!path_isNotFoundPathError(error)) {
397
+ throw error;
398
+ }
399
+ current = external_node_path_namespaceObject.dirname(current);
400
+ }
401
+ }
402
+ return await directory_guard_createAsyncDirectoryGuard(root);
403
+ }
404
+ function directory_guard_createNearestExistingSyncDirectoryGuard(rootReal, targetPath) {
405
+ let current = path.resolve(targetPath);
406
+ const root = path.resolve(rootReal);
407
+ while (current !== root) {
408
+ try {
409
+ return directory_guard_createSyncDirectoryGuard(current);
410
+ }
411
+ catch (error) {
412
+ if (!isNotFoundPathError(error)) {
413
+ throw error;
414
+ }
415
+ current = path.dirname(current);
416
+ }
417
+ }
418
+ return directory_guard_createSyncDirectoryGuard(root);
419
+ }
420
+
421
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/guarded-mkdir.js
422
+
423
+
424
+
425
+
426
+ function isSameOrChildPath(candidate, parent) {
427
+ return candidate === parent || candidate.startsWith(`${parent}${external_node_path_namespaceObject.sep}`);
428
+ }
429
+ function isPathEscape(relativePath) {
430
+ return relativePath === ".." || relativePath.startsWith(`..${external_node_path_namespaceObject.sep}`) || external_node_path_namespaceObject.isAbsolute(relativePath);
431
+ }
432
+ async function mkdirPathComponentsWithGuards(params) {
433
+ const root = external_node_path_namespaceObject.resolve(params.rootReal);
434
+ const target = external_node_path_namespaceObject.resolve(params.targetPath);
435
+ const relative = external_node_path_namespaceObject.relative(root, target);
436
+ if (isPathEscape(relative)) {
437
+ throw new errors_FsSafeError("outside-workspace", "directory is outside workspace root");
438
+ }
439
+ let current = root;
440
+ for (const part of relative.split(external_node_path_namespaceObject.sep).filter(Boolean)) {
441
+ const next = external_node_path_namespaceObject.join(current, part);
442
+ const parentGuard = await directory_guard_createAsyncDirectoryGuard(current);
443
+ await params.beforeComponent?.(next);
444
+ await assertAsyncDirectoryGuard(parentGuard);
445
+ try {
446
+ await promises_namespaceObject.mkdir(next);
447
+ }
448
+ catch (error) {
449
+ if (!error || typeof error !== "object" || !("code" in error) || error.code !== "EEXIST") {
450
+ throw error;
451
+ }
452
+ }
453
+ const stat = await promises_namespaceObject.lstat(next);
454
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
455
+ throw new errors_FsSafeError("not-file", "directory component must be a directory");
456
+ }
457
+ // Node's recursive mkdir follows symlinks in missing components. Build one
458
+ // segment at a time and realpath-check each segment before descending.
459
+ if (!isSameOrChildPath(external_node_path_namespaceObject.resolve(await promises_namespaceObject.realpath(next)), root)) {
460
+ throw new errors_FsSafeError("outside-workspace", "directory escaped workspace root");
461
+ }
462
+ await directory_guard_createAsyncDirectoryGuard(next);
463
+ await assertAsyncDirectoryGuard(parentGuard);
464
+ current = next;
465
+ }
466
+ }
467
+
468
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/guarded-mutation.js
469
+
470
+
471
+
472
+
473
+ async function withAsyncDirectoryGuards(guards, mutate, options = {}) {
474
+ for (const guard of guards) {
475
+ await assertAsyncDirectoryGuard(guard);
476
+ }
477
+ const result = await mutate();
478
+ if (options.verifyAfter !== false) {
479
+ try {
480
+ for (const guard of guards) {
481
+ await assertAsyncDirectoryGuard(guard);
482
+ }
483
+ }
484
+ catch (error) {
485
+ if (options.onPostGuardFailure) {
486
+ try {
487
+ // The mutation may have returned an owned resource before the post-guard
488
+ // check detected a swapped directory. Give callers one chance to close
489
+ // handles without letting cleanup hide the boundary failure.
490
+ await options.onPostGuardFailure(result, error);
491
+ }
492
+ catch {
493
+ // Preserve the boundary failure. Cleanup is best-effort.
494
+ }
495
+ }
496
+ throw error;
497
+ }
498
+ }
499
+ return result;
500
+ }
501
+ function withSyncDirectoryGuards(guards, mutate, options = {}) {
502
+ for (const guard of guards) {
503
+ assertSyncDirectoryGuard(guard);
504
+ }
505
+ const result = mutate();
506
+ if (options.verifyAfter !== false) {
507
+ for (const guard of guards) {
508
+ assertSyncDirectoryGuard(guard);
509
+ }
510
+ }
511
+ return result;
512
+ }
513
+ async function guardedRename(params) {
514
+ const sourceGuard = await createAsyncDirectoryGuard(path.dirname(params.from));
515
+ const targetGuard = params.targetRoot
516
+ ? await createNearestExistingDirectoryGuard(params.targetRoot, path.dirname(params.to))
517
+ : await createAsyncDirectoryGuard(path.dirname(params.to));
518
+ await withAsyncDirectoryGuards([sourceGuard, targetGuard], async () => {
519
+ await fs.rename(params.from, params.to);
520
+ }, { verifyAfter: params.verifyAfter });
521
+ }
522
+ function guardedRenameSync(params) {
523
+ const sourceGuard = createSyncDirectoryGuard(path.dirname(params.from));
524
+ const targetGuard = params.targetRoot
525
+ ? createNearestExistingSyncDirectoryGuard(params.targetRoot, path.dirname(params.to))
526
+ : createSyncDirectoryGuard(path.dirname(params.to));
527
+ withSyncDirectoryGuards([sourceGuard, targetGuard], () => fsSync.renameSync(params.from, params.to), { verifyAfter: params.verifyAfter });
528
+ }
529
+ async function guardedRm(params) {
530
+ const guard = await createAsyncDirectoryGuard(path.dirname(params.target));
531
+ await withAsyncDirectoryGuards([guard], async () => {
532
+ await fs.rm(params.target, {
533
+ ...(params.recursive !== undefined ? { recursive: params.recursive } : {}),
534
+ ...(params.force !== undefined ? { force: params.force } : {}),
535
+ });
536
+ }, { verifyAfter: params.verifyAfter });
537
+ }
538
+ function guardedRmSync(params) {
539
+ const guard = createSyncDirectoryGuard(path.dirname(params.target));
540
+ withSyncDirectoryGuards([guard], () => fsSync.rmSync(params.target, {
541
+ ...(params.recursive !== undefined ? { recursive: params.recursive } : {}),
542
+ ...(params.force !== undefined ? { force: params.force } : {}),
543
+ }), { verifyAfter: params.verifyAfter });
544
+ }
545
+
546
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/pinned-python-config.js
547
+ let overrideConfig = {};
548
+ function parseMode(value) {
549
+ if (!value) {
550
+ return undefined;
551
+ }
552
+ const normalized = value.trim().toLowerCase();
553
+ if (normalized === "0" || normalized === "false" || normalized === "off" || normalized === "never") {
554
+ return "off";
555
+ }
556
+ if (normalized === "1" || normalized === "true" || normalized === "on" || normalized === "auto") {
557
+ return "auto";
558
+ }
559
+ if (normalized === "required" || normalized === "require") {
560
+ return "require";
561
+ }
562
+ return undefined;
563
+ }
564
+ function configureFsSafePython(config) {
565
+ overrideConfig = { ...overrideConfig, ...config };
566
+ }
567
+ function getFsSafePythonConfig() {
568
+ return {
569
+ mode: overrideConfig.mode ??
570
+ parseMode(process.env.FS_SAFE_PYTHON_MODE) ??
571
+ parseMode(process.env.OPENCLAW_FS_SAFE_PYTHON_MODE) ??
572
+ "auto",
573
+ pythonPath: overrideConfig.pythonPath ??
574
+ process.env.FS_SAFE_PYTHON ??
575
+ process.env.OPENCLAW_FS_SAFE_PYTHON ??
576
+ process.env.OPENCLAW_PINNED_PYTHON ??
577
+ process.env.OPENCLAW_PINNED_WRITE_PYTHON,
578
+ };
579
+ }
580
+ function canFallbackFromPythonError(error) {
581
+ const code = error instanceof Error && "code" in error ? error.code : undefined;
582
+ return (getFsSafePythonConfig().mode !== "require" &&
583
+ (code === "helper-unavailable" || code === "unsupported-platform"));
584
+ }
585
+
586
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/pinned-python.js
587
+
588
+
589
+
590
+
591
+ const PINNED_PYTHON_WORKER_SOURCE = String.raw `
592
+ import base64
593
+ import errno
594
+ import json
595
+ import os
596
+ import secrets
597
+ import stat
598
+ import sys
599
+
600
+ DIR_FLAGS = os.O_RDONLY
601
+ if hasattr(os, "O_DIRECTORY"):
602
+ DIR_FLAGS |= os.O_DIRECTORY
603
+ if hasattr(os, "O_NOFOLLOW"):
604
+ DIR_FLAGS |= os.O_NOFOLLOW
605
+ READ_FLAGS = os.O_RDONLY
606
+ if hasattr(os, "O_NOFOLLOW"):
607
+ READ_FLAGS |= os.O_NOFOLLOW
608
+ WRITE_FLAGS = os.O_WRONLY | os.O_CREAT | os.O_EXCL
609
+ if hasattr(os, "O_NOFOLLOW"):
610
+ WRITE_FLAGS |= os.O_NOFOLLOW
611
+
612
+ def split_relative(value):
613
+ if value in ("", "."):
614
+ return []
615
+ if "\x00" in value or value.startswith("/") or value.startswith("//"):
616
+ raise OSError(errno.EPERM, "invalid relative path")
617
+ if value.startswith("..\\"):
618
+ raise OSError(errno.EPERM, "path traversal is not allowed")
619
+ parts = [part for part in value.split("/") if part and part != "."]
620
+ for part in parts:
621
+ if part == "..":
622
+ raise OSError(errno.EPERM, "path traversal is not allowed")
623
+ return parts
624
+
625
+ def open_dir(path_value, dir_fd=None):
626
+ return os.open(path_value, DIR_FLAGS, dir_fd=dir_fd)
627
+
628
+ def walk_dir(root_fd, segments, mkdir_enabled=False):
629
+ current_fd = os.dup(root_fd)
630
+ try:
631
+ for segment in segments:
632
+ try:
633
+ next_fd = open_dir(segment, dir_fd=current_fd)
634
+ except FileNotFoundError:
635
+ if not mkdir_enabled:
636
+ raise
637
+ os.mkdir(segment, 0o777, dir_fd=current_fd)
638
+ next_fd = open_dir(segment, dir_fd=current_fd)
639
+ os.close(current_fd)
640
+ current_fd = next_fd
641
+ return current_fd
642
+ except Exception:
643
+ os.close(current_fd)
644
+ raise
645
+
646
+ def parent_and_basename(root_fd, relative):
647
+ segments = split_relative(relative)
648
+ if not segments:
649
+ raise OSError(errno.EPERM, "operation requires a non-root path")
650
+ parent_fd = walk_dir(root_fd, segments[:-1])
651
+ return parent_fd, segments[-1]
652
+
653
+ def encode_stat(st):
654
+ mode = st.st_mode
655
+ return {
656
+ "dev": st.st_dev,
657
+ "gid": st.st_gid,
658
+ "ino": st.st_ino,
659
+ "isDirectory": stat.S_ISDIR(mode),
660
+ "isFile": stat.S_ISREG(mode),
661
+ "isSymbolicLink": stat.S_ISLNK(mode),
662
+ "mode": mode,
663
+ "mtimeMs": st.st_mtime * 1000,
664
+ "nlink": st.st_nlink,
665
+ "size": st.st_size,
666
+ "uid": st.st_uid,
667
+ }
668
+
669
+ def reject_unsafe_endpoint(st):
670
+ mode = st.st_mode
671
+ if stat.S_ISLNK(mode):
672
+ raise OSError(errno.ELOOP, "symlink endpoint is not allowed")
673
+ if stat.S_ISREG(mode) and st.st_nlink > 1:
674
+ raise OSError(errno.EPERM, "hardlinked file endpoint is not allowed")
675
+
676
+ def stat_path(root_fd, payload):
677
+ relative = payload.get("relativePath", "")
678
+ segments = split_relative(relative)
679
+ if not segments:
680
+ return encode_stat(os.fstat(root_fd))
681
+ parent_fd, basename = parent_and_basename(root_fd, relative)
682
+ try:
683
+ st = os.lstat(basename, dir_fd=parent_fd)
684
+ if payload.get("rejectSymlink", True) and stat.S_ISLNK(st.st_mode):
685
+ raise OSError(errno.ELOOP, "symlink endpoint is not allowed")
686
+ return encode_stat(st)
687
+ finally:
688
+ os.close(parent_fd)
689
+
690
+ def readdir_path(root_fd, payload):
691
+ dir_fd = walk_dir(root_fd, split_relative(payload.get("relativePath", "")))
692
+ try:
693
+ names = sorted(os.listdir(dir_fd))
694
+ if not payload.get("withFileTypes", False):
695
+ return names
696
+ entries = []
697
+ for name in names:
698
+ st = os.lstat(name, dir_fd=dir_fd)
699
+ entry = encode_stat(st)
700
+ entry["name"] = name
701
+ entries.append(entry)
702
+ return entries
703
+ finally:
704
+ os.close(dir_fd)
705
+
706
+ def mkdirp_path(root_fd, payload):
707
+ dir_fd = walk_dir(root_fd, split_relative(payload.get("relativePath", "")), mkdir_enabled=True)
708
+ os.close(dir_fd)
709
+ return None
710
+
711
+ def remove_tree(parent_fd, basename):
712
+ st = os.lstat(basename, dir_fd=parent_fd)
713
+ if stat.S_ISDIR(st.st_mode) and not stat.S_ISLNK(st.st_mode):
714
+ dir_fd = open_dir(basename, dir_fd=parent_fd)
715
+ try:
716
+ for child in os.listdir(dir_fd):
717
+ remove_tree(dir_fd, child)
718
+ finally:
719
+ os.close(dir_fd)
720
+ os.rmdir(basename, dir_fd=parent_fd)
721
+ else:
722
+ os.unlink(basename, dir_fd=parent_fd)
723
+
724
+ def remove_path(root_fd, payload):
725
+ parent_fd, basename = parent_and_basename(root_fd, payload.get("relativePath", ""))
726
+ try:
727
+ try:
728
+ st = os.lstat(basename, dir_fd=parent_fd)
729
+ except FileNotFoundError:
730
+ if payload.get("force", True):
731
+ return None
732
+ raise
733
+ if stat.S_ISDIR(st.st_mode) and not stat.S_ISLNK(st.st_mode):
734
+ if payload.get("recursive", False):
735
+ remove_tree(parent_fd, basename)
736
+ else:
737
+ os.rmdir(basename, dir_fd=parent_fd)
738
+ else:
739
+ os.unlink(basename, dir_fd=parent_fd)
740
+ return None
741
+ finally:
742
+ os.close(parent_fd)
743
+
744
+ def rename_path(root_fd, payload):
745
+ from_parent_fd, from_base = parent_and_basename(root_fd, payload["from"])
746
+ to_parent_fd, to_base = parent_and_basename(root_fd, payload["to"])
747
+ try:
748
+ from_stat = os.lstat(from_base, dir_fd=from_parent_fd)
749
+ reject_unsafe_endpoint(from_stat)
750
+ if not payload.get("overwrite", True):
751
+ try:
752
+ os.lstat(to_base, dir_fd=to_parent_fd)
753
+ raise FileExistsError(errno.EEXIST, "destination exists", to_base)
754
+ except FileNotFoundError:
755
+ pass
756
+ os.rename(from_base, to_base, src_dir_fd=from_parent_fd, dst_dir_fd=to_parent_fd)
757
+ os.fsync(from_parent_fd)
758
+ if from_parent_fd != to_parent_fd:
759
+ os.fsync(to_parent_fd)
760
+ return None
761
+ finally:
762
+ os.close(from_parent_fd)
763
+ os.close(to_parent_fd)
764
+
765
+ def create_temp_file(parent_fd, basename, mode):
766
+ prefix = "." + basename + "."
767
+ for _ in range(128):
768
+ candidate = prefix + secrets.token_hex(6) + ".tmp"
769
+ try:
770
+ fd = os.open(candidate, WRITE_FLAGS, mode, dir_fd=parent_fd)
771
+ return candidate, fd
772
+ except FileExistsError:
773
+ continue
774
+ raise RuntimeError("failed to allocate pinned temp file")
775
+
776
+ def write_path(root_fd, payload):
777
+ parent_fd = walk_dir(root_fd, split_relative(payload.get("relativeParentPath", "")), bool(payload.get("mkdir", True)))
778
+ temp_fd = None
779
+ temp_name = None
780
+ basename = payload["basename"]
781
+ mode = int(payload.get("mode", 0o600))
782
+ overwrite = bool(payload.get("overwrite", True))
783
+ max_bytes = int(payload.get("maxBytes", -1))
784
+ data = base64.b64decode(payload.get("base64", ""))
785
+ try:
786
+ if max_bytes >= 0 and len(data) > max_bytes:
787
+ raise RuntimeError("fs-safe-too-large:%d:%d" % (max_bytes, len(data)))
788
+ if not overwrite:
789
+ try:
790
+ os.lstat(basename, dir_fd=parent_fd)
791
+ raise FileExistsError(errno.EEXIST, "destination exists", basename)
792
+ except FileNotFoundError:
793
+ pass
794
+ temp_name, temp_fd = create_temp_file(parent_fd, basename, mode)
795
+ view = memoryview(data)
796
+ while view:
797
+ written = os.write(temp_fd, view)
798
+ if written <= 0:
799
+ raise OSError(errno.EIO, "short write")
800
+ view = view[written:]
801
+ os.fsync(temp_fd)
802
+ os.close(temp_fd)
803
+ temp_fd = None
804
+ os.replace(temp_name, basename, src_dir_fd=parent_fd, dst_dir_fd=parent_fd)
805
+ temp_name = None
806
+ os.fsync(parent_fd)
807
+ result_stat = os.stat(basename, dir_fd=parent_fd, follow_symlinks=False)
808
+ return {"dev": result_stat.st_dev, "ino": result_stat.st_ino}
809
+ finally:
810
+ if temp_fd is not None:
811
+ os.close(temp_fd)
812
+ if temp_name is not None:
813
+ try:
814
+ os.unlink(temp_name, dir_fd=parent_fd)
815
+ except FileNotFoundError:
816
+ pass
817
+ os.close(parent_fd)
818
+
819
+ def copy_path(root_fd, payload):
820
+ source_fd = os.open(payload["sourcePath"], READ_FLAGS)
821
+ parent_fd = None
822
+ temp_fd = None
823
+ temp_name = None
824
+ try:
825
+ source_stat = os.fstat(source_fd)
826
+ if not stat.S_ISREG(source_stat.st_mode):
827
+ raise RuntimeError("fs-safe-not-file")
828
+ if source_stat.st_dev != int(payload["sourceDev"]) or source_stat.st_ino != int(payload["sourceIno"]):
829
+ raise RuntimeError("fs-safe-source-mismatch")
830
+ basename = payload["basename"]
831
+ mode = int(payload.get("mode", 0o600))
832
+ overwrite = bool(payload.get("overwrite", True))
833
+ max_bytes = int(payload.get("maxBytes", -1))
834
+ if max_bytes >= 0 and source_stat.st_size > max_bytes:
835
+ raise RuntimeError("fs-safe-too-large:%d:%d" % (max_bytes, source_stat.st_size))
836
+ parent_fd = walk_dir(root_fd, split_relative(payload.get("relativeParentPath", "")), bool(payload.get("mkdir", True)))
837
+ if not overwrite:
838
+ try:
839
+ os.lstat(basename, dir_fd=parent_fd)
840
+ raise FileExistsError(errno.EEXIST, "destination exists", basename)
841
+ except FileNotFoundError:
842
+ pass
843
+ temp_name, temp_fd = create_temp_file(parent_fd, basename, mode)
844
+ written_bytes = 0
845
+ while True:
846
+ chunk = os.read(source_fd, 65536)
847
+ if not chunk:
848
+ break
849
+ written_bytes += len(chunk)
850
+ if max_bytes >= 0 and written_bytes > max_bytes:
851
+ raise RuntimeError("fs-safe-too-large:%d:%d" % (max_bytes, written_bytes))
852
+ view = memoryview(chunk)
853
+ while view:
854
+ written = os.write(temp_fd, view)
855
+ if written <= 0:
856
+ raise OSError(errno.EIO, "short write")
857
+ view = view[written:]
858
+ os.fsync(temp_fd)
859
+ os.close(temp_fd)
860
+ temp_fd = None
861
+ os.replace(temp_name, basename, src_dir_fd=parent_fd, dst_dir_fd=parent_fd)
862
+ temp_name = None
863
+ os.fsync(parent_fd)
864
+ result_stat = os.stat(basename, dir_fd=parent_fd, follow_symlinks=False)
865
+ return {"dev": result_stat.st_dev, "ino": result_stat.st_ino}
866
+ finally:
867
+ os.close(source_fd)
868
+ if temp_fd is not None:
869
+ os.close(temp_fd)
870
+ if temp_name is not None and parent_fd is not None:
871
+ try:
872
+ os.unlink(temp_name, dir_fd=parent_fd)
873
+ except FileNotFoundError:
874
+ pass
875
+ if parent_fd is not None:
876
+ os.close(parent_fd)
877
+
878
+ def run_operation(operation, root_path, payload):
879
+ root_fd = open_dir(root_path)
880
+ try:
881
+ if operation == "stat":
882
+ return stat_path(root_fd, payload)
883
+ if operation == "readdir":
884
+ return readdir_path(root_fd, payload)
885
+ if operation == "mkdirp":
886
+ return mkdirp_path(root_fd, payload)
887
+ if operation == "remove":
888
+ return remove_path(root_fd, payload)
889
+ if operation == "rename":
890
+ return rename_path(root_fd, payload)
891
+ if operation == "write":
892
+ return write_path(root_fd, payload)
893
+ if operation == "copy":
894
+ return copy_path(root_fd, payload)
895
+ raise RuntimeError("unknown operation: " + operation)
896
+ finally:
897
+ os.close(root_fd)
898
+
899
+ for line in sys.stdin:
900
+ try:
901
+ request = json.loads(line)
902
+ result = run_operation(request["operation"], request["rootPath"], request.get("payload") or {})
903
+ response = {"id": request["id"], "ok": True, "result": result}
904
+ except Exception as exc:
905
+ response = {
906
+ "id": request.get("id") if isinstance(locals().get("request"), dict) else None,
907
+ "ok": False,
908
+ "code": exc.__class__.__name__,
909
+ "errno": getattr(exc, "errno", None),
910
+ "message": str(exc),
911
+ }
912
+ print(json.dumps(response, separators=(",", ":")), flush=True)
913
+ `;
914
+ let nextRequestId = 1;
915
+ let worker = null;
916
+ function __resetPinnedPythonWorkerForTest() {
917
+ const currentWorker = worker;
918
+ worker = null;
919
+ if (!currentWorker) {
920
+ return;
921
+ }
922
+ currentWorker.pending.clear();
923
+ currentWorker.child.kill("SIGTERM");
924
+ }
925
+ const PYTHON_CANDIDATE_DEFAULTS = [
926
+ "/usr/bin/python3",
927
+ "/opt/homebrew/bin/python3",
928
+ "/usr/local/bin/python3",
929
+ ];
930
+ function canExecute(binPath) {
931
+ try {
932
+ external_node_fs_namespaceObject.accessSync(binPath, external_node_fs_namespaceObject.constants.X_OK);
933
+ return true;
934
+ }
935
+ catch {
936
+ return false;
937
+ }
938
+ }
939
+ function resolvePython() {
940
+ const configured = getFsSafePythonConfig().pythonPath;
941
+ if (configured) {
942
+ return configured;
943
+ }
944
+ for (const candidate of PYTHON_CANDIDATE_DEFAULTS) {
945
+ if (canExecute(candidate)) {
946
+ return candidate;
947
+ }
948
+ }
949
+ return "python3";
950
+ }
951
+ function assertPinnedHelperSupported() {
952
+ if (process.platform === "win32") {
953
+ throw new errors_FsSafeError("unsupported-platform", "fd-relative pinned filesystem operations are not available on Windows");
954
+ }
955
+ if (getFsSafePythonConfig().mode === "off") {
956
+ throw new errors_FsSafeError("helper-unavailable", "Python helper is disabled");
957
+ }
958
+ }
959
+ function isSpawnUnavailable(error) {
960
+ if (!(error instanceof Error)) {
961
+ return false;
962
+ }
963
+ const maybeErrno = error;
964
+ return (typeof maybeErrno.syscall === "string" &&
965
+ maybeErrno.syscall.startsWith("spawn") &&
966
+ ["EACCES", "ENOENT", "ENOEXEC"].includes(maybeErrno.code ?? ""));
967
+ }
968
+ function mapWorkerError(response) {
969
+ const code = typeof response.code === "string" ? response.code : "";
970
+ const errno = typeof response.errno === "number" ? response.errno : undefined;
971
+ const message = typeof response.message === "string" && response.message
972
+ ? response.message
973
+ : "pinned helper failed";
974
+ const tooLarge = message.match(/fs-safe-too-large:(\d+):(\d+)/);
975
+ if (tooLarge) {
976
+ const [, limit, got] = tooLarge;
977
+ return new errors_FsSafeError("too-large", `file exceeds limit of ${limit} bytes (got at least ${got})`);
978
+ }
979
+ if (message.includes("fs-safe-not-file")) {
980
+ return new errors_FsSafeError("not-file", "not a file");
981
+ }
982
+ if (message.includes("fs-safe-source-mismatch")) {
983
+ return new errors_FsSafeError("path-mismatch", "source path changed during copy");
984
+ }
985
+ if (code === "FileNotFoundError" || errno === 2) {
986
+ return new errors_FsSafeError("not-found", "file not found");
987
+ }
988
+ if (code === "FileExistsError" || errno === 17) {
989
+ return new errors_FsSafeError("already-exists", message);
990
+ }
991
+ if (errno === 39) {
992
+ return new errors_FsSafeError("not-empty", "directory is not empty");
993
+ }
994
+ if (errno === 1 || errno === 13 || errno === 21) {
995
+ return new errors_FsSafeError("not-removable", "path is not removable under root");
996
+ }
997
+ if (code === "NotADirectoryError" || code === "OSError" || errno === 20 || errno === 40) {
998
+ return new errors_FsSafeError("path-alias", message);
999
+ }
1000
+ return new errors_FsSafeError("helper-failed", message);
1001
+ }
1002
+ function rejectPending(error) {
1003
+ if (!worker) {
1004
+ return;
1005
+ }
1006
+ setWorkerRef(worker, false);
1007
+ for (const pending of worker.pending.values()) {
1008
+ pending.reject(error);
1009
+ }
1010
+ worker.pending.clear();
1011
+ worker = null;
1012
+ }
1013
+ function handleWorkerLine(line) {
1014
+ if (!worker || !line.trim()) {
1015
+ return;
1016
+ }
1017
+ let decoded;
1018
+ try {
1019
+ decoded = JSON.parse(line);
1020
+ }
1021
+ catch {
1022
+ rejectPending(new errors_FsSafeError("helper-failed", `pinned helper returned invalid JSON: ${line}`));
1023
+ return;
1024
+ }
1025
+ if (typeof decoded !== "object" || decoded === null || !("id" in decoded)) {
1026
+ rejectPending(new errors_FsSafeError("helper-failed", "pinned helper returned invalid response"));
1027
+ return;
1028
+ }
1029
+ const response = decoded;
1030
+ const id = typeof response.id === "number" ? response.id : undefined;
1031
+ if (id === undefined) {
1032
+ return;
1033
+ }
1034
+ const pending = worker.pending.get(id);
1035
+ if (!pending) {
1036
+ return;
1037
+ }
1038
+ worker.pending.delete(id);
1039
+ if (worker.pending.size === 0) {
1040
+ setWorkerRef(worker, false);
1041
+ }
1042
+ if (response.ok === true) {
1043
+ pending.resolve(response.result);
1044
+ return;
1045
+ }
1046
+ pending.reject(mapWorkerError(decoded));
1047
+ }
1048
+ function getWorker() {
1049
+ assertPinnedHelperSupported();
1050
+ if (worker) {
1051
+ return worker;
1052
+ }
1053
+ const child = (0,external_node_child_process_namespaceObject.spawn)(resolvePython(), ["-u", "-c", PINNED_PYTHON_WORKER_SOURCE], {
1054
+ stdio: ["pipe", "pipe", "pipe"],
1055
+ });
1056
+ worker = { child, pending: new Map(), stderr: "", stdoutBuffer: "" };
1057
+ child.stdout.setEncoding("utf8");
1058
+ child.stderr.setEncoding("utf8");
1059
+ child.stdout.on("data", (chunk) => {
1060
+ const current = worker;
1061
+ if (!current) {
1062
+ return;
1063
+ }
1064
+ current.stdoutBuffer += chunk;
1065
+ for (;;) {
1066
+ const newline = current.stdoutBuffer.indexOf("\n");
1067
+ if (newline < 0) {
1068
+ break;
1069
+ }
1070
+ const line = current.stdoutBuffer.slice(0, newline);
1071
+ current.stdoutBuffer = current.stdoutBuffer.slice(newline + 1);
1072
+ handleWorkerLine(line);
1073
+ }
1074
+ });
1075
+ child.stderr.on("data", (chunk) => {
1076
+ if (worker) {
1077
+ worker.stderr = `${worker.stderr}${chunk}`.slice(-4096);
1078
+ }
1079
+ });
1080
+ child.once("error", (error) => {
1081
+ const mapped = isSpawnUnavailable(error)
1082
+ ? new errors_FsSafeError("helper-unavailable", "Python helper is unavailable", { cause: error })
1083
+ : error instanceof Error
1084
+ ? error
1085
+ : new Error(String(error));
1086
+ rejectPending(mapped);
1087
+ });
1088
+ child.once("close", (code, signal) => {
1089
+ const stderr = worker?.stderr.trim();
1090
+ rejectPending(new errors_FsSafeError("helper-failed", stderr || `pinned helper exited with code ${code ?? "null"} (${signal ?? "?"})`));
1091
+ });
1092
+ process.once("exit", () => {
1093
+ child.kill("SIGTERM");
1094
+ });
1095
+ setWorkerRef(worker, false);
1096
+ return worker;
1097
+ }
1098
+ function setRefable(value, ref) {
1099
+ if (!value) {
1100
+ return;
1101
+ }
1102
+ const method = ref ? "ref" : "unref";
1103
+ const refable = value;
1104
+ refable[method]?.();
1105
+ }
1106
+ function setWorkerRef(currentWorker, ref) {
1107
+ setRefable(currentWorker.child, ref);
1108
+ setRefable(currentWorker.child.stdin, ref);
1109
+ setRefable(currentWorker.child.stdout, ref);
1110
+ setRefable(currentWorker.child.stderr, ref);
1111
+ }
1112
+ async function runPinnedPythonOperation(params) {
1113
+ const requestId = nextRequestId++;
1114
+ const currentWorker = getWorker();
1115
+ if (typeof currentWorker.child.stdin?.write !== "function") {
1116
+ throw new errors_FsSafeError("helper-unavailable", "Python helper stdin is unavailable");
1117
+ }
1118
+ setWorkerRef(currentWorker, true);
1119
+ return await new Promise((resolve, reject) => {
1120
+ currentWorker.pending.set(requestId, {
1121
+ reject,
1122
+ resolve: (value) => resolve(value),
1123
+ });
1124
+ const request = JSON.stringify({
1125
+ id: requestId,
1126
+ operation: params.operation,
1127
+ rootPath: params.rootPath,
1128
+ payload: params.payload,
1129
+ });
1130
+ currentWorker.child.stdin.write(`${request}\n`, (error) => {
1131
+ if (error) {
1132
+ currentWorker.pending.delete(requestId);
1133
+ if (currentWorker.pending.size === 0) {
1134
+ setWorkerRef(currentWorker, false);
1135
+ }
1136
+ reject(error);
1137
+ }
1138
+ });
1139
+ });
1140
+ }
1141
+ function assertPinnedPythonOperationAvailable() {
1142
+ const currentWorker = getWorker();
1143
+ if (typeof currentWorker.child.stdin?.write !== "function") {
1144
+ throw new errors_FsSafeError("helper-unavailable", "Python helper stdin is unavailable");
1145
+ }
1146
+ }
1147
+ function validatePinnedOperationPayload(payload) {
1148
+ if (typeof payload.relativePath === "string") {
1149
+ validatePinnedRelativePath(payload.relativePath);
1150
+ }
1151
+ if (typeof payload.relativeParentPath === "string") {
1152
+ validatePinnedRelativePath(payload.relativeParentPath);
1153
+ }
1154
+ if (typeof payload.from === "string") {
1155
+ validatePinnedRelativePath(payload.from);
1156
+ }
1157
+ if (typeof payload.to === "string") {
1158
+ validatePinnedRelativePath(payload.to);
1159
+ }
1160
+ }
1161
+ function isPinnedHelperUnavailable(error) {
1162
+ return error instanceof Error &&
1163
+ "code" in error &&
1164
+ error.code === "helper-unavailable";
1165
+ }
1166
+ function validatePinnedRelativePath(relativePath) {
1167
+ if (relativePath.length === 0 || relativePath === ".") {
1168
+ return;
1169
+ }
1170
+ if (relativePath.includes("\0")) {
1171
+ throw new errors_FsSafeError("invalid-path", "relative path contains a NUL byte");
1172
+ }
1173
+ if (relativePath.startsWith("/") ||
1174
+ relativePath.startsWith("//") ||
1175
+ relativePath === ".." ||
1176
+ relativePath.startsWith("../") ||
1177
+ relativePath.startsWith("..\\")) {
1178
+ throw new errors_FsSafeError("invalid-path", "relative path must not escape root");
1179
+ }
1180
+ for (const segment of relativePath.split("/")) {
1181
+ if (segment === "..") {
1182
+ throw new errors_FsSafeError("invalid-path", "relative path must not contain '..'");
1183
+ }
1184
+ }
1185
+ }
1186
+
1187
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/pinned-helper.js
1188
+
1189
+
1190
+ async function runPinnedHelper(operation, rootDir, payload) {
1191
+ validatePinnedOperationPayload(payload);
1192
+ return await runPinnedPythonOperation({
1193
+ operation,
1194
+ rootPath: rootDir,
1195
+ payload,
1196
+ });
1197
+ }
1198
+ async function helperStat(rootDir, relativePath) {
1199
+ return await runPinnedHelper("stat", rootDir, { relativePath });
1200
+ }
1201
+ async function helperReaddir(rootDir, relativePath, withFileTypes) {
1202
+ return await runPinnedHelper("readdir", rootDir, {
1203
+ relativePath,
1204
+ withFileTypes,
1205
+ });
1206
+ }
1207
+
1208
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/pinned-path.js
1209
+
1210
+
1211
+
1212
+ function isPinnedPathHelperSpawnError(error) {
1213
+ return canFallbackFromPythonError(error);
1214
+ }
1215
+ async function runPinnedPathHelper(params) {
1216
+ try {
1217
+ await runPinnedHelper(params.operation, params.rootPath, {
1218
+ relativePath: params.relativePath,
1219
+ });
1220
+ }
1221
+ catch (error) {
1222
+ if (error instanceof errors_FsSafeError) {
1223
+ throw error;
1224
+ }
1225
+ throw new errors_FsSafeError("helper-failed", "pinned path helper failed", {
1226
+ cause: error instanceof Error ? error : undefined,
1227
+ });
1228
+ }
1229
+ }
1230
+
1231
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/pinned-write.js
1232
+
1233
+
1234
+
1235
+
1236
+
1237
+
1238
+
1239
+
1240
+
1241
+
1242
+
1243
+ function byteLength(input, encoding) {
1244
+ return typeof input === "string"
1245
+ ? Buffer.byteLength(input, encoding ?? "utf8")
1246
+ : input.byteLength;
1247
+ }
1248
+ function assertSafeBasename(basename) {
1249
+ if (!basename ||
1250
+ basename === "." ||
1251
+ basename === ".." ||
1252
+ basename.includes("/") ||
1253
+ basename.includes("\0")) {
1254
+ throw new errors_FsSafeError("invalid-path", "invalid target path");
1255
+ }
1256
+ }
1257
+ function assertWithinMaxBytes(bytes, maxBytes) {
1258
+ if (maxBytes !== undefined && bytes > maxBytes) {
1259
+ throw new errors_FsSafeError("too-large", `file exceeds limit of ${maxBytes} bytes (got at least ${bytes})`);
1260
+ }
1261
+ }
1262
+ function pinned_write_createMaxBytesTransform(maxBytes) {
1263
+ if (maxBytes === undefined) {
1264
+ return undefined;
1265
+ }
1266
+ let bytes = 0;
1267
+ return new external_node_stream_namespaceObject.Transform({
1268
+ transform(chunk, _encoding, callback) {
1269
+ bytes += chunk.byteLength;
1270
+ if (bytes > maxBytes) {
1271
+ callback(new errors_FsSafeError("too-large", `file exceeds limit of ${maxBytes} bytes (got at least ${bytes})`));
1272
+ return;
1273
+ }
1274
+ callback(null, chunk);
1275
+ },
1276
+ });
1277
+ }
1278
+ async function pipelineWithMaxBytes(stream, destination, maxBytes) {
1279
+ const limiter = pinned_write_createMaxBytesTransform(maxBytes);
1280
+ if (limiter) {
1281
+ await (0,external_node_stream_promises_namespaceObject.pipeline)(stream, limiter, destination);
1282
+ return;
1283
+ }
1284
+ await (0,external_node_stream_promises_namespaceObject.pipeline)(stream, destination);
1285
+ }
1286
+ async function inputToBase64(input, maxBytes) {
1287
+ if (input.kind === "buffer") {
1288
+ assertWithinMaxBytes(byteLength(input.data, input.encoding), maxBytes);
1289
+ return (typeof input.data === "string"
1290
+ ? Buffer.from(input.data, input.encoding ?? "utf8")
1291
+ : input.data).toString("base64");
1292
+ }
1293
+ const chunks = [];
1294
+ let bytes = 0;
1295
+ for await (const chunk of input.stream) {
1296
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
1297
+ bytes += buffer.byteLength;
1298
+ assertWithinMaxBytes(bytes, maxBytes);
1299
+ chunks.push(buffer);
1300
+ }
1301
+ return Buffer.concat(chunks, bytes).toString("base64");
1302
+ }
1303
+ async function runPinnedWriteHelper(params) {
1304
+ assertSafeBasename(params.basename);
1305
+ validatePinnedOperationPayload({
1306
+ relativeParentPath: params.relativeParentPath,
1307
+ });
1308
+ if (getFsSafePythonConfig().mode === "off") {
1309
+ return await runPinnedWriteFallback(params);
1310
+ }
1311
+ if (params.input.kind === "stream") {
1312
+ try {
1313
+ assertPinnedPythonOperationAvailable();
1314
+ }
1315
+ catch (error) {
1316
+ if (canFallbackFromPythonError(error)) {
1317
+ return await runPinnedWriteFallback(params);
1318
+ }
1319
+ throw error;
1320
+ }
1321
+ }
1322
+ const payload = {
1323
+ base64: await inputToBase64(params.input, params.maxBytes),
1324
+ basename: params.basename,
1325
+ maxBytes: params.maxBytes ?? -1,
1326
+ mkdir: params.mkdir,
1327
+ mode: params.mode || 0o600,
1328
+ overwrite: params.overwrite !== false,
1329
+ relativeParentPath: params.relativeParentPath,
1330
+ };
1331
+ try {
1332
+ return await runPinnedPythonOperation({
1333
+ operation: "write",
1334
+ rootPath: params.rootPath,
1335
+ payload,
1336
+ });
1337
+ }
1338
+ catch (error) {
1339
+ if (canFallbackFromPythonError(error)) {
1340
+ return await runPinnedWriteFallback(params);
1341
+ }
1342
+ throw error;
1343
+ }
1344
+ }
1345
+ async function runPinnedCopyHelper(params) {
1346
+ assertSafeBasename(params.basename);
1347
+ validatePinnedOperationPayload({
1348
+ relativeParentPath: params.relativeParentPath,
1349
+ });
1350
+ return await runPinnedPythonOperation({
1351
+ operation: "copy",
1352
+ rootPath: params.rootPath,
1353
+ payload: {
1354
+ basename: params.basename,
1355
+ maxBytes: params.maxBytes ?? -1,
1356
+ mkdir: params.mkdir,
1357
+ mode: params.mode || 0o600,
1358
+ overwrite: params.overwrite !== false,
1359
+ relativeParentPath: params.relativeParentPath,
1360
+ sourceDev: params.sourceIdentity.dev,
1361
+ sourceIno: params.sourceIdentity.ino,
1362
+ sourcePath: params.sourcePath,
1363
+ },
1364
+ });
1365
+ }
1366
+ async function runPinnedWriteFallback(params) {
1367
+ const parentPath = params.relativeParentPath
1368
+ ? external_node_path_namespaceObject.join(params.rootPath, ...params.relativeParentPath.split("/"))
1369
+ : params.rootPath;
1370
+ const parentGuard = await directory_guard_createNearestExistingDirectoryGuard(params.rootPath, parentPath);
1371
+ if (params.mkdir) {
1372
+ await withAsyncDirectoryGuards([parentGuard], async () => {
1373
+ await promises_namespaceObject.mkdir(parentPath, { recursive: true });
1374
+ });
1375
+ }
1376
+ const targetPath = external_node_path_namespaceObject.join(parentPath, params.basename);
1377
+ if (params.overwrite === false) {
1378
+ let handle = await withAsyncDirectoryGuards([parentGuard], async () => await promises_namespaceObject.open(targetPath, external_node_fs_namespaceObject.constants.O_WRONLY | external_node_fs_namespaceObject.constants.O_CREAT | external_node_fs_namespaceObject.constants.O_EXCL, params.mode), {
1379
+ onPostGuardFailure: async (openedHandle) => {
1380
+ // The parent failed verification, so targetPath may now resolve
1381
+ // somewhere else. Close the fd, but do not clean up by path.
1382
+ await openedHandle.close().catch(() => undefined);
1383
+ },
1384
+ });
1385
+ let created = true;
1386
+ try {
1387
+ if (params.input.kind === "buffer") {
1388
+ assertWithinMaxBytes(byteLength(params.input.data, params.input.encoding), params.maxBytes);
1389
+ if (typeof params.input.data === "string") {
1390
+ await handle.writeFile(params.input.data, params.input.encoding ?? "utf8");
1391
+ }
1392
+ else {
1393
+ await handle.writeFile(params.input.data);
1394
+ }
1395
+ }
1396
+ else {
1397
+ await pipelineWithMaxBytes(params.input.stream, handle.createWriteStream(), params.maxBytes);
1398
+ }
1399
+ const stat = await handle.stat();
1400
+ created = false;
1401
+ return { dev: stat.dev, ino: stat.ino };
1402
+ }
1403
+ finally {
1404
+ await handle.close().catch(() => undefined);
1405
+ if (created) {
1406
+ await promises_namespaceObject.rm(targetPath, { force: true }).catch(() => undefined);
1407
+ }
1408
+ }
1409
+ }
1410
+ const tempPath = external_node_path_namespaceObject.join(parentPath, `.${params.basename}.${(0,external_node_crypto_namespaceObject.randomUUID)()}.fallback.tmp`);
1411
+ const tempFlags = external_node_fs_namespaceObject.constants.O_WRONLY |
1412
+ external_node_fs_namespaceObject.constants.O_CREAT |
1413
+ external_node_fs_namespaceObject.constants.O_EXCL |
1414
+ (process.platform !== "win32" && "O_NOFOLLOW" in external_node_fs_namespaceObject.constants
1415
+ ? external_node_fs_namespaceObject.constants.O_NOFOLLOW
1416
+ : 0);
1417
+ let handle;
1418
+ let handleClosedByStream = false;
1419
+ try {
1420
+ handle = await promises_namespaceObject.open(tempPath, tempFlags, params.mode);
1421
+ if (params.input.kind === "buffer") {
1422
+ assertWithinMaxBytes(byteLength(params.input.data, params.input.encoding), params.maxBytes);
1423
+ if (typeof params.input.data === "string") {
1424
+ await handle.writeFile(params.input.data, params.input.encoding ?? "utf8");
1425
+ }
1426
+ else {
1427
+ await handle.writeFile(params.input.data);
1428
+ }
1429
+ }
1430
+ else {
1431
+ const writable = handle.createWriteStream();
1432
+ writable.once("close", () => {
1433
+ handleClosedByStream = true;
1434
+ });
1435
+ await pipelineWithMaxBytes(params.input.stream, writable, params.maxBytes);
1436
+ }
1437
+ if (!handleClosedByStream) {
1438
+ await handle.close().catch(() => undefined);
1439
+ handle = undefined;
1440
+ }
1441
+ await withAsyncDirectoryGuards([parentGuard], async () => {
1442
+ await promises_namespaceObject.rename(tempPath, targetPath);
1443
+ });
1444
+ }
1445
+ catch (error) {
1446
+ if (handle && !handleClosedByStream) {
1447
+ await handle.close().catch(() => undefined);
1448
+ }
1449
+ await promises_namespaceObject.rm(tempPath, { force: true }).catch(() => undefined);
1450
+ throw error;
1451
+ }
1452
+ const stat = await promises_namespaceObject.stat(targetPath);
1453
+ return { dev: stat.dev, ino: stat.ino };
1454
+ }
1455
+
1456
+ ;// CONCATENATED MODULE: external "node:os"
1457
+ const external_node_os_namespaceObject = __rspack_createRequire_require("node:os");
1458
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-path.js
1459
+
1460
+
1461
+
1462
+
1463
+
1464
+ const ROOT_PATH_ALIAS_POLICIES = {
1465
+ strict: Object.freeze({
1466
+ allowFinalSymlinkForUnlink: false,
1467
+ allowFinalHardlinkForUnlink: false,
1468
+ }),
1469
+ unlinkTarget: Object.freeze({
1470
+ allowFinalSymlinkForUnlink: true,
1471
+ allowFinalHardlinkForUnlink: true,
1472
+ }),
1473
+ };
1474
+ async function resolveRootPath(params) {
1475
+ const rootPath = external_node_path_namespaceObject.resolve(params.rootPath);
1476
+ const absolutePath = external_node_path_namespaceObject.resolve(params.absolutePath);
1477
+ const rootCanonicalPath = params.rootCanonicalPath
1478
+ ? external_node_path_namespaceObject.resolve(params.rootCanonicalPath)
1479
+ : await resolvePathViaExistingAncestor(rootPath);
1480
+ const context = createBoundaryResolutionContext({
1481
+ resolveParams: params,
1482
+ rootPath,
1483
+ absolutePath,
1484
+ rootCanonicalPath,
1485
+ outsideLexicalCanonicalPath: await resolveOutsideLexicalCanonicalPathAsync({
1486
+ rootPath,
1487
+ absolutePath,
1488
+ }),
1489
+ });
1490
+ const outsideResult = await resolveOutsideRootPathAsync({
1491
+ boundaryLabel: params.boundaryLabel,
1492
+ context,
1493
+ });
1494
+ if (outsideResult) {
1495
+ return outsideResult;
1496
+ }
1497
+ return resolveRootPathLexicalAsync({
1498
+ params,
1499
+ absolutePath: context.absolutePath,
1500
+ rootPath: context.rootPath,
1501
+ rootCanonicalPath: context.rootCanonicalPath,
1502
+ });
1503
+ }
1504
+ function resolveRootPathSync(params) {
1505
+ const rootPath = path.resolve(params.rootPath);
1506
+ const absolutePath = path.resolve(params.absolutePath);
1507
+ const rootCanonicalPath = params.rootCanonicalPath
1508
+ ? path.resolve(params.rootCanonicalPath)
1509
+ : resolvePathViaExistingAncestorSync(rootPath);
1510
+ const context = createBoundaryResolutionContext({
1511
+ resolveParams: params,
1512
+ rootPath,
1513
+ absolutePath,
1514
+ rootCanonicalPath,
1515
+ outsideLexicalCanonicalPath: resolveOutsideLexicalCanonicalPathSync({
1516
+ rootPath,
1517
+ absolutePath,
1518
+ }),
1519
+ });
1520
+ const outsideResult = resolveOutsideRootPathSync({
1521
+ boundaryLabel: params.boundaryLabel,
1522
+ context,
1523
+ });
1524
+ if (outsideResult) {
1525
+ return outsideResult;
1526
+ }
1527
+ return resolveRootPathLexicalSync({
1528
+ params,
1529
+ absolutePath: context.absolutePath,
1530
+ rootPath: context.rootPath,
1531
+ rootCanonicalPath: context.rootCanonicalPath,
1532
+ });
1533
+ }
1534
+ function isPromiseLike(value) {
1535
+ return Boolean(value &&
1536
+ (typeof value === "object" || typeof value === "function") &&
1537
+ "then" in value &&
1538
+ typeof value.then === "function");
1539
+ }
1540
+ function createLexicalTraversalState(params) {
1541
+ const relative = external_node_path_namespaceObject.relative(params.rootPath, params.absolutePath);
1542
+ return {
1543
+ segments: relative.split(external_node_path_namespaceObject.sep).filter(Boolean),
1544
+ allowFinalSymlink: params.params.policy?.allowFinalSymlinkForUnlink === true,
1545
+ canonicalCursor: params.rootCanonicalPath,
1546
+ lexicalCursor: params.rootPath,
1547
+ preserveFinalSymlink: false,
1548
+ };
1549
+ }
1550
+ function assertLexicalCursorInsideBoundary(params) {
1551
+ assertInsideBoundary({
1552
+ boundaryLabel: params.params.boundaryLabel,
1553
+ rootCanonicalPath: params.rootCanonicalPath,
1554
+ candidatePath: params.candidatePath,
1555
+ absolutePath: params.absolutePath,
1556
+ });
1557
+ }
1558
+ function applyMissingSuffixToCanonicalCursor(params) {
1559
+ const missingSuffix = params.state.segments.slice(params.missingFromIndex);
1560
+ params.state.canonicalCursor = external_node_path_namespaceObject.resolve(params.state.canonicalCursor, ...missingSuffix);
1561
+ assertLexicalCursorInsideBoundary({
1562
+ params: params.params,
1563
+ rootCanonicalPath: params.rootCanonicalPath,
1564
+ candidatePath: params.state.canonicalCursor,
1565
+ absolutePath: params.absolutePath,
1566
+ });
1567
+ }
1568
+ function advanceCanonicalCursorForSegment(params) {
1569
+ params.state.canonicalCursor = external_node_path_namespaceObject.resolve(params.state.canonicalCursor, params.segment);
1570
+ assertLexicalCursorInsideBoundary({
1571
+ params: params.params,
1572
+ rootCanonicalPath: params.rootCanonicalPath,
1573
+ candidatePath: params.state.canonicalCursor,
1574
+ absolutePath: params.absolutePath,
1575
+ });
1576
+ }
1577
+ function finalizeLexicalResolution(params) {
1578
+ assertLexicalCursorInsideBoundary({
1579
+ params: params.params,
1580
+ rootCanonicalPath: params.rootCanonicalPath,
1581
+ candidatePath: params.state.canonicalCursor,
1582
+ absolutePath: params.absolutePath,
1583
+ });
1584
+ return buildResolvedRootPath({
1585
+ absolutePath: params.absolutePath,
1586
+ canonicalPath: params.state.canonicalCursor,
1587
+ rootPath: params.rootPath,
1588
+ rootCanonicalPath: params.rootCanonicalPath,
1589
+ kind: params.kind,
1590
+ });
1591
+ }
1592
+ function handleLexicalLstatFailure(params) {
1593
+ if (!path_isNotFoundPathError(params.error)) {
1594
+ return false;
1595
+ }
1596
+ applyMissingSuffixToCanonicalCursor({
1597
+ state: params.state,
1598
+ missingFromIndex: params.missingFromIndex,
1599
+ rootCanonicalPath: params.rootCanonicalPath,
1600
+ params: params.resolveParams,
1601
+ absolutePath: params.absolutePath,
1602
+ });
1603
+ return true;
1604
+ }
1605
+ function handleLexicalStatReadFailure(params) {
1606
+ if (handleLexicalLstatFailure({
1607
+ error: params.error,
1608
+ state: params.state,
1609
+ missingFromIndex: params.missingFromIndex,
1610
+ rootCanonicalPath: params.rootCanonicalPath,
1611
+ resolveParams: params.resolveParams,
1612
+ absolutePath: params.absolutePath,
1613
+ })) {
1614
+ return null;
1615
+ }
1616
+ throw params.error;
1617
+ }
1618
+ function handleLexicalStatDisposition(params) {
1619
+ if (!params.isSymbolicLink) {
1620
+ advanceCanonicalCursorForSegment({
1621
+ state: params.state,
1622
+ segment: params.segment,
1623
+ rootCanonicalPath: params.rootCanonicalPath,
1624
+ params: params.resolveParams,
1625
+ absolutePath: params.absolutePath,
1626
+ });
1627
+ return "continue";
1628
+ }
1629
+ if (params.state.allowFinalSymlink && params.isLast) {
1630
+ params.state.preserveFinalSymlink = true;
1631
+ advanceCanonicalCursorForSegment({
1632
+ state: params.state,
1633
+ segment: params.segment,
1634
+ rootCanonicalPath: params.rootCanonicalPath,
1635
+ params: params.resolveParams,
1636
+ absolutePath: params.absolutePath,
1637
+ });
1638
+ return "break";
1639
+ }
1640
+ return "resolve-link";
1641
+ }
1642
+ function applyResolvedSymlinkHop(params) {
1643
+ if (!path_isPathInside(params.rootCanonicalPath, params.linkCanonical)) {
1644
+ throw symlinkEscapeError({
1645
+ boundaryLabel: params.boundaryLabel,
1646
+ rootCanonicalPath: params.rootCanonicalPath,
1647
+ symlinkPath: params.state.lexicalCursor,
1648
+ });
1649
+ }
1650
+ params.state.canonicalCursor = params.linkCanonical;
1651
+ params.state.lexicalCursor = params.linkCanonical;
1652
+ }
1653
+ function readLexicalStat(params) {
1654
+ try {
1655
+ const stat = params.read(params.state.lexicalCursor);
1656
+ if (isPromiseLike(stat)) {
1657
+ return Promise.resolve(stat).catch((error) => handleLexicalStatReadFailure({ ...params, error }));
1658
+ }
1659
+ return stat;
1660
+ }
1661
+ catch (error) {
1662
+ return handleLexicalStatReadFailure({ ...params, error });
1663
+ }
1664
+ }
1665
+ function resolveAndApplySymlinkHop(params) {
1666
+ const linkCanonical = params.resolveLinkCanonical(params.state.lexicalCursor);
1667
+ if (isPromiseLike(linkCanonical)) {
1668
+ return Promise.resolve(linkCanonical).then((value) => applyResolvedSymlinkHop({
1669
+ state: params.state,
1670
+ linkCanonical: value,
1671
+ rootCanonicalPath: params.rootCanonicalPath,
1672
+ boundaryLabel: params.boundaryLabel,
1673
+ }));
1674
+ }
1675
+ applyResolvedSymlinkHop({
1676
+ state: params.state,
1677
+ linkCanonical,
1678
+ rootCanonicalPath: params.rootCanonicalPath,
1679
+ boundaryLabel: params.boundaryLabel,
1680
+ });
1681
+ }
1682
+ function* iterateLexicalTraversal(state) {
1683
+ for (let idx = 0; idx < state.segments.length; idx += 1) {
1684
+ const segment = state.segments[idx] ?? "";
1685
+ const isLast = idx === state.segments.length - 1;
1686
+ state.lexicalCursor = external_node_path_namespaceObject.join(state.lexicalCursor, segment);
1687
+ yield { idx, segment, isLast };
1688
+ }
1689
+ }
1690
+ async function resolveRootPathLexicalAsync(params) {
1691
+ const state = createLexicalTraversalState(params);
1692
+ const sharedStepParams = {
1693
+ state,
1694
+ rootCanonicalPath: params.rootCanonicalPath,
1695
+ resolveParams: params.params,
1696
+ absolutePath: params.absolutePath,
1697
+ };
1698
+ for (const { idx, segment, isLast } of iterateLexicalTraversal(state)) {
1699
+ const stat = await readLexicalStat({
1700
+ ...sharedStepParams,
1701
+ missingFromIndex: idx,
1702
+ read: (cursor) => promises_namespaceObject.lstat(cursor),
1703
+ });
1704
+ if (!stat) {
1705
+ break;
1706
+ }
1707
+ const disposition = handleLexicalStatDisposition({
1708
+ ...sharedStepParams,
1709
+ isSymbolicLink: stat.isSymbolicLink(),
1710
+ segment,
1711
+ isLast,
1712
+ });
1713
+ if (disposition === "continue") {
1714
+ continue;
1715
+ }
1716
+ if (disposition === "break") {
1717
+ break;
1718
+ }
1719
+ await resolveAndApplySymlinkHop({
1720
+ state,
1721
+ rootCanonicalPath: params.rootCanonicalPath,
1722
+ boundaryLabel: params.params.boundaryLabel,
1723
+ resolveLinkCanonical: (cursor) => resolveSymlinkHopPath(cursor),
1724
+ });
1725
+ }
1726
+ const kind = await getPathKind(params.absolutePath, state.preserveFinalSymlink);
1727
+ return finalizeLexicalResolution({
1728
+ ...params,
1729
+ state,
1730
+ kind,
1731
+ });
1732
+ }
1733
+ function resolveRootPathLexicalSync(params) {
1734
+ const state = createLexicalTraversalState(params);
1735
+ for (let idx = 0; idx < state.segments.length; idx += 1) {
1736
+ const segment = state.segments[idx] ?? "";
1737
+ const isLast = idx === state.segments.length - 1;
1738
+ state.lexicalCursor = path.join(state.lexicalCursor, segment);
1739
+ const maybeStat = readLexicalStat({
1740
+ state,
1741
+ missingFromIndex: idx,
1742
+ rootCanonicalPath: params.rootCanonicalPath,
1743
+ resolveParams: params.params,
1744
+ absolutePath: params.absolutePath,
1745
+ read: (cursor) => fs.lstatSync(cursor),
1746
+ });
1747
+ if (isPromiseLike(maybeStat)) {
1748
+ throw new Error("Unexpected async lexical stat");
1749
+ }
1750
+ const stat = maybeStat;
1751
+ if (!stat) {
1752
+ break;
1753
+ }
1754
+ const disposition = handleLexicalStatDisposition({
1755
+ state,
1756
+ isSymbolicLink: stat.isSymbolicLink(),
1757
+ segment,
1758
+ isLast,
1759
+ rootCanonicalPath: params.rootCanonicalPath,
1760
+ resolveParams: params.params,
1761
+ absolutePath: params.absolutePath,
1762
+ });
1763
+ if (disposition === "continue") {
1764
+ continue;
1765
+ }
1766
+ if (disposition === "break") {
1767
+ break;
1768
+ }
1769
+ const maybeApplied = resolveAndApplySymlinkHop({
1770
+ state,
1771
+ rootCanonicalPath: params.rootCanonicalPath,
1772
+ boundaryLabel: params.params.boundaryLabel,
1773
+ resolveLinkCanonical: (cursor) => resolveSymlinkHopPathSync(cursor),
1774
+ });
1775
+ if (isPromiseLike(maybeApplied)) {
1776
+ throw new Error("Unexpected async symlink resolution");
1777
+ }
1778
+ }
1779
+ const kind = getPathKindSync(params.absolutePath, state.preserveFinalSymlink);
1780
+ return finalizeLexicalResolution({
1781
+ ...params,
1782
+ state,
1783
+ kind,
1784
+ });
1785
+ }
1786
+ function resolveCanonicalOutsideLexicalPath(params) {
1787
+ return params.outsideLexicalCanonicalPath ?? params.absolutePath;
1788
+ }
1789
+ function createBoundaryResolutionContext(params) {
1790
+ const lexicalInside = path_isPathInside(params.rootPath, params.absolutePath);
1791
+ const canonicalOutsideLexicalPath = resolveCanonicalOutsideLexicalPath({
1792
+ absolutePath: params.absolutePath,
1793
+ outsideLexicalCanonicalPath: params.outsideLexicalCanonicalPath,
1794
+ });
1795
+ assertLexicalBoundaryOrCanonicalAlias({
1796
+ skipLexicalRootCheck: params.resolveParams.skipLexicalRootCheck,
1797
+ lexicalInside,
1798
+ canonicalOutsideLexicalPath,
1799
+ rootCanonicalPath: params.rootCanonicalPath,
1800
+ boundaryLabel: params.resolveParams.boundaryLabel,
1801
+ rootPath: params.rootPath,
1802
+ absolutePath: params.absolutePath,
1803
+ });
1804
+ return {
1805
+ rootPath: params.rootPath,
1806
+ absolutePath: params.absolutePath,
1807
+ rootCanonicalPath: params.rootCanonicalPath,
1808
+ lexicalInside,
1809
+ canonicalOutsideLexicalPath,
1810
+ };
1811
+ }
1812
+ async function resolveOutsideRootPathAsync(params) {
1813
+ if (params.context.lexicalInside) {
1814
+ return null;
1815
+ }
1816
+ const kind = await getPathKind(params.context.absolutePath, false);
1817
+ return buildOutsideRootPathFromContext({
1818
+ boundaryLabel: params.boundaryLabel,
1819
+ context: params.context,
1820
+ kind,
1821
+ });
1822
+ }
1823
+ function resolveOutsideRootPathSync(params) {
1824
+ if (params.context.lexicalInside) {
1825
+ return null;
1826
+ }
1827
+ const kind = getPathKindSync(params.context.absolutePath, false);
1828
+ return buildOutsideRootPathFromContext({
1829
+ boundaryLabel: params.boundaryLabel,
1830
+ context: params.context,
1831
+ kind,
1832
+ });
1833
+ }
1834
+ function buildOutsideRootPathFromContext(params) {
1835
+ return buildOutsideLexicalRootPath({
1836
+ boundaryLabel: params.boundaryLabel,
1837
+ rootCanonicalPath: params.context.rootCanonicalPath,
1838
+ absolutePath: params.context.absolutePath,
1839
+ canonicalOutsideLexicalPath: params.context.canonicalOutsideLexicalPath,
1840
+ rootPath: params.context.rootPath,
1841
+ kind: params.kind,
1842
+ });
1843
+ }
1844
+ async function resolveOutsideLexicalCanonicalPathAsync(params) {
1845
+ if (path_isPathInside(params.rootPath, params.absolutePath)) {
1846
+ return undefined;
1847
+ }
1848
+ return await resolvePathViaExistingAncestor(params.absolutePath);
1849
+ }
1850
+ function resolveOutsideLexicalCanonicalPathSync(params) {
1851
+ if (isPathInside(params.rootPath, params.absolutePath)) {
1852
+ return undefined;
1853
+ }
1854
+ return resolvePathViaExistingAncestorSync(params.absolutePath);
1855
+ }
1856
+ function buildOutsideLexicalRootPath(params) {
1857
+ assertInsideBoundary({
1858
+ boundaryLabel: params.boundaryLabel,
1859
+ rootCanonicalPath: params.rootCanonicalPath,
1860
+ candidatePath: params.canonicalOutsideLexicalPath,
1861
+ absolutePath: params.absolutePath,
1862
+ });
1863
+ return buildResolvedRootPath({
1864
+ absolutePath: params.absolutePath,
1865
+ canonicalPath: params.canonicalOutsideLexicalPath,
1866
+ rootPath: params.rootPath,
1867
+ rootCanonicalPath: params.rootCanonicalPath,
1868
+ kind: params.kind,
1869
+ });
1870
+ }
1871
+ function assertLexicalBoundaryOrCanonicalAlias(params) {
1872
+ if (params.skipLexicalRootCheck || params.lexicalInside) {
1873
+ return;
1874
+ }
1875
+ if (path_isPathInside(params.rootCanonicalPath, params.canonicalOutsideLexicalPath)) {
1876
+ return;
1877
+ }
1878
+ throw pathEscapeError({
1879
+ boundaryLabel: params.boundaryLabel,
1880
+ rootPath: params.rootPath,
1881
+ absolutePath: params.absolutePath,
1882
+ });
1883
+ }
1884
+ function buildResolvedRootPath(params) {
1885
+ return {
1886
+ absolutePath: params.absolutePath,
1887
+ canonicalPath: params.canonicalPath,
1888
+ rootPath: params.rootPath,
1889
+ rootCanonicalPath: params.rootCanonicalPath,
1890
+ relativePath: relativeInsideRoot(params.rootCanonicalPath, params.canonicalPath),
1891
+ exists: params.kind.exists,
1892
+ kind: params.kind.kind,
1893
+ };
1894
+ }
1895
+ async function resolvePathViaExistingAncestor(targetPath) {
1896
+ const normalized = external_node_path_namespaceObject.resolve(targetPath);
1897
+ let cursor = normalized;
1898
+ const missingSuffix = [];
1899
+ while (!isFilesystemRoot(cursor) && !(await pathExists(cursor))) {
1900
+ missingSuffix.unshift(external_node_path_namespaceObject.basename(cursor));
1901
+ const parent = external_node_path_namespaceObject.dirname(cursor);
1902
+ if (parent === cursor) {
1903
+ break;
1904
+ }
1905
+ cursor = parent;
1906
+ }
1907
+ if (!(await pathExists(cursor))) {
1908
+ return normalized;
1909
+ }
1910
+ try {
1911
+ const resolvedAncestor = external_node_path_namespaceObject.resolve(await promises_namespaceObject.realpath(cursor));
1912
+ if (missingSuffix.length === 0) {
1913
+ return resolvedAncestor;
1914
+ }
1915
+ return external_node_path_namespaceObject.resolve(resolvedAncestor, ...missingSuffix);
1916
+ }
1917
+ catch {
1918
+ return normalized;
1919
+ }
1920
+ }
1921
+ function resolvePathViaExistingAncestorSync(targetPath) {
1922
+ const normalized = path.resolve(targetPath);
1923
+ let cursor = normalized;
1924
+ const missingSuffix = [];
1925
+ while (!isFilesystemRoot(cursor) && !fs.existsSync(cursor)) {
1926
+ missingSuffix.unshift(path.basename(cursor));
1927
+ const parent = path.dirname(cursor);
1928
+ if (parent === cursor) {
1929
+ break;
1930
+ }
1931
+ cursor = parent;
1932
+ }
1933
+ if (!fs.existsSync(cursor)) {
1934
+ return normalized;
1935
+ }
1936
+ try {
1937
+ // Keep sync behavior aligned with async (`fsp.realpath`) to avoid
1938
+ // platform-specific canonical alias drift (notably on Windows).
1939
+ const resolvedAncestor = path.resolve(fs.realpathSync(cursor));
1940
+ if (missingSuffix.length === 0) {
1941
+ return resolvedAncestor;
1942
+ }
1943
+ return path.resolve(resolvedAncestor, ...missingSuffix);
1944
+ }
1945
+ catch {
1946
+ return normalized;
1947
+ }
1948
+ }
1949
+ async function getPathKind(absolutePath, preserveFinalSymlink) {
1950
+ try {
1951
+ const stat = preserveFinalSymlink
1952
+ ? await promises_namespaceObject.lstat(absolutePath)
1953
+ : await promises_namespaceObject.stat(absolutePath);
1954
+ return { exists: true, kind: toResolvedKind(stat) };
1955
+ }
1956
+ catch (error) {
1957
+ if (path_isNotFoundPathError(error)) {
1958
+ return { exists: false, kind: "missing" };
1959
+ }
1960
+ throw error;
1961
+ }
1962
+ }
1963
+ function getPathKindSync(absolutePath, preserveFinalSymlink) {
1964
+ try {
1965
+ const stat = preserveFinalSymlink ? fs.lstatSync(absolutePath) : fs.statSync(absolutePath);
1966
+ return { exists: true, kind: toResolvedKind(stat) };
1967
+ }
1968
+ catch (error) {
1969
+ if (isNotFoundPathError(error)) {
1970
+ return { exists: false, kind: "missing" };
1971
+ }
1972
+ throw error;
1973
+ }
1974
+ }
1975
+ function toResolvedKind(stat) {
1976
+ if (stat.isFile()) {
1977
+ return "file";
1978
+ }
1979
+ if (stat.isDirectory()) {
1980
+ return "directory";
1981
+ }
1982
+ if (stat.isSymbolicLink()) {
1983
+ return "symlink";
1984
+ }
1985
+ return "other";
1986
+ }
1987
+ function relativeInsideRoot(rootPath, targetPath) {
1988
+ const relative = external_node_path_namespaceObject.relative(external_node_path_namespaceObject.resolve(rootPath), external_node_path_namespaceObject.resolve(targetPath));
1989
+ if (!relative || relative === ".") {
1990
+ return "";
1991
+ }
1992
+ if (relative.startsWith("..") || external_node_path_namespaceObject.isAbsolute(relative)) {
1993
+ return "";
1994
+ }
1995
+ return relative;
1996
+ }
1997
+ function assertInsideBoundary(params) {
1998
+ if (path_isPathInside(params.rootCanonicalPath, params.candidatePath)) {
1999
+ return;
2000
+ }
2001
+ throw new Error(`Path resolves outside ${params.boundaryLabel} (${shortPath(params.rootCanonicalPath)}): ${shortPath(params.absolutePath)}`);
2002
+ }
2003
+ function pathEscapeError(params) {
2004
+ return new Error(`Path escapes ${params.boundaryLabel} (${shortPath(params.rootPath)}): ${shortPath(params.absolutePath)}`);
2005
+ }
2006
+ function symlinkEscapeError(params) {
2007
+ return new Error(`Symlink escapes ${params.boundaryLabel} (${shortPath(params.rootCanonicalPath)}): ${shortPath(params.symlinkPath)}`);
2008
+ }
2009
+ function shortPath(value) {
2010
+ const home = external_node_os_namespaceObject.homedir();
2011
+ if (value.startsWith(home)) {
2012
+ return `~${value.slice(home.length)}`;
2013
+ }
2014
+ return value;
2015
+ }
2016
+ function isFilesystemRoot(candidate) {
2017
+ return external_node_path_namespaceObject.parse(candidate).root === candidate;
2018
+ }
2019
+ async function pathExists(targetPath) {
2020
+ try {
2021
+ await promises_namespaceObject.lstat(targetPath);
2022
+ return true;
2023
+ }
2024
+ catch (error) {
2025
+ if (path_isNotFoundPathError(error)) {
2026
+ return false;
2027
+ }
2028
+ throw error;
2029
+ }
2030
+ }
2031
+ async function resolveSymlinkHopPath(symlinkPath) {
2032
+ try {
2033
+ return external_node_path_namespaceObject.resolve(await promises_namespaceObject.realpath(symlinkPath));
2034
+ }
2035
+ catch (error) {
2036
+ if (!path_isNotFoundPathError(error)) {
2037
+ throw error;
2038
+ }
2039
+ const linkTarget = await promises_namespaceObject.readlink(symlinkPath);
2040
+ const linkAbsolute = external_node_path_namespaceObject.resolve(external_node_path_namespaceObject.dirname(symlinkPath), linkTarget);
2041
+ return resolvePathViaExistingAncestor(linkAbsolute);
2042
+ }
2043
+ }
2044
+ function resolveSymlinkHopPathSync(symlinkPath) {
2045
+ try {
2046
+ return path.resolve(fs.realpathSync(symlinkPath));
2047
+ }
2048
+ catch (error) {
2049
+ if (!isNotFoundPathError(error)) {
2050
+ throw error;
2051
+ }
2052
+ const linkTarget = fs.readlinkSync(symlinkPath);
2053
+ const linkAbsolute = path.resolve(path.dirname(symlinkPath), linkTarget);
2054
+ return resolvePathViaExistingAncestorSync(linkAbsolute);
2055
+ }
2056
+ }
2057
+
2058
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/path-policy.js
2059
+
2060
+
2061
+
2062
+
2063
+ const PATH_ALIAS_POLICIES = ROOT_PATH_ALIAS_POLICIES;
2064
+ async function assertNoPathAliasEscape(params) {
2065
+ const resolved = await resolveRootPath({
2066
+ absolutePath: params.absolutePath,
2067
+ rootPath: params.rootPath,
2068
+ boundaryLabel: params.boundaryLabel,
2069
+ policy: params.policy,
2070
+ });
2071
+ const allowFinalSymlink = params.policy?.allowFinalSymlinkForUnlink === true;
2072
+ if (allowFinalSymlink && resolved.kind === "symlink") {
2073
+ return;
2074
+ }
2075
+ await assertNoHardlinkedFinalPath({
2076
+ filePath: resolved.absolutePath,
2077
+ root: resolved.rootPath,
2078
+ boundaryLabel: params.boundaryLabel,
2079
+ allowFinalHardlinkForUnlink: params.policy?.allowFinalHardlinkForUnlink,
2080
+ });
2081
+ }
2082
+ async function assertNoHardlinkedFinalPath(params) {
2083
+ if (params.allowFinalHardlinkForUnlink) {
2084
+ return;
2085
+ }
2086
+ let stat;
2087
+ try {
2088
+ stat = await promises_namespaceObject.stat(params.filePath);
2089
+ }
2090
+ catch (err) {
2091
+ if (path_isNotFoundPathError(err)) {
2092
+ return;
2093
+ }
2094
+ throw err;
2095
+ }
2096
+ if (!stat.isFile()) {
2097
+ return;
2098
+ }
2099
+ if (stat.nlink > 1) {
2100
+ throw new Error(`Hardlinked path is not allowed under ${params.boundaryLabel} (${path_policy_shortPath(params.root)}): ${path_policy_shortPath(params.filePath)}`);
2101
+ }
2102
+ }
2103
+ function path_policy_shortPath(value) {
2104
+ if (value.startsWith(external_node_os_namespaceObject.homedir())) {
2105
+ return `~${value.slice(external_node_os_namespaceObject.homedir().length)}`;
2106
+ }
2107
+ return value;
2108
+ }
2109
+
2110
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/path-stat.js
2111
+ function pathStatFromStats(stat) {
2112
+ return {
2113
+ dev: Number(stat.dev),
2114
+ gid: Number(stat.gid),
2115
+ ino: Number(stat.ino),
2116
+ isDirectory: stat.isDirectory(),
2117
+ isFile: stat.isFile(),
2118
+ isSymbolicLink: stat.isSymbolicLink(),
2119
+ mode: stat.mode,
2120
+ mtimeMs: stat.mtimeMs,
2121
+ nlink: stat.nlink,
2122
+ size: stat.size,
2123
+ uid: stat.uid,
2124
+ };
2125
+ }
2126
+
2127
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/home-dir.js
2128
+
2129
+
2130
+
2131
+ function normalize(value) {
2132
+ const trimmed = normalizeOptionalString(value);
2133
+ if (!trimmed) {
2134
+ return undefined;
2135
+ }
2136
+ if (trimmed === "undefined" || trimmed === "null") {
2137
+ return undefined;
2138
+ }
2139
+ return trimmed;
2140
+ }
2141
+ function resolveEffectiveHomeDir(env = process.env, homedir = external_node_os_namespaceObject.homedir) {
2142
+ const raw = resolveRawHomeDir(env, homedir);
2143
+ return raw ? external_node_path_namespaceObject.resolve(raw) : undefined;
2144
+ }
2145
+ function resolveOsHomeDir(env = process.env, homedir = os.homedir) {
2146
+ const raw = resolveRawOsHomeDir(env, homedir);
2147
+ return raw ? path.resolve(raw) : undefined;
2148
+ }
2149
+ function resolveRawHomeDir(env, homedir) {
2150
+ const explicitHome = normalize(env.OPENCLAW_HOME);
2151
+ if (!explicitHome) {
2152
+ return resolveRawOsHomeDir(env, homedir);
2153
+ }
2154
+ const segments = external_node_path_namespaceObject.normalize(explicitHome).split(external_node_path_namespaceObject.sep);
2155
+ if (segments[0] !== "~") {
2156
+ return explicitHome;
2157
+ }
2158
+ // OPENCLAW_HOME starts with "~"; expand against the os home dir. Fall
2159
+ // back to undefined when there is no os home to expand against rather
2160
+ // than returning a raw "~"-prefixed path the caller cannot use.
2161
+ const fallbackHome = resolveRawOsHomeDir(env, homedir);
2162
+ if (!fallbackHome) {
2163
+ return undefined;
2164
+ }
2165
+ return expandHomePrefix(explicitHome, { home: fallbackHome });
2166
+ }
2167
+ function resolveRawOsHomeDir(env, homedir) {
2168
+ const envHome = normalize(env.HOME);
2169
+ if (envHome) {
2170
+ return envHome;
2171
+ }
2172
+ const userProfile = normalize(env.USERPROFILE);
2173
+ if (userProfile) {
2174
+ return userProfile;
2175
+ }
2176
+ return normalizeSafe(homedir);
2177
+ }
2178
+ function normalizeSafe(homedir) {
2179
+ try {
2180
+ return normalize(homedir());
2181
+ }
2182
+ catch {
2183
+ return undefined;
2184
+ }
2185
+ }
2186
+ function resolveRequiredHomeDir(env = process.env, homedir = os.homedir) {
2187
+ return resolveEffectiveHomeDir(env, homedir) ?? path.resolve(process.cwd());
2188
+ }
2189
+ function resolveRequiredOsHomeDir(env = process.env, homedir = os.homedir) {
2190
+ return resolveOsHomeDir(env, homedir) ?? path.resolve(process.cwd());
2191
+ }
2192
+ function expandHomePrefix(input, opts) {
2193
+ const segments = external_node_path_namespaceObject.normalize(input).split(external_node_path_namespaceObject.sep);
2194
+ if (segments[0] !== "~") {
2195
+ return input;
2196
+ }
2197
+ const home = normalize(opts?.home) ??
2198
+ resolveEffectiveHomeDir(opts?.env ?? process.env, opts?.homedir ?? external_node_os_namespaceObject.homedir);
2199
+ if (!home) {
2200
+ return input;
2201
+ }
2202
+ return external_node_path_namespaceObject.join(home, ...segments.slice(1));
2203
+ }
2204
+ function resolveHomeRelativePath(input, opts) {
2205
+ if (!input) {
2206
+ return input;
2207
+ }
2208
+ const segments = path.normalize(input).split(path.sep);
2209
+ if (segments[0] !== "~") {
2210
+ return path.resolve(input);
2211
+ }
2212
+ const expanded = expandHomePrefix(input, {
2213
+ home: resolveRequiredHomeDir(opts?.env ?? process.env, opts?.homedir ?? os.homedir),
2214
+ env: opts?.env,
2215
+ homedir: opts?.homedir,
2216
+ });
2217
+ return path.resolve(expanded);
2218
+ }
2219
+ function resolveUserPath(input, optsOrEnv, homedir) {
2220
+ const opts = optsOrEnv && ("env" in optsOrEnv || "homedir" in optsOrEnv)
2221
+ ? optsOrEnv
2222
+ : { env: optsOrEnv, homedir };
2223
+ return resolveHomeRelativePath(input, opts);
2224
+ }
2225
+ function resolveOsHomeRelativePath(input, opts) {
2226
+ if (!input) {
2227
+ return input;
2228
+ }
2229
+ const segments = path.normalize(input).split(path.sep);
2230
+ if (segments[0] !== "~") {
2231
+ return path.resolve(input);
2232
+ }
2233
+ const expanded = expandHomePrefix(input, {
2234
+ home: resolveRequiredOsHomeDir(opts?.env ?? process.env, opts?.homedir ?? os.homedir),
2235
+ env: opts?.env,
2236
+ homedir: opts?.homedir,
2237
+ });
2238
+ return path.resolve(expanded);
2239
+ }
2240
+
2241
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-context.js
2242
+
2243
+
2244
+
2245
+
2246
+
2247
+
2248
+ const ensureTrailingSep = (value) => value.endsWith(external_node_path_namespaceObject.sep) ? value : value + external_node_path_namespaceObject.sep;
2249
+ function assertValidRootRelativePath(relativePath) {
2250
+ path_assertNoNulPathInput(relativePath, "relative path contains a NUL byte");
2251
+ }
2252
+ let cachedHomePath;
2253
+ async function expandRelativePathWithHome(relativePath) {
2254
+ const rawHome = process.env.HOME || process.env.USERPROFILE || external_node_os_namespaceObject.homedir();
2255
+ if (cachedHomePath?.raw !== rawHome) {
2256
+ let realHome = rawHome;
2257
+ try {
2258
+ realHome = await promises_namespaceObject.realpath(rawHome);
2259
+ }
2260
+ catch {
2261
+ // If the home dir cannot be canonicalized, keep lexical expansion behavior.
2262
+ }
2263
+ cachedHomePath = { raw: rawHome, real: realHome };
2264
+ }
2265
+ return expandHomePrefix(relativePath, { home: cachedHomePath.real });
2266
+ }
2267
+ async function resolveRootContext(rootDir) {
2268
+ path_assertNoNulPathInput(rootDir, "root dir contains a NUL byte");
2269
+ let rootReal;
2270
+ try {
2271
+ rootReal = await promises_namespaceObject.realpath(rootDir);
2272
+ const rootStat = await promises_namespaceObject.stat(rootReal);
2273
+ if (!rootStat.isDirectory()) {
2274
+ throw new errors_FsSafeError("invalid-path", "root dir is not a directory");
2275
+ }
2276
+ }
2277
+ catch (err) {
2278
+ if (err instanceof errors_FsSafeError) {
2279
+ throw err;
2280
+ }
2281
+ if (path_isNotFoundPathError(err)) {
2282
+ throw new errors_FsSafeError("not-found", "root dir not found");
2283
+ }
2284
+ throw err;
2285
+ }
2286
+ return {
2287
+ rootDir: external_node_path_namespaceObject.resolve(rootDir),
2288
+ rootReal,
2289
+ rootWithSep: ensureTrailingSep(rootReal),
2290
+ };
2291
+ }
2292
+ async function resolvePathInRoot(root, relativePath) {
2293
+ assertValidRootRelativePath(relativePath);
2294
+ const expanded = await expandRelativePathWithHome(relativePath);
2295
+ const resolved = external_node_path_namespaceObject.resolve(root.rootWithSep, expanded);
2296
+ if (!path_isPathInside(root.rootWithSep, resolved)) {
2297
+ throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
2298
+ }
2299
+ return { rootReal: root.rootReal, rootWithSep: root.rootWithSep, resolved };
2300
+ }
2301
+ async function resolvePathWithinRoot(params) {
2302
+ return await resolvePathInRoot(await resolveRootContext(params.rootDir), params.relativePath);
2303
+ }
2304
+
2305
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-errors.js
2306
+
2307
+
2308
+ function isAlreadyExistsError(error) {
2309
+ return hasNodeErrorCode(error, "EEXIST") || /File exists|EEXIST/i.test(String(error));
2310
+ }
2311
+ function normalizePinnedWriteError(error) {
2312
+ if (error instanceof errors_FsSafeError) {
2313
+ return error;
2314
+ }
2315
+ return new errors_FsSafeError("invalid-path", "path is not a regular file under root", {
2316
+ cause: error instanceof Error ? error : undefined,
2317
+ });
2318
+ }
2319
+ function normalizePinnedPathError(error) {
2320
+ if (error instanceof errors_FsSafeError) {
2321
+ return error;
2322
+ }
2323
+ return new errors_FsSafeError("path-alias", "path is not under root", {
2324
+ cause: error instanceof Error ? error : undefined,
2325
+ });
2326
+ }
2327
+
2328
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/test-hooks.js
2329
+ let test_hooks_fsSafeTestHooks;
2330
+ function allowFsSafeTestHooks() {
2331
+ return false || process.env.VITEST === "true";
2332
+ }
2333
+ function getFsSafeTestHooks() {
2334
+ return test_hooks_fsSafeTestHooks;
2335
+ }
2336
+ function __setFsSafeTestHooksForTest(hooks) {
2337
+ if (hooks && !allowFsSafeTestHooks()) {
2338
+ throw new Error("__setFsSafeTestHooksForTest is only available in tests");
2339
+ }
2340
+ test_hooks_fsSafeTestHooks = hooks;
2341
+ }
2342
+
2343
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/temp-cleanup.js
2344
+
2345
+ const tempCleanupEntries = new Map();
2346
+ let cleanupRegistered = false;
2347
+ function cleanupRegisteredTempPathsSync() {
2348
+ for (const entry of tempCleanupEntries.values()) {
2349
+ try {
2350
+ external_node_fs_namespaceObject.rmSync(entry.path, { force: true, recursive: entry.recursive });
2351
+ }
2352
+ catch {
2353
+ // Process-exit cleanup is best-effort.
2354
+ }
2355
+ }
2356
+ tempCleanupEntries.clear();
2357
+ }
2358
+ function registerTempPathForExit(tempPath, options) {
2359
+ if (!cleanupRegistered) {
2360
+ cleanupRegistered = true;
2361
+ process.once("exit", cleanupRegisteredTempPathsSync);
2362
+ }
2363
+ tempCleanupEntries.set(tempPath, {
2364
+ path: tempPath,
2365
+ recursive: options?.recursive === true,
2366
+ });
2367
+ return () => {
2368
+ tempCleanupEntries.delete(tempPath);
2369
+ };
2370
+ }
2371
+ function __cleanupRegisteredTempPathsForTest() {
2372
+ cleanupRegisteredTempPathsSync();
2373
+ }
2374
+ function __cleanupRegisteredTempPathForTest(tempPath) {
2375
+ const entry = tempCleanupEntries.get(tempPath);
2376
+ if (!entry) {
2377
+ return;
2378
+ }
2379
+ try {
2380
+ fsSync.rmSync(entry.path, { force: true, recursive: entry.recursive });
2381
+ }
2382
+ finally {
2383
+ tempCleanupEntries.delete(tempPath);
2384
+ }
2385
+ }
2386
+
2387
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/write-queue.js
2388
+ const writeQueues = new Map();
2389
+ async function serializePathWrite(key, run) {
2390
+ const previous = writeQueues.get(key) ?? Promise.resolve();
2391
+ const task = (async () => {
2392
+ await previous.catch(() => undefined);
2393
+ return await run();
2394
+ })();
2395
+ const done = task.then(() => undefined, () => undefined);
2396
+ writeQueues.set(key, done);
2397
+ try {
2398
+ return await task;
2399
+ }
2400
+ finally {
2401
+ if (writeQueues.get(key) === done) {
2402
+ writeQueues.delete(key);
2403
+ }
2404
+ }
2405
+ }
2406
+
2407
+ ;// CONCATENATED MODULE: ../../node_modules/@openclaw/fs-safe/dist/root-impl.js
2408
+
2409
+
2410
+
2411
+
2412
+
2413
+
2414
+
2415
+
2416
+
2417
+
2418
+
2419
+
2420
+
2421
+
2422
+
2423
+
2424
+
2425
+
2426
+
2427
+
2428
+
2429
+
2430
+
2431
+
2432
+ function logWarn(message) {
2433
+ if (process.env.FS_SAFE_DEBUG_WARNINGS === "1") {
2434
+ console.warn(message);
2435
+ }
2436
+ }
2437
+ const SUPPORTS_NOFOLLOW = process.platform !== "win32" && "O_NOFOLLOW" in external_node_fs_namespaceObject.constants;
2438
+ const NONBLOCK_OPEN_FLAG = "O_NONBLOCK" in external_node_fs_namespaceObject.constants ? external_node_fs_namespaceObject.constants.O_NONBLOCK : 0;
2439
+ const OPEN_READ_FLAGS = external_node_fs_namespaceObject.constants.O_RDONLY | (SUPPORTS_NOFOLLOW ? external_node_fs_namespaceObject.constants.O_NOFOLLOW : 0);
2440
+ const OPEN_READ_NONBLOCK_FLAGS = OPEN_READ_FLAGS | NONBLOCK_OPEN_FLAG;
2441
+ const OPEN_READ_FOLLOW_FLAGS = external_node_fs_namespaceObject.constants.O_RDONLY;
2442
+ const OPEN_READ_FOLLOW_NONBLOCK_FLAGS = OPEN_READ_FOLLOW_FLAGS | NONBLOCK_OPEN_FLAG;
2443
+ const OPEN_WRITE_EXISTING_FLAGS = external_node_fs_namespaceObject.constants.O_WRONLY | (SUPPORTS_NOFOLLOW ? external_node_fs_namespaceObject.constants.O_NOFOLLOW : 0);
2444
+ const OPEN_WRITE_CREATE_FLAGS = external_node_fs_namespaceObject.constants.O_WRONLY |
2445
+ external_node_fs_namespaceObject.constants.O_CREAT |
2446
+ external_node_fs_namespaceObject.constants.O_EXCL |
2447
+ (SUPPORTS_NOFOLLOW ? external_node_fs_namespaceObject.constants.O_NOFOLLOW : 0);
2448
+ const OPEN_APPEND_EXISTING_FLAGS = external_node_fs_namespaceObject.constants.O_RDWR | external_node_fs_namespaceObject.constants.O_APPEND | (SUPPORTS_NOFOLLOW ? external_node_fs_namespaceObject.constants.O_NOFOLLOW : 0);
2449
+ const OPEN_APPEND_CREATE_FLAGS = external_node_fs_namespaceObject.constants.O_RDWR |
2450
+ external_node_fs_namespaceObject.constants.O_APPEND |
2451
+ external_node_fs_namespaceObject.constants.O_CREAT |
2452
+ external_node_fs_namespaceObject.constants.O_EXCL |
2453
+ (SUPPORTS_NOFOLLOW ? external_node_fs_namespaceObject.constants.O_NOFOLLOW : 0);
2454
+ const DEFAULT_ROOT_MAX_BYTES = 16 * 1024 * 1024;
2455
+ function closeHandleForDispose(handle) {
2456
+ return handle.close().catch(() => undefined);
2457
+ }
2458
+ function openResult(params) {
2459
+ return {
2460
+ handle: params.handle,
2461
+ realPath: params.realPath,
2462
+ stat: params.stat,
2463
+ [Symbol.asyncDispose]: async () => {
2464
+ await closeHandleForDispose(params.handle);
2465
+ },
2466
+ };
2467
+ }
2468
+ async function openVerifiedLocalFile(filePath, options) {
2469
+ const fsSafeTestHooks = getFsSafeTestHooks();
2470
+ // Reject directories before opening so we never surface EISDIR to callers (e.g. tool
2471
+ // results that get sent to messaging channels). See openclaw/openclaw#31186.
2472
+ try {
2473
+ const preStat = await promises_namespaceObject.lstat(filePath);
2474
+ if (preStat.isDirectory()) {
2475
+ throw new errors_FsSafeError("not-file", "not a file");
2476
+ }
2477
+ await fsSafeTestHooks?.afterPreOpenLstat?.(filePath);
2478
+ }
2479
+ catch (err) {
2480
+ if (err instanceof errors_FsSafeError) {
2481
+ throw err;
2482
+ }
2483
+ // ENOENT and other lstat errors: fall through and let fs.open handle.
2484
+ }
2485
+ let handle;
2486
+ try {
2487
+ const openFlags = options?.symlinks === "follow-within-root"
2488
+ ? options?.nonBlockingRead
2489
+ ? OPEN_READ_FOLLOW_NONBLOCK_FLAGS
2490
+ : OPEN_READ_FOLLOW_FLAGS
2491
+ : options?.nonBlockingRead
2492
+ ? OPEN_READ_NONBLOCK_FLAGS
2493
+ : OPEN_READ_FLAGS;
2494
+ await fsSafeTestHooks?.beforeOpen?.(filePath, openFlags);
2495
+ handle = await promises_namespaceObject.open(filePath, openFlags);
2496
+ try {
2497
+ await fsSafeTestHooks?.afterOpen?.(filePath, handle);
2498
+ }
2499
+ catch (err) {
2500
+ await handle.close().catch(() => { });
2501
+ throw err;
2502
+ }
2503
+ }
2504
+ catch (err) {
2505
+ if (path_isNotFoundPathError(err)) {
2506
+ throw new errors_FsSafeError("not-found", "file not found");
2507
+ }
2508
+ if (isSymlinkOpenError(err)) {
2509
+ throw new errors_FsSafeError("symlink", "symlink open blocked", { cause: err });
2510
+ }
2511
+ // Defensive: if open still throws EISDIR (e.g. race), sanitize so it never leaks.
2512
+ if (hasNodeErrorCode(err, "EISDIR")) {
2513
+ throw new errors_FsSafeError("not-file", "not a file");
2514
+ }
2515
+ throw err;
2516
+ }
2517
+ try {
2518
+ const stat = await handle.stat();
2519
+ if (!stat.isFile()) {
2520
+ throw new errors_FsSafeError("not-file", "not a file");
2521
+ }
2522
+ if (options?.hardlinks === "reject" && stat.nlink > 1) {
2523
+ throw new errors_FsSafeError("hardlink", "hardlinked path not allowed");
2524
+ }
2525
+ if (options?.symlinks === "follow-within-root") {
2526
+ const pathStat = await promises_namespaceObject.stat(filePath);
2527
+ if (!file_identity_sameFileIdentity(stat, pathStat)) {
2528
+ throw new errors_FsSafeError("path-mismatch", "path changed during read");
2529
+ }
2530
+ }
2531
+ else {
2532
+ const pathStat = await promises_namespaceObject.lstat(filePath);
2533
+ if (pathStat.isSymbolicLink()) {
2534
+ throw new errors_FsSafeError("symlink", "symlink not allowed");
2535
+ }
2536
+ if (!file_identity_sameFileIdentity(stat, pathStat)) {
2537
+ throw new errors_FsSafeError("path-mismatch", "path changed during read");
2538
+ }
2539
+ }
2540
+ const realPath = await resolveOpenedFileRealPathForHandle(handle, filePath);
2541
+ const realStat = await promises_namespaceObject.stat(realPath);
2542
+ if (options?.hardlinks === "reject" && realStat.nlink > 1) {
2543
+ throw new errors_FsSafeError("hardlink", "hardlinked path not allowed");
2544
+ }
2545
+ if (!file_identity_sameFileIdentity(stat, realStat)) {
2546
+ throw new errors_FsSafeError("path-mismatch", "path mismatch");
2547
+ }
2548
+ return openResult({ handle, realPath, stat });
2549
+ }
2550
+ catch (err) {
2551
+ await handle.close().catch(() => { });
2552
+ if (err instanceof errors_FsSafeError) {
2553
+ throw err;
2554
+ }
2555
+ if (path_isNotFoundPathError(err)) {
2556
+ throw new errors_FsSafeError("not-found", "file not found");
2557
+ }
2558
+ throw err;
2559
+ }
2560
+ }
2561
+ class RootHandle {
2562
+ rootDir;
2563
+ rootReal;
2564
+ rootWithSep;
2565
+ defaults;
2566
+ constructor(context, defaults = {}) {
2567
+ this.rootDir = context.rootDir;
2568
+ this.rootReal = context.rootReal;
2569
+ this.rootWithSep = context.rootWithSep;
2570
+ this.defaults = defaults;
2571
+ }
2572
+ get context() {
2573
+ return {
2574
+ rootDir: this.rootDir,
2575
+ rootReal: this.rootReal,
2576
+ rootWithSep: this.rootWithSep,
2577
+ };
2578
+ }
2579
+ async resolve(relativePath) {
2580
+ return (await resolvePathInRoot(this.context, relativePath)).resolved;
2581
+ }
2582
+ async open(relativePath, options = {}) {
2583
+ return await openFileInRoot(this.context, {
2584
+ relativePath,
2585
+ ...readDefaults(this.defaults),
2586
+ ...options,
2587
+ });
2588
+ }
2589
+ async read(relativePath, options = {}) {
2590
+ return await readFileInRoot(this.context, {
2591
+ relativePath,
2592
+ ...readDefaults(this.defaults),
2593
+ ...options,
2594
+ });
2595
+ }
2596
+ async readBytes(relativePath, options = {}) {
2597
+ return (await this.read(relativePath, options)).buffer;
2598
+ }
2599
+ async readText(relativePath, options = {}) {
2600
+ const { encoding = "utf8", ...readOptions } = options;
2601
+ return (await this.read(relativePath, readOptions)).buffer.toString(encoding);
2602
+ }
2603
+ async readJson(relativePath, options = {}) {
2604
+ return JSON.parse(await this.readText(relativePath, options));
2605
+ }
2606
+ async readAbsolute(filePath, options = {}) {
2607
+ return await readPathInRoot(this.context, {
2608
+ filePath,
2609
+ ...readDefaults(this.defaults),
2610
+ ...options,
2611
+ });
2612
+ }
2613
+ reader(options = {}) {
2614
+ return async (filePath) => {
2615
+ return (await this.readAbsolute(filePath, options)).buffer;
2616
+ };
2617
+ }
2618
+ async openWritable(relativePath, options = {}) {
2619
+ const writeMode = options.writeMode ?? "replace";
2620
+ return await openWritableFileInRoot(this.context, {
2621
+ relativePath,
2622
+ mkdir: this.defaults.mkdir,
2623
+ mode: this.defaults.mode,
2624
+ ...options,
2625
+ append: writeMode === "append",
2626
+ truncateExisting: writeMode === "replace",
2627
+ });
2628
+ }
2629
+ async append(relativePath, data, options = {}) {
2630
+ await appendFileInRoot(this.context, {
2631
+ relativePath,
2632
+ data,
2633
+ mkdir: this.defaults.mkdir,
2634
+ mode: this.defaults.mode,
2635
+ ...options,
2636
+ });
2637
+ }
2638
+ async remove(relativePath) {
2639
+ assertValidRootRelativePath(relativePath);
2640
+ await removePathInRoot(this.context, relativePath);
2641
+ }
2642
+ async mkdir(relativePath) {
2643
+ assertValidRootRelativePath(relativePath);
2644
+ await mkdirPathInRoot(this.context, { relativePath });
2645
+ }
2646
+ async ensureRoot() {
2647
+ await mkdirPathInRoot(this.context, { relativePath: "", allowRoot: true });
2648
+ }
2649
+ async write(relativePath, data, options = {}) {
2650
+ await writeFileInRoot(this.context, {
2651
+ relativePath,
2652
+ data,
2653
+ mkdir: this.defaults.mkdir,
2654
+ mode: this.defaults.mode,
2655
+ ...options,
2656
+ });
2657
+ }
2658
+ async create(relativePath, data, options = {}) {
2659
+ await writeFileInRoot(this.context, {
2660
+ relativePath,
2661
+ data,
2662
+ mkdir: this.defaults.mkdir,
2663
+ mode: this.defaults.mode,
2664
+ ...options,
2665
+ overwrite: false,
2666
+ });
2667
+ }
2668
+ async writeJson(relativePath, data, options = {}) {
2669
+ const { replacer, space, trailingNewline = true, ...writeOptions } = options;
2670
+ const json = JSON.stringify(data, replacer, space);
2671
+ await this.write(relativePath, trailingNewline ? `${json}\n` : json, writeOptions);
2672
+ }
2673
+ async createJson(relativePath, data, options = {}) {
2674
+ const { replacer, space, trailingNewline = true, ...writeOptions } = options;
2675
+ const json = JSON.stringify(data, replacer, space);
2676
+ await this.create(relativePath, trailingNewline ? `${json}\n` : json, writeOptions);
2677
+ }
2678
+ async copyIn(relativePath, sourcePath, options = {}) {
2679
+ assertValidRootRelativePath(relativePath);
2680
+ await copyFileInRoot(this.context, {
2681
+ sourcePath,
2682
+ relativePath,
2683
+ maxBytes: this.defaults.maxBytes,
2684
+ mkdir: this.defaults.mkdir,
2685
+ mode: this.defaults.mode,
2686
+ ...options,
2687
+ });
2688
+ }
2689
+ async exists(relativePath) {
2690
+ try {
2691
+ await this.stat(relativePath);
2692
+ return true;
2693
+ }
2694
+ catch (err) {
2695
+ if (err instanceof errors_FsSafeError && err.code === "not-found") {
2696
+ return false;
2697
+ }
2698
+ throw err;
2699
+ }
2700
+ }
2701
+ async stat(relativePath) {
2702
+ assertValidRootRelativePath(relativePath);
2703
+ try {
2704
+ return await helperStat(this.rootReal, relativePath);
2705
+ }
2706
+ catch (error) {
2707
+ if (canFallbackFromPythonError(error)) {
2708
+ return await statPathFallback(this.context, relativePath);
2709
+ }
2710
+ throw error;
2711
+ }
2712
+ }
2713
+ async list(relativePath, options = {}) {
2714
+ assertValidRootRelativePath(relativePath);
2715
+ try {
2716
+ return options.withFileTypes === true
2717
+ ? await helperReaddir(this.rootReal, relativePath, true)
2718
+ : await helperReaddir(this.rootReal, relativePath, false);
2719
+ }
2720
+ catch (error) {
2721
+ if (canFallbackFromPythonError(error)) {
2722
+ return await listPathFallback(this.context, relativePath, options.withFileTypes === true);
2723
+ }
2724
+ throw error;
2725
+ }
2726
+ }
2727
+ async move(fromRelative, toRelative, options = {}) {
2728
+ assertValidRootRelativePath(fromRelative);
2729
+ assertValidRootRelativePath(toRelative);
2730
+ try {
2731
+ await runPinnedHelper("rename", this.rootReal, {
2732
+ from: fromRelative,
2733
+ overwrite: options.overwrite ?? false,
2734
+ to: toRelative,
2735
+ });
2736
+ }
2737
+ catch (error) {
2738
+ if (canFallbackFromPythonError(error)) {
2739
+ await movePathFallback(this.context, {
2740
+ fromRelative,
2741
+ overwrite: options.overwrite ?? false,
2742
+ toRelative,
2743
+ });
2744
+ return;
2745
+ }
2746
+ throw error;
2747
+ }
2748
+ }
2749
+ }
2750
+ function readDefaults(defaults) {
2751
+ return {
2752
+ hardlinks: defaults.hardlinks,
2753
+ maxBytes: defaults.maxBytes ?? DEFAULT_ROOT_MAX_BYTES,
2754
+ nonBlockingRead: defaults.nonBlockingRead,
2755
+ symlinks: defaults.symlinks,
2756
+ };
2757
+ }
2758
+ async function root_impl_root(rootDir, defaults = {}) {
2759
+ return new RootHandle(await resolveRootContext(rootDir), defaults);
2760
+ }
2761
+ async function openFileInRoot(root, params) {
2762
+ const { rootWithSep, resolved } = await resolvePathInRoot(root, params.relativePath);
2763
+ let opened;
2764
+ try {
2765
+ opened = await openVerifiedLocalFile(resolved, {
2766
+ nonBlockingRead: params.nonBlockingRead,
2767
+ symlinks: params.symlinks,
2768
+ });
2769
+ }
2770
+ catch (err) {
2771
+ if (err instanceof errors_FsSafeError) {
2772
+ throw err;
2773
+ }
2774
+ throw err;
2775
+ }
2776
+ if (params.hardlinks !== "allow" && opened.stat.nlink > 1) {
2777
+ await opened.handle.close().catch(() => { });
2778
+ throw new errors_FsSafeError("hardlink", "hardlinked path not allowed");
2779
+ }
2780
+ if (!path_isPathInside(rootWithSep, opened.realPath)) {
2781
+ await opened.handle.close().catch(() => { });
2782
+ throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
2783
+ }
2784
+ return opened;
2785
+ }
2786
+ async function readFileInRoot(root, params) {
2787
+ const opened = await openFileInRoot(root, params);
2788
+ try {
2789
+ return await readOpenedFileSafely({ opened, maxBytes: params.maxBytes });
2790
+ }
2791
+ finally {
2792
+ await opened.handle.close().catch(() => { });
2793
+ }
2794
+ }
2795
+ async function readPathInRoot(root, params) {
2796
+ const rootDir = root.rootDir;
2797
+ const candidatePath = external_node_path_namespaceObject.isAbsolute(params.filePath)
2798
+ ? external_node_path_namespaceObject.resolve(params.filePath)
2799
+ : external_node_path_namespaceObject.resolve(rootDir, params.filePath);
2800
+ const relativePath = external_node_path_namespaceObject.relative(rootDir, candidatePath);
2801
+ return await readFileInRoot(root, {
2802
+ relativePath,
2803
+ hardlinks: params.hardlinks,
2804
+ maxBytes: params.maxBytes,
2805
+ nonBlockingRead: params.nonBlockingRead,
2806
+ symlinks: params.symlinks,
2807
+ });
2808
+ }
2809
+ async function readLocalFileSafely(params) {
2810
+ const opened = await openLocalFileSafely({ filePath: params.filePath });
2811
+ try {
2812
+ return await readOpenedFileSafely({ opened, maxBytes: params.maxBytes });
2813
+ }
2814
+ finally {
2815
+ await opened.handle.close().catch(() => { });
2816
+ }
2817
+ }
2818
+ async function openLocalFileSafely(params) {
2819
+ assertNoNulPathInput(params.filePath, "file path contains a NUL byte");
2820
+ return await openVerifiedLocalFile(params.filePath);
2821
+ }
2822
+ async function readOpenedFileSafely(params) {
2823
+ if (params.maxBytes !== undefined && params.opened.stat.size > params.maxBytes) {
2824
+ throw new errors_FsSafeError("too-large", `file exceeds limit of ${params.maxBytes} bytes (got ${params.opened.stat.size})`);
2825
+ }
2826
+ const buffer = await params.opened.handle.readFile();
2827
+ if (params.maxBytes !== undefined && buffer.byteLength > params.maxBytes) {
2828
+ throw new errors_FsSafeError("too-large", `file exceeds limit of ${params.maxBytes} bytes (got ${buffer.byteLength})`);
2829
+ }
2830
+ return {
2831
+ buffer,
2832
+ realPath: params.opened.realPath,
2833
+ stat: params.opened.stat,
2834
+ };
2835
+ }
2836
+ function emitWriteBoundaryWarning(reason) {
2837
+ logWarn(`security: fs-safe write boundary warning (${reason})`);
2838
+ }
2839
+ function buildAtomicWriteTempPath(targetPath) {
2840
+ const dir = external_node_path_namespaceObject.dirname(targetPath);
2841
+ const base = external_node_path_namespaceObject.basename(targetPath);
2842
+ return external_node_path_namespaceObject.join(dir, `.${base}.${process.pid}.${(0,external_node_crypto_namespaceObject.randomUUID)()}.tmp`);
2843
+ }
2844
+ function rootWriteQueueKey(root, relativePath) {
2845
+ return `${root.rootReal}\0${relativePath}`;
2846
+ }
2847
+ async function writeTempFileForAtomicReplace(params) {
2848
+ const tempHandle = await promises_namespaceObject.open(params.tempPath, OPEN_WRITE_CREATE_FLAGS, params.mode);
2849
+ try {
2850
+ if (typeof params.data === "string") {
2851
+ await tempHandle.writeFile(params.data, params.encoding ?? "utf8");
2852
+ }
2853
+ else {
2854
+ await tempHandle.writeFile(params.data);
2855
+ }
2856
+ return await tempHandle.stat();
2857
+ }
2858
+ finally {
2859
+ await tempHandle.close().catch(() => { });
2860
+ }
2861
+ }
2862
+ async function verifyAtomicWriteResult(params) {
2863
+ const opened = await openVerifiedLocalFile(params.targetPath, { hardlinks: "reject" });
2864
+ try {
2865
+ if (!file_identity_sameFileIdentity(opened.stat, params.expectedIdentity)) {
2866
+ throw new errors_FsSafeError("path-mismatch", "path changed during write");
2867
+ }
2868
+ if (!path_isPathInside(params.root.rootWithSep, opened.realPath)) {
2869
+ throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
2870
+ }
2871
+ }
2872
+ finally {
2873
+ await opened.handle.close().catch(() => { });
2874
+ }
2875
+ }
2876
+ async function resolveOpenedFileRealPathForHandle(handle, ioPath) {
2877
+ const handleStat = await handle.stat();
2878
+ const fdCandidates = process.platform === "linux"
2879
+ ? [`/proc/self/fd/${handle.fd}`, `/dev/fd/${handle.fd}`]
2880
+ : process.platform === "win32"
2881
+ ? []
2882
+ : [`/dev/fd/${handle.fd}`];
2883
+ for (const fdPath of fdCandidates) {
2884
+ try {
2885
+ const fdRealPath = await promises_namespaceObject.realpath(fdPath);
2886
+ const fdRealStat = await promises_namespaceObject.stat(fdRealPath);
2887
+ if (file_identity_sameFileIdentity(handleStat, fdRealStat)) {
2888
+ return fdRealPath;
2889
+ }
2890
+ }
2891
+ catch {
2892
+ // try next fd path
2893
+ }
2894
+ }
2895
+ try {
2896
+ const ioRealPath = await promises_namespaceObject.realpath(ioPath);
2897
+ const ioRealStat = await promises_namespaceObject.stat(ioRealPath);
2898
+ if (file_identity_sameFileIdentity(handleStat, ioRealStat)) {
2899
+ return ioRealPath;
2900
+ }
2901
+ }
2902
+ catch (err) {
2903
+ if (!path_isNotFoundPathError(err)) {
2904
+ throw err;
2905
+ }
2906
+ }
2907
+ const parentResolved = await resolveOpenedFileRealPathFromParent(handleStat, ioPath);
2908
+ if (parentResolved) {
2909
+ return parentResolved;
2910
+ }
2911
+ throw new errors_FsSafeError("path-mismatch", "unable to resolve opened file path");
2912
+ }
2913
+ async function resolveOpenedFileRealPathFromParent(handleStat, ioPath) {
2914
+ let parentReal;
2915
+ try {
2916
+ parentReal = await promises_namespaceObject.realpath(external_node_path_namespaceObject.dirname(ioPath));
2917
+ }
2918
+ catch (err) {
2919
+ if (path_isNotFoundPathError(err)) {
2920
+ return null;
2921
+ }
2922
+ throw err;
2923
+ }
2924
+ let entries;
2925
+ try {
2926
+ entries = await promises_namespaceObject.readdir(parentReal);
2927
+ }
2928
+ catch (err) {
2929
+ if (path_isNotFoundPathError(err)) {
2930
+ return null;
2931
+ }
2932
+ throw err;
2933
+ }
2934
+ for (const entry of entries.toSorted()) {
2935
+ const candidatePath = external_node_path_namespaceObject.join(parentReal, entry);
2936
+ try {
2937
+ const candidateStat = await promises_namespaceObject.lstat(candidatePath);
2938
+ if (candidateStat.isFile() && file_identity_sameFileIdentity(handleStat, candidateStat)) {
2939
+ return await promises_namespaceObject.realpath(candidatePath);
2940
+ }
2941
+ }
2942
+ catch (err) {
2943
+ if (!path_isNotFoundPathError(err)) {
2944
+ throw err;
2945
+ }
2946
+ }
2947
+ }
2948
+ return null;
2949
+ }
2950
+ async function openWritableFileInRoot(root, params) {
2951
+ const { rootReal, rootWithSep, resolved } = await resolvePathInRoot(root, params.relativePath);
2952
+ try {
2953
+ await assertNoPathAliasEscape({
2954
+ absolutePath: resolved,
2955
+ rootPath: rootReal,
2956
+ boundaryLabel: "root",
2957
+ });
2958
+ }
2959
+ catch (err) {
2960
+ throw new errors_FsSafeError("path-alias", "path alias escape blocked", { cause: err });
2961
+ }
2962
+ if (params.mkdir !== false) {
2963
+ const parentGuard = await directory_guard_createNearestExistingDirectoryGuard(rootReal, external_node_path_namespaceObject.dirname(resolved));
2964
+ await withAsyncDirectoryGuards([parentGuard], async () => {
2965
+ await promises_namespaceObject.mkdir(external_node_path_namespaceObject.dirname(resolved), { recursive: true });
2966
+ });
2967
+ }
2968
+ let ioPath = resolved;
2969
+ try {
2970
+ const resolvedRealPath = await promises_namespaceObject.realpath(resolved);
2971
+ if (!path_isPathInside(rootWithSep, resolvedRealPath)) {
2972
+ throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
2973
+ }
2974
+ ioPath = resolvedRealPath;
2975
+ }
2976
+ catch (err) {
2977
+ if (err instanceof errors_FsSafeError) {
2978
+ throw err;
2979
+ }
2980
+ if (!path_isNotFoundPathError(err)) {
2981
+ throw err;
2982
+ }
2983
+ }
2984
+ const mode = params.mode ?? 0o600;
2985
+ let handle;
2986
+ let createdForWrite = false;
2987
+ const existingFlags = params.append ? OPEN_APPEND_EXISTING_FLAGS : OPEN_WRITE_EXISTING_FLAGS;
2988
+ const createFlags = params.append ? OPEN_APPEND_CREATE_FLAGS : OPEN_WRITE_CREATE_FLAGS;
2989
+ try {
2990
+ try {
2991
+ handle = await promises_namespaceObject.open(ioPath, existingFlags, mode);
2992
+ }
2993
+ catch (err) {
2994
+ if (!path_isNotFoundPathError(err)) {
2995
+ throw err;
2996
+ }
2997
+ handle = await promises_namespaceObject.open(ioPath, createFlags, mode);
2998
+ createdForWrite = true;
2999
+ }
3000
+ }
3001
+ catch (err) {
3002
+ if (path_isNotFoundPathError(err)) {
3003
+ throw new errors_FsSafeError("not-found", "file not found");
3004
+ }
3005
+ if (isSymlinkOpenError(err)) {
3006
+ throw new errors_FsSafeError("symlink", "symlink open blocked", { cause: err });
3007
+ }
3008
+ if (hasNodeErrorCode(err, "EISDIR")) {
3009
+ throw new errors_FsSafeError("not-file", "not a file", { cause: err });
3010
+ }
3011
+ throw err;
3012
+ }
3013
+ let realPathForCleanup = null;
3014
+ try {
3015
+ const stat = await handle.stat();
3016
+ if (!stat.isFile()) {
3017
+ throw new errors_FsSafeError("invalid-path", "path is not a regular file under root");
3018
+ }
3019
+ if (stat.nlink > 1) {
3020
+ throw new errors_FsSafeError("hardlink", "hardlinked path not allowed");
3021
+ }
3022
+ try {
3023
+ const lstat = await promises_namespaceObject.lstat(ioPath);
3024
+ if (lstat.isSymbolicLink() || !lstat.isFile()) {
3025
+ throw new errors_FsSafeError(lstat.isSymbolicLink() ? "symlink" : "not-file", "path is not a regular file under root");
3026
+ }
3027
+ if (!file_identity_sameFileIdentity(stat, lstat)) {
3028
+ throw new errors_FsSafeError("path-mismatch", "path changed during write");
3029
+ }
3030
+ }
3031
+ catch (err) {
3032
+ if (!path_isNotFoundPathError(err)) {
3033
+ throw err;
3034
+ }
3035
+ }
3036
+ const realPath = await resolveOpenedFileRealPathForHandle(handle, ioPath);
3037
+ realPathForCleanup = realPath;
3038
+ const realStat = await promises_namespaceObject.stat(realPath);
3039
+ if (!file_identity_sameFileIdentity(stat, realStat)) {
3040
+ throw new errors_FsSafeError("path-mismatch", "path mismatch");
3041
+ }
3042
+ if (realStat.nlink > 1) {
3043
+ throw new errors_FsSafeError("hardlink", "hardlinked path not allowed");
3044
+ }
3045
+ if (!path_isPathInside(rootWithSep, realPath)) {
3046
+ throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
3047
+ }
3048
+ // Truncate only after boundary and identity checks complete. This avoids
3049
+ // irreversible side effects if a symlink target changes before validation.
3050
+ if (params.append !== true && params.truncateExisting !== false && !createdForWrite) {
3051
+ await handle.truncate(0);
3052
+ }
3053
+ return {
3054
+ handle,
3055
+ createdForWrite,
3056
+ realPath,
3057
+ stat,
3058
+ [Symbol.asyncDispose]: async () => {
3059
+ await closeHandleForDispose(handle);
3060
+ },
3061
+ };
3062
+ }
3063
+ catch (err) {
3064
+ const cleanupCreatedPath = createdForWrite && err instanceof errors_FsSafeError;
3065
+ const cleanupPath = realPathForCleanup ?? ioPath;
3066
+ await handle.close().catch(() => { });
3067
+ if (cleanupCreatedPath) {
3068
+ await promises_namespaceObject.rm(cleanupPath, { force: true }).catch(() => { });
3069
+ }
3070
+ throw err;
3071
+ }
3072
+ }
3073
+ async function appendFileInRoot(root, params) {
3074
+ const target = await openWritableFileInRoot(root, {
3075
+ relativePath: params.relativePath,
3076
+ mkdir: params.mkdir,
3077
+ mode: params.mode,
3078
+ truncateExisting: false,
3079
+ append: true,
3080
+ });
3081
+ try {
3082
+ let prefix = "";
3083
+ if (params.prependNewlineIfNeeded === true &&
3084
+ !target.createdForWrite &&
3085
+ target.stat.size > 0 &&
3086
+ ((typeof params.data === "string" && !params.data.startsWith("\n")) ||
3087
+ (Buffer.isBuffer(params.data) && params.data.length > 0 && params.data[0] !== 0x0a))) {
3088
+ const lastByte = Buffer.alloc(1);
3089
+ const { bytesRead } = await target.handle.read(lastByte, 0, 1, target.stat.size - 1);
3090
+ if (bytesRead === 1 && lastByte[0] !== 0x0a) {
3091
+ prefix = "\n";
3092
+ }
3093
+ }
3094
+ if (typeof params.data === "string") {
3095
+ await target.handle.appendFile(`${prefix}${params.data}`, params.encoding ?? "utf8");
3096
+ return;
3097
+ }
3098
+ const payload = prefix.length > 0 ? Buffer.concat([Buffer.from(prefix, "utf8"), params.data]) : params.data;
3099
+ await target.handle.appendFile(payload);
3100
+ }
3101
+ finally {
3102
+ await target.handle.close().catch(() => { });
3103
+ }
3104
+ }
3105
+ async function removePathInRoot(root, relativePath) {
3106
+ const resolved = await resolvePinnedRemovePathInRoot(root, relativePath);
3107
+ if (process.platform === "win32") {
3108
+ await removePathFallback(resolved);
3109
+ return;
3110
+ }
3111
+ try {
3112
+ await runPinnedPathHelper({
3113
+ operation: "remove",
3114
+ rootPath: resolved.rootReal,
3115
+ relativePath: resolved.relativePosix,
3116
+ });
3117
+ }
3118
+ catch (error) {
3119
+ if (isPinnedPathHelperSpawnError(error)) {
3120
+ await removePathFallback(resolved);
3121
+ return;
3122
+ }
3123
+ throw normalizePinnedPathError(error);
3124
+ }
3125
+ }
3126
+ async function mkdirPathInRoot(root, params) {
3127
+ const resolved = await resolvePinnedPathInRoot(root, params);
3128
+ if (process.platform === "win32") {
3129
+ await mkdirPathFallback(resolved);
3130
+ return;
3131
+ }
3132
+ try {
3133
+ await runPinnedPathHelper({
3134
+ operation: "mkdirp",
3135
+ rootPath: resolved.rootReal,
3136
+ relativePath: resolved.relativePosix,
3137
+ });
3138
+ }
3139
+ catch (error) {
3140
+ if (isPinnedPathHelperSpawnError(error)) {
3141
+ await mkdirPathFallback(resolved);
3142
+ return;
3143
+ }
3144
+ throw normalizePinnedPathError(error);
3145
+ }
3146
+ }
3147
+ async function writeFileInRoot(root, params) {
3148
+ if (process.platform === "win32") {
3149
+ await serializePathWrite(rootWriteQueueKey(root, params.relativePath), async () => {
3150
+ await writeFileFallback(root, params);
3151
+ });
3152
+ return;
3153
+ }
3154
+ const pinned = await resolvePinnedWriteTargetInRoot(root, params.relativePath, params.mode);
3155
+ await serializePathWrite(pinned.targetPath, async () => {
3156
+ let identity;
3157
+ try {
3158
+ identity = await runPinnedWriteHelper({
3159
+ rootPath: pinned.rootReal,
3160
+ relativeParentPath: pinned.relativeParentPath,
3161
+ basename: pinned.basename,
3162
+ mkdir: params.mkdir !== false,
3163
+ mode: params.mode ?? pinned.mode,
3164
+ overwrite: params.overwrite,
3165
+ input: {
3166
+ kind: "buffer",
3167
+ data: params.data,
3168
+ encoding: params.encoding,
3169
+ },
3170
+ });
3171
+ }
3172
+ catch (error) {
3173
+ if (params.overwrite === false && isAlreadyExistsError(error)) {
3174
+ throw new errors_FsSafeError("already-exists", "file already exists", {
3175
+ cause: error instanceof Error ? error : undefined,
3176
+ });
3177
+ }
3178
+ throw normalizePinnedWriteError(error);
3179
+ }
3180
+ try {
3181
+ await verifyAtomicWriteResult({
3182
+ root,
3183
+ targetPath: pinned.targetPath,
3184
+ expectedIdentity: identity,
3185
+ });
3186
+ }
3187
+ catch (err) {
3188
+ emitWriteBoundaryWarning(`post-write verification failed: ${String(err)}`);
3189
+ throw err;
3190
+ }
3191
+ });
3192
+ }
3193
+ async function copyFileInRoot(root, params) {
3194
+ assertValidRootRelativePath(params.relativePath);
3195
+ path_assertNoNulPathInput(params.sourcePath, "source path contains a NUL byte");
3196
+ const source = await openVerifiedLocalFile(params.sourcePath, {
3197
+ hardlinks: params.sourceHardlinks,
3198
+ });
3199
+ if (params.maxBytes !== undefined && source.stat.size > params.maxBytes) {
3200
+ await source.handle.close().catch(() => { });
3201
+ throw new errors_FsSafeError("too-large", `file exceeds limit of ${params.maxBytes} bytes (got ${source.stat.size})`);
3202
+ }
3203
+ try {
3204
+ if (process.platform === "win32") {
3205
+ await serializePathWrite(rootWriteQueueKey(root, params.relativePath), async () => {
3206
+ await copyFileFallback(root, params, source);
3207
+ });
3208
+ return;
3209
+ }
3210
+ const pinned = await resolvePinnedWriteTargetInRoot(root, params.relativePath, params.mode);
3211
+ await serializePathWrite(pinned.targetPath, async () => {
3212
+ let identity;
3213
+ try {
3214
+ if (getFsSafePythonConfig().mode === "off") {
3215
+ await copyFileFallback(root, params, source);
3216
+ return;
3217
+ }
3218
+ identity = await runPinnedCopyHelper({
3219
+ rootPath: pinned.rootReal,
3220
+ relativeParentPath: pinned.relativeParentPath,
3221
+ basename: pinned.basename,
3222
+ mkdir: params.mkdir !== false,
3223
+ mode: pinned.mode,
3224
+ overwrite: true,
3225
+ maxBytes: params.maxBytes,
3226
+ sourcePath: source.realPath,
3227
+ sourceIdentity: { dev: source.stat.dev, ino: source.stat.ino },
3228
+ });
3229
+ }
3230
+ catch (error) {
3231
+ if (canFallbackFromPythonError(error)) {
3232
+ await copyFileFallback(root, params, source);
3233
+ return;
3234
+ }
3235
+ throw normalizePinnedWriteError(error);
3236
+ }
3237
+ try {
3238
+ await verifyAtomicWriteResult({
3239
+ root,
3240
+ targetPath: pinned.targetPath,
3241
+ expectedIdentity: identity,
3242
+ });
3243
+ }
3244
+ catch (err) {
3245
+ emitWriteBoundaryWarning(`post-copy verification failed: ${String(err)}`);
3246
+ throw err;
3247
+ }
3248
+ });
3249
+ }
3250
+ finally {
3251
+ await source.handle.close().catch(() => { });
3252
+ }
3253
+ }
3254
+ async function resolvePinnedWriteTargetInRoot(root, relativePath, requestedMode) {
3255
+ const { rootReal, rootWithSep, resolved } = await resolvePathInRoot(root, relativePath);
3256
+ try {
3257
+ await assertNoPathAliasEscape({
3258
+ absolutePath: resolved,
3259
+ rootPath: rootReal,
3260
+ boundaryLabel: "root",
3261
+ });
3262
+ }
3263
+ catch (err) {
3264
+ throw new errors_FsSafeError("path-alias", "path alias escape blocked", { cause: err });
3265
+ }
3266
+ // resolvePathInRoot already enforces isPathInside, so any actual escape
3267
+ // is rejected upstream.
3268
+ const relativeResolved = external_node_path_namespaceObject.relative(rootReal, resolved);
3269
+ if (external_node_path_namespaceObject.isAbsolute(relativeResolved)) {
3270
+ throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
3271
+ }
3272
+ const relativePosix = relativeResolved
3273
+ ? relativeResolved.split(external_node_path_namespaceObject.sep).join(external_node_path_namespaceObject.posix.sep)
3274
+ : "";
3275
+ const basename = external_node_path_namespaceObject.posix.basename(relativePosix);
3276
+ if (!basename || basename === "." || basename === "/") {
3277
+ throw new errors_FsSafeError("invalid-path", "invalid target path");
3278
+ }
3279
+ let mode = requestedMode ?? 0o600;
3280
+ try {
3281
+ const opened = await openFileInRoot(root, {
3282
+ relativePath,
3283
+ hardlinks: "reject",
3284
+ nonBlockingRead: true,
3285
+ });
3286
+ try {
3287
+ mode = requestedMode ?? (opened.stat.mode & 0o777);
3288
+ if (!path_isPathInside(rootWithSep, opened.realPath)) {
3289
+ throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
3290
+ }
3291
+ }
3292
+ finally {
3293
+ await opened.handle.close().catch(() => { });
3294
+ }
3295
+ }
3296
+ catch (err) {
3297
+ if (!(err instanceof errors_FsSafeError) || err.code !== "not-found") {
3298
+ throw err;
3299
+ }
3300
+ }
3301
+ return {
3302
+ rootReal,
3303
+ targetPath: resolved,
3304
+ relativeParentPath: external_node_path_namespaceObject.posix.dirname(relativePosix) === "." ? "" : external_node_path_namespaceObject.posix.dirname(relativePosix),
3305
+ basename,
3306
+ mode: mode || 0o600,
3307
+ };
3308
+ }
3309
+ async function resolvePinnedPathInRoot(root, params) {
3310
+ return await resolvePinnedOperationPathInRoot(root, {
3311
+ allowRoot: params.allowRoot,
3312
+ relativePath: params.relativePath,
3313
+ policy: PATH_ALIAS_POLICIES.strict,
3314
+ });
3315
+ }
3316
+ async function resolvePinnedRemovePathInRoot(root, relativePath) {
3317
+ return await resolvePinnedOperationPathInRoot(root, {
3318
+ relativePath,
3319
+ policy: PATH_ALIAS_POLICIES.unlinkTarget,
3320
+ });
3321
+ }
3322
+ async function resolvePinnedOperationPathInRoot(root, params) {
3323
+ const resolved = await resolvePinnedRootPathInRoot(root, {
3324
+ relativePath: params.relativePath,
3325
+ policy: params.policy,
3326
+ });
3327
+ const relativeResolved = external_node_path_namespaceObject.relative(resolved.rootReal, resolved.canonicalPath);
3328
+ if ((relativeResolved === "" || relativeResolved === ".") && params.allowRoot === true) {
3329
+ return { rootReal: resolved.rootReal, resolved: resolved.canonicalPath, relativePosix: "" };
3330
+ }
3331
+ const firstSegment = relativeResolved.split(external_node_path_namespaceObject.sep)[0];
3332
+ if (relativeResolved === "" ||
3333
+ relativeResolved === "." ||
3334
+ firstSegment === ".." ||
3335
+ external_node_path_namespaceObject.isAbsolute(relativeResolved)) {
3336
+ throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
3337
+ }
3338
+ const relativePosix = relativeResolved.split(external_node_path_namespaceObject.sep).join(external_node_path_namespaceObject.posix.sep);
3339
+ if (!path_isPathInside(resolved.rootWithSep, resolved.canonicalPath)) {
3340
+ throw new errors_FsSafeError("outside-workspace", "file is outside workspace root");
3341
+ }
3342
+ return { rootReal: resolved.rootReal, resolved: resolved.canonicalPath, relativePosix };
3343
+ }
3344
+ async function resolvePinnedRootPathInRoot(root, params) {
3345
+ const rootReal = root.rootReal;
3346
+ let resolved;
3347
+ try {
3348
+ resolved = await resolveRootPath({
3349
+ absolutePath: external_node_path_namespaceObject.resolve(rootReal, await expandRelativePathWithHome(params.relativePath)),
3350
+ rootPath: rootReal,
3351
+ rootCanonicalPath: rootReal,
3352
+ boundaryLabel: "root",
3353
+ policy: params.policy,
3354
+ });
3355
+ }
3356
+ catch (err) {
3357
+ throw new errors_FsSafeError("path-alias", "path alias escape blocked", { cause: err });
3358
+ }
3359
+ const rootWithSep = ensureTrailingSep(resolved.rootCanonicalPath);
3360
+ return {
3361
+ rootReal: resolved.rootCanonicalPath,
3362
+ rootWithSep,
3363
+ canonicalPath: resolved.canonicalPath,
3364
+ };
3365
+ }
3366
+ async function removePathFallback(resolved) {
3367
+ const guard = await directory_guard_createAsyncDirectoryGuard(external_node_path_namespaceObject.dirname(resolved.resolved));
3368
+ await getFsSafeTestHooks()?.beforeRootFallbackMutation?.("remove", resolved.resolved);
3369
+ await assertAsyncDirectoryGuard(guard);
3370
+ await ((await promises_namespaceObject.lstat(resolved.resolved)).isDirectory() ? promises_namespaceObject.rmdir(resolved.resolved) : promises_namespaceObject.rm(resolved.resolved));
3371
+ await assertAsyncDirectoryGuard(guard).catch(() => undefined);
3372
+ }
3373
+ async function mkdirPathFallback(resolved) {
3374
+ await mkdirPathComponentsWithGuards({
3375
+ rootReal: resolved.rootReal, targetPath: resolved.resolved,
3376
+ beforeComponent: async (componentPath) => await getFsSafeTestHooks()?.beforeRootFallbackMutation?.("mkdir", componentPath),
3377
+ });
3378
+ }
3379
+ async function statPathFallback(root, relativePath) {
3380
+ const resolved = await resolvePinnedPathInRoot(root, { relativePath, allowRoot: true });
3381
+ try {
3382
+ return pathStatFromStats(await promises_namespaceObject.lstat(resolved.resolved));
3383
+ }
3384
+ catch (error) {
3385
+ if (path_isNotFoundPathError(error)) {
3386
+ throw new errors_FsSafeError("not-found", "file not found", {
3387
+ cause: error instanceof Error ? error : undefined,
3388
+ });
3389
+ }
3390
+ throw error;
3391
+ }
3392
+ }
3393
+ async function listPathFallback(root, relativePath, withFileTypes) {
3394
+ const resolved = await resolvePinnedPathInRoot(root, { relativePath, allowRoot: true });
3395
+ try {
3396
+ const names = await promises_namespaceObject.readdir(resolved.resolved);
3397
+ const sortedNames = names.toSorted();
3398
+ if (!withFileTypes) {
3399
+ return sortedNames;
3400
+ }
3401
+ const entries = [];
3402
+ for (const name of sortedNames) {
3403
+ entries.push({
3404
+ name,
3405
+ ...pathStatFromStats(await promises_namespaceObject.lstat(external_node_path_namespaceObject.join(resolved.resolved, name))),
3406
+ });
3407
+ }
3408
+ return entries;
3409
+ }
3410
+ catch (error) {
3411
+ if (path_isNotFoundPathError(error)) {
3412
+ throw new errors_FsSafeError("not-found", "directory not found", {
3413
+ cause: error instanceof Error ? error : undefined,
3414
+ });
3415
+ }
3416
+ throw error;
3417
+ }
3418
+ }
3419
+ async function movePathFallback(root, params) {
3420
+ const source = await resolvePathInRoot(root, params.fromRelative);
3421
+ await resolvePinnedRootPathInRoot(root, {
3422
+ relativePath: params.fromRelative,
3423
+ policy: PATH_ALIAS_POLICIES.strict,
3424
+ });
3425
+ const target = await resolvePathInRoot(root, params.toRelative);
3426
+ await resolvePinnedRootPathInRoot(root, {
3427
+ relativePath: params.toRelative,
3428
+ policy: PATH_ALIAS_POLICIES.unlinkTarget,
3429
+ });
3430
+ try {
3431
+ await assertNoPathAliasEscape({
3432
+ absolutePath: target.resolved,
3433
+ rootPath: target.rootReal,
3434
+ boundaryLabel: "root",
3435
+ });
3436
+ }
3437
+ catch (error) {
3438
+ throw new errors_FsSafeError("path-alias", "path alias escape blocked", {
3439
+ cause: error instanceof Error ? error : undefined,
3440
+ });
3441
+ }
3442
+ let sourceStat;
3443
+ try {
3444
+ sourceStat = await promises_namespaceObject.lstat(source.resolved);
3445
+ }
3446
+ catch (error) {
3447
+ if (path_isNotFoundPathError(error)) {
3448
+ throw new errors_FsSafeError("not-found", "file not found", {
3449
+ cause: error instanceof Error ? error : undefined,
3450
+ });
3451
+ }
3452
+ throw error;
3453
+ }
3454
+ if (sourceStat.isSymbolicLink()) {
3455
+ throw new errors_FsSafeError("symlink", "symlink not allowed");
3456
+ }
3457
+ if (sourceStat.isFile() && sourceStat.nlink > 1) {
3458
+ throw new errors_FsSafeError("hardlink", "hardlinked path not allowed");
3459
+ }
3460
+ if (!params.overwrite) {
3461
+ try {
3462
+ await promises_namespaceObject.lstat(target.resolved);
3463
+ throw new errors_FsSafeError("already-exists", "destination exists");
3464
+ }
3465
+ catch (error) {
3466
+ if (error instanceof errors_FsSafeError) {
3467
+ throw error;
3468
+ }
3469
+ if (!path_isNotFoundPathError(error)) {
3470
+ throw error;
3471
+ }
3472
+ }
3473
+ }
3474
+ const sourceParentGuard = await directory_guard_createAsyncDirectoryGuard(external_node_path_namespaceObject.dirname(source.resolved));
3475
+ const targetParentGuard = await directory_guard_createNearestExistingDirectoryGuard(target.rootReal, external_node_path_namespaceObject.dirname(target.resolved));
3476
+ await getFsSafeTestHooks()?.beforeRootFallbackMutation?.("move", target.resolved);
3477
+ await assertAsyncDirectoryGuard(sourceParentGuard);
3478
+ await assertAsyncDirectoryGuard(targetParentGuard);
3479
+ try {
3480
+ await promises_namespaceObject.rename(source.resolved, target.resolved);
3481
+ }
3482
+ catch (error) {
3483
+ if (path_isNotFoundPathError(error)) {
3484
+ throw new errors_FsSafeError("not-found", "file not found", {
3485
+ cause: error instanceof Error ? error : undefined,
3486
+ });
3487
+ }
3488
+ if (hasNodeErrorCode(error, "EEXIST")) {
3489
+ throw new errors_FsSafeError("already-exists", "destination exists", {
3490
+ cause: error instanceof Error ? error : undefined,
3491
+ });
3492
+ }
3493
+ throw error;
3494
+ }
3495
+ await assertAsyncDirectoryGuard(targetParentGuard).catch(() => undefined);
3496
+ }
3497
+ async function writeFileFallback(root, params) {
3498
+ if (params.overwrite === false) {
3499
+ await writeMissingFileFallback(root, params);
3500
+ return;
3501
+ }
3502
+ const target = await openWritableFileInRoot(root, {
3503
+ relativePath: params.relativePath,
3504
+ mkdir: params.mkdir,
3505
+ mode: params.mode,
3506
+ truncateExisting: false,
3507
+ });
3508
+ const destinationPath = target.realPath;
3509
+ const mode = params.mode ?? (target.stat.mode & 0o777);
3510
+ await target.handle.close().catch(() => { });
3511
+ const destinationGuard = await directory_guard_createAsyncDirectoryGuard(external_node_path_namespaceObject.dirname(destinationPath));
3512
+ let tempPath = null;
3513
+ let unregisterTempPath = null;
3514
+ try {
3515
+ tempPath = buildAtomicWriteTempPath(destinationPath);
3516
+ unregisterTempPath = registerTempPathForExit(tempPath);
3517
+ const writtenStat = await writeTempFileForAtomicReplace({
3518
+ tempPath,
3519
+ data: params.data,
3520
+ encoding: params.encoding,
3521
+ mode: mode || 0o600,
3522
+ });
3523
+ const commitTempPath = tempPath;
3524
+ await withAsyncDirectoryGuards([destinationGuard], async () => {
3525
+ await promises_namespaceObject.rename(commitTempPath, destinationPath);
3526
+ });
3527
+ tempPath = null;
3528
+ unregisterTempPath();
3529
+ unregisterTempPath = null;
3530
+ try {
3531
+ await verifyAtomicWriteResult({
3532
+ root,
3533
+ targetPath: destinationPath,
3534
+ expectedIdentity: writtenStat,
3535
+ });
3536
+ }
3537
+ catch (err) {
3538
+ emitWriteBoundaryWarning(`post-write verification failed: ${String(err)}`);
3539
+ throw err;
3540
+ }
3541
+ }
3542
+ finally {
3543
+ if (tempPath) {
3544
+ await promises_namespaceObject.rm(tempPath, { force: true }).catch(() => { });
3545
+ }
3546
+ unregisterTempPath?.();
3547
+ }
3548
+ }
3549
+ async function writeMissingFileFallback(root, params) {
3550
+ const { rootReal, resolved } = await resolvePathInRoot(root, params.relativePath);
3551
+ try {
3552
+ await assertNoPathAliasEscape({
3553
+ absolutePath: resolved,
3554
+ rootPath: rootReal,
3555
+ boundaryLabel: "root",
3556
+ });
3557
+ }
3558
+ catch (err) {
3559
+ throw new errors_FsSafeError("path-alias", "path alias escape blocked", { cause: err });
3560
+ }
3561
+ if (params.mkdir !== false) {
3562
+ await promises_namespaceObject.mkdir(external_node_path_namespaceObject.dirname(resolved), { recursive: true });
3563
+ }
3564
+ const parentGuard = await directory_guard_createAsyncDirectoryGuard(external_node_path_namespaceObject.dirname(resolved));
3565
+ let created = false;
3566
+ try {
3567
+ const { handle, writtenStat } = await withAsyncDirectoryGuards([parentGuard], async () => {
3568
+ const handle = await promises_namespaceObject.open(resolved, OPEN_WRITE_CREATE_FLAGS, params.mode ?? 0o600);
3569
+ created = true;
3570
+ try {
3571
+ if (typeof params.data === "string") {
3572
+ await handle.writeFile(params.data, params.encoding ?? "utf8");
3573
+ }
3574
+ else {
3575
+ await handle.writeFile(params.data);
3576
+ }
3577
+ return { handle, writtenStat: await handle.stat() };
3578
+ }
3579
+ catch (error) {
3580
+ await handle.close().catch(() => undefined);
3581
+ throw error;
3582
+ }
3583
+ }, {
3584
+ onPostGuardFailure: async ({ handle }) => {
3585
+ created = false; // Parent is untrusted now; skip outer path cleanup by name.
3586
+ await handle.close().catch(() => undefined);
3587
+ },
3588
+ });
3589
+ await handle.close();
3590
+ await verifyAtomicWriteResult({
3591
+ root,
3592
+ targetPath: resolved,
3593
+ expectedIdentity: writtenStat,
3594
+ });
3595
+ created = false;
3596
+ }
3597
+ catch (err) {
3598
+ if (hasNodeErrorCode(err, "EEXIST")) {
3599
+ throw new errors_FsSafeError("already-exists", "file already exists", {
3600
+ cause: err instanceof Error ? err : undefined,
3601
+ });
3602
+ }
3603
+ throw err;
3604
+ }
3605
+ finally {
3606
+ if (created) {
3607
+ await promises_namespaceObject.rm(resolved, { force: true }).catch(() => undefined);
3608
+ }
3609
+ }
3610
+ }
3611
+ async function copyFileFallback(root, params, source) {
3612
+ let target = null;
3613
+ let sourceClosedByStream = false;
3614
+ let targetClosedByUs = false;
3615
+ let tempHandle = null;
3616
+ let tempPath = null;
3617
+ let unregisterTempPath = null;
3618
+ let tempClosedByStream = false;
3619
+ try {
3620
+ target = await openWritableFileInRoot(root, {
3621
+ relativePath: params.relativePath,
3622
+ mkdir: params.mkdir,
3623
+ mode: params.mode,
3624
+ truncateExisting: false,
3625
+ });
3626
+ const destinationPath = target.realPath;
3627
+ const mode = params.mode ?? (target.stat.mode & 0o777);
3628
+ await target.handle.close().catch(() => { });
3629
+ targetClosedByUs = true;
3630
+ const destinationGuard = await directory_guard_createAsyncDirectoryGuard(external_node_path_namespaceObject.dirname(destinationPath));
3631
+ tempPath = buildAtomicWriteTempPath(destinationPath);
3632
+ unregisterTempPath = registerTempPathForExit(tempPath);
3633
+ tempHandle = await promises_namespaceObject.open(tempPath, OPEN_WRITE_CREATE_FLAGS, mode || 0o600);
3634
+ const sourceStream = createBoundedReadStream(source, params.maxBytes);
3635
+ const targetStream = tempHandle.createWriteStream();
3636
+ sourceStream.once("close", () => {
3637
+ sourceClosedByStream = true;
3638
+ });
3639
+ targetStream.once("close", () => {
3640
+ tempClosedByStream = true;
3641
+ });
3642
+ await (0,external_node_stream_promises_namespaceObject.pipeline)(sourceStream, targetStream);
3643
+ const writtenStat = await promises_namespaceObject.stat(tempPath);
3644
+ if (!tempClosedByStream) {
3645
+ await tempHandle.close().catch(() => { });
3646
+ tempClosedByStream = true;
3647
+ }
3648
+ tempHandle = null;
3649
+ const commitTempPath = tempPath;
3650
+ await withAsyncDirectoryGuards([destinationGuard], async () => {
3651
+ await promises_namespaceObject.rename(commitTempPath, destinationPath);
3652
+ });
3653
+ tempPath = null;
3654
+ unregisterTempPath();
3655
+ unregisterTempPath = null;
3656
+ try {
3657
+ await verifyAtomicWriteResult({
3658
+ root,
3659
+ targetPath: destinationPath,
3660
+ expectedIdentity: writtenStat,
3661
+ });
3662
+ }
3663
+ catch (err) {
3664
+ emitWriteBoundaryWarning(`post-copy verification failed: ${String(err)}`);
3665
+ throw err;
3666
+ }
3667
+ }
3668
+ catch (err) {
3669
+ if (target?.createdForWrite) {
3670
+ await promises_namespaceObject.rm(target.realPath, { force: true }).catch(() => { });
3671
+ }
3672
+ throw err;
3673
+ }
3674
+ finally {
3675
+ if (!sourceClosedByStream) {
3676
+ await source.handle.close().catch(() => { });
3677
+ }
3678
+ if (tempHandle && !tempClosedByStream) {
3679
+ await tempHandle.close().catch(() => { });
3680
+ }
3681
+ if (tempPath) {
3682
+ await promises_namespaceObject.rm(tempPath, { force: true }).catch(() => { });
3683
+ }
3684
+ unregisterTempPath?.();
3685
+ if (target && !targetClosedByUs) {
3686
+ await target.handle.close().catch(() => { });
3687
+ }
3688
+ }
3689
+ }
3690
+
3691
+ ;// CONCATENATED MODULE: ./src/lib/safe-fs.ts
3692
+
3693
+ function mapFsSafeError(error, relativePath) {
3694
+ if (error instanceof errors_FsSafeError) {
3695
+ switch(error.code){
3696
+ case "outside-workspace":
3697
+ case "invalid-path":
3698
+ throw new Error(`Resolved path is outside target directory: ${relativePath}`, {
3699
+ cause: error
3700
+ });
3701
+ case "path-alias":
3702
+ case "symlink":
3703
+ throw new Error(`Symlinks are not allowed: path contains symbolic link: ${relativePath}`, {
3704
+ cause: error
3705
+ });
3706
+ case "too-large":
3707
+ throw new Error(`File ${relativePath} exceeds size limit: ${error.message}`, {
3708
+ cause: error
3709
+ });
3710
+ default:
3711
+ throw error;
3712
+ }
3713
+ }
3714
+ throw error;
3715
+ }
3716
+ async function createSafeRoot(targetDir, maxBytes) {
3717
+ return root_impl_root(targetDir, {
3718
+ hardlinks: "reject",
3719
+ maxBytes,
3720
+ symlinks: "reject"
3721
+ });
3722
+ }
3723
+ function toSafeDirEntry(entry) {
3724
+ return {
3725
+ name: entry.name,
3726
+ isDirectory: ()=>entry.isDirectory,
3727
+ isFile: ()=>entry.isFile,
3728
+ isSymbolicLink: ()=>entry.isSymbolicLink
3729
+ };
3730
+ }
3731
+ async function readBytesWithinRoot(targetDir, relativePath, maxBytes) {
3732
+ try {
3733
+ const safeRoot = await createSafeRoot(targetDir, maxBytes);
3734
+ return await safeRoot.readBytes(relativePath, {
3735
+ maxBytes
3736
+ });
3737
+ } catch (error) {
3738
+ mapFsSafeError(error, relativePath);
3739
+ }
3740
+ }
3741
+ async function readTextWithinRoot(targetDir, relativePath, maxBytes) {
3742
+ try {
3743
+ const safeRoot = await createSafeRoot(targetDir, maxBytes);
3744
+ return await safeRoot.readText(relativePath, {
3745
+ maxBytes
3746
+ });
3747
+ } catch (error) {
3748
+ mapFsSafeError(error, relativePath);
3749
+ }
3750
+ }
3751
+ async function listDirectoryWithinRoot(targetDir, relativePath) {
3752
+ try {
3753
+ const safeRoot = await createSafeRoot(targetDir);
3754
+ const entries = await safeRoot.list(relativePath, {
3755
+ withFileTypes: true
3756
+ });
3757
+ return entries.map(toSafeDirEntry);
3758
+ } catch (error) {
3759
+ mapFsSafeError(error, relativePath);
3760
+ }
3761
+ }
3762
+ async function statWithinRoot(targetDir, relativePath) {
3763
+ try {
3764
+ const safeRoot = await createSafeRoot(targetDir);
3765
+ return await safeRoot.stat(relativePath);
3766
+ } catch (error) {
3767
+ mapFsSafeError(error, relativePath);
3768
+ }
3769
+ }
3770
+ async function pathExistsWithinRoot(targetDir, relativePath) {
3771
+ try {
3772
+ const safeRoot = await createSafeRoot(targetDir);
3773
+ return await safeRoot.exists(relativePath);
3774
+ } catch (error) {
3775
+ mapFsSafeError(error, relativePath);
3776
+ }
3777
+ }
3778
+
80
3779
  ;// CONCATENATED MODULE: ./src/gateways/project-scanner.ts
81
3780
 
82
3781
 
@@ -97,33 +3796,39 @@ const LANGUAGE_MARKERS = {
97
3796
  "build.gradle": "java",
98
3797
  "build.gradle.kts": "java"
99
3798
  };
100
- async function fileExists(path) {
3799
+ async function fileExists(rootDir, relativePath) {
101
3800
  try {
102
- const s = await (0,promises_namespaceObject.stat)(path);
103
- return s.isFile();
3801
+ if (!await pathExistsWithinRoot(rootDir, relativePath)) {
3802
+ return false;
3803
+ }
3804
+ const s = await statWithinRoot(rootDir, relativePath);
3805
+ return s.isFile;
104
3806
  } catch {
105
3807
  return false;
106
3808
  }
107
3809
  }
108
- async function dirExists(path) {
3810
+ async function dirExists(rootDir, relativePath) {
109
3811
  try {
110
- const s = await (0,promises_namespaceObject.stat)(path);
111
- return s.isDirectory();
3812
+ if (!await pathExistsWithinRoot(rootDir, relativePath)) {
3813
+ return false;
3814
+ }
3815
+ const s = await statWithinRoot(rootDir, relativePath);
3816
+ return s.isDirectory;
112
3817
  } catch {
113
3818
  return false;
114
3819
  }
115
3820
  }
116
3821
  async function discoverScripts(targetDir) {
117
- const packageJsonPath = (0,external_node_path_namespaceObject.join)(targetDir, "package.json");
118
- if (!await fileExists(packageJsonPath)) {
3822
+ const packageJsonPath = "package.json";
3823
+ if (!await fileExists(targetDir, packageJsonPath)) {
119
3824
  return [];
120
3825
  }
121
3826
  try {
122
- const fileStat = await (0,promises_namespaceObject.stat)(packageJsonPath);
3827
+ const fileStat = await statWithinRoot(targetDir, packageJsonPath);
123
3828
  if (fileStat.size > MAX_FILE_SIZE_BYTES) {
124
3829
  return [];
125
3830
  }
126
- const content = await (0,promises_namespaceObject.readFile)(packageJsonPath, "utf-8");
3831
+ const content = await readTextWithinRoot(targetDir, packageJsonPath, MAX_FILE_SIZE_BYTES);
127
3832
  const parsed = JSON.parse(content);
128
3833
  if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
129
3834
  return [];
@@ -148,13 +3853,14 @@ async function discoverScripts(targetDir) {
148
3853
  }
149
3854
  }
150
3855
  async function discoverWorkflowCommands(targetDir) {
151
- const workflowsDir = (0,external_node_path_namespaceObject.join)(targetDir, ".github", "workflows");
152
- if (!await dirExists(workflowsDir)) {
3856
+ const workflowsDir = (0,external_node_path_namespaceObject.join)(".github", "workflows");
3857
+ if (!await dirExists(targetDir, workflowsDir)) {
153
3858
  return [];
154
3859
  }
155
3860
  let files;
156
3861
  try {
157
- files = await (0,promises_namespaceObject.readdir)(workflowsDir);
3862
+ const entries = await listDirectoryWithinRoot(targetDir, workflowsDir);
3863
+ files = entries.filter((entry)=>entry.isFile()).map((entry)=>entry.name);
158
3864
  } catch {
159
3865
  return [];
160
3866
  }
@@ -163,11 +3869,11 @@ async function discoverWorkflowCommands(targetDir) {
163
3869
  for (const file of yamlFiles){
164
3870
  try {
165
3871
  const filePath = (0,external_node_path_namespaceObject.join)(workflowsDir, file);
166
- const fileStat = await (0,promises_namespaceObject.stat)(filePath);
3872
+ const fileStat = await statWithinRoot(targetDir, filePath);
167
3873
  if (fileStat.size > MAX_FILE_SIZE_BYTES) {
168
3874
  continue;
169
3875
  }
170
- const content = await (0,promises_namespaceObject.readFile)(filePath, "utf-8");
3876
+ const content = await readTextWithinRoot(targetDir, filePath, MAX_FILE_SIZE_BYTES);
171
3877
  const commands = extractRunCommandsFromYaml(content);
172
3878
  allCommands.push(...commands);
173
3879
  } catch {}
@@ -299,16 +4005,16 @@ function isUsefulCommand(cmd) {
299
4005
  * Parse mise.toml to extract task definitions.
300
4006
  * Uses simple line-based parsing for [tasks.*] sections.
301
4007
  */ async function discoverMiseTasks(targetDir) {
302
- const miseTomlPath = (0,external_node_path_namespaceObject.join)(targetDir, "mise.toml");
303
- if (!await fileExists(miseTomlPath)) {
4008
+ const miseTomlPath = "mise.toml";
4009
+ if (!await fileExists(targetDir, miseTomlPath)) {
304
4010
  return [];
305
4011
  }
306
4012
  try {
307
- const fileStat = await (0,promises_namespaceObject.stat)(miseTomlPath);
4013
+ const fileStat = await statWithinRoot(targetDir, miseTomlPath);
308
4014
  if (fileStat.size > MAX_FILE_SIZE_BYTES) {
309
4015
  return [];
310
4016
  }
311
- const content = await (0,promises_namespaceObject.readFile)(miseTomlPath, "utf-8");
4017
+ const content = await readTextWithinRoot(targetDir, miseTomlPath, MAX_FILE_SIZE_BYTES);
312
4018
  return parseMiseTomlTasks(content);
313
4019
  } catch {
314
4020
  return [];
@@ -373,7 +4079,7 @@ function parseMiseTomlTasks(content) {
373
4079
  async function detectLanguages(targetDir) {
374
4080
  const detected = new Set();
375
4081
  for (const [filename, language] of Object.entries(LANGUAGE_MARKERS)){
376
- if (await fileExists((0,external_node_path_namespaceObject.join)(targetDir, filename))) {
4082
+ if (await fileExists(targetDir, filename)) {
377
4083
  detected.add(language);
378
4084
  }
379
4085
  }
@@ -727,7 +4433,7 @@ function jsonStringifyReplacer(_, value) {
727
4433
  return value.toString();
728
4434
  return value;
729
4435
  }
730
- function cached(getter) {
4436
+ function util_cached(getter) {
731
4437
  const set = false;
732
4438
  return {
733
4439
  get value() {
@@ -843,7 +4549,7 @@ const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrac
843
4549
  function util_isObject(data) {
844
4550
  return typeof data === "object" && data !== null && !Array.isArray(data);
845
4551
  }
846
- const util_allowsEval = /* @__PURE__*/ cached(() => {
4552
+ const util_allowsEval = /* @__PURE__*/ util_cached(() => {
847
4553
  // Skip the probe under `jitless`: strict CSPs report the caught `new Function`
848
4554
  // as a `securitypolicyviolation` even though the throw is swallowed.
849
4555
  if (globalConfig.jitless) {
@@ -3093,7 +6799,7 @@ const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => {
3093
6799
  },
3094
6800
  });
3095
6801
  }
3096
- const _normalized = cached(() => normalizeDef(def));
6802
+ const _normalized = util_cached(() => normalizeDef(def));
3097
6803
  defineLazy(inst._zod, "propValues", () => {
3098
6804
  const shape = def.shape;
3099
6805
  const propValues = {};
@@ -3147,7 +6853,7 @@ const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) =>
3147
6853
  // requires cast because technically $ZodObject doesn't extend
3148
6854
  $ZodObject.init(inst, def);
3149
6855
  const superParse = inst._zod.parse;
3150
- const _normalized = cached(() => normalizeDef(def));
6856
+ const _normalized = util_cached(() => normalizeDef(def));
3151
6857
  const generateFastpass = (shape) => {
3152
6858
  const doc = new Doc(["shape", "payload", "ctx"]);
3153
6859
  const normalized = _normalized.value;
@@ -3421,7 +7127,7 @@ $constructor("$ZodDiscriminatedUnion", (inst, def) => {
3421
7127
  }
3422
7128
  return propValues;
3423
7129
  });
3424
- const disc = cached(() => {
7130
+ const disc = util_cached(() => {
3425
7131
  const opts = def.options;
3426
7132
  const map = new Map();
3427
7133
  for (const o of opts) {
@@ -8797,8 +12503,6 @@ function hasProtoKey(value) {
8797
12503
  return hasProtoKeyAtDepth(value, 0);
8798
12504
  }
8799
12505
 
8800
- ;// CONCATENATED MODULE: external "node:fs"
8801
- const external_node_fs_namespaceObject = __rspack_createRequire_require("node:fs");
8802
12506
  ;// CONCATENATED MODULE: external "node:module"
8803
12507
  const external_node_module_namespaceObject = __rspack_createRequire_require("node:module");
8804
12508
  ;// CONCATENATED MODULE: external "node:url"
@@ -8984,6 +12688,7 @@ ${miseList}
8984
12688
 
8985
12689
  const DEFAULT_MODEL = "claude-sonnet-4-6";
8986
12690
  const MAX_FILE_READ_BYTES = 102_400;
12691
+ const MAX_PROJECT_FILE_BYTES = 20 * 1024 * 1024;
8987
12692
  const AnalysisResponseSchema = schemas_object({
8988
12693
  additionalAllowRules: schemas_array(schemas_string().max(512)).max(100),
8989
12694
  suggestions: schemas_array(schemas_string().max(1024)).max(100)
@@ -9044,28 +12749,33 @@ const AnalysisResponseSchema = schemas_object({
9044
12749
  error: "Path is outside the repository"
9045
12750
  };
9046
12751
  }
12752
+ const cleanRoot = repoRoot.replace(/\/+$/, "") || "/";
12753
+ const relPath = (0,external_node_path_namespaceObject.relative)(cleanRoot, safePath);
9047
12754
  let fileBuffer;
12755
+ let truncated = false;
9048
12756
  try {
9049
- const root = repoRoot.replace(/\/+$/, "") || "/";
9050
- const [realRoot, realPath] = await Promise.all([
9051
- (0,promises_namespaceObject.realpath)(root),
9052
- (0,promises_namespaceObject.realpath)(safePath)
9053
- ]);
9054
- const realPrefix = realRoot === "/" ? "/" : `${realRoot}/`;
9055
- if (!realPath.startsWith(realPrefix) && realPath !== realRoot) {
12757
+ const fileStat = await statWithinRoot(repoRoot, relPath);
12758
+ truncated = fileStat.size > MAX_FILE_READ_BYTES;
12759
+ if (fileStat.size > MAX_PROJECT_FILE_BYTES) {
12760
+ return {
12761
+ error: "File not found or unreadable"
12762
+ };
12763
+ }
12764
+ fileBuffer = await readBytesWithinRoot(repoRoot, relPath, MAX_PROJECT_FILE_BYTES);
12765
+ } catch (error) {
12766
+ const message = error instanceof Error ? error.message : String(error);
12767
+ if (message.includes("symbolic link")) {
9056
12768
  return {
9057
12769
  error: "Path is outside the repository"
9058
12770
  };
9059
12771
  }
9060
- fileBuffer = await (0,promises_namespaceObject.readFile)(realPath);
9061
- } catch {
9062
12772
  return {
9063
12773
  error: "File not found or unreadable"
9064
12774
  };
9065
12775
  }
9066
12776
  // Buffer processing outside I/O catch — programming bugs in
9067
12777
  // findUtf8Boundary propagate instead of being silently swallowed.
9068
- if (fileBuffer.length <= MAX_FILE_READ_BYTES) {
12778
+ if (!truncated) {
9069
12779
  return {
9070
12780
  content: fileBuffer.toString("utf-8"),
9071
12781
  truncated: false
@@ -9574,9 +13284,9 @@ function detectExistingFeatures(config) {
9574
13284
  hasPostToolUse: hasHookCommand(config.hooks.postToolUse, AGENT_SHELL_RECORD)
9575
13285
  };
9576
13286
  }
9577
- async function loadExistingHooksConfig(hooksPath, deps) {
13287
+ async function loadExistingHooksConfig(repoRoot, hooksPath, deps) {
9578
13288
  try {
9579
- const raw = await deps.readFile(hooksPath, "utf-8");
13289
+ const raw = deps.readFileWithinRoot ? await deps.readFileWithinRoot(repoRoot, init_command_HOOKS_SUBPATH, 524_288) : await deps.readFile(hooksPath, "utf-8");
9580
13290
  const parsed = JSON.parse(raw);
9581
13291
  if (hasProtoKey(parsed)) {
9582
13292
  throw new Error("hooks schema validation failed");
@@ -9720,7 +13430,7 @@ async function writeConfigFile(repoRoot, subpath, content, deps) {
9720
13430
  async function handleInit(flags, deps) {
9721
13431
  const repoRoot = deps.getRepositoryRoot();
9722
13432
  const hooksPath = (0,external_node_path_namespaceObject.join)(repoRoot, init_command_HOOKS_SUBPATH);
9723
- const { config: existingConfig, error: loadError } = await loadExistingHooksConfig(hooksPath, deps);
13433
+ const { config: existingConfig, error: loadError } = await loadExistingHooksConfig(repoRoot, hooksPath, deps);
9724
13434
  if (loadError) {
9725
13435
  return false;
9726
13436
  }
@@ -9813,7 +13523,7 @@ async function handleInit(flags, deps) {
9813
13523
  const policyPath = (0,external_node_path_namespaceObject.join)(repoRoot, init_command_POLICY_SUBPATH);
9814
13524
  let existingContent = null;
9815
13525
  try {
9816
- existingContent = await deps.readFile(policyPath, "utf-8");
13526
+ existingContent = deps.readFileWithinRoot ? await deps.readFileWithinRoot(repoRoot, init_command_POLICY_SUBPATH, 524_288) : await deps.readFile(policyPath, "utf-8");
9817
13527
  } catch (error) {
9818
13528
  if (!isPathNotFoundError(error)) {
9819
13529
  throw error;
@@ -9905,7 +13615,7 @@ async function resolveReadEventsDir(env, deps) {
9905
13615
  if (logDir !== undefined && logDir !== "") {
9906
13616
  const projectRootReal = await deps.realpath(projectRoot);
9907
13617
  const candidate = (0,external_node_path_namespaceObject.resolve)(projectRoot, logDir);
9908
- if (!isWithinProjectRoot(candidate, projectRoot) && !isWithinProjectRoot(candidate, projectRootReal)) {
13618
+ if (!(0,external_node_path_namespaceObject.isAbsolute)(logDir) && !isWithinProjectRoot(candidate, projectRoot) && !isWithinProjectRoot(candidate, projectRootReal)) {
9909
13619
  return {
9910
13620
  dir: "",
9911
13621
  error: "AGENTSHELL_LOG_DIR resolves outside project root"
@@ -10161,6 +13871,8 @@ function formatEventsJson(events) {
10161
13871
 
10162
13872
 
10163
13873
 
13874
+
13875
+
10164
13876
  function parseLogArgs(args) {
10165
13877
  const options = {
10166
13878
  failures: false,
@@ -10209,19 +13921,42 @@ function parseLogArgs(args) {
10209
13921
  }
10210
13922
  return options;
10211
13923
  }
13924
+ function relativePathUnderRoot(rootDir, path) {
13925
+ const relativePath = (0,external_node_path_namespaceObject.relative)(rootDir, path);
13926
+ if (relativePath === "" || relativePath === ".." || relativePath.startsWith(`..${external_node_path_namespaceObject.sep}`) || (0,external_node_path_namespaceObject.isAbsolute)(relativePath)) {
13927
+ throw new Error("Path resolves outside project root");
13928
+ }
13929
+ return relativePath;
13930
+ }
13931
+ async function* readSafeFileLines(rootDir, path) {
13932
+ const relativePath = relativePathUnderRoot(rootDir, path);
13933
+ await statWithinRoot(rootDir, relativePath);
13934
+ const rl = (0,external_node_readline_namespaceObject.createInterface)({
13935
+ input: (0,external_node_fs_namespaceObject.createReadStream)((0,external_node_path_namespaceObject.join)(rootDir, relativePath)),
13936
+ crlfDelay: Infinity
13937
+ });
13938
+ for await (const line of rl){
13939
+ yield line;
13940
+ }
13941
+ }
10212
13942
  function createDefaultQueryDeps() {
13943
+ const rootDir = process.cwd();
10213
13944
  return {
10214
- readdir: (path)=>(0,promises_namespaceObject.readdir)(path),
10215
- stat: (path)=>(0,promises_namespaceObject.stat)(path).then((s)=>({
10216
- mtimeMs: s.mtimeMs
10217
- })),
13945
+ readdir: async (path)=>{
13946
+ const relativePath = relativePathUnderRoot(rootDir, path);
13947
+ const entries = await listDirectoryWithinRoot(rootDir, relativePath);
13948
+ return entries.map((entry)=>entry.name);
13949
+ },
13950
+ stat: async (path)=>{
13951
+ const relativePath = relativePathUnderRoot(rootDir, path);
13952
+ const s = await statWithinRoot(rootDir, relativePath);
13953
+ return {
13954
+ mtimeMs: s.mtimeMs
13955
+ };
13956
+ },
10218
13957
  realpath: (path)=>(0,promises_namespaceObject.realpath)(path),
10219
13958
  cwd: ()=>process.cwd(),
10220
- readFileLines: (path)=>(0,external_node_readline_namespaceObject.createInterface)({
10221
- input: (0,external_node_fs_namespaceObject.createReadStream)(path, {
10222
- encoding: "utf-8"
10223
- })
10224
- }),
13959
+ readFileLines: (path)=>readSafeFileLines(rootDir, path),
10225
13960
  writeStderr: (msg)=>{
10226
13961
  process.stderr.write(msg);
10227
13962
  }
@@ -10390,6 +14125,13 @@ function resolvePolicyPath(env, repoRoot) {
10390
14125
  isOverride: false
10391
14126
  };
10392
14127
  }
14128
+ function policy_relativePathUnderRoot(repoRoot, path) {
14129
+ const relativePath = (0,external_node_path_namespaceObject.relative)(repoRoot, path);
14130
+ if (relativePath === "" || relativePath === ".." || relativePath.startsWith(`..${external_node_path_namespaceObject.sep}`) || (0,external_node_path_namespaceObject.isAbsolute)(relativePath)) {
14131
+ return null;
14132
+ }
14133
+ return relativePath;
14134
+ }
10393
14135
  async function loadPolicy(env, deps) {
10394
14136
  const rawRepoRoot = deps.getRepositoryRoot();
10395
14137
  const repoRoot = await deps.realpath(rawRepoRoot);
@@ -10410,8 +14152,12 @@ async function loadPolicy(env, deps) {
10410
14152
  throw new Error(`Policy file path resolves outside the repository root: ${sanitizePath(resolvedPath)}`);
10411
14153
  }
10412
14154
  let content;
14155
+ const relativePolicyPath = policy_relativePathUnderRoot(repoRoot, candidatePath);
14156
+ if (relativePolicyPath === null) {
14157
+ throw new Error(`Policy file path resolves outside the repository root: ${sanitizePath(candidatePath)}`);
14158
+ }
10413
14159
  try {
10414
- content = await deps.readFile(resolvedPath, "utf-8");
14160
+ content = deps.readFileWithinRoot ? await deps.readFileWithinRoot(repoRoot, relativePolicyPath, 524_288) : await deps.readFile(resolvedPath, "utf-8");
10415
14161
  } catch (error) {
10416
14162
  if (isPathNotFoundError(error)) {
10417
14163
  if (isOverride) {
@@ -10691,6 +14437,7 @@ async function handleRecord(deps) {
10691
14437
 
10692
14438
 
10693
14439
 
14440
+
10694
14441
  const VERSION = "0.1.0";
10695
14442
  const USAGE = `Usage: agent-shell -c <command>
10696
14443
  agent-shell init [--flight-recorder] [--policy] [--no-flight-recorder] [--no-policy]
@@ -10735,6 +14482,7 @@ async function main() {
10735
14482
  policyDeps: {
10736
14483
  realpath: (path)=>(0,promises_namespaceObject.realpath)(path),
10737
14484
  readFile: (path, encoding)=>(0,promises_namespaceObject.readFile)(path, encoding),
14485
+ readFileWithinRoot: (rootDir, relativePath, maxBytes)=>readTextWithinRoot(rootDir, relativePath, maxBytes),
10738
14486
  getRepositoryRoot
10739
14487
  },
10740
14488
  telemetryDeps: createDefaultDeps()
@@ -10818,6 +14566,7 @@ async function main() {
10818
14566
  writeStdout: (data)=>process.stdout.write(data),
10819
14567
  writeStderr: (data)=>process.stderr.write(data),
10820
14568
  readFile: (path, encoding)=>(0,promises_namespaceObject.readFile)(path, encoding),
14569
+ readFileWithinRoot: (rootDir, relativePath, maxBytes)=>readTextWithinRoot(rootDir, relativePath, maxBytes),
10821
14570
  writeFile: (path, content, options)=>(0,promises_namespaceObject.writeFile)(path, content, options),
10822
14571
  rename: (oldPath, newPath)=>(0,promises_namespaceObject.rename)(oldPath, newPath),
10823
14572
  unlink: (path)=>(0,promises_namespaceObject.unlink)(path),
@@ -11033,4 +14782,4 @@ if (installedChunkData !== 0) { // 0 means "already installed".'
11033
14782
  // module factories are used so entry inlining is disabled
11034
14783
  // startup
11035
14784
  // Load entry module and return exports
11036
- var __webpack_exports__ = __webpack_require__(176);
14785
+ var __webpack_exports__ = __webpack_require__(391);