331 lines
13 KiB
Python
331 lines
13 KiB
Python
"""
|
|
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 = ("<html><body style='background:#111;color:#eee;font-family:monospace'>"
|
|
"<h2>Honen Gateway</h2>"
|
|
f"<p>pool: {pool_n} | quarantined: {len(q)} | models: honen-assistant (Claude, 15 msg/mo per acc), honen-sandbox (bash/python, quota-free)</p>"
|
|
"<table border=1 cellpadding=4><tr><th>email</th><th>workspace</th><th>msgs used</th><th>quarantine</th></tr>"
|
|
+ "".join(f"<tr><td>{r['email']}</td><td>{r['ws']}</td><td>{r['used']}</td><td>{r['quarantined']}</td></tr>" for r in rows)
|
|
+ "</table></body></html>")
|
|
self._send(200, html.encode(), "text/html; charset=utf-8")
|
|
else:
|
|
self._send(404, {"error": "not found"})
|
|
|
|
def do_POST(self):
|
|
if self.path != "/v1/chat/completions":
|
|
return self._send(404, {"error": "not found"})
|
|
auth = self.headers.get("Authorization", "")
|
|
if self.api_key and auth != "Bearer " + self.api_key:
|
|
return self._send(401, {"error": {"message": "invalid api key"}})
|
|
try:
|
|
n = int(self.headers.get("Content-Length", 0))
|
|
body = json.loads(self.rfile.read(n))
|
|
except Exception:
|
|
return self._send(400, {"error": {"message": "bad json"}})
|
|
model = body.get("model", "honen-assistant")
|
|
messages = body.get("messages") or []
|
|
stream = bool(body.get("stream"))
|
|
if not messages:
|
|
return self._send(400, {"error": {"message": "messages required"}})
|
|
|
|
acc = pick_account()
|
|
if not acc:
|
|
return self._send(503, {"error": {"message": "no live accounts in pool"}})
|
|
|
|
cmid = f"chatcmpl-honen-{int(time.time()*1000)}"
|
|
created = int(time.time())
|
|
try:
|
|
if model == "honen-sandbox":
|
|
script = messages[-1].get("content")
|
|
if isinstance(script, list):
|
|
script = " ".join(x.get("text", "") for x in script if isinstance(x, dict))
|
|
out_text = sandbox_exec(acc, str(script))
|
|
else:
|
|
if stream:
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "text/event-stream")
|
|
self.send_header("Cache-Control", "no-cache")
|
|
self.send_header("Access-Control-Allow-Origin", "*")
|
|
self.end_headers()
|
|
|
|
def writer(delta):
|
|
if not delta:
|
|
return
|
|
chunk = {"id": cmid, "object": "chat.completion.chunk", "created": created,
|
|
"model": model,
|
|
"choices": [{"index": 0, "delta": {"content": delta}, "finish_reason": None}]}
|
|
self.wfile.write(f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n".encode())
|
|
self.wfile.flush()
|
|
|
|
res = chat_assistant(acc, messages, stream_writer=writer)
|
|
end = {"id": cmid, "object": "chat.completion.chunk", "created": created,
|
|
"model": model,
|
|
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}
|
|
self.wfile.write(f"data: {json.dumps(end)}\n\ndata: [DONE]\n\n".encode())
|
|
return
|
|
out_text = chat_assistant(acc, messages)["content"]
|
|
resp = {"id": cmid, "object": "chat.completion", "created": created, "model": model,
|
|
"choices": [{"index": 0, "message": {"role": "assistant", "content": out_text},
|
|
"finish_reason": "stop"}],
|
|
"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}}
|
|
self._send(200, resp)
|
|
except Exception as e:
|
|
# failover once to another account
|
|
try:
|
|
acc2 = pick_account()
|
|
if acc2 and acc2["email"] != acc["email"]:
|
|
if model == "honen-sandbox":
|
|
out_text = sandbox_exec(acc2, str(script))
|
|
else:
|
|
out_text = chat_assistant(acc2, messages)["content"]
|
|
resp = {"id": cmid, "object": "chat.completion", "created": created, "model": model,
|
|
"choices": [{"index": 0, "message": {"role": "assistant", "content": out_text},
|
|
"finish_reason": "stop"}],
|
|
"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}}
|
|
return self._send(200, resp)
|
|
except Exception as e2:
|
|
e = e2
|
|
self._send(502, {"error": {"message": f"{type(e).__name__}: {str(e)[:300]}"}})
|
|
|
|
|
|
def main():
|
|
port = 8600
|
|
key = "honen-local-2026"
|
|
argv = sys.argv[1:]
|
|
for i, a in enumerate(argv):
|
|
if a == "--port":
|
|
port = int(argv[i + 1])
|
|
elif a == "--key":
|
|
key = argv[i + 1]
|
|
Handler.api_key = key
|
|
load_pool()
|
|
threading.Thread(target=reloader, daemon=True).start()
|
|
srv = ThreadingHTTPServer(("0.0.0.0", port), Handler)
|
|
print(f"honen gateway on :{port} pool={len(POOL)} key=***")
|
|
srv.serve_forever()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|