#!/usr/bin/env python """ctx_shim.py — local Context.dev gateway with API-key rotation. Endpoints: GET /search?q=&num= -> context.dev /v1/web/search POST /scrape {"url": "...", "formats": {...}} -> /v1/web/scrape GET /answers?task=<...> -> /v1/web/answers (fast) GET /map?domain=stripe.com -> /v1/web/urls GET /status -> key pool state + credits Keys are reloaded from bank.jsonl on every 30 s; dead keys are parked. """ import json, os, threading, time, urllib.parse, urllib.request, urllib.error from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer BASE = os.path.dirname(os.path.abspath(__file__)) BANK = os.path.join(BASE, "bank.jsonl") API = "https://api.context.dev/v1" PORT = int(os.environ.get("CTX_SHIM_PORT", "8891")) lock = threading.Lock() keys = [] # list of dicts {email, key, credits, dead} last_load = 0.0 def load_keys(): global keys, last_load if time.time() - last_load < 30 and keys: return with lock: if time.time() - last_load < 30 and keys: return seen, out = set(), [] try: for line in open(BANK): line = line.strip() if not line: continue d = json.loads(line) k = d.get("key") if not k or k in seen: continue seen.add(k) out.append({"email": d.get("email"), "key": k, "credits": d.get("credits"), "dead": False}) except FileNotFoundError: pass old = {x["key"]: x for x in keys} for x in out: if x["key"] in old: x["credits"] = old[x["key"]]["credits"] x["dead"] = old[x["key"]]["dead"] keys = out last_load = time.time() def pick(): load_keys() with lock: live = [k for k in keys if not k["dead"]] if not live: return None live.sort(key=lambda x: (x["credits"] if isinstance(x["credits"], int) else 0), reverse=True) return live[0] def call(method, path, payload=None, key=None, timeout=60): data = json.dumps(payload).encode() if payload is not None else None req = urllib.request.Request(API + path, data=data, method=method, headers={"Authorization": "Bearer " + key, "Content-Type": "application/json"}) try: with urllib.request.urlopen(req, timeout=timeout) as r: body = r.read().decode("utf-8", "replace") return r.status, body, dict(r.headers) except urllib.error.HTTPError as e: return e.code, e.read().decode("utf-8", "replace"), dict(e.headers) except Exception as e: return 0, json.dumps({"error": str(e)}), {} def do_call(method, path, payload=None): """Try keys until one works; park dead ones.""" load_keys() with lock: cands = [k for k in keys if not k["dead"]] if not cands: return 503, {"error": "no live keys"} cands.sort(key=lambda x: (x["credits"] if isinstance(x["credits"], int) else 0), reverse=True) last = (0, "{}") for k in cands[:12]: st, body, hd = call(method, path, payload, k["key"]) if st == 429: # free plan allows 2 concurrent per key: rotate to the next key, do not park last = (429, body) continue if st in (401, 402, 403): with lock: k["dead"] = True last = (st, body) continue # refresh credits from metadata if present try: j = json.loads(body) cr = j.get("key_metadata", {}).get("credits_remaining") if isinstance(cr, int): with lock: k["credits"] = cr except Exception: pass return st, body return last[0] or 502, last[1] class H(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def _send(self, code, obj): raw = obj if isinstance(obj, str) else json.dumps(obj, ensure_ascii=False) b = raw.encode() self.send_response(code) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(b))) self.end_headers() self.wfile.write(b) def log_message(self, *a): pass def do_GET(self): u = urllib.parse.urlparse(self.path) q = urllib.parse.parse_qs(u.query) if u.path == "/status": load_keys() with lock: return self._send(200, {"keys": len(keys), "live": sum(1 for k in keys if not k["dead"]), "credits_total": sum(k["credits"] for k in keys if isinstance(k["credits"], int)), "details": [{"email": k["email"], "credits": k["credits"], "dead": k["dead"]} for k in keys]}) if u.path == "/search": qs = q.get("q", [""])[0] num = int(q.get("num", ["10"])[0]) if not qs: return self._send(400, {"error": "q required"}) payload = {"query": qs, "numResults": num} if q.get("markdown", ["0"])[0] == "1": payload["markdown"] = True if q.get("fresh", ["0"])[0] == "1": payload["maxAgeMs"] = 0 st, body = do_call("POST", "/web/search", payload) return self._send(st if st else 502, body) if u.path == "/map": dom = q.get("domain", [""])[0] if not dom: return self._send(400, {"error": "domain required"}) st, body = do_call("GET", "/web/urls?domain=" + urllib.parse.quote(dom)) return self._send(st if st else 502, body) if u.path == "/answers": task = q.get("task", [""])[0] if not task: return self._send(400, {"error": "task required"}) st, body = do_call("POST", "/web/answers", {"task": task, "mode": "fast"}) return self._send(st if st else 502, body) return self._send(404, {"error": "unknown path", "paths": ["/search", "/scrape", "/map", "/answers", "/status"]}) def do_POST(self): u = urllib.parse.urlparse(self.path) n = int(self.headers.get("Content-Length") or 0) try: payload = json.loads(self.rfile.read(n) or b"{}") except Exception: return self._send(400, {"error": "bad json"}) if u.path == "/scrape": url = payload.get("url") if not url: return self._send(400, {"error": "url required"}) body = {"url": url, "formats": payload.get("formats") or {"markdown": True}} if payload.get("mainContentOnly") is not None: body["sharedParams"] = {"mainContentOnly": payload["mainContentOnly"]} st, resp = do_call("POST", "/web/scrape", body) return self._send(st if st else 502, resp) return self._send(404, {"error": "unknown path"}) if __name__ == "__main__": load_keys() print("ctx shim on :%d, keys=%d" % (PORT, len(keys)), flush=True) ThreadingHTTPServer(("0.0.0.0", PORT), H).serve_forever()