Agently / app /tools /write_file.py
CI Deploy
Deploy 2026-07-03 10:22 UTC
60072ac
Raw
History Blame Contribute Delete
1.24 kB
from __future__ import annotations
from pathlib import Path
from langchain_core.tools import tool
from app.utils.logger import get_logger
logger = get_logger(__name__)
ALLOWED_ROOT = Path.home() / "Desktop" / "AI-workingdir"
def _resolve_safe_write_path(path: str) -> Path | None:
try:
ALLOWED_ROOT.mkdir(parents=True, exist_ok=True)
target = (ALLOWED_ROOT / path).resolve()
if ALLOWED_ROOT.resolve() not in target.parents and ALLOWED_ROOT.resolve() != target:
logger.warning("Path traversal detected: %s", path)
return None
return target
except Exception:
return None
@tool("write_file")
def write_file(filename: str, content: str) -> str:
"""Write content to a file in the sandboxed working directory."""
target = _resolve_safe_write_path(filename)
if not target:
return f"Access denied. Can only write to {ALLOWED_ROOT}"
try:
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(content, encoding="utf-8")
return f"Successfully wrote to {target}"
except Exception:
logger.exception("File write failed: %s", filename)
return "Write failed. Unable to write to the file."