klaw-sync: app.py (rev-numbered WS sync, matrix store/search, Gemini vendors, TEI, OCR)
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206"""klaw-sync — KLAW Command Center state sync + tool gateway (Hugging Face Docker Space, port 7860)
WS /ws?workspace=<id> ops: {op:"pull"} | {op:"patch", baseRev:int, state:{...}} replies/broadcasts: {op:"state", rev:int, state:{...}} ; conflict → current state GET /state/<workspace> current {rev,state} POST /state/<workspace> {baseRev, state} (HTTP alternative to WS patch) POST /embed proxy to TEI_URL (/embed) POST /vendors Gemini 2.5 Flash + google_search grounding ({need, location}) POST /ocr Docling (multipart file) → markdown POST /matrix/upload store SecondBrain matrix/chunks files under /data/matrix/ GET /matrix/<name> fetch a stored matrix file GET /matrix/search?q= naive substring search over /data/matrix/chunks.jsonl (first 50 hits) GET /health
State lives in /data/<workspace>.json (attach an HF Storage Bucket at /data so it survives restarts).Secrets ONLY via Space secrets/env: GEMINI_API_KEY, TEI_URL, KLAW_WS_TOKEN (optional shared token).Credentials are never written to state, logs, or responses."""import os, json, asyncio, time, tempfilefrom pathlib import Pathfrom typing import Dict, Set
import httpxfrom fastapi import FastAPI, WebSocket, WebSocketDisconnect, UploadFile, File, HTTPException, Request, Queryfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import JSONResponse, PlainTextResponse, FileResponse
DATA = Path(os.environ.get("KLAW_DATA_DIR", "/data")); DATA.mkdir(parents=True, exist_ok=True)MATRIX = DATA / "matrix"; MATRIX.mkdir(exist_ok=True)TEI = os.environ.get("TEI_URL", "")GEMINI = os.environ.get("GEMINI_API_KEY", "")TOKEN = os.environ.get("KLAW_WS_TOKEN", "") # optional; if set, clients pass ?token=SECRET_KEYS = {"api_key", "apikey", "token", "secret", "password", "private_key", "hf_token", "oci_key", "wireguard_key"}
app = FastAPI(title="klaw-sync", version="5.0.0")app.add_middleware(CORSMiddleware, allow_origin_regex=r"https://([a-z0-9-]+\.)?(claude\.ai|claude\.com|anthropic\.com|hf\.space|huggingface\.co)$|http://localhost(:\d+)?", allow_credentials=False, allow_methods=["*"], allow_headers=["*"])
clients: Dict[str, Set[WebSocket]] = {}locks: Dict[str, asyncio.Lock] = {}
def _ws_path(ws_id: str) -> Path: ws_id = "".join(c for c in ws_id if c.isalnum() or c in "-_.")[:64] or "default" return DATA / f"{ws_id}.json"
def _scrub(obj): """Strip anything that looks like a credential before it touches disk (defense in depth).""" if isinstance(obj, dict): return {k: ("[REDACTED]" if k.lower() in SECRET_KEYS else _scrub(v)) for k, v in obj.items()} if isinstance(obj, list): return [_scrub(x) for x in obj] return obj
def load(ws_id: str) -> dict: p = _ws_path(ws_id) if p.exists(): try: return json.loads(p.read_text()) except Exception: pass return {"rev": 0, "state": {}}
def save(ws_id: str, doc: dict): p = _ws_path(ws_id) tmp = tempfile.NamedTemporaryFile("w", dir=str(DATA), delete=False, suffix=".tmp") json.dump(doc, tmp); tmp.flush(); os.fsync(tmp.fileno()); tmp.close() os.replace(tmp.name, p)
def _auth(token: str | None): if TOKEN and token != TOKEN: raise HTTPException(403, "bad token")
async def broadcast(ws_id: str, msg: dict, exclude: WebSocket | None = None): dead = [] for c in list(clients.get(ws_id, ())): if c is exclude: continue try: await c.send_text(json.dumps(msg)) except Exception: dead.append(c) for c in dead: clients[ws_id].discard(c)
@app.get("/")def root(): return {"ok": True, "service": "klaw-sync", "version": "5.0.0", "workspaces": sorted(p.stem for p in DATA.glob("*.json"))}
@app.get("/health")def health(): return {"ok": True, "t": time.time(), "tei": bool(TEI), "gemini": bool(GEMINI), "data_dir": str(DATA)}
@app.websocket("/ws")async def ws_endpoint(sock: WebSocket, workspace: str = "default", token: str | None = None): if TOKEN and token != TOKEN: await sock.close(code=4403); return await sock.accept() clients.setdefault(workspace, set()).add(sock) lock = locks.setdefault(workspace, asyncio.Lock()) try: while True: raw = await sock.receive_text() try: m = json.loads(raw) except Exception: continue op = m.get("op") if op == "heartbeat": await sock.send_text(json.dumps({"op": "heartbeat", "t": time.time()})); continue async with lock: doc = load(workspace) if op == "patch" and isinstance(m.get("state"), dict) and int(m.get("baseRev", -1)) == int(doc["rev"]): doc = {"rev": doc["rev"] + 1, "state": _scrub(m["state"]), "updated": time.time()} save(workspace, doc) await sock.send_text(json.dumps({"op": "state", **doc, "ack": True})) await broadcast(workspace, {"op": "state", **doc}, exclude=sock) else: # pull, or stale patch (conflict): return current authoritative state await sock.send_text(json.dumps({"op": "state", **doc, "conflict": op == "patch"})) except WebSocketDisconnect: pass finally: clients.get(workspace, set()).discard(sock)
@app.get("/state/{workspace}")def get_state(workspace: str, token: str | None = None): _auth(token); return load(workspace)
@app.post("/state/{workspace}")async def post_state(workspace: str, req: Request, token: str | None = None): _auth(token) m = await req.json() lock = locks.setdefault(workspace, asyncio.Lock()) async with lock: doc = load(workspace) if int(m.get("baseRev", -1)) != int(doc["rev"]): return JSONResponse({"op": "state", **doc, "conflict": True}, status_code=409) doc = {"rev": doc["rev"] + 1, "state": _scrub(m.get("state", {})), "updated": time.time()} save(workspace, doc) await broadcast(workspace, {"op": "state", **doc}) return {"op": "state", **doc, "ack": True}
@app.post("/embed")async def embed(body: dict): if not TEI: raise HTTPException(503, "TEI_URL not configured") async with httpx.AsyncClient(timeout=60) as c: r = await c.post(f"{TEI.rstrip('/')}/embed", json=body) return JSONResponse(r.json(), status_code=r.status_code)
@app.post("/vendors")async def vendors(body: dict): """Gemini 2.5 Flash with Google Search grounding — results carry source links.""" if not GEMINI: raise HTTPException(503, "GEMINI_API_KEY not configured") need = body.get("need", "commercial trash removal"); loc = body.get("location", "Houston TX 77096") prompt = (f"Find 5 real commercial vendors for: {need} near {loc}. Return ONLY a JSON array of objects with keys " f"name, phone, website, address, pricing, services (array), notes, source_urls (array). Include only facts you can cite.") url = "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" payload = {"contents": [{"parts": [{"text": prompt}]}], "tools": [{"google_search": {}}], "generationConfig": {"temperature": 0.2}} async with httpx.AsyncClient(timeout=90) as c: r = await c.post(url, params={"key": GEMINI}, json=payload) if r.status_code != 200: raise HTTPException(r.status_code, r.text[:500]) j = r.json() text = "".join(p.get("text", "") for p in j.get("candidates", [{}])[0].get("content", {}).get("parts", [])) grounding = j.get("candidates", [{}])[0].get("groundingMetadata", {}) try: s, e = text.find("["), text.rfind("]") items = json.loads(text[s:e+1]) if s != -1 else [] except Exception: items = [] return {"vendors": items, "raw": text if not items else None, "sources": [c.get("web", {}).get("uri") for c in grounding.get("groundingChunks", []) if c.get("web")]}
@app.post("/ocr")async def ocr(f: UploadFile = File(...)): try: from docling.document_converter import DocumentConverter except Exception as e: raise HTTPException(503, f"docling unavailable: {e}") inbox = DATA / "inbox"; inbox.mkdir(exist_ok=True) p = inbox / ("".join(ch for ch in f.filename if ch.isalnum() or ch in "-_.") or "upload") p.write_bytes(await f.read()) doc = DocumentConverter().convert(str(p)).document return {"filename": p.name, "markdown": doc.export_to_markdown()}
@app.post("/matrix/upload")async def matrix_upload(f: UploadFile = File(...), token: str | None = None): _auth(token) name = "".join(ch for ch in f.filename if ch.isalnum() or ch in "-_.") if name not in {"secondbrain_matrix.json", "secondbrain_embed.json", "chunks.jsonl", "secondbrain_matrix.md", "abz_inventory.json"}: raise HTTPException(400, "unexpected matrix file") dest = MATRIX / name with open(dest, "wb") as out: while chunk := await f.read(1 << 20): out.write(chunk) return {"ok": True, "name": name, "bytes": dest.stat().st_size}
@app.get("/matrix/{name}")def matrix_get(name: str): p = MATRIX / name if not p.exists() or ".." in name: raise HTTPException(404) return FileResponse(str(p))
@app.get("/matrix/search")def matrix_search(q: str = Query(..., min_length=2), limit: int = 50): p = MATRIX / "chunks.jsonl" if not p.exists(): raise HTTPException(404, "chunks.jsonl not uploaded") ql = q.lower(); hits = [] with open(p) as fh: for line in fh: if ql in line.lower(): try: c = json.loads(line) except Exception: continue hits.append({"id": c.get("id"), "doc": c.get("doc"), "url": c.get("url"), "model": c.get("model"), "text": c.get("text", "")[:600]}) if len(hits) >= limit: break return {"q": q, "hits": hits}app.pyAdded+206