File Agent Capabilities

  • Organise a folder by file type, date, or AI-classified content
  • Bulk rename files using date patterns, regex, or semantic rules
  • Convert formats: DOCX → PDF, XLSX → CSV, PNG → WEBP
  • Watch a folder and auto-process new files as they arrive
  • Detect and remove duplicate files
  • Archive old files based on access date or size
Always dry-run first. Run with dry_run: true to preview all actions before applying them. File operations are hard to reverse.

Required Tools

ToolPurpose
filesystemList, copy, move, delete files and directories
pattern_renameRename files using regex or date-extraction patterns
file_transformConvert file formats (requires pandoc / ImageMagick)
hash_checkerCompute MD5/SHA256 hashes for duplicate detection

Organise Downloads Folder Agent

# agents/file-organizer.yaml
name: file-organizer
model: gpt-4o-mini
temperature: 0.0
tools:
  - filesystem
system: |
  You are a file organiser. Given a list of files, move each one to the
  correct subfolder based on extension:
    .pdf .doc .docx .txt → Documents/
    .jpg .jpeg .png .gif .webp .svg → Images/
    .mp4 .mov .avi .mkv → Videos/
    .mp3 .flac .wav .aac → Audio/
    .zip .tar.gz .7z .rar → Archives/
    .py .js .ts .go .rs .yaml .json → Code/
    Anything else → Misc/
  ALWAYS confirm the move list before executing.
  Use dry_run=true for the first confirmation pass.
from openclaw import Agent
import os

agent = Agent.from_config("agents/file-organizer.yaml")
downloads = os.path.expanduser("~/Downloads")
files = os.listdir(downloads)
file_list = "\n".join(files)

# First: dry run
plan = agent.run(f"Plan (dry run) how to organise these files in {downloads}:\n{file_list}")
print(plan)

# After human review:
# result = agent.run(f"Execute the organisation of {downloads}")

Bulk Rename with Regex Agent

from openclaw import Agent
import re, os, shutil
from pathlib import Path

agent = Agent.from_config("agents/file-organizer.yaml")

def bulk_rename(folder: str, task: str, dry_run: bool = True) -> list[tuple[str,str]]:
    """
    Ask the agent to produce a rename plan, then (optionally) execute it.
    Returns list of (old_name, new_name) tuples.
    """
    files = os.listdir(folder)
    file_list = "\n".join(files)
    
    plan_prompt = (
        f"Files to rename in {folder}:\n{file_list}\n\n"
        f"Task: {task}\n\n"
        f"Return ONLY a JSON array of {{\"old\": \"...\", \"new\": \"...\"}} objects."
    )
    import json
    raw = agent.run(plan_prompt)
    m = re.search(r'\[.*\]', raw, re.DOTALL)
    renames = json.loads(m.group()) if m else []
    
    if not dry_run:
        for r in renames:
            old = Path(folder) / r["old"]
            new = Path(folder) / r["new"]
            if old.exists():
                old.rename(new)
    return [(r["old"], r["new"]) for r in renames]

# Preview only
plan = bulk_rename("~/Photos/2024", "Rename to YYYY-MM-DD-[original].jpg using EXIF date", dry_run=True)
for old, new in plan[:5]:
    print(f"  {old} → {new}")

Watch Folder Agent

import time
from pathlib import Path
from openclaw import Agent

agent = Agent.from_config("agents/file-organizer.yaml")
WATCH_DIR = Path("~/incoming").expanduser()
PROCESSED: set[str] = set()

def process_new_file(filepath: Path) -> None:
    result = agent.run(
        f"A new file arrived: {filepath.name}\n"
        f"Size: {filepath.stat().st_size} bytes\n"
        f"Classify and suggest where to move it."
    )
    print(f"[{filepath.name}] → {result}")

print(f"Watching {WATCH_DIR} for new files...")
while True:
    for f in WATCH_DIR.iterdir():
        if f.is_file() and f.name not in PROCESSED:
            PROCESSED.add(f.name)
            process_new_file(f)
    time.sleep(5)

Duplicate File Detection Agent

import hashlib
from pathlib import Path
from collections import defaultdict

def find_duplicates(folder: str) -> dict[str, list[str]]:
    """Find files with identical content using SHA-256."""
    hashes: dict[str, list[str]] = defaultdict(list)
    for path in Path(folder).rglob("*"):
        if path.is_file():
            sha256 = hashlib.sha256(path.read_bytes()).hexdigest()
            hashes[sha256].append(str(path))
    return {h: paths for h, paths in hashes.items() if len(paths) > 1}

dupes = find_duplicates("~/Documents")
print(f"Found {len(dupes)} sets of duplicate files:")
for sha, paths in dupes.items():
    print(f"\n  {sha[:12]}... ({len(paths)} copies):")
    for p in paths:
        print(f"    {p}")

Scheduling File Agents with Cron

# Run organiser nightly at 23:00
0 23 * * * /path/to/.venv/bin/python /path/to/organise.py >> /var/log/file-agent.log 2>&1

# Watch folder is better run as a systemd service:
# /etc/systemd/system/file-watcher.service
[Unit]
Description=OpenClaw File Watcher
[Service]
ExecStart=/path/to/.venv/bin/python /path/to/watch.py
Restart=always
[Install]
WantedBy=multi-user.target