diff --git a/core.py b/core.py index 6b958ad..1f22c18 100644 --- a/core.py +++ b/core.py @@ -24,7 +24,7 @@ from flow import solve_captcha API = "https://api.minara.ai" INVITE = os.environ.get("MINARA_INVITE", "UM9Y8P") PROXIES = [p.strip() for p in os.environ.get("MINARA_PROXY_POOL", "").split(",") if p.strip()] -IMAPMAP_PATH = os.environ.get("MINARA_IMAPMAP", "discovered_imap.json") +IMAPMAP_PATH = os.environ.get("MINARA_IMAPMAP") or os.path.join(HERE, "discovered_imap.json") IMAPMAP = json.load(open(IMAPMAP_PATH)) if os.path.exists(IMAPMAP_PATH) else {} POP_HOSTS = {"rediffmail.com": ("pop.rediffmail.com", 995)} BANK = os.environ.get("MINARA_BANK", HERE + "/bank.jsonl") diff --git a/domain_score.py b/domain_score.py index 976955a..05a3e96 100644 --- a/domain_score.py +++ b/domain_score.py @@ -15,103 +15,108 @@ def bump(d, k): d[k] = d.get(k, 0) + 1 -for path in glob.glob(HERE + "/farm*.log"): - for line in io.open(path, encoding="utf8", errors="ignore"): - line = line.rstrip() - if not line or "@" not in line: +def main(): + for path in glob.glob(HERE + "/farm*.log"): + for line in io.open(path, encoding="utf8", errors="ignore"): + line = line.rstrip() + if not line or "@" not in line: + continue + m = re.search(r"@([A-Za-z0-9._-]+)", line) + if not m: + continue + dom = m.group(1).lower() + if line.startswith("OK "): + bump(ok, dom) + elif "FAIL" in line: + bump(bad, dom) + + stats = {} + for dom in set(list(ok) + list(bad)): + o, b = ok.get(dom, 0), bad.get(dom, 0) + stats[dom] = {"ok": o, "bad": b, "rate": round(o / (o + b), 3) if o + b else 0} + json.dump(stats, io.open(HERE + "/domain_stats.json", "w", encoding="utf8"), ensure_ascii=False, indent=1) + + min_rate = float(sys.argv[1]) if len(sys.argv) > 1 else 0.4 + min_ok = int(sys.argv[2]) if len(sys.argv) > 2 else 1 + + good = {d for d, s in stats.items() if s["ok"] >= min_ok and s["rate"] >= min_rate} + dead = {d for d, s in stats.items() if s["ok"] == 0 and s["bad"] >= 2} + + rows, seen = [], set() + + # не выдавать повторно уже обработанные ящики (farm_done) и зарегистрированные (bank) + for name in ("farm_done.txt", "bank.jsonl"): + p = os.path.join(HERE, name) + if not os.path.exists(p): continue - m = re.search(r"@([A-Za-z0-9._-]+)", line) - if not m: + for line in io.open(p, encoding="utf8", errors="ignore"): + line = line.strip() + if not line: + continue + em = line.split("\t")[0].strip().lower() + if name == "bank.jsonl": + try: + em = (json.loads(line).get("email") or "").strip().lower() + except Exception: + pass + if em: + seen.add(em) + + for f in ("pool_mix.jsonl", "pool.jsonl"): + p = os.path.join(HERE, f) + if not os.path.exists(p): continue - dom = m.group(1).lower() - if line.startswith("OK "): - bump(ok, dom) - elif "FAIL" in line: - bump(bad, dom) - -stats = {} -for dom in set(list(ok) + list(bad)): - o, b = ok.get(dom, 0), bad.get(dom, 0) - stats[dom] = {"ok": o, "bad": b, "rate": round(o / (o + b), 3) if o + b else 0} -json.dump(stats, io.open(HERE + "/domain_stats.json", "w", encoding="utf8"), ensure_ascii=False, indent=1) - -min_rate = float(sys.argv[1]) if len(sys.argv) > 1 else 0.4 -min_ok = int(sys.argv[2]) if len(sys.argv) > 2 else 1 - -good = {d for d, s in stats.items() if s["ok"] >= min_ok and s["rate"] >= min_rate} -dead = {d for d, s in stats.items() if s["ok"] == 0 and s["bad"] >= 2} - -rows, seen = [], set() - -# не выдавать повторно уже обработанные ящики (farm_done) и зарегистрированные (bank) -for name in ("farm_done.txt", "bank.jsonl"): - p = os.path.join(HERE, name) - if not os.path.exists(p): - continue - for line in io.open(p, encoding="utf8", errors="ignore"): - line = line.strip() - if not line: - continue - em = line.split("\t")[0].strip().lower() - if name == "bank.jsonl": + for line in io.open(p, encoding="utf8", errors="ignore"): + line = line.strip() + if not line: + continue try: - em = (json.loads(line).get("email") or "").strip().lower() + r = json.loads(line) except Exception: - pass - if em: + continue + dom = (r.get("dom") or "").lower() + em = (r.get("email") or "").lower() + if em in seen or dom in dead or dom not in good: + continue seen.add(em) + rows.append(r) -for f in ("pool_mix.jsonl", "pool.jsonl"): - p = os.path.join(HERE, f) - if not os.path.exists(p): - continue - for line in io.open(p, encoding="utf8", errors="ignore"): - line = line.strip() - if not line: - continue - try: - r = json.loads(line) - except Exception: - continue - dom = (r.get("dom") or "").lower() - em = (r.get("email") or "").lower() - if em in seen or dom in dead or dom not in good: - continue - seen.add(em) - rows.append(r) + with io.open(HERE + "/pool_whitelist.jsonl", "w", encoding="utf8") as fh: + for r in rows: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") -with io.open(HERE + "/pool_whitelist.jsonl", "w", encoding="utf8") as fh: - for r in rows: - fh.write(json.dumps(r, ensure_ascii=False) + "\n") - -# exploration lane: домены без статистики (новые), чтобы расширять whitelist -explore = [] -seen2 = set() -for f in ("pool_mix.jsonl", "pool.jsonl"): - p = os.path.join(HERE, f) - if not os.path.exists(p): - continue - for line in io.open(p, encoding="utf8", errors="ignore"): - line = line.strip() - if not line: + # exploration lane: домены без статистики (новые), чтобы расширять whitelist + explore = [] + seen2 = set() + for f in ("pool_mix.jsonl", "pool.jsonl"): + p = os.path.join(HERE, f) + if not os.path.exists(p): continue - try: - r = json.loads(line) - except Exception: - continue - dom = (r.get("dom") or "").lower() - em = (r.get("email") or "").lower() - if dom in stats or em in seen or em in seen2: - continue - seen2.add(em) - explore.append(r) -with io.open(HERE + "/pool_explore.jsonl", "w", encoding="utf8") as fh: - for r in explore: - fh.write(json.dumps(r, ensure_ascii=False) + "\n") + for line in io.open(p, encoding="utf8", errors="ignore"): + line = line.strip() + if not line: + continue + try: + r = json.loads(line) + except Exception: + continue + dom = (r.get("dom") or "").lower() + em = (r.get("email") or "").lower() + if dom in stats or em in seen or em in seen2: + continue + seen2.add(em) + explore.append(r) + with io.open(HERE + "/pool_explore.jsonl", "w", encoding="utf8") as fh: + for r in explore: + fh.write(json.dumps(r, ensure_ascii=False) + "\n") -print("explore pool (unseen domains):", len(explore), "| domains:", len({r["dom"] for r in explore})) + print("explore pool (unseen domains):", len(explore), "| domains:", len({r["dom"] for r in explore})) -print("domains scored:", len(stats), "| good:", len(good), "| dead:", len(dead)) -print("whitelist pool:", len(rows), "| domains:", len({r["dom"] for r in rows})) -top = sorted(stats.items(), key=lambda kv: (-kv[1]["rate"], -kv[1]["ok"]))[:10] -print("top:", [(d, s["ok"], s["bad"]) for d, s in top]) \ No newline at end of file + print("domains scored:", len(stats), "| good:", len(good), "| dead:", len(dead)) + print("whitelist pool:", len(rows), "| domains:", len({r["dom"] for r in rows})) + top = sorted(stats.items(), key=lambda kv: (-kv[1]["rate"], -kv[1]["ok"]))[:10] + print("top:", [(d, s["ok"], s["bad"]) for d, s in top]) + + +if __name__ == "__main__": + main() diff --git a/patch_gates2.py b/patch_gates2.py index b34e228..5f04157 100644 --- a/patch_gates2.py +++ b/patch_gates2.py @@ -2,58 +2,73 @@ """Patch iishko gates for minara-pool models (line-based, no escape games).""" import json, py_compile, shutil, time -MODELS = json.load(open("/root/minara_models.json", encoding="utf-8")) -ts = time.strftime("%Y%m%d-%H%M%S") -TAG = " # [MINARA 1106]" +import os +import sys -line_sso = "MODELS += [m for m in " + repr(MODELS) + " if m not in MODELS]" + TAG -line_rank = " models += [m for m in " + repr(MODELS) + " if m not in models]" + TAG -line_tool = "ALLOW += [m for m in " + repr(MODELS) + " if m not in ALLOW]" + TAG +MODELS_PATH = os.environ.get("MINARA_MODELS_JSON", "minara_models.json") +GATE_SSO = os.environ.get("MINARA_GATE_SSO", "/root/sso_limits.py") +GATE_LEGACY = os.environ.get("MINARA_GATE_LEGACY", "/opt/grok-bot/iishko/legacy.py") +GATE_TOOL = os.environ.get("MINARA_GATE_TOOL", "/root/toolgate.py") -def insert_after(path, anchor, newline): - lines = open(path, encoding="utf-8").read().split("\n") - if any("MINARA 1106" in l for l in lines): - return "already" - idx = [i for i, l in enumerate(lines) if anchor in l] - if not idx: - return "anchor-missing" - shutil.copy2(path, path + ".bak-minara-" + ts) - out = lines[:idx[0] + 1] + [newline] + lines[idx[0] + 1:] - open(path, "w", encoding="utf-8").write("\n".join(out)) - py_compile.compile(path, doraise=True) - return "patched" +def main(): + + MODELS = json.load(open(MODELS_PATH, encoding="utf-8")) + ts = time.strftime("%Y%m%d-%H%M%S") + TAG = " # [MINARA 1106]" + + line_sso = "MODELS += [m for m in " + repr(MODELS) + " if m not in MODELS]" + TAG + line_rank = " models += [m for m in " + repr(MODELS) + " if m not in models]" + TAG + line_tool = "ALLOW += [m for m in " + repr(MODELS) + " if m not in ALLOW]" + TAG -def insert_before(path, anchor, newline): - lines = open(path, encoding="utf-8").read().split("\n") - if any("MINARA 1106" in l for l in lines): - return "already" - idx = [i for i, l in enumerate(lines) if anchor in l] - if not idx: - return "anchor-missing" - shutil.copy2(path, path + ".bak-minara-" + ts) - out = lines[:idx[0]] + [newline] + lines[idx[0]:] - open(path, "w", encoding="utf-8").write("\n".join(out)) - py_compile.compile(path, doraise=True) - return "patched" + def insert_after(path, anchor, newline): + lines = open(path, encoding="utf-8").read().split("\n") + if any("MINARA 1106" in l for l in lines): + return "already" + idx = [i for i, l in enumerate(lines) if anchor in l] + if not idx: + return "anchor-missing" + shutil.copy2(path, path + ".bak-minara-" + ts) + out = lines[:idx[0] + 1] + [newline] + lines[idx[0] + 1:] + open(path, "w", encoding="utf-8").write("\n".join(out)) + py_compile.compile(path, doraise=True) + return "patched" -def append_line(path, newline): - lines = open(path, encoding="utf-8").read().split("\n") - if any("MINARA 1106" in l for l in lines): - return "already" - shutil.copy2(path, path + ".bak-minara-" + ts) - out = lines + [newline, ""] - open(path, "w", encoding="utf-8").write("\n".join(out)) - py_compile.compile(path, doraise=True) - return "patched" + def insert_before(path, anchor, newline): + lines = open(path, encoding="utf-8").read().split("\n") + if any("MINARA 1106" in l for l in lines): + return "already" + idx = [i for i, l in enumerate(lines) if anchor in l] + if not idx: + return "anchor-missing" + shutil.copy2(path, path + ".bak-minara-" + ts) + out = lines[:idx[0]] + [newline] + lines[idx[0]:] + open(path, "w", encoding="utf-8").write("\n".join(out)) + py_compile.compile(path, doraise=True) + return "patched" -print("sso_limits:", insert_before("/root/sso_limits.py", "parts = [x.strip()", line_sso)) -print("legacy:", insert_after("/opt/grok-bot/iishko/legacy.py", - "models += IMG_MODELS + IMG_ALWAYS + DISC_MODELS + WUS_MODELS", line_rank)) -print("toolgate:", append_line("/root/toolgate.py", line_tool)) -for p in ("/root/sso_limits.py", "/opt/grok-bot/iishko/legacy.py", "/root/toolgate.py"): - n = sum(1 for l in open(p, encoding="utf-8") if "MINARA 1106" in l) - print(p, "markers:", n) \ No newline at end of file + def append_line(path, newline): + lines = open(path, encoding="utf-8").read().split("\n") + if any("MINARA 1106" in l for l in lines): + return "already" + shutil.copy2(path, path + ".bak-minara-" + ts) + out = lines + [newline, ""] + open(path, "w", encoding="utf-8").write("\n".join(out)) + py_compile.compile(path, doraise=True) + return "patched" + + + print("sso_limits:", insert_before(GATE_SSO, "parts = [x.strip()", line_sso)) + print("legacy:", insert_after(GATE_LEGACY, + "models += IMG_MODELS + IMG_ALWAYS + DISC_MODELS + WUS_MODELS", line_rank)) + print("toolgate:", append_line(GATE_TOOL, line_tool)) + for p in (GATE_SSO, GATE_LEGACY, GATE_TOOL): + n = sum(1 for l in open(p, encoding="utf-8") if "MINARA 1106" in l) + print(p, "markers:", n) + + +if __name__ == "__main__": + main() diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..5d56fc2 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,4 @@ +requests>=2.31 +curl-cffi>=0.7 # MINARA_IMPERSONATE=chrome +playwright>=1.40 # browser_farm.py +psutil>=5.9 diff --git a/shim.py b/shim.py index 3c44317..3a5b1f6 100644 --- a/shim.py +++ b/shim.py @@ -16,7 +16,7 @@ Env: MINARA_TOKENS (default /opt/minara-shim/tokens.jsonl) MINARA_STATE (default /opt/minara-shim/state.json) """ -import json, os, re, sys, threading, time +import json, os, random, re, sys, threading, time from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer import requests @@ -96,10 +96,17 @@ def pick(n=8): start = RR[0] % len(live) RR[0] += 1 live = live[start:] + live[:start] - return live[:n] + 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(): diff --git a/smoke_test.py b/smoke_test.py new file mode 100644 index 0000000..1d0069b --- /dev/null +++ b/smoke_test.py @@ -0,0 +1,100 @@ +#!/usr/bin/env python3 +"""Smoke-тест: импорты без побочек + шим поднимается и отдаёт /health на пустом пуле. + +Запуск: python smoke_test.py +Код возврата 0 = всё зелёное. +""" +import json +import os +import subprocess +import sys +import tempfile +import time +import urllib.error +import urllib.request + +HERE = os.path.dirname(os.path.abspath(__file__)) +sys.path.insert(0, HERE) +FAILS = [] + + +def check(name, cond, extra=""): + print(("PASS " if cond else "FAIL ") + name + (" " + extra if extra else "")) + if not cond: + FAILS.append(name) + + +# 1. импорты не должны тянуть сеть/файлы/печатать +for mod in ("core", "farm_parallel", "domain_score", "flow", "shim", "sync_tokens", "patch_gates2", "browser_farm"): + try: + __import__(mod) + check("import " + mod, True) + except Exception as e: + check("import " + mod, False, type(e).__name__ + " " + str(e)[:60]) + +# 2. шим на пустом пуле +port = 48199 +tmp = tempfile.mkdtemp() +tokens = os.path.join(tmp, "tokens.jsonl") +open(tokens, "w").close() +env = dict(os.environ) +env.update({"MINARA_PORT": str(port), "MINARA_TOKENS": tokens, + "MINARA_STATE": os.path.join(tmp, "state.json")}) +env.pop("PYTHONPATH", None) +proc = subprocess.Popen([sys.executable, os.path.join(HERE, "shim.py")], env=env, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) +try: + ok = False + for _ in range(30): + time.sleep(0.5) + try: + with urllib.request.urlopen("http://127.0.0.1:%d/health" % port, timeout=2) as r: + body = json.loads(r.read().decode()) + ok = r.status == 200 and body.get("tokens") == 0 + break + except Exception: + continue + check("shim /health on empty pool", ok) + # 503 когда токенов нет + try: + body = json.dumps({"model": "claude-haiku-5.5", "messages": [{"role": "user", "content": "hi"}]}).encode() + req = urllib.request.Request("http://127.0.0.1:%d/v1/chat/completions" % port, data=body, + headers={"Content-Type": "application/json"}) + try: + urllib.request.urlopen(req, timeout=5) + check("shim 503 without tokens", False, "unexpected 200") + except urllib.error.HTTPError as e: + check("shim 503 without tokens", e.code == 503, "code=%d" % e.code) + except Exception as e: + check("shim 503 without tokens", False, str(e)[:60]) +finally: + proc.terminate() + try: + proc.wait(timeout=5) + except Exception: + proc.kill() + +# 3. map_model нормализует короткие имена +import shim # noqa: E402 +shim.MODELS_CACHE["data"] = {"data": [{"id": "anthropic/claude-haiku-5.5"}, {"id": "openai/gpt-6.1-sol"}]} +check("map_model short name", shim.map_model("claude-haiku-5.5") == "anthropic/claude-haiku-5.5") +check("map_model passthrough", shim.map_model("openai/gpt-6.1-sol") == "openai/gpt-6.1-sol") + +# 4. domain_score считает статистику на синтетическом логе +os.chdir(tmp) +open(os.path.join(tmp, "farm_test.log"), "w").write( + "OK a@good.com \r\nOK b@good.com \r\nFAIL c@dead.com mail \r\nFAIL d@dead.com mail \r\n") +import io +os.environ["MINARA_HOME"] = tmp +import importlib +import domain_score +importlib.reload(domain_score) +io.open(os.path.join(tmp, "pool_mix.jsonl"), "w").write( + json.dumps({"email": "e@good.com", "pw": "x", "dom": "good.com"}) + "\n" + + json.dumps({"email": "f@dead.com", "pw": "x", "dom": "dead.com"}) + "\n") +domain_score.main() +wl = io.open(os.path.join(tmp, "pool_whitelist.jsonl")).read().strip() +check("domain_score keeps only good domains", "e@good.com" in wl and "f@dead.com" not in wl, wl[:60]) + +print("\nRESULT:", "OK" if not FAILS else "FAILED %d: %s" % (len(FAILS), ",".join(FAILS))) +sys.exit(0 if not FAILS else 1) \ No newline at end of file