The core keeps the services index (names, README line, GOAL.md, last commit)
that service: tags, goals, artefacts and file chips need, and the service
page's shell (README, CLAUDE.md, commits, conversations, memories). Compose /
Traefik parsing, containers, URLs, auth chain, env keys and the file browser
(/api/service-file) leave services/catalog.py (667 → 186 lines) for the
services plugin in ai-agent-plugins.
Two plugin extension points make it work: provides.service.cards (the host
runs the plugin's action and merges whitelisted card fields into
/api/services and /api/service, services/enrich.py) and the services.read
capability (AIA_SERVICES_DIR for the owner's handler runs). ui.slots now
render (PluginSlots, service.detail with {slug}), and every plugin frame gets
the app's theme tokens.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
187 lines
6.1 KiB
Python
187 lines
6.1 KiB
Python
"""Homelab services index — the core half of the Services catalogue.
|
|
|
|
Every directory under ``SERVICES_DIR`` is a self-hosted service. The core
|
|
keeps what the rest of the hub needs about them — ``service:`` tags (the
|
|
composer, the tag registry, the graph), GOAL.md boards, artefacts, the file
|
|
chips (``files/hostfiles.py``):
|
|
|
|
* the **index**: each dir's name, the first line of its README, its GOAL.md
|
|
rollup and its last commit (one bucketed git walk, :mod:`githist`);
|
|
* the **page shell** of one service: README / CLAUDE.md, GOAL.md and its
|
|
recent commits.
|
|
|
|
What the compose and Traefik files say — containers, routers, URLs, the auth
|
|
chain, env keys, the file tree and previews, the homepage icons — is the
|
|
``services`` live plugin's since 2026-11-25 (``~/projects/ai-agent-plugins/
|
|
plugins/services``): a standalone hub has no services dir, so it is not core.
|
|
The plugin's ``cards`` action fills the card fields (:mod:`services.enrich`)
|
|
and its ``service.detail`` slot draws the rest of the page.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import re
|
|
import threading
|
|
import time
|
|
from pathlib import Path
|
|
|
|
import githist
|
|
from goals import goalmd
|
|
|
|
SERVICES_DIR = Path(os.environ.get("SERVICES_DIR", "/services-src")).resolve()
|
|
# Superproject root (its .git is mounted read-only) — used to read each
|
|
# service dir's git history via a pathspec, since services have no own .git.
|
|
REPO_DIR = Path(os.environ.get("REPO_DIR", "/workspace")).resolve()
|
|
# Where the services dir lives *inside the repo* for git pathspecs.
|
|
REPO_SERVICES_REL = os.environ.get("REPO_SERVICES_REL", "services")
|
|
|
|
MAX_TEXT = 40_000 # cap README / CLAUDE.md payloads
|
|
|
|
|
|
def _read_text(p: Path, limit: int = MAX_TEXT) -> str | None:
|
|
try:
|
|
t = p.read_text(encoding="utf-8", errors="replace")
|
|
except OSError:
|
|
return None
|
|
if len(t) > limit:
|
|
t = t[:limit] + f"\n\n… [{len(t) - limit} more chars truncated]"
|
|
return t
|
|
|
|
|
|
def _readme_path(root: Path) -> Path | None:
|
|
for cand in ("README.md", "README", "readme.md", "Readme.md"):
|
|
p = root / cand
|
|
if p.is_file():
|
|
return p
|
|
return None
|
|
|
|
|
|
def _clean(text: str) -> str:
|
|
if "@@" in text:
|
|
return ""
|
|
text = re.sub(r"\[([^\]]+)\]\([^)]*\)", r"\1", text)
|
|
text = re.sub(r"[*`]+", "", text)
|
|
return text.strip()
|
|
|
|
|
|
def _description(root: Path) -> str:
|
|
"""The README's first prose line (the plugin may fill an empty one from
|
|
the homepage dashboard)."""
|
|
rp = _readme_path(root)
|
|
readme = _read_text(rp) if rp else None
|
|
for line in (readme or "").splitlines():
|
|
cleaned = _clean(line.strip())
|
|
if not cleaned or cleaned.startswith(("#", "!", "<", "---", "```", "http")):
|
|
continue
|
|
return cleaned
|
|
return ""
|
|
|
|
|
|
# One bucketed history walk for all services, cached on the repo HEAD (see
|
|
# githist.py); a per-request `git log` per service made this 11 s.
|
|
_HISTORY = githist.BucketedHistory(REPO_DIR, REPO_SERVICES_REL)
|
|
|
|
|
|
def _last_commit(name: str) -> tuple[int | None, str | None]:
|
|
b = _HISTORY.get(name)
|
|
return (b["ts"], b["iso"]) if b else (None, None)
|
|
|
|
|
|
def _recent_commits(name: str) -> list[dict]:
|
|
b = _HISTORY.get(name)
|
|
return list(b["commits"]) if b else []
|
|
|
|
|
|
def _index_record(entry: Path) -> dict:
|
|
ts, iso = _last_commit(entry.name)
|
|
return {
|
|
"dir": entry.name,
|
|
"name": entry.name,
|
|
"description": _description(entry),
|
|
"goal": goalmd.goal_summary(entry),
|
|
"updatedAt": iso,
|
|
"_ts": ts,
|
|
}
|
|
|
|
|
|
# --------------------------------------------------------------------------- #
|
|
# public API
|
|
# --------------------------------------------------------------------------- #
|
|
_LIST_TTL_SECS = 30.0
|
|
_LIST_LOCK = threading.Lock()
|
|
_LIST_CACHE: tuple[float, tuple[Path, Path], list[dict]] | None = None
|
|
_LIST_REFRESHING = False
|
|
|
|
|
|
def _scan_services() -> list[dict]:
|
|
if not SERVICES_DIR.is_dir():
|
|
return []
|
|
items = [_index_record(e) for e in sorted(SERVICES_DIR.iterdir(), key=lambda p: p.name.lower())
|
|
if e.is_dir() and not e.name.startswith(".")]
|
|
# newest commit first
|
|
items.sort(key=lambda i: i["_ts"] if i["_ts"] is not None else -1, reverse=True)
|
|
for i in items:
|
|
i.pop("_ts", None)
|
|
return items
|
|
|
|
|
|
def _refresh_services_bg(roots: tuple[Path, Path]) -> None:
|
|
global _LIST_CACHE, _LIST_REFRESHING
|
|
try:
|
|
items = _scan_services()
|
|
with _LIST_LOCK:
|
|
_LIST_CACHE = (time.monotonic(), roots, items)
|
|
finally:
|
|
with _LIST_LOCK:
|
|
_LIST_REFRESHING = False
|
|
|
|
|
|
def list_services() -> list[dict]:
|
|
"""The index: every service dir (30 s TTL, stale-while-revalidate)."""
|
|
global _LIST_CACHE, _LIST_REFRESHING
|
|
roots = (SERVICES_DIR, REPO_DIR)
|
|
now = time.monotonic()
|
|
with _LIST_LOCK:
|
|
hit = _LIST_CACHE
|
|
if hit is not None and hit[1] == roots:
|
|
if now - hit[0] >= _LIST_TTL_SECS and not _LIST_REFRESHING:
|
|
_LIST_REFRESHING = True
|
|
threading.Thread(target=_refresh_services_bg, args=(roots,),
|
|
daemon=True, name="services-index-refresh").start()
|
|
return [dict(it) for it in hit[2]]
|
|
items = _scan_services()
|
|
with _LIST_LOCK:
|
|
_LIST_CACHE = (time.monotonic(), roots, items)
|
|
return [dict(it) for it in items]
|
|
|
|
|
|
def _safe_entry(slug: str) -> Path | None:
|
|
name = Path(slug).name
|
|
if not name or name.startswith("."):
|
|
return None
|
|
entry = (SERVICES_DIR / name).resolve()
|
|
try:
|
|
entry.relative_to(SERVICES_DIR)
|
|
except ValueError:
|
|
return None
|
|
return entry if entry.is_dir() else None
|
|
|
|
|
|
def service_detail(slug: str) -> dict | None:
|
|
"""The page shell of one service: the index record + README, CLAUDE.md,
|
|
GOAL.md and recent commits."""
|
|
entry = _safe_entry(slug)
|
|
if not entry:
|
|
return None
|
|
rec = _index_record(entry)
|
|
rec.pop("_ts", None)
|
|
rp = _readme_path(entry)
|
|
claude = entry / "CLAUDE.md"
|
|
rec.update({
|
|
"readme": _read_text(rp) if rp else None,
|
|
"claudeMd": _read_text(claude) if claude.is_file() else None,
|
|
"goal": goalmd.goal_detail(entry),
|
|
"commits": _recent_commits(entry.name),
|
|
})
|
|
return rec
|