Files
ai-agent/sidecar/tools.py
gabrielvidal aaab115fa2 fix(sidecar): Monitor through the guard, fail-closed, scoped runs ignore project Claude settings; safe git, egress, ship from a copy
Monitor ran shell commands the guard never saw; the owner CLI, docker and ssh
rules fell to ordinary spellings (the CLI now refuses under AIA_GUEST); a guard
exception let the call through; chat-level runs still had the owner's gitea.lab
and gh credential helpers. Scoped lab runs: --setting-sources user,
--strict-mcp-config, hooks under python -I, the project CLAUDE.md appended as
text, scope.noBash. 3d-render uploads carry data: URIs only; a guest's video
URL resolves to public addresses through a vetting proxy; git on a guest repo
runs with fsmonitor, hooks, filters and textconv out of reach; the ship broker
deploys a checked copy; tokens leave argv.
Co-Authored-By: Claude <noreply@anthropic.com>
2026-11-15 15:23:05 +01:00

539 lines
23 KiB
Python

"""
``/tools/…`` — the host half of the hub's tool proxy (backend ``toolproxy/``):
the lab tools that have to run on this machine, for callers who never touch
it — a guest's run, a guest's computer, the owner's Macs.
* **video-extract** — one job at a time (it fills the EVOX2's CPU, or this
box's), in a **library per caller**: the owner's is the lab's own
(``~/homelab/data/video-extract``), a guest's is
``~/homelab/data/video-extract-guests/<uid>`` with the search model linked
from the owner's (1.4 GB, built once). The EVOX2 is woken first (``evox2
wake``) — a guest's job wakes it, Gabriel's pick. A source is an http(s)
URL or a file uploaded here first (``PUT /tools/video-extract/upload``):
never a path on this machine. A **guest's URL is fetched from the lab**, so
it may only reach the public internet: checked when the job is filed, and
enforced while it downloads — their job's ``yt-dlp`` goes through
``egress.py``'s proxy, which refuses every address that isn't globally
routable, redirects included (this box's loopback is the owner on the hub;
the docker networks, the LAN and the tailnet answer without Authelia).
* **3d-render** — a glb in, the contact sheet out, with an allowlist of flags.
The model must be self-contained: a glTF ``uri`` that isn't ``data:`` is a
path the renderer would read off this machine, as the owner.
The hub decides *who* may (its access checks, the ledger); this only runs the
fixed commands. Refused on a worker: only the lab has these tools.
"""
from __future__ import annotations
import json
import os
import pathlib
import re
import secrets
import shutil
import struct
import subprocess
import tarfile
import tempfile
import threading
import time
from fastapi import APIRouter, Header, HTTPException, Request
from fastapi.responses import FileResponse, Response
from pydantic import BaseModel
from starlette.background import BackgroundTask
import egress
from config import IS_WORKER, RUN_ENV_STRIP
from validate import _auth
HOME = pathlib.Path(os.path.expanduser("~"))
HOMELAB = pathlib.Path(os.path.expanduser(os.environ.get("SIDECAR_HOMELAB_DIR", "~/homelab")))
VX_OWNER = pathlib.Path(os.path.expanduser(
os.environ.get("SIDECAR_VIDEO_EXTRACT_HOME", str(HOMELAB / "data" / "video-extract"))))
VX_GUESTS = pathlib.Path(os.path.expanduser(
os.environ.get("SIDECAR_VIDEO_EXTRACT_GUESTS", str(HOMELAB / "data" / "video-extract-guests"))))
VX_CMD = os.environ.get("SIDECAR_VIDEO_EXTRACT_CMD",
str(HOMELAB / ".claude/skills/video-extract/scripts/video-extract.sh"))
WAKE_CMD = os.environ.get("SIDECAR_EVOX2_WAKE_CMD",
str(HOMELAB / ".claude/skills/evox2/scripts/evox2.sh") + " wake")
RENDER_BIN = os.environ.get("SIDECAR_3D_RENDER_BIN", str(HOME / ".cargo/bin/3d-render"))
VX_TIMEOUT_S = float(os.environ.get("SIDECAR_VIDEO_EXTRACT_TIMEOUT_S", "5400"))
WAKE_TIMEOUT_S = 240
RENDER_TIMEOUT_S = 180
MAX_UPLOAD = int(os.environ.get("SIDECAR_TOOLS_MAX_UPLOAD", str(2 * 1024 ** 3)))
MAX_GLB = 300 * 1024 ** 2
# The JSON part of a model (a glb's first chunk, or a whole .gltf) read here
# to vet its URIs before the renderer sees it.
MAX_GLTF_JSON = 64 * 1024 ** 2
# What a guest is told when their video's URL can't be fetched — never
# yt-dlp's own line, which says what answered inside the lab.
VX_FETCH_ERROR = ("couldn't download that video — the link must be a public video page or "
"file the lab can reach (or upload the file instead)")
_LIB_RE = re.compile(r"^(owner|guest-[a-z0-9][a-z0-9_-]{0,63})$")
_VID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}$")
_JOB_RE = re.compile(r"^[a-f0-9]{16}$")
_NAME_RE = re.compile(r"[^A-Za-z0-9._-]+")
_URL_RE = re.compile(r"^https?://[^\s'\"<>]{3,2000}$")
# What a video's bundle carries: the report and what it links to — not the
# source video, the 2 fps thumbnails or the embeddings.
_BUNDLE_SKIP = ("frames", "embeddings.npy", "frames.json")
router = APIRouter()
def _host_only() -> None:
if IS_WORKER:
raise HTTPException(404, "the lab's tools run on the lab")
# ── libraries ────────────────────────────────────────────────────────────────
def library_dir(library: str) -> pathlib.Path:
"""The folder of a caller's video library (created on first use)."""
if not _LIB_RE.match(library or ""):
raise HTTPException(400, "bad library")
if library == "owner":
return VX_OWNER
d = VX_GUESTS / library[len("guest-"):]
if not d.is_dir():
d.mkdir(parents=True, exist_ok=True)
models = d / "models"
if not models.exists() and (VX_OWNER / "models").is_dir():
try:
models.symlink_to(VX_OWNER / "models")
except OSError:
pass
return d
def video_dir(library: str, vid: str) -> pathlib.Path:
if not _VID_RE.match(vid or "") or vid in ("models", "_uploads"):
raise HTTPException(400, "bad video id")
d = library_dir(library) / vid
if not (d / "report.md").is_file():
raise HTTPException(404, f"unknown video {vid}")
return d
def _env(library: str) -> dict:
env = {k: v for k, v in os.environ.items() if k not in RUN_ENV_STRIP
and not k.startswith("AIA_")}
env["VIDEO_EXTRACT_HOME"] = str(library_dir(library))
env["PATH"] = f"{HOME}/.local/bin:{HOME}/.cargo/bin:{env.get('PATH', '/usr/bin:/bin')}"
if library != "owner":
_guest_egress(env)
return env
def _guest_egress(env: dict) -> None:
"""A guest's job downloads through the public-only proxy: a ``yt-dlp``
of ours comes first on its PATH and hands the real one ``--proxy``. Only
the download — the job's own calls (the EVOX2 over SSH, the brain) are the
lab's and stay direct. No real yt-dlp ⇒ nothing to wrap (and no URL job)."""
real = shutil.which("yt-dlp", path=env["PATH"])
if not real:
return
shim = egress.ytdlp_shim()
env["VX_REAL_YTDLP"] = real
env["VX_EGRESS_PROXY"] = egress.proxy_url()
env["PATH"] = f"{shim}:{env['PATH']}"
for k in ("http_proxy", "https_proxy", "all_proxy", "HTTP_PROXY", "HTTPS_PROXY",
"ALL_PROXY"):
env.pop(k, None) # yt-dlp's --proxy wins anyway; nothing else is proxied
def _vx(library: str, *args: str, timeout: float = 120) -> dict:
"""``video-extract --json <args>`` on a library; its JSON, or 4xx/5xx
with its error line."""
try:
p = subprocess.run([VX_CMD, "--json", *args], env=_env(library), cwd=str(HOMELAB),
capture_output=True, text=True, timeout=timeout,
stdin=subprocess.DEVNULL)
except subprocess.TimeoutExpired:
raise HTTPException(504, "video-extract took too long") from None
except OSError as e:
raise HTTPException(503, f"video-extract isn't runnable here: {e}") from None
if p.returncode != 0:
err = [ln for ln in (p.stderr or "").splitlines() if ln.startswith("error:")]
raise HTTPException(422 if p.returncode in (1, 2) else 500,
(err[-1][6:].strip() if err else (p.stderr or "failed")[-400:]))
try:
return json.loads(p.stdout)
except ValueError:
raise HTTPException(500, "video-extract printed no JSON") from None
def _relative(library: str, payload):
"""Lab paths in a reply → relative to the library (the caller can't read
this machine's paths; it fetches files by their relative path)."""
root = str(library_dir(library)).rstrip("/") + "/"
if isinstance(payload, dict):
return {k: _relative(library, v) for k, v in payload.items()}
if isinstance(payload, list):
return [_relative(library, v) for v in payload]
if isinstance(payload, str) and payload.startswith(root):
return payload[len(root):]
return payload
# ── uploads ──────────────────────────────────────────────────────────────────
@router.put("/tools/video-extract/upload")
async def vx_upload(request: Request, library: str, name: str = "video.mp4",
authorization: str | None = Header(None)):
_auth(authorization)
_host_only()
inbox = library_dir(library) / "_uploads"
inbox.mkdir(parents=True, exist_ok=True)
clean = _NAME_RE.sub("-", pathlib.Path(name).name)[-80:].strip(".-") or "video.mp4"
uid = secrets.token_hex(8)
dest = inbox / f"{uid}-{clean}"
size = 0
try:
with open(dest, "wb") as f:
async for chunk in request.stream():
size += len(chunk)
if size > MAX_UPLOAD:
raise HTTPException(413, f"over {MAX_UPLOAD // 1024 ** 2} MB")
f.write(chunk)
except BaseException:
dest.unlink(missing_ok=True)
raise
if size == 0:
dest.unlink(missing_ok=True)
raise HTTPException(400, "empty upload")
return {"upload": dest.name, "size": size}
def _source(library: str, source: str) -> str:
if _URL_RE.match(source or ""):
if library != "owner" and not egress.public_url(source):
raise HTTPException(400, "that link isn't on the public internet — the lab only "
"fetches public video links for you (or upload the file)")
return source
if re.fullmatch(r"[a-f0-9]{16}-[A-Za-z0-9._-]{1,80}", source or ""):
p = library_dir(library) / "_uploads" / source
if p.is_file():
return str(p)
raise HTTPException(400, "the source is an http(s) URL or an upload of this library")
# ── jobs ─────────────────────────────────────────────────────────────────────
class VxJob(BaseModel):
library: str
source: str
fps: float | None = None
asr: str | None = None
lang: str | None = None
describe: bool | None = None
title: str | None = None
force: bool = False
_jobs: dict[str, dict] = {}
_jobs_lock = threading.Lock()
_one_at_a_time = threading.Semaphore(1)
_ASR = {"auto", "whisper-turbo", "whisper-small", "whisper-base", "whisper-large-v3",
"parakeet", "none"}
def _args(body: VxJob, src: str) -> list[str]:
a = ["run", src, "--on", "auto"]
if body.fps is not None:
a += ["--fps", str(min(4.0, max(0.25, float(body.fps))))]
if body.asr:
if body.asr not in _ASR:
raise HTTPException(400, f"--asr is one of {', '.join(sorted(_ASR))}")
a += ["--asr", body.asr]
if body.lang:
if not re.fullmatch(r"[a-z]{2,3}", body.lang):
raise HTTPException(400, "bad --lang")
a += ["--lang", body.lang]
if body.describe is not None:
a.append("--describe" if body.describe else "--no-describe")
if body.title:
a += ["--title", body.title.replace("\n", " ")[:120]]
if body.force:
a.append("--force")
return a
def _run_job(jid: str, library: str, args: list[str]) -> None:
job = _jobs[jid]
with _one_at_a_time:
job.update(status="running", startedAt=time.time())
try:
subprocess.run(WAKE_CMD.split(), env=_env(library), cwd=str(HOMELAB),
capture_output=True, timeout=WAKE_TIMEOUT_S, stdin=subprocess.DEVNULL)
except (subprocess.TimeoutExpired, OSError):
pass # --on auto runs it here when the box didn't come up
try:
out = _vx(library, *args, timeout=VX_TIMEOUT_S)
job.update(status="done", result=_relative(library, {
k: out.get(k) for k in ("id", "title", "duration", "language", "counts",
"ran_on", "wall_s", "described", "report")}))
except HTTPException as e:
job.update(status="failed", error=_job_error(library, str(e.detail)))
except Exception as e: # never leave a job running forever
job.update(status="failed", error=f"{type(e).__name__}: {e}"
if library == "owner" else "the job failed on the lab")
finally:
job["endedAt"] = time.time()
def _job_error(library: str, detail: str) -> str:
"""A failed job's message. The owner reads the tool's own line; a guest
never reads what the download said (a status, a body, a refused port —
of whatever their link reached) nor a path of this machine."""
if library == "owner":
return detail
root = str(library_dir(library)).rstrip("/") + "/"
detail = detail.replace(root, "").replace(str(HOME), "~")
if re.search(r"yt-dlp|download|proxy|HTTP Error|urlopen|Unable to", detail, re.I):
return VX_FETCH_ERROR
return detail[:300]
@router.post("/tools/video-extract/jobs")
def vx_start(body: VxJob, authorization: str | None = Header(None)):
_auth(authorization)
_host_only()
src = _source(body.library, body.source)
args = _args(body, src)
jid = secrets.token_hex(8)
with _jobs_lock:
ahead = sum(1 for j in _jobs.values() if j["status"] in ("queued", "running"))
# Forget finished jobs after a day.
for k in [k for k, j in _jobs.items() if j.get("endedAt", time.time()) < time.time() - 86400]:
_jobs.pop(k, None)
_jobs[jid] = {"id": jid, "library": body.library, "status": "queued",
"source": body.source, "queuedAt": time.time()}
threading.Thread(target=_run_job, args=(jid, body.library, args), daemon=True).start()
return {"job": jid, "ahead": ahead}
@router.get("/tools/video-extract/jobs/{jid}")
def vx_job(jid: str, library: str, authorization: str | None = Header(None)):
_auth(authorization)
_host_only()
job = _jobs.get(jid) if _JOB_RE.match(jid or "") else None
if not job or job["library"] != library:
raise HTTPException(404, "unknown job")
out = dict(job)
if out["status"] == "queued":
out["ahead"] = sum(1 for j in _jobs.values() if j["status"] in ("queued", "running")
and j["queuedAt"] < job["queuedAt"])
return out
# ── the library ──────────────────────────────────────────────────────────────
@router.get("/tools/video-extract/videos")
def vx_ls(library: str, authorization: str | None = Header(None)):
_auth(authorization)
_host_only()
if not (library_dir(library) / "library.db").exists():
return {"videos": []}
return _relative(library, _vx(library, "ls"))
@router.get("/tools/video-extract/videos/{vid}")
def vx_show(vid: str, library: str, authorization: str | None = Header(None)):
_auth(authorization)
_host_only()
d = video_dir(library, vid)
try:
meta = json.loads((d / "video.json").read_text())
except (OSError, ValueError):
meta = {}
return {"id": vid, "report": (d / "report.md").read_text(encoding="utf-8", errors="replace"),
"video": _relative(library, meta)}
@router.delete("/tools/video-extract/videos/{vid}")
def vx_rm(vid: str, library: str, authorization: str | None = Header(None)):
_auth(authorization)
_host_only()
video_dir(library, vid)
return _vx(library, "rm", vid)
@router.get("/tools/video-extract/videos/{vid}/file")
def vx_file(vid: str, library: str, path: str, authorization: str | None = Header(None)):
_auth(authorization)
_host_only()
d = video_dir(library, vid).resolve()
f = (d / path).resolve()
if not str(f).startswith(str(d) + "/") or not f.is_file() or f.name.startswith("source."):
raise HTTPException(404, "no such file")
return FileResponse(f)
@router.get("/tools/video-extract/videos/{vid}/bundle")
def vx_bundle(vid: str, library: str, authorization: str | None = Header(None)):
"""The video's folder as a tar.gz: report.md, the JSON, the subtitles and
the keyframes it links."""
_auth(authorization)
_host_only()
d = video_dir(library, vid)
fd, tmp = tempfile.mkstemp(suffix=".tar.gz")
os.close(fd)
with tarfile.open(tmp, "w:gz") as tar:
for p in sorted(d.rglob("*")):
rel = p.relative_to(d)
if not p.is_file() or p.is_symlink() or rel.parts[0] in _BUNDLE_SKIP \
or p.name.startswith("source."):
continue
tar.add(p, arcname=f"{vid}/{rel.as_posix()}")
return FileResponse(tmp, media_type="application/gzip", filename=f"{vid}.tar.gz",
background=BackgroundTask(os.unlink, tmp))
class VxSearch(BaseModel):
library: str
q: str
mode: str = "all"
video: str | None = None
k: int = 8
@router.post("/tools/video-extract/search")
def vx_search(body: VxSearch, authorization: str | None = Header(None)):
_auth(authorization)
_host_only()
if body.mode not in ("all", "visual", "text"):
raise HTTPException(400, "mode is all, visual or text")
if not body.q.strip() or len(body.q) > 500:
raise HTTPException(400, "bad query")
if not (library_dir(body.library) / "library.db").exists():
return {"query": body.q, "hits": []}
args = ["search", body.q, "--mode", body.mode, "-k", str(min(50, max(1, body.k)))]
if body.video:
video_dir(body.library, body.video)
args += ["--video", body.video]
return _relative(body.library, _vx(body.library, *args, timeout=600))
# ── 3d-render ────────────────────────────────────────────────────────────────
_GLB_JSON = 0x4E4F534A
def gltf_json(path: pathlib.Path) -> bytes:
"""The JSON of an uploaded model: a glb's first chunk, or the whole file
of a ``.gltf``. 422 when it is neither."""
size = path.stat().st_size
with open(path, "rb") as f:
head = f.read(20)
if head[:4] == b"glTF":
if len(head) < 20:
raise HTTPException(422, "not a readable glb")
length, kind = struct.unpack("<II", head[12:20])
if kind != _GLB_JSON or length > size - 20:
raise HTTPException(422, "not a readable glb")
if length > MAX_GLTF_JSON:
raise HTTPException(413, "the model's JSON part is too big")
return f.read(length)
if size > MAX_GLTF_JSON:
raise HTTPException(413, "a .gltf this big — send a .glb")
f.seek(0)
return f.read()
def self_contained(path: pathlib.Path) -> None:
"""Refuse (422) a model that names a file: every ``uri`` anywhere in its
JSON must be a ``data:`` URI. The renderer resolves any other against this
machine's disk — ``/home/…/.ssh/id_ed25519`` as a buffer, a private photo
as a texture — and what it read comes back in the picture. Every key named
``uri`` counts, a repeated one too, so no two parsers can disagree on
which value is the real one."""
def pairs(items):
for k, v in items:
if k == "uri" and not (isinstance(v, str) and v.startswith("data:")):
raise HTTPException(422, "this model points at external files — export it as "
"one self-contained .glb (embedded buffers and textures)")
return dict(items)
try:
doc = json.loads(gltf_json(path).decode("utf-8-sig"), object_pairs_hook=pairs)
except (ValueError, UnicodeDecodeError, RecursionError):
raise HTTPException(422, "not a readable glTF/glb") from None
if not isinstance(doc, dict):
raise HTTPException(422, "not a readable glTF/glb")
_VIEWS_RE = re.compile(r"^[a-z0-9:/,.-]{1,200}$")
_MODES_RE = re.compile(r"^(textured|clay|wireframe|normals)(,(textured|clay|wireframe|normals)){0,3}$")
@router.post("/tools/3d-render")
async def render(request: Request, views: str | None = None, modes: str | None = None,
size: int | None = None, ss: int | None = None, bg: str | None = None,
ortho: bool = False, fov: float | None = None, title: str | None = None,
authorization: str | None = Header(None)):
"""A glb (the body) → its contact sheet (PNG), the stats in
``X-Render-Stats``."""
_auth(authorization)
_host_only()
args: list[str] = []
if views:
if not _VIEWS_RE.match(views):
raise HTTPException(400, "bad --views")
args += ["--views", views]
if modes:
if not _MODES_RE.match(modes):
raise HTTPException(400, "bad --modes")
args += ["--modes", modes]
if size is not None:
args += ["--size", str(min(1568, max(64, int(size))))]
if ss is not None:
args += ["--ss", str(min(4, max(1, int(ss))))]
if bg:
if bg not in ("dark", "light", "transparent"):
raise HTTPException(400, "bg is dark, light or transparent")
args += ["--bg", bg]
if ortho:
args.append("--ortho")
if fov is not None:
args += ["--fov", str(min(120.0, max(5.0, float(fov))))]
if title:
args += ["--title", title.replace("\n", " ")[:80]]
work = pathlib.Path(tempfile.mkdtemp(prefix="3d-render-"))
glb = work / "model.glb"
size_in = 0
try:
with open(glb, "wb") as f:
async for chunk in request.stream():
size_in += len(chunk)
if size_in > MAX_GLB:
raise HTTPException(413, f"a model over {MAX_GLB // 1024 ** 2} MB")
f.write(chunk)
if size_in < 12:
raise HTTPException(400, "no model in the body")
self_contained(glb)
out = work / "sheet.png"
try:
p = subprocess.run([RENDER_BIN, "--json", str(glb), "-o", str(out), *args],
capture_output=True, text=True, timeout=RENDER_TIMEOUT_S,
stdin=subprocess.DEVNULL, cwd=str(work))
except subprocess.TimeoutExpired:
raise HTTPException(504, "the render took too long") from None
except OSError as e:
raise HTTPException(503, f"3d-render isn't runnable here: {e}") from None
if p.returncode != 0 or not out.is_file():
# its own words (no meshes, an unsupported extension), minus this
# machine's paths
err = (p.stderr or "").replace(str(work) + "/", "").replace(str(work), "")
err = err.replace(str(HOME), "~").strip()[-400:]
raise HTTPException(422, err or "render failed")
try:
stats = json.loads(p.stdout).get("stats") or {}
except (ValueError, AttributeError):
stats = {}
return Response(out.read_bytes(), media_type="image/png",
headers={"X-Render-Stats": json.dumps(stats, ensure_ascii=True)[:4000]})
finally:
shutil.rmtree(work, ignore_errors=True)
def make_router():
return router