#!/usr/bin/env python3 """ kb-server.py: a tiny READ-ONLY web reader for the KB, so a digest can LINK into it and you can read the wiki from your phone. WHY. One-line digest items are too compressed to stand alone ("of course we're doing that", with no way to find out what "that" was). Every substantial digest item links to its full wiki page, and this server is what makes those links resolve. - READ-ONLY: GET only. No writes, no deletes, no POST. - Renders .md (tables, lists, code) and resolves [[wikilinks]] by page name; .txt raw sources in a readable frame; .html as-is; directories as listings; /search greps the wiki. - LATEST BOX: living pages get appended at the bottom, so a link used to land on stale text. On long pages the NEWEST dated section ("## 2026-01-15 ..." headings) is shown first, whatever the file order. - /home: a one-link landing page (search + latest digest + your own links) for a phone home screen. Links come from home-links.json at the KB root (gitignored): {"Section": {"Label": "url", ...}, ...} - TOKEN GATE: every request except /healthz needs the token. The first hit carries the token as the "k" query parameter (put it in the digest's links); the server then sets an HttpOnly cookie. No token = 403. The token is generated on first run at $KB_TOKEN_FILE (default ~/.config/agent-kb/kb-server-token, 0600). - BLOCKED paths (never served, never searched): .git plus $KB_BLOCKED (comma-separated, e.g. private originals). - Binds 127.0.0.1 by default. Set KB_HOST=0.0.0.0 to reach it from other devices, and only behind the token, ideally on a private network overlay rather than shared wifi. Run: python3 scripts/kb-server.py (uses the `markdown` package if installed, else a built-in renderer) Env: KB_ROOT, KB_HOST, KB_PORT (8787), KB_BLOCKED, KB_TOKEN_FILE """ import hmac, html, http.cookies, json, mimetypes, os, re, secrets, subprocess, time, urllib.parse from datetime import datetime from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path ROOT = Path(os.environ.get("KB_ROOT", Path(__file__).resolve().parent.parent)).resolve() HOST = os.environ.get("KB_HOST", "127.0.0.1") PORT = int(os.environ.get("KB_PORT", "8787")) BLOCKED = {".git"} | {b.strip().strip("/") for b in os.environ.get("KB_BLOCKED", "").split(",") if b.strip()} TOKEN_FILE = Path(os.environ.get("KB_TOKEN_FILE", Path.home() / ".config" / "agent-kb" / "kb-server-token")) LATEST_MIN_WORDS = 1200 # shorter pages render as-is LATEST_ONLY_WORDS = 15000 # longer pages serve only the Latest box unless ?v=full def load_token(): if TOKEN_FILE.exists() and TOKEN_FILE.read_text().strip(): return TOKEN_FILE.read_text().strip() t = secrets.token_urlsafe(24) TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True) TOKEN_FILE.write_text(t) TOKEN_FILE.chmod(0o600) return t TOKEN = load_token() try: import markdown as _md def md_to_html(src): return _md.Markdown(extensions=["extra", "tables", "sane_lists"]).convert(src) except ImportError: # dependency-free fallback: headings, lists, code, quotes, tables, inline marks def _inline(s): s = html.escape(s, quote=False) s = re.sub(r"`([^`]+)`", r"\1", s) s = re.sub(r"\[([^\]]+)\]\(([^)\s]+)\)", r'\1', s) s = re.sub(r"\*\*([^*]+)\*\*", r"\1", s) return re.sub(r"(?\1", s) def md_to_html(src): out, mode = [], None def close(): nonlocal mode if mode: out.append({"ul": "", "table": ""}.get(mode, "")) mode = None lines = src.split("\n") i = 0 while i < len(lines): ln = lines[i] if ln.strip().startswith("```"): close(); j = i + 1 while j < len(lines) and not lines[j].strip().startswith("```"): j += 1 out.append("
" + html.escape("\n".join(lines[i + 1:j])) + "
"); i = j + 1; continue m = re.match(r"^(#{1,6})\s+(.*)", ln) if m: close(); n = len(m.group(1)); out.append(f"{_inline(m.group(2))}") elif re.match(r"^\s*\|.*\|\s*$", ln): if re.match(r"^\s*\|[\s:|-]+\|\s*$", ln): i += 1; continue if mode != "table": close(); out.append(""); mode = "table" cells = [c.strip() for c in ln.strip().strip("|").split("|")] out.append("" + "".join(f"" for c in cells) + "") elif re.match(r"^\s*[-*]\s+", ln): if mode != "ul": close(); out.append("
{_inline(c)}