PUT /uploads/<batch>/<name> (raw bytes, 50 MB cap) writes the file under ~/.local/share/ai-agent-worker/uploads (WORKER_UPLOADS_DIR) — outside every repo — atomically, and answers its absolute path. Batches older than WORKER_UPLOADS_KEEP_DAYS (30) are pruned on the next upload. Refused on the host sidecar; `ai-agent-worker uninstall` removes the folder. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
90 lines
3.4 KiB
Python
90 lines
3.4 KiB
Python
"""
|
|
``/uploads`` — the composer's attachments, copied onto this machine for a run.
|
|
|
|
A file attached in the hub's composer lands in the hub's uploads store, and the
|
|
prompt names it ``services/ai-agent/data/uploads/<batch>/<name>`` — a path only
|
|
the lab has. Before a prompt naming one goes to a run here, the hub PUTs the
|
|
file's bytes to this endpoint and swaps that path for the one it answers, so
|
|
the agent reads the file where it actually is (backend ``runs/attachments.py``):
|
|
|
|
PUT /uploads/<batch>/<name> (raw bytes) → {"path": "/Users/…/<batch>/<name>"}
|
|
|
|
Files land under ``WORKER_UPLOADS_DIR`` — outside every repo, so nothing shows
|
|
up in a run's ``git status`` — written to a temp name and renamed, so a run
|
|
never reads half a file. Batches older than ``WORKER_UPLOADS_KEEP_DAYS`` are
|
|
pruned on the next upload. Refused on the host sidecar: the lab has the
|
|
originals.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import pathlib
|
|
import re
|
|
import shutil
|
|
import time
|
|
from typing import Callable
|
|
|
|
from fastapi import APIRouter, Header, HTTPException, Request
|
|
|
|
from config import IS_WORKER
|
|
|
|
UPLOADS_DIR = pathlib.Path(os.path.expanduser(os.environ.get(
|
|
"WORKER_UPLOADS_DIR", "~/.local/share/ai-agent-worker/uploads")))
|
|
KEEP_DAYS = float(os.environ.get("WORKER_UPLOADS_KEEP_DAYS", "30"))
|
|
MAX_BYTES = int(os.environ.get("WORKER_UPLOADS_MAX_BYTES", 50 * 1024 * 1024))
|
|
# The hub's own shapes (files/assets.py): a uuid4 hex batch, a sanitized name.
|
|
_BATCH_RE = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
|
|
_NAME_RE = re.compile(r"^[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}$")
|
|
|
|
|
|
def prune(root: pathlib.Path, keep_days: float = KEEP_DAYS) -> list[str]:
|
|
"""Drop the batches untouched for ``keep_days``; the names it dropped."""
|
|
if keep_days <= 0 or not root.is_dir():
|
|
return []
|
|
cutoff = time.time() - keep_days * 86400
|
|
gone = []
|
|
for d in root.iterdir():
|
|
try:
|
|
if d.is_dir() and not d.is_symlink() and d.stat().st_mtime < cutoff:
|
|
shutil.rmtree(d, ignore_errors=True)
|
|
gone.append(d.name)
|
|
except OSError:
|
|
pass
|
|
return gone
|
|
|
|
|
|
def make_router(auth: Callable[[str | None], None],
|
|
root: Callable[[], pathlib.Path] = lambda: UPLOADS_DIR) -> APIRouter:
|
|
router = APIRouter()
|
|
|
|
@router.put("/uploads/{batch}/{name}")
|
|
async def put_upload(batch: str, name: str, request: Request,
|
|
authorization: str | None = Header(default=None)) -> dict:
|
|
auth(authorization)
|
|
if not IS_WORKER:
|
|
raise HTTPException(409, "the host sidecar reads the hub's uploads in place")
|
|
if not _BATCH_RE.match(batch) or not _NAME_RE.match(name):
|
|
raise HTTPException(400, "bad upload path")
|
|
base = root()
|
|
prune(base)
|
|
dest = base / batch / name
|
|
dest.parent.mkdir(parents=True, exist_ok=True)
|
|
tmp = dest.with_name(f".{name}.part")
|
|
size = 0
|
|
try:
|
|
with open(tmp, "wb") as w:
|
|
async for chunk in request.stream():
|
|
size += len(chunk)
|
|
if size > MAX_BYTES:
|
|
raise HTTPException(413, f"{name} exceeds "
|
|
f"{MAX_BYTES // (1 << 20)} MB")
|
|
w.write(chunk)
|
|
os.replace(tmp, dest)
|
|
except BaseException:
|
|
tmp.unlink(missing_ok=True)
|
|
raise
|
|
return {"path": str(dest.resolve()), "size": size}
|
|
|
|
return router
|