Files
ai-agent/backend/files/hostfiles.py
gabrielvidalandClaude Opus 5.5 b7427475be feat(plugins): move the file explorer/viewer and the context editor into live plugins
The host file browser + viewer (/file/*, HostFilePage, the project Files
card) and the context tree + editor (/_/*, Editor, the FilesPanel tree) are
the file-explorer and context-editor plugins' now.

- bridges (plugins/hubfiles.py): hostfiles.read (as the caller; operator-
  approved; machine tokens refused), context.read / context.write (owner)
- /api/bundle, /api/file, /api/host-file, /api/host-files[/recent] retired;
  /api/host-file/raw stays for media and downloads
- pages that route themselves: aiAgentPlugin.setRoute / onRoute; download,
  back; plugin pages pad above the phone composer
- /file/* and /_/* redirect through opens (host-file, context-file)
- mock: filesPlugins.ts; docs and CLAUDE.md updated

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 13:44:41 +01:00

375 lines
14 KiB
Python

"""Files on the host, addressed by the path a message names.
Claude writes the full path of the files it makes or changes
(``/home/<u>/projects/calamite/marketing/report.md``, or ``~/projects/…``);
the viewer turns the ones the caller may read into a link that opens the file,
and the Project page browses the same files. A path resolves to one of the
container's mounts:
- ``~/projects/<slug>/…`` → ``PROJECTS_DIR`` — anyone with *view* on <slug>;
- owner only: ``~/homelab/…`` → ``HOMELAB_DIR`` (the whole repo, read-only;
without that mount, the parts the app already mounts: ``services/``,
``data/``, ``.claude/``, ``CLAUDE.md``, ``GOAL.md``, ``docs/screenshots/``)
and ``~/worktrees/<dir>/…``.
Paths come back spelled ``~/…`` so nothing here needs the host's home dir.
Never listed or served, to anyone: secrets (``.env*`` but the examples, keys,
credentials, databases, ACME stores), the noise dirs (``.git``,
``node_modules``, …) and the lab's runtime state (``services/*/data``,
``data/tmp``) — a hidden path answers 404 like a missing one.
"""
from __future__ import annotations
import dataclasses
import datetime
import os
import re
from pathlib import Path, PurePosixPath
import projects as projects_mod
from core.config import IMAGE_EXTS, MD_EXTS, SCREENSHOTS_DIR, WORKSPACE
# The homelab checkout, mounted read-only (services/ai-agent/docker-compose.yml).
HOMELAB_DIR = Path(os.environ.get("HOMELAB_DIR", "/homelab"))
from diff.worktreediff import WORKTREES_DIR
from servicesdir import SERVICES_DIR
from users.caller import Caller
# `/home/<user>/`, `~/` or `$HOME/` — what precedes a served root in a message.
_HOME_RE = re.compile(r"^(?:/home/[^/]+|~|\$HOME|\$\{HOME\})/")
NOISE_DIRS = {
".git", "node_modules", ".venv", "venv", "__pycache__", ".turbo", ".cache",
".next", ".pytest_cache", ".mypy_cache", ".ruff_cache", "pb_data",
".gradle", ".expo",
}
_SECRET_NAME_RE = re.compile(
r"^(?:\.env(?!\.(?:example|sample|template|dist)$)(?:\..*)?"
r"|.*\.(?:pem|key|p12|pfx|keystore|jks|kdbx)"
r"|id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?"
r"|\.(?:npmrc|netrc|pypirc|git-credentials)"
r"|(?:credentials|service-account|secrets?)(?:[._-].*)?\.(?:json|ya?ml|toml|txt)"
r"|\.credentials\.json|acme(?:[._-].*)?\.json|users_database\.ya?ml"
r"|.*\.(?:sqlite3?|db)(?:-(?:wal|shm|journal))?|\.storage|secrets?)$",
re.IGNORECASE)
CSV_EXTS = {".csv", ".tsv"}
VIDEO_EXTS = {".mp4", ".webm", ".mov", ".m4v", ".ogv"}
_TEXT_EXTS = {
".txt", ".json", ".jsonl", ".yml", ".yaml", ".toml", ".ini", ".cfg", ".conf",
".py", ".sh", ".bash", ".js", ".mjs", ".cjs", ".ts", ".tsx", ".jsx", ".css",
".scss", ".html", ".htm", ".xml", ".svg", ".sql", ".go", ".rs", ".java",
".kt", ".swift", ".c", ".h", ".cpp", ".hpp", ".rb", ".php", ".lua", ".log",
".gitignore", ".dockerignore", ".editorconfig", ".jinja", ".j2",
".vue", ".svelte", ".astro", ".gd", ".glsl", ".wgsl", ".tex", ".rst", ".org",
}
# What "Recent documents" on the Project page lists: things people read, not code.
# (No .html: in a web project that is the site's own pages.)
DOC_EXTS = MD_EXTS | CSV_EXTS | {".pdf", ".txt", ".xlsx", ".xls",
".docx", ".odt", ".ods", ".pptx"}
TEXT_MAX_BYTES = 512 * 1024
LIST_MAX = 2000
RECENT_SCAN_MAX = 20000
@dataclasses.dataclass(frozen=True)
class Resolved:
host: str # `~/projects/calamite/marketing/report.md`
abs: Path # the container path
root_host: str # the root it lives under (`~/projects/calamite`)
root_abs: Path
project: str | None # the project slug, when under ~/projects
rel: str # path below the root ("" = the root itself)
def child(self, name: str) -> "Resolved":
rel = f"{self.rel}/{name}" if self.rel else name
return dataclasses.replace(self, host=f"{self.host}/{name}",
abs=self.abs / name, rel=rel)
# Below ~/homelab: the services' runtime state (mailboxes, databases, tokens)
# and data/tmp (scratch + secrets), whichever root the path came through.
_LAB_STATE_RE = re.compile(r"^(?:services/[^/]+/data|data/tmp)(?:/|$)")
def hidden(rel: str | PurePosixPath, root_host: str = "") -> bool:
"""A path nobody reads through the viewer: noise dirs, secrets, lab state."""
parts = PurePosixPath(rel).parts
if any(p in NOISE_DIRS for p in parts) or any(_SECRET_NAME_RE.match(p) for p in parts):
return True
full = f"{root_host}/{rel}" if rel else root_host
return full.startswith("~/homelab/") and bool(_LAB_STATE_RE.match(full[len("~/homelab/"):]))
def _tail(path: str) -> list[str] | None:
"""The parts of ``path`` below the home dir, or None if it isn't a
home-relative absolute path (or tries to climb out)."""
p = (path or "").strip().replace("\\", "/")
m = _HOME_RE.match(p)
if not m:
return None
parts = [x for x in p[m.end():].split("/") if x not in ("", ".")]
if not parts or ".." in parts:
return None
return parts
def _root(parts: list[str], caller: Caller) -> tuple[str, Path, str | None, int] | None:
"""``(root host path, root container dir, project slug, parts consumed)``."""
head = parts[0]
if head == "projects" and len(parts) >= 2:
slug = parts[1]
if not caller.can(slug, "view"):
return None
entry = projects_mod._safe_entry(slug)
if entry is None:
return None
return f"~/projects/{slug}", entry, slug, 2
if not caller.is_owner:
return None
if head == "worktrees" and len(parts) >= 2 and not parts[1].startswith("."):
return f"~/worktrees/{parts[1]}", WORKTREES_DIR / parts[1], None, 2
if head == "homelab" and HOMELAB_DIR.is_dir():
return "~/homelab", HOMELAB_DIR, None, 1
if head == "homelab" and len(parts) >= 2:
sub = parts[1]
if sub == "services":
return "~/homelab/services", SERVICES_DIR, None, 2
if sub in ("data", ".claude"):
return f"~/homelab/{sub}", WORKSPACE / sub, None, 2
if sub in ("CLAUDE.md", "GOAL.md") and len(parts) == 2:
return f"~/homelab/{sub}", WORKSPACE / sub, None, 2
if parts[1:3] == ["docs", "screenshots"]:
return "~/homelab/docs/screenshots", SCREENSHOTS_DIR, None, 3
return None
def resolve(caller: Caller, path: str) -> Resolved | None:
"""``path`` as this caller may read it, or None (unknown, not theirs,
hidden, or a symlink out of its root). Existence is not checked."""
parts = _tail(path)
if not parts:
return None
root = _root(parts, caller)
if root is None:
return None
root_host, root_abs, slug, used = root
rest = parts[used:]
rel = "/".join(rest)
if hidden(rel, root_host):
return None
try:
root_real = root_abs.resolve()
ap = (root_abs / rel).resolve() if rest else root_real
real_rel = ap.relative_to(root_real)
except (OSError, ValueError):
return None
if rest and hidden(real_rel.as_posix(), root_host):
# A link inside the root to something nobody reads: `notes.txt → .env`
# has an innocent name and a secret behind it.
return None
host = root_host + (f"/{rel}" if rel else "")
return Resolved(host=host, abs=ap, root_host=root_host, root_abs=root_real,
project=slug, rel=rel)
def project_root(caller: Caller, slug: str) -> Resolved | None:
return resolve(caller, f"~/projects/{slug}")
# ── what a file is ───────────────────────────────────────────────────────────
def kind_of(name: str) -> str:
ext = PurePosixPath(name).suffix.lower()
if ext in MD_EXTS:
return "markdown"
if ext in CSV_EXTS:
return "csv"
if ext in IMAGE_EXTS:
return "image"
if ext in VIDEO_EXTS:
return "video"
if ext == ".pdf":
return "pdf"
if ext in _TEXT_EXTS or name in ("Dockerfile", "Makefile", "LICENSE"):
return "text"
return "binary"
def _looks_text(head: bytes) -> bool:
if b"\0" in head:
return False
try:
head.decode("utf-8")
return True
except UnicodeDecodeError as e:
# A multi-byte char cut by the sniff window is still text.
return e.start >= len(head) - 3
def _escapes(root_real: Path, entry_path: str, is_link: bool) -> bool:
"""A symlink whose target is outside the root, or is a hidden path inside
it — a secret, a noise dir (resolve() refuses both)."""
if not is_link:
return False
try:
return hidden(Path(os.path.realpath(entry_path)).relative_to(root_real).as_posix())
except ValueError:
return True
def _iso(ts: float) -> str:
return datetime.datetime.fromtimestamp(ts, datetime.timezone.utc).isoformat()
def _parent(r: Resolved) -> str | None:
if not r.rel:
return None
up = r.rel.rsplit("/", 1)[0] if "/" in r.rel else ""
return r.root_host + (f"/{up}" if up else "")
def file_payload(r: Resolved) -> dict:
"""A file's card + its text (≤ ``TEXT_MAX_BYTES``) when it is text."""
st = r.abs.stat()
name = r.abs.name
kind = kind_of(name)
content = None
truncated = False
if kind in ("markdown", "csv", "text") or kind == "binary":
with open(r.abs, "rb") as f:
raw = f.read(TEXT_MAX_BYTES + 1)
if kind == "binary" and raw and _looks_text(raw[:8192]):
kind = "text"
if kind != "binary":
truncated = len(raw) > TEXT_MAX_BYTES
content = raw[:TEXT_MAX_BYTES].decode("utf-8", errors="replace")
return {
"path": r.host,
"name": name,
"dir": _parent(r) or r.root_host,
"root": r.root_host,
"project": r.project,
"rel": r.rel,
"kind": kind,
"size": st.st_size,
"mtime": _iso(st.st_mtime),
"content": content,
"truncated": truncated,
}
def list_dir(r: Resolved) -> dict:
"""One directory level, folders first, hidden entries left out."""
entries = []
with os.scandir(r.abs) as it:
for e in it:
c = r.child(e.name)
if hidden(c.rel, r.root_host):
continue
try:
is_dir = e.is_dir()
st = e.stat()
except OSError:
continue
if _escapes(r.root_abs, e.path, e.is_symlink()):
continue
entries.append({
"name": e.name,
"path": c.host,
"isDir": is_dir,
"size": 0 if is_dir else st.st_size,
"mtime": _iso(st.st_mtime),
"kind": "dir" if is_dir else kind_of(e.name),
})
if len(entries) >= LIST_MAX:
break
entries.sort(key=lambda x: (not x["isDir"], x["name"].lower()))
return {
"path": r.host,
"name": r.abs.name if r.rel else r.root_host.rsplit("/", 1)[-1],
"root": r.root_host,
"project": r.project,
"rel": r.rel,
"parent": _parent(r),
"entries": entries,
"truncated": len(entries) >= LIST_MAX,
}
def recent_documents(r: Resolved, limit: int = 12) -> list[dict]:
"""The documents under ``r`` (reports, notes, tables…), newest first."""
found: list[tuple[float, str, int]] = []
seen = 0
for dirpath, dirnames, filenames in os.walk(r.abs):
dirnames[:] = [d for d in dirnames
if d not in NOISE_DIRS and d not in ("dist", "build")
and not _SECRET_NAME_RE.match(d)]
for fn in filenames:
seen += 1
if PurePosixPath(fn).suffix.lower() not in DOC_EXTS or _SECRET_NAME_RE.match(fn):
continue
ap = os.path.join(dirpath, fn)
if _escapes(r.root_abs, ap, os.path.islink(ap)):
continue
try:
st = os.stat(ap)
except OSError:
continue
found.append((st.st_mtime, ap, st.st_size))
if seen > RECENT_SCAN_MAX:
break
found.sort(reverse=True)
out = []
base = str(r.abs)
for mtime, ap, size in found[:limit]:
rel = os.path.relpath(ap, base)
name = os.path.basename(ap)
out.append({
"name": name,
"path": f"{r.host}/{rel}",
"isDir": False,
"size": size,
"mtime": _iso(mtime),
"kind": kind_of(name),
})
return out
def roots(caller: Caller) -> list[dict]:
"""Where this caller may start browsing: their projects (a guest: the ones
granted to them, never a listing of the folder), and for the owner every
project, ``~/homelab`` (or the parts of it mounted) and each worktree."""
out: list[dict] = []
if caller.is_owner:
try:
slugs = sorted(p.name for p in projects_mod.PROJECTS_DIR.iterdir()
if not p.name.startswith("."))
except OSError:
slugs = []
else:
slugs = sorted(caller.projects)
for slug in slugs:
r = project_root(caller, slug)
if r is not None and r.abs.is_dir():
out.append({"path": r.host, "name": slug, "kind": "project", "isDir": True})
if not caller.is_owner:
return out
lab = ["~/homelab"] if HOMELAB_DIR.is_dir() else [
"~/homelab/services", "~/homelab/data", "~/homelab/.claude", "~/homelab/CLAUDE.md"]
for p in lab:
r = resolve(caller, p)
if r is not None and r.abs.exists():
out.append({"path": r.host, "name": r.host[2:], "kind": "homelab",
"isDir": r.abs.is_dir()})
try:
trees = sorted(p.name for p in WORKTREES_DIR.iterdir()
if p.is_dir() and not p.name.startswith("."))
except OSError:
trees = []
for name in trees:
r = resolve(caller, f"~/worktrees/{name}")
if r is not None:
out.append({"path": r.host, "name": name, "kind": "worktree", "isDir": True})
return out