""" gateway.py — OpenAI-compatible gateway over a pool of free Honen.com accounts. Models: honen-assistant -> Workspace Assistant (Claude via AI SDK stream), general chat + tools info honen-sandbox -> raw bash/python execution in the account's cloud sandbox (prompt = script; response = stdout/stderr; no LLM, no message quota) Free tier per account: 15 AI msgs/month (assistant/editor chat). Sandbox calls via assistant chat also spend aiMessages; pure MCP bash does NOT (separate quota-free path). Run: python gateway.py [--port 8600] [--key honen-local-2026] Bank: accounts.jsonl (from honen_farm.py). Hot-reload every 60s. Endpoints: GET / dashboard (pool state) GET /v1/models POST /v1/chat/completions (stream + non-stream) """ import json import os import sys import threading import time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from honen_api import Honen, HonenMCP, HonenError HERE = os.path.dirname(os.path.abspath(__file__)) BANK = os.path.join(HERE, "accounts.jsonl") STATE_LOCK = threading.Lock() POOL = [] # list of account dicts QUARANTINE = {} # email -> reason USAGE = {} # email -> {"used": int, "remaining": int, "ts": float} def load_pool(): global POOL accs = [] if os.path.exists(BANK): with open(BANK, encoding="utf-8") as f: for ln in f: ln = ln.strip() if ln: try: accs.append(json.loads(ln)) except ValueError: pass with STATE_LOCK: POOL = accs for a in accs: if a.get("pro"): u = USAGE.setdefault(a["email"], {"used": 0, "remaining": 15, "ts": 0}) u["remaining"] = max(u["remaining"], a.get("ai_remaining", 999999)) def reloader(): while True: time.sleep(60) try: load_pool() except Exception: pass def pick_account(): with STATE_LOCK: cands = [a for a in POOL if a["email"] not in QUARANTINE] if not cands: return None # pro accounts first, then round-robin by fewest recent uses cands.sort(key=lambda a: (not a.get("pro"), USAGE.get(a["email"], {}).get("used", 0))) return cands[0] def mark_usage(email, used_delta=1): u = USAGE.setdefault(email, {"used": 0, "remaining": 15, "ts": 0}) u["used"] += used_delta u["remaining"] = max(0, u["remaining"] - used_delta) u["ts"] = time.time() if u["remaining"] <= 0: with STATE_LOCK: QUARANTINE[email] = "ai quota exhausted" def quarantine(email, reason): with STATE_LOCK: QUARANTINE[email] = reason def get_honen(acc): h = Honen(acc["cookie"]) try: s = h.session() if not s or not s.get("user"): raise HonenError("dead session") return h except Exception: # relogin try: h = Honen.login(acc["email"], acc["password"]) acc["cookie"] = h.cookie return h except Exception as e: quarantine(acc["email"], f"relogin failed: {str(e)[:80]}") raise def chat_assistant(acc, messages, stream_writer=None): h = get_honen(acc) hist = [] for m in messages[:-1]: c = m.get("content") if isinstance(c, list): c = " ".join(x.get("text", "") for x in c if isinstance(x, dict)) hist.append({"role": "user" if m.get("role") == "user" else "assistant", "text": str(c)}) last = messages[-1] c = last.get("content") if isinstance(c, list): c = " ".join(x.get("text", "") for x in c if isinstance(x, dict)) text = str(c) session_id = acc.get("_session_id") out = {} def on_event(t, ev): if t == "text-delta" and stream_writer: stream_writer(ev.get("delta", "")) try: res = h.assistant_chat(text, acc["workspace_id"], session_id=session_id, history=hist[-10:], timeout=240, on_event=on_event) except HonenError as e: msg = str(e) if "PAYWALL" in msg.upper() or "LIMIT" in msg.upper() or "QUOTA" in msg.upper(): quarantine(acc["email"], "quota: " + msg[:100]) raise acc["_session_id"] = res.get("sessionId") or session_id mark_usage(acc["email"]) out["content"] = res.get("text") or "" if res.get("tools"): tl = [] for t in res["tools"]: o = str(t.get("output", "")) tl.append(f"[tool {t.get('name')}] {json.dumps(t.get('input'), ensure_ascii=False)[:300]}" + (f"\n-> {o[:800]}" if o else "")) out["content"] = (out["content"] + "\n\n" + "\n\n".join(tl)).strip() return out def _bank_update(acc): """Persist updated fields of one account back to accounts.jsonl.""" try: lines = [json.loads(l) for l in open(BANK, encoding="utf-8") if l.strip()] for a in lines: if a.get("email") == acc.get("email"): a.update({k: v for k, v in acc.items() if k in ("oauth_token", "oauth_refresh", "mcp_token", "cookie", "pro", "ai_remaining")}) with open(BANK, "w", encoding="utf-8") as f: for a in lines: f.write(json.dumps(a, ensure_ascii=False) + "\n") except Exception: pass def sandbox_exec(acc, script): tok = acc.get("oauth_token") or acc.get("mcp_token") mcp = HonenMCP(tok) try: return mcp.bash(acc["workspace_id"], script, timeout=180) except Exception as e: # oauth/mcp token could expire or lack scope; re-issue via full OAuth flow try: h = get_honen(acc) from honen_oauth import get_oauth_token t = get_oauth_token(h, h.cookie.split("courses_session=")[-1]) acc["oauth_token"] = t["access_token"] if "refresh_token" in t: acc["oauth_refresh"] = t["refresh_token"] _bank_update(acc) mcp = HonenMCP(acc["oauth_token"]) return mcp.bash(acc["workspace_id"], script, timeout=180) except Exception as e2: quarantine(acc["email"], f"mcp dead: {str(e2)[:100]}") raise class Handler(BaseHTTPRequestHandler): api_key = "honen-local-2026" def log_message(self, *a): pass def _send(self, code, obj, ctype="application/json"): b = obj if isinstance(obj, bytes) else json.dumps(obj, ensure_ascii=False).encode() self.send_response(code) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(b))) self.send_header("Access-Control-Allow-Origin", "*") self.end_headers() self.wfile.write(b) def do_OPTIONS(self): self.send_response(204) self.send_header("Access-Control-Allow-Origin", "*") self.send_header("Access-Control-Allow-Headers", "*") self.send_header("Access-Control-Allow-Methods", "*") self.end_headers() def do_GET(self): if self.path == "/v1/models": self._send(200, {"object": "list", "data": [ {"id": "honen-assistant", "object": "model", "owned_by": "honen"}, {"id": "honen-sandbox", "object": "model", "owned_by": "honen"}, ]}) elif self.path == "/": with STATE_LOCK: pool_n = len(POOL) q = dict(QUARANTINE) rows = [] for a in POOL: u = USAGE.get(a["email"], {}) rows.append({"email": a["email"], "ws": a["workspace_id"], "used": u.get("used", 0), "quarantined": q.get(a["email"], "")}) html = ("
" "pool: {pool_n} | quarantined: {len(q)} | models: honen-assistant (Claude, 15 msg/mo per acc), honen-sandbox (bash/python, quota-free)
" "| workspace | msgs used | quarantine | |
|---|---|---|---|
| {r['email']} | {r['ws']} | {r['used']} | {r['quarantined']} |