Update Modules/File_System.py
Browse files- Modules/File_System.py +60 -340
Modules/File_System.py
CHANGED
|
@@ -2,16 +2,20 @@ from __future__ import annotations
|
|
| 2 |
|
| 3 |
import json
|
| 4 |
import os
|
| 5 |
-
import re
|
| 6 |
import shutil
|
| 7 |
-
import stat
|
| 8 |
-
from datetime import datetime
|
| 9 |
from typing import Annotated, Optional
|
| 10 |
|
| 11 |
import gradio as gr
|
| 12 |
|
| 13 |
from app import _log_call_end, _log_call_start, _truncate_for_log
|
| 14 |
from ._docstrings import autodoc
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
|
| 17 |
TOOL_SUMMARY = (
|
|
@@ -53,335 +57,29 @@ HELP_TEXT = (
|
|
| 53 |
)
|
| 54 |
|
| 55 |
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
root = os.getenv("NYMBO_TOOLS_ROOT")
|
| 59 |
-
if root and root.strip():
|
| 60 |
-
return os.path.abspath(os.path.expanduser(root.strip()))
|
| 61 |
-
# Default to "Nymbo-Tools/Filesystem" alongside this module package
|
| 62 |
-
try:
|
| 63 |
-
here = os.path.abspath(__file__)
|
| 64 |
-
tools_dir = os.path.dirname(os.path.dirname(here)) # .../Nymbo-Tools
|
| 65 |
-
default_root = os.path.abspath(os.path.join(tools_dir, "Filesystem"))
|
| 66 |
-
return default_root
|
| 67 |
-
except Exception:
|
| 68 |
-
# Final fallback
|
| 69 |
-
return os.path.abspath(os.getcwd())
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
ROOT_DIR = _default_root()
|
| 73 |
-
# Ensure the default root directory exists to make listing/writing more convenient
|
| 74 |
-
try:
|
| 75 |
-
os.makedirs(ROOT_DIR, exist_ok=True)
|
| 76 |
-
except Exception:
|
| 77 |
-
pass
|
| 78 |
-
ALLOW_ABS = bool(int(os.getenv("UNSAFE_ALLOW_ABS_PATHS", "0")))
|
| 79 |
-
|
| 80 |
-
def _safe_err(exc: Exception | str) -> str:
|
| 81 |
-
"""Return an error string with any absolute root replaced by '/' and slashes normalized.
|
| 82 |
-
This handles variants like backslashes and duplicate slashes in OS messages.
|
| 83 |
-
"""
|
| 84 |
-
s = str(exc)
|
| 85 |
-
# Normalize to forward slashes for comparison
|
| 86 |
-
s_norm = s.replace("\\", "/")
|
| 87 |
-
root_fwd = ROOT_DIR.replace("\\", "/")
|
| 88 |
-
# Collapse duplicate slashes in root representation
|
| 89 |
-
root_variants = {ROOT_DIR, root_fwd, re.sub(r"/+", "/", root_fwd)}
|
| 90 |
-
for variant in root_variants:
|
| 91 |
-
if variant:
|
| 92 |
-
s_norm = s_norm.replace(variant, "/")
|
| 93 |
-
# Collapse duplicate slashes in final output
|
| 94 |
-
s_norm = re.sub(r"/+", "/", s_norm)
|
| 95 |
-
return s_norm
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
def _err(code: str, message: str, *, path: Optional[str] = None, hint: Optional[str] = None, data: Optional[dict] = None) -> str:
|
| 99 |
-
"""Return a structured error JSON string.
|
| 100 |
-
Fields: status='error', code, message, path?, hint?, data?, root='/'
|
| 101 |
-
"""
|
| 102 |
-
payload = {
|
| 103 |
-
"status": "error",
|
| 104 |
-
"code": code,
|
| 105 |
-
"message": message,
|
| 106 |
-
"root": "/",
|
| 107 |
-
}
|
| 108 |
-
if path is not None and path != "":
|
| 109 |
-
payload["path"] = path
|
| 110 |
-
if hint:
|
| 111 |
-
payload["hint"] = hint
|
| 112 |
-
if data:
|
| 113 |
-
payload["data"] = data
|
| 114 |
-
return json.dumps(payload, ensure_ascii=False)
|
| 115 |
-
|
| 116 |
|
| 117 |
def _resolve_path(path: str) -> tuple[str, str]:
|
| 118 |
-
"""
|
| 119 |
-
|
| 120 |
-
(unless UNSAFE_ALLOW_ABS_PATHS=1). Returns (abs_path, error_message). error_message is empty when ok.
|
| 121 |
-
"""
|
| 122 |
-
try:
|
| 123 |
-
user_input = (path or "/").strip() or "/"
|
| 124 |
-
if user_input.startswith("/"):
|
| 125 |
-
# Treat leading '/' as the virtual root for the tool.
|
| 126 |
-
rel_part = user_input.lstrip("/") or "."
|
| 127 |
-
raw = os.path.expanduser(rel_part)
|
| 128 |
-
treat_as_relative = True
|
| 129 |
-
else:
|
| 130 |
-
raw = os.path.expanduser(user_input)
|
| 131 |
-
treat_as_relative = False
|
| 132 |
-
|
| 133 |
-
if not treat_as_relative and os.path.isabs(raw):
|
| 134 |
-
if not ALLOW_ABS:
|
| 135 |
-
# Absolute paths are not allowed in safe mode
|
| 136 |
-
return "", _err(
|
| 137 |
-
"absolute_path_disabled",
|
| 138 |
-
"Absolute paths are disabled in safe mode.",
|
| 139 |
-
path=raw.replace("\\", "/"),
|
| 140 |
-
hint="Use a path relative to / (e.g., /notes/todo.txt)."
|
| 141 |
-
)
|
| 142 |
-
abs_path = os.path.abspath(raw)
|
| 143 |
-
else:
|
| 144 |
-
abs_path = os.path.abspath(os.path.join(ROOT_DIR, raw))
|
| 145 |
-
# Constrain to ROOT when not unsafe mode
|
| 146 |
-
if not ALLOW_ABS:
|
| 147 |
-
try:
|
| 148 |
-
common = os.path.commonpath([os.path.normpath(ROOT_DIR), os.path.normpath(abs_path)])
|
| 149 |
-
if common != os.path.normpath(ROOT_DIR):
|
| 150 |
-
return "", _err("path_outside_root", "Path is outside the sandbox root.", path=abs_path)
|
| 151 |
-
except Exception:
|
| 152 |
-
return "", _err("path_outside_root", "Path is outside the sandbox root.", path=abs_path)
|
| 153 |
-
|
| 154 |
-
return abs_path, ""
|
| 155 |
-
except Exception as exc:
|
| 156 |
-
return "", _err(
|
| 157 |
-
"resolve_path_failed",
|
| 158 |
-
"Failed to resolve path.",
|
| 159 |
-
path=(path or ""),
|
| 160 |
-
data={"error": _safe_err(exc)}
|
| 161 |
-
)
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
def safe_open(file, *args, **kwargs):
|
| 165 |
-
"""
|
| 166 |
-
A drop-in replacement for open() that enforces sandbox constraints.
|
| 167 |
-
"""
|
| 168 |
-
# Handle integer file descriptors (pass through) or bytes (decode)
|
| 169 |
-
if isinstance(file, int):
|
| 170 |
-
return open(file, *args, **kwargs)
|
| 171 |
-
|
| 172 |
-
path_str = os.fspath(file)
|
| 173 |
-
abs_path, err = _resolve_path(path_str)
|
| 174 |
-
if err:
|
| 175 |
-
# Extract message from JSON error if possible
|
| 176 |
-
try:
|
| 177 |
-
msg = json.loads(err)["message"]
|
| 178 |
-
except:
|
| 179 |
-
msg = err
|
| 180 |
-
raise PermissionError(f"Sandboxed open() failed: {msg}")
|
| 181 |
-
|
| 182 |
-
return open(abs_path, *args, **kwargs)
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
def _fmt_size(num_bytes: int) -> str:
|
| 189 |
-
units = ["B", "KB", "MB", "GB", "TB"]
|
| 190 |
-
size = float(num_bytes)
|
| 191 |
-
for unit in units:
|
| 192 |
-
if size < 1024.0:
|
| 193 |
-
return f"{size:.1f} {unit}"
|
| 194 |
-
size /= 1024.0
|
| 195 |
-
return f"{size:.1f} PB"
|
| 196 |
-
|
| 197 |
|
| 198 |
def _display_path(abs_path: str) -> str:
|
| 199 |
-
"""
|
| 200 |
-
|
| 201 |
-
try:
|
| 202 |
-
norm_root = os.path.normpath(ROOT_DIR)
|
| 203 |
-
norm_abs = os.path.normpath(abs_path)
|
| 204 |
-
common = os.path.commonpath([norm_root, norm_abs])
|
| 205 |
-
if os.path.normcase(common) == os.path.normcase(norm_root):
|
| 206 |
-
rel = os.path.relpath(norm_abs, norm_root)
|
| 207 |
-
if rel == ".":
|
| 208 |
-
return "/"
|
| 209 |
-
return "/" + rel.replace("\\", "/")
|
| 210 |
-
except Exception:
|
| 211 |
-
pass
|
| 212 |
-
# Fallback to original absolute path
|
| 213 |
-
return abs_path.replace("\\", "/")
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
def _list_dir(abs_path: str, *, show_hidden: bool, recursive: bool, max_entries: int) -> str:
|
| 217 |
-
from ._tree_utils import format_dir_listing
|
| 218 |
-
|
| 219 |
-
return format_dir_listing(
|
| 220 |
-
abs_path,
|
| 221 |
-
_display_path(abs_path),
|
| 222 |
-
show_hidden=show_hidden,
|
| 223 |
-
recursive=recursive,
|
| 224 |
-
max_entries=max_entries,
|
| 225 |
-
fmt_size_fn=_fmt_size,
|
| 226 |
-
)
|
| 227 |
-
|
| 228 |
|
| 229 |
-
def
|
| 230 |
-
|
| 231 |
-
|
| 232 |
-
*,
|
| 233 |
-
recursive: bool,
|
| 234 |
-
show_hidden: bool,
|
| 235 |
-
max_results: int,
|
| 236 |
-
case_sensitive: bool,
|
| 237 |
-
start_index: int,
|
| 238 |
-
) -> str:
|
| 239 |
-
if not os.path.exists(abs_path):
|
| 240 |
-
return _err("path_not_found", f"Path not found: {_display_path(abs_path)}", path=_display_path(abs_path))
|
| 241 |
-
|
| 242 |
-
query = query or ""
|
| 243 |
-
normalized_query = query if case_sensitive else query.lower()
|
| 244 |
-
if normalized_query == "":
|
| 245 |
-
return _err(
|
| 246 |
-
"missing_search_query",
|
| 247 |
-
"Search query is required for the search action.",
|
| 248 |
-
hint="Provide text in the Content field to search for.",
|
| 249 |
-
)
|
| 250 |
-
|
| 251 |
-
max_results = max(1, int(max_results) if max_results is not None else 20)
|
| 252 |
-
start_index = max(0, int(start_index) if start_index is not None else 0)
|
| 253 |
-
matches: list[tuple[str, int, str]] = []
|
| 254 |
-
errors: list[str] = []
|
| 255 |
-
files_scanned = 0
|
| 256 |
-
truncated = False
|
| 257 |
-
total_matches = 0
|
| 258 |
-
|
| 259 |
-
def _should_skip(name: str) -> bool:
|
| 260 |
-
return not show_hidden and name.startswith('.')
|
| 261 |
-
|
| 262 |
-
def _handle_match(file_path: str, line_no: int, line_text: str) -> bool:
|
| 263 |
-
nonlocal truncated, total_matches
|
| 264 |
-
total_matches += 1
|
| 265 |
-
if total_matches <= start_index:
|
| 266 |
-
return False
|
| 267 |
-
if len(matches) < max_results:
|
| 268 |
-
snippet = line_text.strip()
|
| 269 |
-
if len(snippet) > 200:
|
| 270 |
-
snippet = snippet[:197] + "…"
|
| 271 |
-
matches.append((_display_path(file_path), line_no, snippet))
|
| 272 |
-
return False
|
| 273 |
-
truncated = True
|
| 274 |
-
return True
|
| 275 |
-
|
| 276 |
-
def _search_file(file_path: str) -> bool:
|
| 277 |
-
nonlocal files_scanned
|
| 278 |
-
files_scanned += 1
|
| 279 |
-
try:
|
| 280 |
-
with open(file_path, 'r', encoding='utf-8', errors='replace') as handle:
|
| 281 |
-
for line_no, line in enumerate(handle, start=1):
|
| 282 |
-
haystack = line if case_sensitive else line.lower()
|
| 283 |
-
if normalized_query in haystack:
|
| 284 |
-
if _handle_match(file_path, line_no, line):
|
| 285 |
-
return True
|
| 286 |
-
except Exception as exc:
|
| 287 |
-
errors.append(f"{_display_path(file_path)} ({_safe_err(exc)})")
|
| 288 |
-
return truncated
|
| 289 |
-
|
| 290 |
-
if os.path.isfile(abs_path):
|
| 291 |
-
_search_file(abs_path)
|
| 292 |
-
else:
|
| 293 |
-
for root, dirs, files in os.walk(abs_path):
|
| 294 |
-
dirs[:] = [d for d in dirs if not _should_skip(d)]
|
| 295 |
-
visible_files = [f for f in files if show_hidden or not f.startswith('.')]
|
| 296 |
-
for name in visible_files:
|
| 297 |
-
file_path = os.path.join(root, name)
|
| 298 |
-
if _search_file(file_path):
|
| 299 |
-
break
|
| 300 |
-
if truncated:
|
| 301 |
-
break
|
| 302 |
-
if not recursive:
|
| 303 |
-
break
|
| 304 |
-
|
| 305 |
-
header_lines = [
|
| 306 |
-
f"Search results for {query!r}",
|
| 307 |
-
f"Scope: {_display_path(abs_path)}",
|
| 308 |
-
f"Recursive: {'yes' if recursive else 'no'}, Hidden: {'yes' if show_hidden else 'no'}, Case-sensitive: {'yes' if case_sensitive else 'no'}",
|
| 309 |
-
f"Start offset: {start_index}",
|
| 310 |
-
f"Matches returned: {len(matches)}" + (" (truncated)" if truncated else ""),
|
| 311 |
-
f"Files scanned: {files_scanned}",
|
| 312 |
-
]
|
| 313 |
-
|
| 314 |
-
next_cursor = start_index + len(matches) if truncated else None
|
| 315 |
-
|
| 316 |
-
if truncated:
|
| 317 |
-
header_lines.append(f"Matches encountered before truncation: {total_matches}")
|
| 318 |
-
header_lines.append(f"Truncated: yes — re-run with offset={next_cursor} to continue.")
|
| 319 |
-
header_lines.append(f"Next cursor: {next_cursor}")
|
| 320 |
-
else:
|
| 321 |
-
header_lines.append(f"Total matches found: {total_matches}")
|
| 322 |
-
header_lines.append("Truncated: no — end of results.")
|
| 323 |
-
header_lines.append("Next cursor: None")
|
| 324 |
-
|
| 325 |
-
if not matches:
|
| 326 |
-
if total_matches > 0 and start_index >= total_matches:
|
| 327 |
-
hint_limit = max(total_matches - 1, 0)
|
| 328 |
-
body_lines = [
|
| 329 |
-
f"No matches found at or after offset {start_index}. Total matches available: {total_matches}.",
|
| 330 |
-
(f"Try a smaller offset (≤ {hint_limit})." if hint_limit >= 0 else ""),
|
| 331 |
-
]
|
| 332 |
-
body_lines = [line for line in body_lines if line]
|
| 333 |
-
else:
|
| 334 |
-
body_lines = [
|
| 335 |
-
"No matches found.",
|
| 336 |
-
(f"Total matches encountered: {total_matches}." if total_matches else ""),
|
| 337 |
-
]
|
| 338 |
-
body_lines = [line for line in body_lines if line]
|
| 339 |
-
else:
|
| 340 |
-
body_lines = [f"{idx}. {path}:{line_no}: {text}" for idx, (path, line_no, text) in enumerate(matches, start=1)]
|
| 341 |
-
|
| 342 |
-
if errors:
|
| 343 |
-
shown = errors[:5]
|
| 344 |
-
body_lines.extend(["", "Warnings:"])
|
| 345 |
-
body_lines.extend(shown)
|
| 346 |
-
if len(errors) > len(shown):
|
| 347 |
-
body_lines.append(f"… {len(errors) - len(shown)} additional files could not be read.")
|
| 348 |
-
|
| 349 |
-
return "\n".join(header_lines) + "\n\n" + "\n".join(body_lines)
|
| 350 |
|
|
|
|
|
|
|
|
|
|
| 351 |
|
| 352 |
-
def _read_file(abs_path: str, *, offset: int, max_chars: int) -> str:
|
| 353 |
-
if not os.path.exists(abs_path):
|
| 354 |
-
return _err("file_not_found", f"File not found: {_display_path(abs_path)}", path=_display_path(abs_path))
|
| 355 |
-
if os.path.isdir(abs_path):
|
| 356 |
-
return _err("is_directory", f"Path is a directory, not a file: {_display_path(abs_path)}", path=_display_path(abs_path), hint="Provide a file path.")
|
| 357 |
-
try:
|
| 358 |
-
with open(abs_path, 'r', encoding='utf-8', errors='replace') as f:
|
| 359 |
-
data = f.read()
|
| 360 |
-
except Exception as exc:
|
| 361 |
-
return _err("read_failed", "Failed to read file.", path=_display_path(abs_path), data={"error": _safe_err(exc)})
|
| 362 |
-
total = len(data)
|
| 363 |
-
start = max(0, min(offset, total))
|
| 364 |
-
if max_chars > 0:
|
| 365 |
-
end = min(total, start + max_chars)
|
| 366 |
-
else:
|
| 367 |
-
end = total
|
| 368 |
-
chunk = data[start:end]
|
| 369 |
-
next_cursor = end if end < total else None
|
| 370 |
-
meta = {
|
| 371 |
-
"offset": start,
|
| 372 |
-
"returned": len(chunk),
|
| 373 |
-
"total": total,
|
| 374 |
-
"next_cursor": next_cursor,
|
| 375 |
-
"path": _display_path(abs_path),
|
| 376 |
-
}
|
| 377 |
-
header = (
|
| 378 |
-
f"Reading {_display_path(abs_path)}\n"
|
| 379 |
-
f"Offset {start}, returned {len(chunk)} of {total}."
|
| 380 |
-
+ (f"\nNext cursor: {next_cursor}" if next_cursor is not None else "")
|
| 381 |
-
)
|
| 382 |
-
sep = "\n\n---\n\n"
|
| 383 |
-
return header + sep + chunk
|
| 384 |
|
|
|
|
|
|
|
|
|
|
| 385 |
|
| 386 |
def _ensure_parent(abs_path: str, create_dirs: bool) -> None:
|
| 387 |
parent = os.path.dirname(abs_path)
|
|
@@ -416,7 +114,6 @@ def _move_copy(action: str, src: str, dst: str, *, overwrite: bool) -> str:
|
|
| 416 |
if not os.path.exists(src):
|
| 417 |
return _err("source_not_found", f"Source not found: {_display_path(src)}", path=_display_path(src))
|
| 418 |
if os.path.isdir(dst):
|
| 419 |
-
# allow moving into an existing directory
|
| 420 |
dst_path = os.path.join(dst, os.path.basename(src))
|
| 421 |
else:
|
| 422 |
dst_path = dst
|
|
@@ -451,7 +148,6 @@ def _delete(abs_path: str, *, recursive: bool) -> str:
|
|
| 451 |
return _err("path_not_found", f"Path not found: {_display_path(abs_path)}", path=_display_path(abs_path))
|
| 452 |
if os.path.isdir(abs_path):
|
| 453 |
if not recursive:
|
| 454 |
-
# Refuse to delete a dir unless recursive=True
|
| 455 |
return _err("requires_recursive", "Refusing to delete a directory without recursive=True", path=_display_path(abs_path), hint="Pass recursive=True to delete a directory.")
|
| 456 |
shutil.rmtree(abs_path)
|
| 457 |
else:
|
|
@@ -460,22 +156,46 @@ def _delete(abs_path: str, *, recursive: bool) -> str:
|
|
| 460 |
except Exception as exc:
|
| 461 |
return _err("delete_failed", "Failed to delete path.", path=_display_path(abs_path), data={"error": _safe_err(exc)})
|
| 462 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 463 |
|
| 464 |
def _info(abs_path: str) -> str:
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
| 468 |
-
return _err("stat_failed", "Failed to stat path.", path=_display_path(abs_path), data={"error": _safe_err(exc)})
|
| 469 |
-
info = {
|
| 470 |
-
"path": _display_path(abs_path),
|
| 471 |
-
"type": "directory" if stat.S_ISDIR(st.st_mode) else "file",
|
| 472 |
-
"size": st.st_size,
|
| 473 |
-
"modified": datetime.fromtimestamp(st.st_mtime).isoformat(sep=' ', timespec='seconds'),
|
| 474 |
-
"created": datetime.fromtimestamp(st.st_ctime).isoformat(sep=' ', timespec='seconds'),
|
| 475 |
-
"mode": oct(st.st_mode),
|
| 476 |
-
"root": "/",
|
| 477 |
-
}
|
| 478 |
-
return json.dumps(info, indent=2)
|
| 479 |
|
| 480 |
|
| 481 |
@autodoc(summary=TOOL_SUMMARY)
|
|
|
|
| 2 |
|
| 3 |
import json
|
| 4 |
import os
|
|
|
|
| 5 |
import shutil
|
|
|
|
|
|
|
| 6 |
from typing import Annotated, Optional
|
| 7 |
|
| 8 |
import gradio as gr
|
| 9 |
|
| 10 |
from app import _log_call_end, _log_call_start, _truncate_for_log
|
| 11 |
from ._docstrings import autodoc
|
| 12 |
+
from ._core import (
|
| 13 |
+
filesystem_sandbox,
|
| 14 |
+
ROOT_DIR,
|
| 15 |
+
ALLOW_ABS,
|
| 16 |
+
safe_open,
|
| 17 |
+
_fmt_size,
|
| 18 |
+
)
|
| 19 |
|
| 20 |
|
| 21 |
TOOL_SUMMARY = (
|
|
|
|
| 57 |
)
|
| 58 |
|
| 59 |
|
| 60 |
+
# Convenience aliases using the filesystem sandbox
|
| 61 |
+
_sandbox = filesystem_sandbox
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
def _resolve_path(path: str) -> tuple[str, str]:
|
| 64 |
+
"""Resolve path using the filesystem sandbox."""
|
| 65 |
+
return _sandbox.resolve_path(path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
def _display_path(abs_path: str) -> str:
|
| 68 |
+
"""Display path using the filesystem sandbox."""
|
| 69 |
+
return _sandbox.display_path(abs_path)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
def _err(code: str, message: str, *, path: Optional[str] = None, hint: Optional[str] = None, data: Optional[dict] = None) -> str:
|
| 72 |
+
"""Return a structured error JSON string."""
|
| 73 |
+
return _sandbox.err(code, message, path=path, hint=hint, data=data)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
+
def _safe_err(exc: Exception | str) -> str:
|
| 76 |
+
"""Return an error string with root replaced."""
|
| 77 |
+
return _sandbox.safe_err(exc)
|
| 78 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
+
# ---------------------------------------------------------------------------
|
| 81 |
+
# File_System-specific operations (write, mkdir, move, copy, delete)
|
| 82 |
+
# ---------------------------------------------------------------------------
|
| 83 |
|
| 84 |
def _ensure_parent(abs_path: str, create_dirs: bool) -> None:
|
| 85 |
parent = os.path.dirname(abs_path)
|
|
|
|
| 114 |
if not os.path.exists(src):
|
| 115 |
return _err("source_not_found", f"Source not found: {_display_path(src)}", path=_display_path(src))
|
| 116 |
if os.path.isdir(dst):
|
|
|
|
| 117 |
dst_path = os.path.join(dst, os.path.basename(src))
|
| 118 |
else:
|
| 119 |
dst_path = dst
|
|
|
|
| 148 |
return _err("path_not_found", f"Path not found: {_display_path(abs_path)}", path=_display_path(abs_path))
|
| 149 |
if os.path.isdir(abs_path):
|
| 150 |
if not recursive:
|
|
|
|
| 151 |
return _err("requires_recursive", "Refusing to delete a directory without recursive=True", path=_display_path(abs_path), hint="Pass recursive=True to delete a directory.")
|
| 152 |
shutil.rmtree(abs_path)
|
| 153 |
else:
|
|
|
|
| 156 |
except Exception as exc:
|
| 157 |
return _err("delete_failed", "Failed to delete path.", path=_display_path(abs_path), data={"error": _safe_err(exc)})
|
| 158 |
|
| 159 |
+
# ---------------------------------------------------------------------------
|
| 160 |
+
# Read-only operations delegated to sandbox
|
| 161 |
+
# ---------------------------------------------------------------------------
|
| 162 |
+
|
| 163 |
+
def _list_dir(abs_path: str, *, show_hidden: bool, recursive: bool, max_entries: int) -> str:
|
| 164 |
+
"""List directory contents as a visual tree."""
|
| 165 |
+
return _sandbox.list_dir(abs_path, show_hidden=show_hidden, recursive=recursive, max_entries=max_entries)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _search_text(
|
| 169 |
+
abs_path: str,
|
| 170 |
+
query: str,
|
| 171 |
+
*,
|
| 172 |
+
recursive: bool,
|
| 173 |
+
show_hidden: bool,
|
| 174 |
+
max_results: int,
|
| 175 |
+
case_sensitive: bool,
|
| 176 |
+
start_index: int,
|
| 177 |
+
) -> str:
|
| 178 |
+
"""Search for text within files."""
|
| 179 |
+
return _sandbox.search_text(
|
| 180 |
+
abs_path,
|
| 181 |
+
query,
|
| 182 |
+
recursive=recursive,
|
| 183 |
+
show_hidden=show_hidden,
|
| 184 |
+
max_results=max_results,
|
| 185 |
+
case_sensitive=case_sensitive,
|
| 186 |
+
start_index=start_index,
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def _read_file(abs_path: str, *, offset: int, max_chars: int) -> str:
|
| 191 |
+
"""Read file contents with optional offset and character limit."""
|
| 192 |
+
return _sandbox.read_file(abs_path, offset=offset, max_chars=max_chars)
|
| 193 |
+
|
| 194 |
|
| 195 |
def _info(abs_path: str) -> str:
|
| 196 |
+
"""Get file/directory metadata as JSON."""
|
| 197 |
+
return _sandbox.info(abs_path)
|
| 198 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 199 |
|
| 200 |
|
| 201 |
@autodoc(summary=TOOL_SUMMARY)
|