File size: 17,451 Bytes
674d2cf 40466a6 674d2cf 7581d8d 674d2cf 7581d8d 674d2cf 7581d8d 674d2cf 7581d8d 674d2cf 7581d8d 674d2cf 7581d8d 674d2cf 7581d8d 674d2cf 7581d8d 674d2cf 40466a6 674d2cf 7581d8d 674d2cf 08f69d2 40466a6 08f69d2 40466a6 08f69d2 40466a6 08f69d2 40466a6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 | """
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/search?q= naive substring search over /data/matrix/chunks.jsonl (first 50 hits)
GET /matrix/<name> fetch a stored matrix file
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, tempfile
from pathlib import Path
from typing import Dict, Set
import httpx
from fastapi import FastAPI, WebSocket, WebSocketDisconnect, UploadFile, File, HTTPException, Request, Query
from fastapi.middleware.cors import CORSMiddleware
from 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)
LOCKED = True # Space is LOCKED BY DEFAULT: every data endpoint requires KLAW_WS_TOKEN. Set the secret, then pass ?token= from the Command Center.
def _auth(token: str | None):
if not TOKEN: raise HTTPException(503, "locked: set the KLAW_WS_TOKEN Space secret, then pass ?token= from the Command Center")
if 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"} # reveals nothing without a token
@app.get("/health")
def health(token: str | None = None):
if not TOKEN or token != TOKEN: return {"ok": True, "locked": True}
return {"ok": True, "t": time.time(), "tei": bool(TEI), "gemini": bool(GEMINI), "mt": bool(MT_ORG and MT_KEY), "data_dir": str(DATA),
"workspaces": sorted(p.stem for p in DATA.glob("*.json"))}
@app.websocket("/ws")
async def ws_endpoint(sock: WebSocket, workspace: str = "default", token: str | None = None):
if not TOKEN or 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, token: str | None = None):
_auth(token)
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, token: str | None = None):
_auth(token)
"""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(...), token: str | None = None):
_auth(token)
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}
# NOTE: /matrix/search must be declared BEFORE /matrix/{name}, or the {name} route swallows it.
@app.get("/matrix/search")
def matrix_search(q: str = Query(..., min_length=2), limit: int = 50, token: str | None = None):
_auth(token)
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.get("/matrix/{name}")
def matrix_get(name: str, token: str | None = None):
_auth(token)
p = MATRIX / name
if not p.exists() or ".." in name: raise HTTPException(404)
return FileResponse(str(p))
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
# MODERN TREASURY LINK β credentials live ONLY in Space secrets:
# MT_ORG_ID (organization id) MT_API_KEY (API key) β HTTP Basic auth per MT docs
# Base: https://app.moderntreasury.com/api (the key decides live vs sandbox)
# Read endpoints are open to the Command Center (optionally gated by KLAW_WS_TOKEN);
# write endpoints additionally require the Space secret MT_ALLOW_WRITES=true.
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
import base64, uuid
MT_BASE = "https://app.moderntreasury.com/api"
MT_ORG = os.environ.get("MT_ORG_ID", ""); MT_KEY = os.environ.get("MT_API_KEY", "")
MT_WRITES = os.environ.get("MT_ALLOW_WRITES", "false").lower() == "true"
MT_READ_PATHS = {"internal_accounts", "external_accounts", "counterparties", "payment_orders", "expected_payments",
"ledger_accounts", "ledgers", "ledger_transactions", "transactions", "returns", "webhooks",
"connections", "virtual_accounts", "account_collection_flows", "invoices", "paper_items", "incoming_payment_details"}
def _mt_headers(idem: str | None = None):
if not (MT_ORG and MT_KEY): raise HTTPException(503, "Modern Treasury not linked: set MT_ORG_ID and MT_API_KEY as Space secrets")
h = {"Authorization": "Basic " + base64.b64encode(f"{MT_ORG}:{MT_KEY}".encode()).decode(), "Accept": "application/json"}
if idem: h["Idempotency-Key"] = idem
return h
@app.get("/mt/health")
async def mt_health(token: str | None = None):
_auth(token)
if not (MT_ORG and MT_KEY): return {"linked": False, "reason": "MT_ORG_ID / MT_API_KEY not set in Space secrets"}
async with httpx.AsyncClient(timeout=30) as c:
r = await c.get(f"{MT_BASE}/internal_accounts", params={"per_page": 1}, headers=_mt_headers())
return {"linked": r.status_code == 200, "status": r.status_code, "writes_enabled": MT_WRITES, "org_id_last4": MT_ORG[-4:]}
@app.get("/mt/{resource}")
async def mt_list(resource: str, request: Request, token: str | None = None):
_auth(token)
if resource not in MT_READ_PATHS: raise HTTPException(404, "unknown or non-readable MT resource")
params = dict(request.query_params); params.pop("token", None); params.setdefault("per_page", "100")
async with httpx.AsyncClient(timeout=60) as c:
r = await c.get(f"{MT_BASE}/{resource}", params=params, headers=_mt_headers())
body = r.json() if "json" in r.headers.get("content-type", "") else {"raw": r.text[:2000]}
return JSONResponse({"resource": resource, "status": r.status_code, "data": body,
"next_cursor": r.headers.get("X-After-Cursor"), "per_page": r.headers.get("X-Per-Page")}, status_code=200 if r.status_code < 500 else 502)
@app.get("/mt/{resource}/{rid}")
async def mt_get(resource: str, rid: str, token: str | None = None):
_auth(token)
if resource not in MT_READ_PATHS: raise HTTPException(404)
async with httpx.AsyncClient(timeout=60) as c:
r = await c.get(f"{MT_BASE}/{resource}/{rid}", headers=_mt_headers())
return JSONResponse({"resource": resource, "status": r.status_code, "data": r.json()}, status_code=200 if r.status_code < 500 else 502)
@app.post("/mt/sync")
async def mt_sync(token: str | None = None):
"""One call: pull everything the dashboard needs. Returns a normalized snapshot (also cached at /data/mt_snapshot.json)."""
_auth(token)
out = {"synced_at": time.time(), "resources": {}}
async with httpx.AsyncClient(timeout=90) as c:
for res in ["internal_accounts", "external_accounts", "counterparties", "payment_orders", "expected_payments", "ledger_accounts", "transactions", "returns", "webhooks", "connections", "virtual_accounts"]:
items, cursor = [], None
for _ in range(10): # up to 1,000 rows per resource
params = {"per_page": "100"}
if cursor: params["after_cursor"] = cursor
r = await c.get(f"{MT_BASE}/{res}", params=params, headers=_mt_headers())
if r.status_code != 200: out["resources"][res] = {"error": r.status_code, "detail": r.text[:300]}; break
page = r.json(); items += page if isinstance(page, list) else []
cursor = r.headers.get("X-After-Cursor")
if not cursor: break
if res not in out["resources"]: out["resources"][res] = {"count": len(items), "items": _scrub(items)}
# normalized account view for the Treasury cards
accts = []
for a in out["resources"].get("internal_accounts", {}).get("items", []):
accts.append({"id": a.get("id"), "name": a.get("name"), "party": a.get("party_name"), "currency": a.get("currency"),
"account_type": a.get("account_type"), "connection": (a.get("connection") or {}).get("vendor_name"),
"routing_last4": (next((d.get("routing_number", "")[-4:] for d in a.get("routing_details", []) if d.get("routing_number")), None)),
"account_last4": (next((d.get("account_number", "")[-4:] for d in a.get("account_details", []) if d.get("account_number")), None)),
"balances": a.get("balances") or {}})
out["accounts"] = accts
(DATA / "mt_snapshot.json").write_text(json.dumps(out))
return out
@app.get("/mt_snapshot")
def mt_snapshot(token: str | None = None):
_auth(token); p = DATA / "mt_snapshot.json"
return json.loads(p.read_text()) if p.exists() else {"synced_at": None, "resources": {}, "accounts": []}
@app.post("/mt/payment_orders")
async def mt_create_payment_order(body: dict, token: str | None = None):
"""Creates a real payment order. Disabled unless MT_ALLOW_WRITES=true in Space secrets. Idempotency-Key always sent."""
_auth(token)
if not MT_WRITES: raise HTTPException(403, "writes disabled: set MT_ALLOW_WRITES=true in Space secrets to enable real payment orders")
idem = body.pop("idempotency_key", None) or str(uuid.uuid4())
async with httpx.AsyncClient(timeout=60) as c:
r = await c.post(f"{MT_BASE}/payment_orders", json=body, headers=_mt_headers(idem))
return JSONResponse({"status": r.status_code, "idempotency_key": idem, "data": r.json() if "json" in r.headers.get("content-type", "") else r.text[:1000]}, status_code=200 if r.status_code < 500 else 502)
|