Files
minara-autoreg/shim.py
T

275 lines
9.5 KiB
Python

#!/usr/bin/env python3
"""Minara AI -> OpenAI-compatible pool shim.
Upstream is already OpenAI-shaped: https://api.minara.ai/v1 (118 models).
Shim only pools account access_tokens (300 credits each), rotates them,
marks burned ones dead and relays SSE streams as-is.
Endpoints:
GET /v1/models
POST /v1/chat/completions (stream supported)
GET /health
GET /pool (per-token credit snapshot)
Env:
MINARA_PORT (default 48140)
MINARA_TOKENS (default /opt/minara-shim/tokens.jsonl)
MINARA_STATE (default /opt/minara-shim/state.json)
"""
import json, os, random, re, sys, threading, time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import requests
HERE = os.path.dirname(os.path.abspath(__file__))
UP = "https://api.minara.ai"
TOKENS_PATH = os.environ.get("MINARA_TOKENS") or os.path.join(HERE, "tokens.jsonl")
STATE_PATH = os.environ.get("MINARA_STATE") or os.path.join(HERE, "state.json")
PORT = int(os.environ.get("MINARA_PORT", sys.argv[1] if len(sys.argv) > 1 else "48140"))
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36"
DEAD_TTL = int(os.environ.get("MINARA_DEAD_TTL", "1800"))
LOCK = threading.Lock()
RR = [0]
TOKENS = [] # [{email, token, dead_until, credits, fail}]
MODELS_CACHE = {"ts": 0, "data": None}
def log(*a):
print(time.strftime("%H:%M:%S"), *a, flush=True)
def load_tokens():
global TOKENS
rows = []
if os.path.exists(TOKENS_PATH):
for line in open(TOKENS_PATH, encoding="utf-8"):
line = line.strip()
if not line:
continue
try:
r = json.loads(line)
except Exception:
continue
if r.get("token"):
rows.append(r)
st = {}
if os.path.exists(STATE_PATH):
try:
st = json.load(open(STATE_PATH, encoding="utf-8"))
except Exception:
st = {}
out = []
for r in rows:
s = st.get(r["token"][-12:], {})
out.append({"email": r.get("email", ""), "token": r["token"],
"dead_until": s.get("dead_until", 0), "credits": s.get("credits"),
"fail": s.get("fail", 0)})
TOKENS = out
log("tokens loaded: %d alive / %d" % (sum(1 for t in TOKENS if t["dead_until"] < time.time()), len(TOKENS)))
def save_state():
st = {}
for t in TOKENS:
st[t["token"][-12:]] = {"dead_until": t["dead_until"], "credits": t["credits"], "fail": t["fail"]}
try:
tmp = STATE_PATH + ".tmp"
json.dump(st, open(tmp, "w", encoding="utf-8"))
os.replace(tmp, STATE_PATH)
except Exception:
pass
def hdrs(token):
return {"Authorization": "Bearer " + token, "Content-Type": "application/json",
"Origin": "https://minara.ai", "Referer": "https://minara.ai/", "User-Agent": UA}
def pick(n=8):
"""Round-robin over live tokens; returns list of candidates."""
now = time.time()
with LOCK:
live = [t for t in TOKENS if t["dead_until"] < now]
if not live:
return []
start = RR[0] % len(live)
RR[0] += 1
live = live[start:] + live[:start]
head = live[:n]
random.shuffle(head) # иначе первые живые токены получают весь трафик
return head
def mark_dead(t, code, body=""):
"""Помечаем токен мёртвым только на реальных отказах доступа.
400/404/422 — это ошибка тела запроса или имени модели, токен тут не виноват:
раньше любой 400 от невалидного запроса выключал живой аккаунт на 30 минут.
"""
with LOCK:
t["fail"] = t.get("fail", 0) + 1
if code in (401, 402, 403) or "insufficient" in (body or "").lower() or "quota" in (body or "").lower():
t["dead_until"] = time.time() + DEAD_TTL
t["credits"] = 0
log("dead %s code=%s" % (t["email"], code))
save_state()
def _ids():
d = MODELS_CACHE["data"] or {}
if isinstance(d, dict):
d = d.get("data") or []
return [m.get("id") for m in d if isinstance(m, dict)]
def ensure_models():
if MODELS_CACHE["data"] and time.time() - MODELS_CACHE["ts"] < 600:
return True
for t in pick(3):
try:
r = requests.get(UP + "/v1/models", headers=hdrs(t["token"]), timeout=30)
if r.status_code == 200:
MODELS_CACHE["data"] = r.json()
MODELS_CACHE["ts"] = time.time()
return True
mark_dead(t, r.status_code, r.text[:200])
except Exception as e:
mark_dead(t, 0, str(e))
return False
def map_model(name):
"""Accept both 'anthropic/claude-opus-5.5' and 'claude-opus-5.5'."""
ids = _ids()
if name in ids:
return name
low = name.lower()
for i in ids:
if i.lower() == low:
return i
for i in ids:
if i.lower().split("/")[-1] == low:
return i
short = low.replace("-", ".")
for i in ids:
tail = i.lower().split("/")[-1].replace("-", ".")
if tail == short:
return i
return name
class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def log_message(self, *a):
pass
def sendj(self, code, obj):
b = json.dumps(obj, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def err(self, code, msg):
self.sendj(code, {"error": {"message": msg, "type": "upstream_error", "code": code}})
def do_GET(self):
p = self.path.split("?")[0]
if p in ("/health", "/"):
now = time.time()
alive = [t for t in TOKENS if t["dead_until"] < now]
return self.sendj(200, {"ok": True, "tokens": len(TOKENS), "alive": len(alive),
"credits": round(sum(t["credits"] or 0 for t in alive), 2)})
if p == "/pool":
return self.sendj(200, {"tokens": TOKENS})
if p.endswith("/models"):
if MODELS_CACHE["data"] and time.time() - MODELS_CACHE["ts"] < 600:
return self.sendj(200, MODELS_CACHE["data"])
for t in pick(5):
try:
r = requests.get(UP + "/v1/models", headers=hdrs(t["token"]), timeout=30)
if r.status_code == 200:
MODELS_CACHE["data"] = r.json()
MODELS_CACHE["ts"] = time.time()
return self.sendj(200, MODELS_CACHE["data"])
mark_dead(t, r.status_code, r.text[:200])
except Exception as e:
mark_dead(t, 0, str(e))
if MODELS_CACHE["data"]:
return self.sendj(200, MODELS_CACHE["data"])
return self.err(503, "no live tokens")
return self.err(404, "not found")
def do_POST(self):
p = self.path.split("?")[0]
if not p.endswith("/chat/completions"):
return self.err(404, "not found")
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n) if n else b"{}"
try:
body = json.loads(raw or b"{}")
except Exception:
return self.err(400, "bad json")
ensure_models()
body["model"] = map_model(body.get("model") or "")
stream = bool(body.get("stream"))
last = None
for t in pick(8):
try:
r = requests.post(UP + "/v1/chat/completions", headers=hdrs(t["token"]),
json=body, timeout=600, stream=stream)
except Exception as e:
mark_dead(t, 0, str(e))
last = str(e)
continue
if r.status_code != 200:
txt = r.text[:300]
mark_dead(t, r.status_code, txt)
last = txt
continue
if stream:
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Cache-Control", "no-cache")
self.send_header("Connection", "close")
self.end_headers()
try:
for chunk in r.iter_content(chunk_size=None):
if chunk:
self.wfile.write(chunk)
self.wfile.flush()
except Exception:
pass
return
data = r.content
self.send_response(200)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
self.end_headers()
self.wfile.write(data)
return
self.err(503, "all tokens failed: %s" % (last or "")[:200])
def reloader():
while True:
time.sleep(60)
try:
if os.path.exists(TOKENS_PATH):
m = os.path.getmtime(TOKENS_PATH)
if m > reloader.last:
reloader.last = m
load_tokens()
except Exception:
pass
reloader.last = 0
if __name__ == "__main__":
load_tokens()
threading.Thread(target=reloader, daemon=True).start()
log("minara shim on :%d" % PORT)
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()