Files
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

172 lines
6.4 KiB
Python

"""``hostfiles.read``, ``context.read`` and ``context.write`` — hub bridges
for the ``file-explorer`` and ``context-editor`` live plugins.
* ``hostfiles.read`` (caller-scoped; guests reach their granted projects only,
the owner every served root; secrets & noise dirs always 404):
- ``GET …/hub/host-file?path=`` → one file's metadata + text content (≤ 512 KB)
- ``GET …/hub/host-files?path=`` → one directory listing (folders first)
- ``GET …/hub/host-files/recent?project=&limit=`` → a project's recent docs
- ``GET …/hub/host-files/roots`` → where the caller may start browsing
* ``context.read`` (owner-only, operator approval):
- ``GET …/hub/context/bundle`` → the workspace context catalog (metadata +
real token counts + cost totals + pricing)
- ``GET …/hub/context/file?path=`` → one context file with content
* ``context.write`` (owner-only, operator approval, handler-only):
- ``PUT …/hub/context/file`` ``{"path", "content"}`` → save an editable
context file and refresh the file index
A paired machine's proxy token (``via == "worker"`` — an owner's worker reads
as the owner on the tool-proxy door) is refused on all of them: the retired
``/api/host-file`` / ``/api/bundle`` never answered a machine, nothing on a
machine needs these, and an owner's devbox must not read ``~/homelab``.
"""
from __future__ import annotations
import json
from typing import Any
from fastapi import APIRouter, HTTPException, Request
from starlette.concurrency import run_in_threadpool
from plugins.hubbridge import _caller_for_who, _check_cap
from plugins.proxyroutes import _error
router = APIRouter(include_in_schema=False)
_BASE = "/proxy/tools/plugins/{pid}/hub"
CAP_HOST = "hostfiles.read"
CAP_CTX_READ = "context.read"
CAP_CTX_WRITE = "context.write"
def _gate(request: Request, pid: str, cap: str, **kw):
"""``_check_cap`` plus: no machine token (see the module docstring)."""
deps, who, rec, err = _check_cap(request, pid, cap, **kw)
if not err and getattr(who, "via", None) == "worker":
err = _error(403, f"{cap} isn't open to a machine's token", "capability")
return deps, who, rec, err
def _http_err(e: HTTPException):
d = e.detail
msg = d.get("message") if isinstance(d, dict) else str(d)
kind = (d.get("kind") if isinstance(d, dict) else None) or (
"not_found" if e.status_code == 404
else "forbidden" if e.status_code == 403
else "bad_request" if e.status_code == 400
else "error"
)
return _error(e.status_code, str(msg or "error"), kind)
async def _json_body(request: Request) -> dict[str, Any] | None:
try:
body = await request.json()
except (ValueError, json.JSONDecodeError):
return None
return body if isinstance(body, dict) else None
# ── hostfiles.read (caller-scoped: owner + guests) ───────────────────────────
async def _run_host(request: Request, pid: str, fn):
deps, who, _rec, err = _gate(request, pid, CAP_HOST)
if err:
return err
caller = _caller_for_who(deps, who)
if caller is None:
return _error(403, "unknown user", "auth")
try:
return await run_in_threadpool(fn, caller)
except HTTPException as e:
return _http_err(e)
@router.get(_BASE + "/host-file")
async def hub_host_file(pid: str, request: Request, path: str = ""):
from files.hostfiles import file_payload, resolve
def _call(caller):
r = resolve(caller, path)
if r is None or not r.abs.is_file():
raise HTTPException(404, "file not found")
return file_payload(r)
return await _run_host(request, pid, _call)
@router.get(_BASE + "/host-files")
async def hub_host_files(pid: str, request: Request, path: str = ""):
from files.hostfiles import list_dir, resolve
def _call(caller):
r = resolve(caller, path)
if r is None or not r.abs.is_dir():
raise HTTPException(404, "folder not found")
return list_dir(r)
return await _run_host(request, pid, _call)
@router.get(_BASE + "/host-files/recent")
async def hub_host_files_recent(pid: str, request: Request, project: str = "", limit: int = 12):
from files.hostfiles import project_root, recent_documents
def _call(caller):
r = project_root(caller, project)
if r is None or not r.abs.is_dir():
raise HTTPException(404, "project not found")
return {"root": r.host, "project": project,
"entries": recent_documents(r, max(1, min(limit, 50)))}
return await _run_host(request, pid, _call)
@router.get(_BASE + "/host-files/roots")
async def hub_host_files_roots(pid: str, request: Request):
from files.hostfiles import roots
return await _run_host(request, pid, lambda caller: {"roots": roots(caller)})
# ── context.read / context.write (owner-only) ────────────────────────────────
@router.get(_BASE + "/context/bundle")
async def hub_context_bundle(pid: str, request: Request):
deps, _who, _rec, err = _gate(request, pid, CAP_CTX_READ, owner_only=True)
if err:
return err
from files.routes import bundle_data
return await run_in_threadpool(bundle_data, deps)
@router.get(_BASE + "/context/file")
async def hub_context_file(pid: str, request: Request, path: str = ""):
deps, _who, _rec, err = _gate(request, pid, CAP_CTX_READ, owner_only=True)
if err:
return err
if not path:
return _error(400, "path is required", "bad_request")
from files.routes import read_context_file
try:
return await run_in_threadpool(read_context_file, deps, path)
except HTTPException as e:
return _http_err(e)
@router.put(_BASE + "/context/file")
async def hub_context_file_put(pid: str, request: Request):
deps, _who, _rec, err = _gate(request, pid, CAP_CTX_WRITE,
owner_only=True, handler_only=True)
if err:
return err
body = await _json_body(request)
if body is None or not isinstance(body.get("path"), str) or not isinstance(body.get("content"), str):
return _error(400, "path and content strings are required", "bad_request")
from files.routes import write_context_file
try:
return await run_in_threadpool(write_context_file, deps, body["path"], body["content"])
except HTTPException as e:
return _http_err(e)