The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(local-runtime): Hugging Face browser + sideload — any GGUF becomes a normal model
emozillad963245aa5ca
diff --git a/hermes_cli/local_runtime/hf_browse.py b/hermes_cli/local_runtime/hf_browse.pynew file mode 100644index 00000000000..c146c2e36da--- /dev/null+++ b/hermes_cli/local_runtime/hf_browse.py@@ -0,0 +1,161 @@+"""Browse Hugging Face for GGUF models the user can run.++The curated catalog is the front page; this module is the firehose behind+it — day-0 models NVIDIA or we haven't blessed yet, community quants,+anything. Three rules keep it safe and honest:++1. Acquisition only. Nothing here serves a model: a browsed download+ lands in the machine-scoped models dir and from that moment the+ normal machinery owns it — staleness bounce, preset generation from+ the real GGUF header, fit policy, placement pills.+2. The fit verdict shown BEFORE download is a rough cut priced from file+ size alone (weights dominate; KV/overhead use conservative fill-ins).+ After download the GGUF header is the authority, as everywhere.+3. HF is queried directly with short timeouts and a small in-process+ cache. No third-party proxy service; if HF rate limits ever bite at+ fleet scale, a proxy is a product decision to make then.+"""++from __future__ import annotations++import json+import logging+import re+import time+import urllib.parse+import urllib.request+from dataclasses import dataclass, field++logger = logging.getLogger(__name__)++_HF = "https://huggingface.co"+_TIMEOUT_S = 15+# Rough-fit fill-ins for pre-download pricing: a mid-size model's 64K-floor+# KV plus runtime overhead. Deliberately round numbers — the verdict bands+# are coarse (fits GPU / needs RAM / too big), not window grants.+_ROUGH_KV_AND_OVERHEAD = 4 << 30++# Tiny TTL cache: the pane fires a search per keystroke pause and re-opens+# repos the user flips between. Process-local, size-capped, no invalidation+# subtleties — upstream truth changes slowly at this granularity.+_CACHE: dict[str, tuple[float, object]] = {}+_CACHE_TTL_S = 300+_CACHE_MAX = 128+++def _get_json(url: str) -> object:+ now = time.monotonic()+ hit = _CACHE.get(url)+ if hit and now - hit[0] < _CACHE_TTL_S:+ return hit[1]+ req = urllib.request.Request(url, headers={"User-Agent": "hermes-local-models"})+ with urllib.request.urlopen(req, timeout=_TIMEOUT_S) as r:+ data = json.load(r)+ if len(_CACHE) >= _CACHE_MAX:+ _CACHE.pop(min(_CACHE, key=lambda k: _CACHE[k][0]))+ _CACHE[url] = (now, data)+ return data+++@dataclass(frozen=True)+class HFModelHit:+ repo: str # e.g. "unsloth/Qwen3.8-27B-GGUF"+ downloads: int+ likes: int+ updated: str # ISO date from HF+ gated: bool+++@dataclass(frozen=True)+class HFFileGroup:+ """One downloadable quant: a single GGUF or all parts of a split one."""++ label: str # e.g. "Q4_K_M" or the file stem+ paths: tuple[str, ...] # repo-relative, split parts in order+ total_bytes: int+ fit: str = "unknown" # fits-gpu | needs-ram | too-big | unknown+++_QUANT_RE = re.compile(+ r"(?:IQ|Q)\d[_A-Z0-9]*|F16|BF16|F32", re.IGNORECASE)+_SPLIT_RE = re.compile(r"-(\d{5})-of-(\d{5})\.gguf$", re.IGNORECASE)+++def search_models(query: str, limit: int = 20) -> list[HFModelHit]:+ """Full-text search over HF models that ship GGUF files, most+ downloaded first (the closest public signal to 'trending')."""+ q = urllib.parse.quote(query.strip())+ url = (f"{_HF}/api/models?search={q}&filter=gguf&sort=downloads"+ f"&direction=-1&limit={max(1, min(int(limit), 50))}")+ out: list[HFModelHit] = []+ for m in _get_json(url):+ out.append(HFModelHit(+ repo=str(m.get("id", "")),+ downloads=int(m.get("downloads") or 0),+ likes=int(m.get("likes") or 0),+ updated=str(m.get("lastModified") or ""),+ gated=bool(m.get("gated")),+ ))+ return out+++def _quant_label(filename: str) -> str:+ m = _QUANT_RE.search(filename)+ return m.group(0).upper() if m else filename+++def repo_files(repo: str) -> list[HFFileGroup]:+ """The servable GGUFs in a repo, grouped: split parts collapse into one+ entry (first part is what llama.cpp loads), mmproj/draft companions are+ excluded (they aren't standalone models). Largest quant first."""+ url = f"{_HF}/api/models/{urllib.parse.quote(repo)}/tree/main?recursive=true"+ files = _get_json(url)++ singles: list[tuple[str, int]] = []+ splits: dict[str, list[tuple[int, str, int]]] = {}+ for f in files:+ path = str(f.get("path", ""))+ if not path.lower().endswith(".gguf"):+ continue+ name = path.rsplit("/", 1)[-1].lower()+ if name.startswith("mmproj") or name.startswith("dspark") or "draft" in name:+ continue+ size = int(f.get("size") or 0)+ m = _SPLIT_RE.search(path)+ if m:+ stem = path[: m.start()]+ splits.setdefault(stem, []).append((int(m.group(1)), path, size))+ else:+ singles.append((path, size))++ groups: list[HFFileGroup] = []+ for path, size in singles:+ groups.append(HFFileGroup(label=_quant_label(path), paths=(path,),+ total_bytes=size))+ for stem, parts in splits.items():+ parts.sort()+ groups.append(HFFileGroup(+ label=_quant_label(stem),+ paths=tuple(p for _, p, _ in parts),+ total_bytes=sum(s for _, _, s in parts)))+ groups.sort(key=lambda g: g.total_bytes, reverse=True)+ return groups+++def rough_fit(total_bytes: int, budget) -> str:+ """Coarse pre-download verdict from file size alone. The GGUF header+ refines this after download; bands match the catalog pills' language.+ File size ≈ in-memory weights for GGUF (mmap'd as-is)."""+ need = total_bytes + _ROUGH_KV_AND_OVERHEAD+ if need <= budget.usable_vram_bytes:+ return "fits-gpu"+ if need <= budget.usable_vram_bytes + budget.ram_available_bytes:+ return "needs-ram"+ return "too-big"+++def priced_repo_files(repo: str, budget) -> list[HFFileGroup]:+ from dataclasses import replace++ return [replace(g, fit=rough_fit(g.total_bytes, budget))+ for g in repo_files(repo)]diff --git a/hermes_cli/web_routers/local_models.py b/hermes_cli/web_routers/local_models.pyindex b1b964cbc76..e2ad77043f1 100644--- a/hermes_cli/web_routers/local_models.py+++ b/hermes_cli/web_routers/local_models.py@@ -19,6 +19,7 @@ import jsonimport loggingimport threadingimport time+import urllib.parseimport urllib.requestimport uuidfrom pathlib import Path@@ -980,3 +981,140 @@ async def local_models_job(job_id: str):if out["total_bytes"]:out["percent"] = min(100, round(out["done_bytes"] / out["total_bytes"] * 100))return out+++# ── Hugging Face browser: search, repo files, arbitrary download ─++[email protected]("/api/local-models/search")+async def local_models_search(q: str, limit: int = 20):+ """Full-text HF search over GGUF models — the firehose behind the+ curated catalog. The pane's per-quant fit pills come from the+ repo-files call once the user opens a hit."""+ from starlette.concurrency import run_in_threadpool++ from hermes_cli.local_runtime.hf_browse import search_models++ if not q.strip():+ return {"hits": []}+ try:+ hits = await run_in_threadpool(search_models, q, limit)+ except Exception as exc: # noqa: BLE001+ raise HTTPException(status_code=502,+ detail=f"Hugging Face search unavailable: {exc}") from exc+ return {"hits": [h.__dict__ for h in hits]}++[email protected]("/api/local-models/search/files")+async def local_models_search_files(repo: str):+ """The servable GGUFs in one HF repo with a rough pre-download fit+ verdict per quant (file size + conservative fill-ins — the GGUF+ header refines it after download)."""+ from starlette.concurrency import run_in_threadpool++ from hermes_cli.local_runtime.hardware import probe_budget+ from hermes_cli.local_runtime.hf_browse import priced_repo_files++ try:+ groups = await run_in_threadpool(+ priced_repo_files, repo, probe_budget(planning=True))+ except Exception as exc: # noqa: BLE001+ raise HTTPException(status_code=502,+ detail=f"Could not list {repo}: {exc}") from exc+ return {"files": [dict(g.__dict__, paths=list(g.paths)) for g in groups]}+++class BrowsedDownloadBody(BaseModel):+ repo: str+ paths: list[str] # one GGUF, or every part of a split, in order++[email protected]("/api/local-models/download-browsed")+async def local_models_download_browsed(body: BrowsedDownloadBody):+ """Download an arbitrary HF GGUF (browsed or pasted) into the managed+ models dir. From the moment it lands it is a normal staged model: the+ post-download bounce regenerates presets from its real header and the+ fit policy owns its launch. No catalog entry — it serves 'unverified',+ capabilities answered from the live server only."""+ import re as _re++ from hermes_cli.local_runtime.bootstrap import staged_model_ids++ paths = [p for p in (body.paths or []) if p.lower().endswith(".gguf")]+ if not paths:+ raise HTTPException(status_code=422, detail="no .gguf files given")+ first = paths[0].rsplit("/", 1)[-1]+ model_id = _re.sub(r"-\d{5}-of-\d{5}\.gguf$", "", first, flags=_re.IGNORECASE)+ model_id = model_id[:-5] if model_id.lower().endswith(".gguf") else model_id+ if model_id in staged_model_ids():+ return {"job_id": None, "already_downloaded": True, "model_id": model_id}++ job = _job("model-download", f"{model_id} (from {body.repo})",+ model_id=model_id)++ def _run():+ try:+ job["phase"] = "downloading"+ for p in paths:+ url = (f"https://huggingface.co/{body.repo}"+ f"/resolve/main/{urllib.parse.quote(p)}")+ dest = _models_dir() / p.rsplit("/", 1)[-1]+ if dest.exists():+ continue+ download_file(url, dest, job,+ base_done=int(job.get("done_bytes") or 0),+ keep_totals=bool(job.get("total_bytes")))+ job["phase"] = "downloading"+ job["phase"] = "done"+ job["status"] = "done"+ job["detail"] = f"{model_id} ready"+ try:+ from hermes_cli.local_runtime.bootstrap import refresh_local_runtime++ refresh_local_runtime()+ except Exception: # noqa: BLE001+ logger.debug("post-download runtime refresh skipped", exc_info=True)+ except Exception as exc: # noqa: BLE001+ job["status"] = "error"+ job["error"] = str(exc)++ threading.Thread(target=_run, daemon=True, name="lm-download-browsed").start()+ return {"job_id": job["job_id"], "model_id": model_id}+++class SideloadBody(BaseModel):+ path: str # absolute path to a .gguf on this machine++[email protected]("/api/local-models/sideload")+async def local_models_sideload(body: SideloadBody):+ """Register a GGUF that already exists on this machine: link it into+ the managed models dir (copy only when linking is impossible) and+ bounce the router so it serves immediately. The original stays where+ it is; delete-from-Hermes removes only our link."""+ import os+ import shutil++ from starlette.concurrency import run_in_threadpool++ src = Path(body.path)+ if not src.is_file() or src.suffix.lower() != ".gguf":+ raise HTTPException(status_code=422, detail="Pick a .gguf model file")+ dest = _models_dir() / src.name+ if dest.exists():+ return {"ok": True, "model_id": dest.stem, "already_present": True}+ dest.parent.mkdir(parents=True, exist_ok=True)+ try:+ os.link(src, dest) # hardlink: instant, no extra disk+ except OSError:+ try:+ os.symlink(src, dest) # cross-volume fallback+ except OSError:+ await run_in_threadpool(shutil.copyfile, src, dest)+ try:+ from hermes_cli.local_runtime.bootstrap import refresh_local_runtime++ refresh_local_runtime()+ except Exception: # noqa: BLE001+ logger.debug("post-sideload runtime refresh skipped", exc_info=True)+ return {"ok": True, "model_id": dest.stem}diff --git a/tests/hermes_cli/test_hf_browse.py b/tests/hermes_cli/test_hf_browse.pynew file mode 100644index 00000000000..7e7e689a908--- /dev/null+++ b/tests/hermes_cli/test_hf_browse.py@@ -0,0 +1,186 @@+"""The HF browser: search the firehose, price it roughly, and let any+GGUF become a normal staged model.++Parsing contracts run against canned HF API shapes (no network); route+contracts run against the real FastAPI app with the HF client stubbed."""++from __future__ import annotations++import pytest+from fastapi.testclient import TestClient++from hermes_cli.local_runtime.estimator import HardwareBudget+from hermes_cli.local_runtime.hf_browse import (+ HFFileGroup,+ HFModelHit,+ repo_files,+ rough_fit,+ search_models,+)++GIB = 1 << 30+++def client(tmp_path, monkeypatch):+ monkeypatch.setenv("HERMES_HOME", str(tmp_path / ".hermes"))+ (tmp_path / ".hermes").mkdir()+ from hermes_cli import web_server++ test_client = TestClient(web_server.app)+ test_client.headers[web_server._SESSION_HEADER_NAME] = web_server._SESSION_TOKEN+ return test_client+++def _budget(vram_gib, ram_gib=64):+ return HardwareBudget(usable_vram_bytes=int(vram_gib * GIB),+ total_device_bytes=int(vram_gib * GIB),+ ram_available_bytes=int(ram_gib * GIB))+++def test_search_parses_hf_hits(monkeypatch):+ canned = [+ {"id": "unsloth/Qwen3.8-27B-GGUF", "downloads": 872724, "likes": 47,+ "lastModified": "2026-08-18", "gated": False},+ {"id": "bartowski/whatever-GGUF", "downloads": 5, "likes": 0,+ "lastModified": "2026-01-01", "gated": "auto"},+ ]+ monkeypatch.setattr("hermes_cli.local_runtime.hf_browse._get_json",+ lambda url: canned)+ hits = search_models("qwen")+ assert hits[0].repo == "unsloth/Qwen3.8-27B-GGUF"+ assert hits[0].downloads == 872724+ assert hits[1].gated is True # HF 'auto'-gated counts as gated+++def test_repo_files_groups_splits_and_excludes_companions(monkeypatch):+ canned = [+ {"path": "Qwen3.8-27B-Q4_K_M.gguf", "size": 17 * GIB},+ {"path": "mmproj-BF16.gguf", "size": 1 * GIB},+ {"path": "UD-Q8/model-00001-of-00002.gguf", "size": 30 * GIB},+ {"path": "UD-Q8/model-00002-of-00002.gguf", "size": 12 * GIB},+ {"path": "README.md", "size": 1000},+ {"path": "dspark-draft-Q8_0.gguf", "size": 9 * GIB},+ ]+ monkeypatch.setattr("hermes_cli.local_runtime.hf_browse._get_json",+ lambda url: canned)+ groups = repo_files("any/repo")+ labels = {g.label: g for g in groups}+ assert "Q4_K_M" in labels and labels["Q4_K_M"].total_bytes == 17 * GIB+ # Split parts collapse into one group, ordered, summed.+ split = next(g for g in groups if len(g.paths) == 2)+ assert split.total_bytes == 42 * GIB+ assert split.paths[0].endswith("00001-of-00002.gguf")+ # Companions (mmproj, draft) are not standalone models.+ assert not any("mmproj" in p or "dspark" in p+ for g in groups for p in g.paths)+ # Largest first.+ assert groups[0].total_bytes >= groups[-1].total_bytes+++def test_rough_fit_bands():+ b = _budget(29.6, ram_gib=64)+ assert rough_fit(20 * GIB, b) == "fits-gpu" # + fill-ins under 29.6+ assert rough_fit(28 * GIB, b) == "needs-ram" # weights spill+ assert rough_fit(120 * GIB, b) == "too-big"+++def test_search_route_requires_query_and_maps_errors(client, monkeypatch):+ r = client.get("/api/local-models/search", params={"q": " "})+ assert r.status_code == 200 and r.json() == {"hits": []}++ def boom(q, limit):+ raise RuntimeError("HF down")++ monkeypatch.setattr("hermes_cli.local_runtime.hf_browse.search_models", boom)+ r = client.get("/api/local-models/search", params={"q": "qwen"})+ assert r.status_code == 502+++def test_browsed_download_stages_and_bounces(client, tmp_path, monkeypatch):+ """A browsed download must land in the machine-scoped models dir and+ bounce the router — the seam that makes it a NORMAL model."""+ body = b"GGUF" + b"\x00" * 60++ class FakeResponse:+ headers = {"Content-Length": str(len(body))}++ def __init__(self):+ self._data = body++ def read(self, n=-1):+ out, self._data = self._data, b""+ return out++ def __enter__(self):+ return self++ def __exit__(self, *a):+ return False++ monkeypatch.setattr("urllib.request.urlopen",+ lambda *a, **k: FakeResponse())+ bounced = {}+ monkeypatch.setattr(+ "hermes_cli.local_runtime.bootstrap.refresh_local_runtime",+ lambda: bounced.setdefault("yes", True))++ r = client.post("/api/local-models/download-browsed",+ json={"repo": "someone/Some-GGUF",+ "paths": ["Some-Model-Q4_K_M.gguf"]})+ assert r.status_code == 200+ job_id = r.json()["job_id"]++ import time as _time++ deadline = _time.time() + 10+ status = None+ while _time.time() < deadline:+ status = client.get(f"/api/local-models/jobs/{job_id}").json()+ if status["status"] in ("done", "error"):+ break+ _time.sleep(0.05)+ assert status["status"] == "done", status.get("error")++ from hermes_cli.local_runtime.bootstrap import models_dir++ assert (models_dir() / "Some-Model-Q4_K_M.gguf").exists()+ assert bounced.get("yes") is True+++def test_browsed_download_rejects_non_gguf(client):+ r = client.post("/api/local-models/download-browsed",+ json={"repo": "a/b", "paths": ["model.safetensors"]})+ assert r.status_code == 422+++def test_sideload_links_and_bounces(client, tmp_path, monkeypatch):+ src = tmp_path / "My-Local-Model-Q5_K_M.gguf"+ src.write_bytes(b"GGUF" + b"\x00" * 32)+ bounced = {}+ monkeypatch.setattr(+ "hermes_cli.local_runtime.bootstrap.refresh_local_runtime",+ lambda: bounced.setdefault("yes", True))++ r = client.post("/api/local-models/sideload", json={"path": str(src)})+ assert r.status_code == 200+ assert r.json()["model_id"] == "My-Local-Model-Q5_K_M"++ from hermes_cli.local_runtime.bootstrap import models_dir++ dest = models_dir() / src.name+ assert dest.exists()+ assert bounced.get("yes") is True+ # The original must be untouched.+ assert src.exists()++ # Idempotent: sideloading again short-circuits.+ r = client.post("/api/local-models/sideload", json={"path": str(src)})+ assert r.json().get("already_present") is True+++def test_sideload_rejects_non_gguf(client, tmp_path):+ src = tmp_path / "model.bin"+ src.write_bytes(b"nope")+ r = client.post("/api/local-models/sideload", json={"path": str(src)})+ assert r.status_code == 422