"""Tool server. Every call: credential must be present and not revoked; tool must be enabled in tools.json. Calls are logged with a timestamp. /job starts a background job on the server side (it keeps running if only the agent is stopped).""" import json, time, threading, pathlib, sys from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer HERE = pathlib.Path(__file__).parent import os NOCHECK = os.environ.get("NOCHECK") == "1" JOBS = {}; LOCK = threading.Lock() def jload(n): return json.loads((HERE / n).read_text()) def log(rec): rec["t"] = time.time() with LOCK, open(HERE / "calls.jsonl", "a") as f: f.write(json.dumps(rec) + "\n") def job(agent, jid, seconds): for i in range(seconds * 10): if JOBS[jid]["cancel"]: break log({"kind": "job-heartbeat", "agent": agent, "job": jid}); time.sleep(0.1) JOBS[jid]["done"] = True class H(BaseHTTPRequestHandler): def log_message(self, *a): pass def _s(self, c, o): b = json.dumps(o).encode(); self.send_response(c); self.send_header("Content-Length", str(len(b))); self.end_headers(); self.wfile.write(b) def do_POST(self): body = json.loads(self.rfile.read(int(self.headers.get("Content-Length") or 0)) or b"{}") creds = jload("creds.json"); c = creds.get(self.headers.get("Authorization", "")[7:]) if NOCHECK and c: pass # NOCHECK=1: a server with no revocation or tool checks (control off) elif not c or c["revoked"]: return self._s(401, {"error": "credential revoked or unknown"}) agent = c["agent"] if self.path == "/act": if not NOCHECK and not jload("tools.json").get(body["tool"], {}).get("enabled", False): log({"kind": "refused", "agent": agent, "tool": body["tool"], "why": "tool revoked"}); return self._s(403, {"error": "tool revoked"}) started = time.time(); time.sleep(body.get("duration", 0.05)) # the work the tool does log({"kind": "call", "agent": agent, "tool": body["tool"], "started": started}); return self._s(200, {"ok": True}) if self.path == "/job": jid = f"{agent}-job"; JOBS[jid] = {"cancel": False, "done": False} threading.Thread(target=job, args=(agent, jid, body["seconds"]), daemon=True).start(); return self._s(200, {"job": jid}) if self.path == "/job/cancel": for k, j in JOBS.items(): if body.get("agent") is None or k == f"{body['agent']}-job": j["cancel"] = True return self._s(200, {"ok": True}) if __name__ == "__main__": ThreadingHTTPServer(("127.0.0.1", 29200), H).serve_forever()