v1.2: multi-mail providers (catchall/imap/tonline), auto-import to gateway on activation, MCP server (8 tools), start_all one-click, PC metrics CPU/RAM + services panel in dashboard

This commit is contained in:
aaronjaworski710
2026-10-15 12:08:00 +03:00
parent 9f4ec0e615
commit eeb1674788
9 changed files with 743 additions and 14 deletions
+36
View File
@@ -106,3 +106,39 @@ cd gateway && npm install && node server.mjs
--- ---
[AlStack](https://t.me/AlStack) — больше разборов и тулкитов [AlStack](https://t.me/AlStack) — больше разборов и тулкитов
## v1.2 — Multi-mail, MCP, one-click
### Почтовые вариации (mail_providers.py + config.json)
Цепочка провайдеров в `config.json → mail.providers` (первый исчерпан → следующий):
- **catchall** — свой домен с catch-all forwarding (ForwardEmail/Cloudflare) → код читается из Gmail IMAP. Безлимит адресов `lg<rand>@yourdomain.com`. Clerk НЕ блокирует собственные домены. E2E проверено: vortexio-style домен → org активирован → auto-import 201.
- **imap** — любой свой ящик (Gmail app-password / Outlook / свой сервер), plus/dot-алиасы.
- **tonline** — пул `email:pass` файл, IMAP secureimap.t-online.de.
- Temp-mail (voidash и т.п.) — **заблокирован Clerk** ("temporary email services are not allowed"), не использовать.
Секреты — только env (`GMAIL_APP_PW`) или локальный config.json (в репо только config.example.json).
### Авто-активация + мгновенный endpoint
Каждый новый акк в волне: регистрация → free captcha → код → **tenant активация** → **auto-import в gateway (201)** — endpoint `http://127.0.0.1:18789/v1` доступен сразу, без ручных шагов. Отключение: `config.json → gateway.auto_import=false`.
### MCP-сервер (тулзы видит любой агент)
`mcp_server.py` — stdio JSON-RPC (stdlib-only), 8 тулзов: `logicc_status, pc_stats, list_services, bank_list, wave_start, wave_stop, gateway_import, chat`.
Регистрация в Hermes `config.yaml`:
```yaml
mcp_servers:
logicc:
command: python
args: ["<path>/mcp_server.py"]
```
Или Claude Desktop `claude_desktop_config.json` — тот же формат.
### One-click запуск
```
pip install -r requirements.txt # curl_cffi
python start_all.py # dashboard :8560 + gateway :18789 + sidecar ping
python start_all.py --stop # остановить всё
```
Пути настраиваются env: `LG_HOME, LG_GW_DIR, LG_DASH_PORT, LG_POOL, GMAIL_APP_PW`.
### ПК-метрики в дашборде
`/api/status → pc {cpu_pct, ram_used_gb, ram_total_gb}` (ctypes GetSystemTimes/GlobalMemoryStatusEx, Linux fallback /proc) + `services {sidecar, gateway, dashboard, wave}`. В UI — карточки System (CPU/RAM/Disk бары) и Services (живые UP/DOWN точки).
+27
View File
@@ -0,0 +1,27 @@
{
"mail": {
"providers": [
"catchall",
"tonline"
],
"catchall": {
"domains": [
"yourdomain.com"
],
"gmail_user": "your-inbox@gmail.com",
"gmail_app_pass_env": "GMAIL_APP_PW",
"prefix": "lg"
},
"tonline": {
"pool_file": "path/to/working_mails.txt"
}
},
"gateway": {
"url": "http://127.0.0.1:18789",
"admin": "1",
"auto_import": true
},
"sidecar": {
"url": "http://127.0.0.1:8877"
}
}
+72
View File
@@ -105,6 +105,76 @@ def captcha_balances():
return out return out
def pc_stats():
"""CPU/RAM через ctypes (Windows) с фолбэком на /proc (Linux). stdlib-only."""
out = {"cpu_pct": None, "ram_used_gb": None, "ram_total_gb": None}
try:
import ctypes
class FILETIME(ctypes.Structure):
_fields_ = [("lo", ctypes.c_ulong), ("hi", ctypes.c_ulong)]
def ft(v):
return (v.hi << 32) | v.lo
def sample():
idle, kern, user = FILETIME(), FILETIME(), FILETIME()
ctypes.windll.kernel32.GetSystemTimes(
ctypes.byref(idle), ctypes.byref(kern), ctypes.byref(user))
return ft(idle), ft(kern), ft(user)
i1, k1, u1 = sample()
time.sleep(0.4)
i2, k2, u2 = sample()
busy = (k2 - k1) + (u2 - u1) - (i2 - i1)
total = (k2 - k1) + (u2 - u1)
if total > 0:
out["cpu_pct"] = round(100.0 * busy / total, 1)
class MEMORYSTATUSEX(ctypes.Structure):
_fields_ = [("dwLength", ctypes.c_ulong), ("dwMemoryLoad", ctypes.c_ulong),
("ullTotalPhys", ctypes.c_ulonglong), ("ullAvailPhys", ctypes.c_ulonglong),
("ullTotalPageFile", ctypes.c_ulonglong), ("ullAvailPageFile", ctypes.c_ulonglong),
("ullTotalVirtual", ctypes.c_ulonglong), ("ullAvailVirtual", ctypes.c_ulonglong),
("ullAvailExtendedVirtual", ctypes.c_ulonglong)]
ms = MEMORYSTATUSEX()
ms.dwLength = ctypes.sizeof(MEMORYSTATUSEX)
ctypes.windll.kernel32.GlobalMemoryStatusEx(ctypes.byref(ms))
out["ram_total_gb"] = round(ms.ullTotalPhys / 2**30, 1)
out["ram_used_gb"] = round((ms.ullTotalPhys - ms.ullAvailPhys) / 2**30, 1)
except Exception:
try: # Linux fallback
with open("/proc/meminfo") as f:
mi = dict((l.split(":")[0], int(l.split()[1])) for l in f if ":" in l)
out["ram_total_gb"] = round(mi.get("MemTotal", 0) / 2**20, 1)
out["ram_used_gb"] = round((mi.get("MemTotal", 0) - mi.get("MemAvailable", 0)) / 2**20, 1)
out["cpu_pct"] = round(os.getloadavg()[0] * 100.0 / max(1, os.cpu_count()), 1)
except Exception:
pass
return out
def services_ping():
"""Стек-сервисы: sidecar (free captcha), gateway, dashboard."""
sv = {"sidecar": False, "gateway": False, "dashboard": True}
try:
side = os.environ.get("LG_SIDE", "http://127.0.0.1:8877")
req = urllib.request.Request(side + "/health")
with urllib.request.urlopen(req, timeout=3) as r:
sv["sidecar"] = r.status < 500
except urllib.error.HTTPError:
sv["sidecar"] = True # живой, но требует auth
except Exception:
pass
try:
with urllib.request.urlopen(GW + "/health", timeout=3) as r:
sv["gateway"] = r.status == 200
except Exception:
pass
return sv
def status_all(): def status_all():
with _lock: with _lock:
rows = load_bank() rows = load_bank()
@@ -153,6 +223,8 @@ def status_all():
"gateway": {"up": gw_code == 200, "code": gw_code, "models": gw_models}, "gateway": {"up": gw_code == 200, "code": gw_code, "models": gw_models},
"pool_left": pool_left, "pool_left": pool_left,
"disk_free_gb": round(disk.free / 2**30, 1), "disk_free_gb": round(disk.free / 2**30, 1),
"pc": pc_stats(),
"services": services_ping(),
"captcha": captcha_balances(), "captcha": captcha_balances(),
"log": tail, "log": tail,
} }
+56 -1
View File
@@ -231,7 +231,7 @@
<div class="grid gap-5 sm:grid-cols-2"> <div class="grid gap-5 sm:grid-cols-2">
<article class="card"> <article class="card">
<div class="card-header flex items-center justify-between"><h3 class="card-title">Mail pool</h3><span class="badge badge-outline">t-online</span></div> <div class="card-header flex items-center justify-between"><h3 class="card-title">Mail pool</h3><span class="badge badge-outline">catchall + t-online</span></div>
<div class="card-content flex items-baseline gap-3"><span id="c-pool" class="stat-value loading">—</span><span class="text-xs text-muted-foreground">addresses available</span></div> <div class="card-content flex items-baseline gap-3"><span id="c-pool" class="stat-value loading">—</span><span class="text-xs text-muted-foreground">addresses available</span></div>
</article> </article>
<article class="card"> <article class="card">
@@ -240,6 +240,30 @@
</article> </article>
</div> </div>
<div class="grid gap-5 lg:grid-cols-2">
<article class="card">
<div class="card-header flex items-center justify-between"><div><h3 class="card-title">System</h3><p class="card-description">PC resources, real time</p></div><span class="badge badge-outline mono">local</span></div>
<div class="card-content space-y-5">
<div>
<div class="mb-2.5 flex items-center justify-between gap-3 text-xs"><span class="text-zinc-400">CPU</span><span class="mono text-green-400" id="pc-cpu">—</span></div>
<div class="progress" role="progressbar" aria-label="CPU load"><div class="progress-fill" id="pc-cpu-bar" style="width:0%;background:var(--success)"></div></div>
</div>
<div>
<div class="mb-2.5 flex items-center justify-between gap-3 text-xs"><span class="text-zinc-400">RAM</span><span class="mono text-green-400" id="pc-ram">—</span></div>
<div class="progress" role="progressbar" aria-label="RAM usage"><div class="progress-fill" id="pc-ram-bar" style="width:0%;background:var(--success)"></div></div>
</div>
<div>
<div class="mb-2.5 flex items-center justify-between gap-3 text-xs"><span class="text-zinc-400">Disk free</span><span class="mono text-green-400" id="pc-disk2">—</span></div>
<div class="progress" role="progressbar" aria-label="Disk free"><div class="progress-fill" id="pc-disk-bar" style="width:0%;background:var(--success)"></div></div>
</div>
</div>
</article>
<article class="card">
<div class="card-header flex items-center justify-between"><div><h3 class="card-title">Services</h3><p class="card-description">Stack health — видно агенту и ПК</p></div><span class="badge badge-outline mono">auto</span></div>
<div class="card-content" id="services"><div class="skeleton h-4 w-full"></div></div>
</article>
</div>
<article class="card"> <article class="card">
<div class="card-header"><h3 class="card-title">Quick actions</h3><p class="card-description">Manage the next account or synchronize your gateway.</p></div> <div class="card-header"><h3 class="card-title">Quick actions</h3><p class="card-description">Manage the next account or synchronize your gateway.</p></div>
<div class="card-content"> <div class="card-content">
@@ -475,6 +499,36 @@
}).join('') || '<p class="text-xs text-zinc-500">No captcha balances reported.</p>'; }).join('') || '<p class="text-xs text-zinc-500">No captcha balances reported.</p>';
} }
function renderSystem(S) {
const pc = S.pc || {};
const setBar = (id, pct, txt) => {
const bar = $(id + '-bar'); const el = $(id);
if (el) el.textContent = txt;
if (bar) {
const p = Math.min(100, Math.max(0, pct || 0));
bar.style.width = p + '%';
bar.style.background = p > 85 ? 'var(--destructive)' : p > 60 ? '#f59e0b' : 'var(--success)';
}
};
setBar('pc-cpu', pc.cpu_pct, pc.cpu_pct != null ? pc.cpu_pct + '%' : '—');
const ramPct = pc.ram_total_gb ? (pc.ram_used_gb / pc.ram_total_gb * 100) : 0;
setBar('pc-ram', ramPct, pc.ram_total_gb ? pc.ram_used_gb + ' / ' + pc.ram_total_gb + ' GB' : '—');
const d = $('pc-disk2'); if (d) d.textContent = (S.disk_free_gb ?? '—') + ' GB';
const db = $('pc-disk-bar'); if (db) { db.style.width = Math.min(100, (S.disk_free_gb || 0) / 5) + '%'; }
const sv = S.services || {};
const waveUp = !!(S.wave && S.wave.running);
const items = [
['Captcha sidecar', ':8877 free turnstile', !!sv.sidecar],
['LLM gateway', ':18789 OpenAI-compat', !!sv.gateway],
['Dashboard', ':8560 control plane', !!sv.dashboard],
['Reg wave', waveUp ? 'running' : 'idle', waveUp],
];
$('services').innerHTML = items.map(([name, desc, up]) => `<div class="mb-3 flex items-center justify-between gap-3 text-xs last:mb-0">
<div class="flex items-center gap-2.5"><span class="inline-block h-2 w-2 rounded-full" style="background:${up ? 'var(--success)' : 'var(--destructive)'};box-shadow:0 0 6px ${up ? 'var(--success)' : 'var(--destructive)'}"></span>
<span class="text-zinc-300">${name}</span><span class="text-zinc-500">${desc}</span></div>
<span class="mono ${up ? 'text-green-400' : 'text-red-400'}">${up ? 'UP' : 'DOWN'}</span></div>`).join('');
}
async function refresh() { async function refresh() {
if (statusLoading) return; if (statusLoading) return;
statusLoading = true; statusLoading = true;
@@ -505,6 +559,7 @@
$('wave-pill').className = 'badge ' + (S.wave.running ? 'badge-success' : 'badge-outline'); $('wave-pill').className = 'badge ' + (S.wave.running ? 'badge-success' : 'badge-outline');
updateWaveButtons(); updateWaveButtons();
renderCaptcha(S.captcha || []); renderCaptcha(S.captcha || []);
renderSystem(S);
renderModels(S.gateway.models || []); renderModels(S.gateway.models || []);
if (Array.isArray(S.log) && currentTab !== 'log') renderLog(S.log); if (Array.isArray(S.log) && currentTab !== 'log') renderLog(S.log);
} catch (error) { } catch (error) {
+44 -13
View File
@@ -2,6 +2,7 @@
import json, os, random, re, ssl, sys, time, urllib.parse, urllib.request, http.cookiejar import json, os, random, re, ssl, sys, time, urllib.parse, urllib.request, http.cookiejar
import imaplib, email as emaillib import imaplib, email as emaillib
from email.header import decode_header from email.header import decode_header
import mail_providers as MP
BASE_CLERK = "https://clerk.logicc.com" BASE_CLERK = "https://clerk.logicc.com"
SITEKEY = "0x4AAAAAAAWXJGBD7bONzLBd" SITEKEY = "0x4AAAAAAAWXJGBD7bONzLBd"
@@ -274,7 +275,7 @@ def vd_wait_code(sk, timeout=240):
time.sleep(8) time.sleep(8)
return "" return ""
def register(em, pw): def register(em, pw, wait_code=None):
jar = http.cookiejar.CookieJar() jar = http.cookiejar.CookieJar()
tok = solve_turnstile() tok = solve_turnstile()
if not tok: if not tok:
@@ -310,7 +311,7 @@ def register(em, pw):
log("prepare ok") log("prepare ok")
except urllib.error.HTTPError as e: except urllib.error.HTTPError as e:
log("prepare http", e.code, e.read().decode("utf-8", "replace")[:150]) log("prepare http", e.code, e.read().decode("utf-8", "replace")[:150])
code = imap_wait_code(em, pw, t0, timeout=420) code = wait_code(t0, 420) if wait_code else imap_wait_code(em, pw, t0, timeout=420)
if not code: if not code:
return {"email": em, "err": "no_code", "su_id": su_id, "password": password} return {"email": em, "err": "no_code", "su_id": su_id, "password": password}
log("code", code) log("code", code)
@@ -396,10 +397,35 @@ def activate_account(rec):
except Exception as e: except Exception as e:
log("activate exc", repr(e)); return "" log("activate exc", repr(e)); return ""
def gw_auto_import(rec):
"""Сразу после активации отправить акк в gateway — endpoint доступен мгновенно."""
try:
cfg = MP.load_cfg().get("gateway", {})
if not cfg.get("auto_import", True):
return
if not (rec.get("client_cookie") and rec.get("session_id")):
return
url = cfg.get("url", "http://127.0.0.1:18789") + "/api/accounts/import"
payload = json.dumps({"accounts": [{
"name": rec["email"].split("@")[0],
"clientCookie": rec["client_cookie"],
"sessionId": rec["session_id"],
}]}).encode()
req = urllib.request.Request(url, data=payload, headers={
"Content-Type": "application/json",
"X-Logicc-Admin": str(cfg.get("admin", "1")),
})
with urllib.request.urlopen(req, timeout=90) as r:
log("auto-import ok", r.status)
except urllib.error.HTTPError as e:
log("auto-import http", e.code)
except Exception as e:
log("auto-import unavailable:", repr(e)[:80])
def main(): def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1 n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
pool = load_pool() chain = MP.MailChain(MP.load_cfg())
st = load_state() log("mail providers:", " -> ".join(p.name for p in chain.chain))
used = set() used = set()
if os.path.exists(BANK): if os.path.exists(BANK):
for line in open(BANK, encoding="utf-8"): for line in open(BANK, encoding="utf-8"):
@@ -407,15 +433,18 @@ def main():
except Exception: pass except Exception: pass
ok = fail = 0 ok = fail = 0
for i in range(n): for i in range(n):
while st["idx"] < len(pool) and pool[st["idx"]][0] in used: prov, r = None, None
st["idx"] += 1 for _ in range(300):
if st["idx"] >= len(pool): prov, r = chain.next_address()
log("pool exhausted"); break if r is None or r[0] not in used:
em, pw = pool[st["idx"]] break
st["idx"] += 1 if r is None:
save_state(st) log("mail exhausted (all providers)"); break
log(f"[{i+1}/{n}] reg {em}") em, pw, wait_code = r
rec = register(em, pw) used.add(em)
log(f"[{i+1}/{n}] reg {em} via {prov}")
rec = register(em, pw, wait_code)
rec["mail_provider"] = prov
if rec.get("client_cookie") and rec.get("session_id"): if rec.get("client_cookie") and rec.get("session_id"):
org = activate_account(rec) org = activate_account(rec)
if org: if org:
@@ -424,6 +453,8 @@ def main():
log("activated", org) log("activated", org)
with open(BANK, "a", encoding="utf-8") as f: with open(BANK, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n") f.write(json.dumps(rec, ensure_ascii=False) + "\n")
if rec.get("activated"):
gw_auto_import(rec)
if rec.get("client_cookie") and rec.get("session_id"): if rec.get("client_cookie") and rec.get("session_id"):
ok += 1 ok += 1
log("OK", rec["session_id"]) log("OK", rec["session_id"])
+250
View File
@@ -0,0 +1,250 @@
# -*- coding: utf-8 -*-
"""
mail_providers.py — сменные почтовые провайдеры для logicc autoreg.
Провайдеры (порядок задаёт config.json → mail.providers):
tonline — пул t-online.de (файл email:pass), IMAP secureimap.t-online.de
catchall — СВОЙ домен с catch-all forwarding (ForwardEmail/Cloudflare) → Gmail IMAP.
Clerk НЕ блокирует собственные домены (temporary-email blocklist не срабатывает).
Безлимит адресов: lg<rand>@domain
imap — произвольный ящик (Gmail/Outlook/свой сервер) с plus- или dot-алиасами
voidash — temp-mail (ВНИМАНИЕ: Clerk логирует «temporary email services are not allowed»,
все voidash-домены заблокированы на sign_up; провайдер оставлен для других целей)
Секреты — только через env (поля *_env в конфиге) или config.json локально (не коммитить).
"""
import os, re, json, time, random, string, imaplib, email as emlib, ssl
HERE = os.path.dirname(os.path.abspath(__file__))
STATE = os.path.join(HERE, "mail_state.json")
CODE_RE = re.compile(r"\b(\d{6})\b")
def _load_state():
try:
return json.load(open(STATE, encoding="utf-8"))
except Exception:
return {}
def _save_state(st):
tmp = STATE + ".tmp"
with open(tmp, "w", encoding="utf-8") as f:
json.dump(st, f)
os.replace(tmp, STATE)
def _secret(cfg_block, key):
"""Значение секрета: прямое поле или *_env-ссылка."""
envk = cfg_block.get(key + "_env")
if envk:
return os.environ.get(envk, "")
return cfg_block.get(key, "")
# ───────────────────────── readers (ждут код письма) ─────────────────────────
def _imap_read_code(host, port, user, pw, target_email, since_ts, timeout, use_ssl=True,
strict_from=("logicc", "clerk")):
"""Универсальный IMAP-ридер 6-значного кода. target_email — кому (для catch-all/алиасов)."""
deadline = time.time() + timeout
conn = None
while time.time() < deadline:
try:
if use_ssl:
conn = imaplib.IMAP4_SSL(host, port)
else:
conn = imaplib.IMAP4(host, port)
conn.login(user, pw)
conn.select("INBOX")
ids = []
for q in ['(TO "%s")' % target_email, '(TEXT "%s")' % target_email]:
try:
typ, data = conn.search(None, q)
ids = data[0].split()
if ids:
break
except Exception:
continue
for i in ids[-8:]:
typ, md = conn.fetch(i, "(RFC822)")
raw = md[0][1]
msg = emlib.message_from_bytes(raw)
frm = str(msg.get("From", "")).lower()
if strict_from and not any(s in frm for s in strict_from):
continue
body = ""
if msg.is_multipart():
for part in msg.walk():
if part.get_content_type() in ("text/html", "text/plain"):
body = part.get_payload(decode=True).decode("utf-8", "replace")
break
else:
body = msg.get_payload(decode=True).decode("utf-8", "replace")
subj = str(msg.get("Subject", ""))
m = CODE_RE.search(subj) or CODE_RE.search(body)
if m:
try:
conn.logout()
except Exception:
pass
return m.group(1)
try:
conn.logout()
except Exception:
pass
except Exception:
pass
time.sleep(8)
return None
# ───────────────────────── providers ─────────────────────────
class Provider:
name = "?"
def next_address(self):
"""-> (email, imap_password_or_None, wait_code(since_ts, timeout) -> code|None)"""
raise NotImplementedError
class TOnline(Provider):
name = "tonline"
def __init__(self, cfg):
self.pool_file = cfg.get("pool_file", "")
self.host = cfg.get("imap_host", "secureimap.t-online.de")
self.port = int(cfg.get("imap_port", 993))
def _load(self):
out = []
with open(self.pool_file, encoding="utf-8", errors="replace") as f:
for ln in f:
ln = ln.strip()
if "@t-online.de" not in ln:
continue
parts = ln.split(":")
if len(parts) >= 2:
out.append((parts[0].strip(), parts[1].strip()))
return out
def next_address(self):
st = _load_state()
idx = st.get("tonline_idx", 0)
rows = self._load()
if idx >= len(rows):
return None
em, pw = rows[idx]
st["tonline_idx"] = idx + 1
_save_state(st)
host, port = self.host, self.port
def wait_code(since_ts, timeout=420):
return _imap_read_code(host, port, em, pw, em, since_ts, timeout)
return em, pw, wait_code
class CatchAll(Provider):
"""Свой домен + forwarding в Gmail. Безлимит адресов."""
name = "catchall"
def __init__(self, cfg):
self.domains = cfg.get("domains", [])
self.gmail_user = cfg.get("gmail_user", "")
self.gmail_pw = _secret(cfg, "gmail_app_pass")
self.prefix = cfg.get("prefix", "lg")
def next_address(self):
if not self.domains or not self.gmail_user or not self.gmail_pw:
return None
dom = random.choice(self.domains)
addr = "%s%s@%s" % (self.prefix, "".join(random.choices(string.ascii_lowercase + string.digits, k=9)), dom)
gu, gp = self.gmail_user, self.gmail_pw
def wait_code(since_ts, timeout=420):
return _imap_read_code("imap.gmail.com", 993, gu, gp, addr, since_ts, timeout,
strict_from=("logicc", "clerk"))
return addr, None, wait_code
class GenericIMAP(Provider):
"""Произвольный ящик + алиасы (plus: user+tag@dom, dot: u.ser@dom для gmail)."""
name = "imap"
def __init__(self, cfg):
self.host = cfg.get("imap_host", "")
self.port = int(cfg.get("imap_port", 993))
self.user = cfg.get("user", "")
self.pw = _secret(cfg, "password")
self.mode = cfg.get("alias", "plus") # plus | dot | none
def next_address(self):
if not (self.host and self.user and self.pw):
return None
tag = "".join(random.choices(string.ascii_lowercase + string.digits, k=8))
base, dom = self.user.split("@", 1)
if self.mode == "plus":
addr = "%s+%s@%s" % (base, tag, dom)
elif self.mode == "dot":
addr = base + "." + tag[:6] + "@" + dom
else:
addr = self.user
h, p, u, pw = self.host, self.port, self.user, self.pw
def wait_code(since_ts, timeout=420):
return _imap_read_code(h, p, u, pw, addr if self.mode != "dot" else u, since_ts, timeout)
return addr, None, wait_code
BUILDERS = {"tonline": TOnline, "catchall": CatchAll, "imap": GenericIMAP}
class MailChain:
"""Цепочка провайдеров по config: первый исчерпан/упал → следующий."""
def __init__(self, cfg):
mail = (cfg or {}).get("mail", {})
names = mail.get("providers", ["tonline"])
self.chain = []
for n in names:
cls = BUILDERS.get(n)
if cls:
self.chain.append(cls(mail.get(n, {})))
self.chain.append(TOnline(mail.get("tonline", {}))) # фолбэк всегда
def next_address(self):
for p in self.chain:
try:
r = p.next_address()
if r:
return p.name, r
except Exception:
continue
return None, None
def load_cfg():
for name in ("config.json",):
fp = os.path.join(HERE, name)
if os.path.exists(fp):
try:
return json.load(open(fp, encoding="utf-8"))
except Exception:
pass
return {}
if __name__ == "__main__":
cfg = load_cfg()
ch = MailChain(cfg)
prov, r = ch.next_address()
if r:
em, pw, _ = r
masked = em[:3] + "***" + em[-12:]
print("provider:", prov, "| next address:", masked)
else:
print("NO PROVIDER AVAILABLE")
+134
View File
@@ -0,0 +1,134 @@
# -*- coding: utf-8 -*-
"""
mcp_server.py — MCP-сервер (stdio, JSON-RPC, newline-delimited) для Logicc farm.
Работает на stdlib, проксирует в dashboard control-plane (:8560).
Запуск: python mcp_server.py
Регистрация (Hermes config.yaml):
mcp_servers:
logicc:
command: C:/Users/User/AppData/Local/Programs/Python/Python311/python.exe
args: ["C:/Users/User/tmp/logicc_autoreg/mcp_server.py"]
Claude Desktop (claude_desktop_config.json):
"mcpServers": {"logicc": {"command": "python", "args": ["<path>/mcp_server.py"]}}
Тулзы: logicc_status, pc_stats, list_services, bank_list, wave_start, wave_stop,
gateway_import, chat
"""
import json
import os
import sys
import urllib.request
import urllib.error
DASH = os.environ.get("LG_DASH", "http://127.0.0.1:8560")
TOOLS = [
{"name": "logicc_status", "description": "Logicc farm status: bank counters, gateway models, mail pool, disk, PC load, services health", "inputSchema": {"type": "object", "properties": {}}},
{"name": "pc_stats", "description": "PC metrics: CPU %, RAM used/total GB, disk free GB", "inputSchema": {"type": "object", "properties": {}}},
{"name": "list_services", "description": "Stack services health: captcha sidecar :8877, LLM gateway :18789, dashboard :8560, reg wave", "inputSchema": {"type": "object", "properties": {}}},
{"name": "bank_list", "description": "Account bank rows: email(masked-able), status, activated, org, session", "inputSchema": {"type": "object", "properties": {"limit": {"type": "integer", "description": "max rows, default 50"}}}},
{"name": "wave_start", "description": "Start autoreg wave in background (free captcha + mail chain + auto activation + auto gateway import)", "inputSchema": {"type": "object", "properties": {"n": {"type": "integer", "description": "accounts to register, default 5"}}, "required": []}},
{"name": "wave_stop", "description": "Stop running autoreg wave", "inputSchema": {"type": "object", "properties": {}}},
{"name": "gateway_import", "description": "Import all activated bank accounts into OpenAI-compatible gateway (per-account, tolerates duplicates)", "inputSchema": {"type": "object", "properties": {}}},
{"name": "chat", "description": "Send a chat completion through the Logicc gateway (models: gpt-6-luna, gpt-6.1-sol, claude-5.5-sonnet, gemini-3.8-flash, ...)", "inputSchema": {"type": "object", "properties": {"model": {"type": "string"}, "prompt": {"type": "string"}}, "required": ["model", "prompt"]}},
]
def dash(path, method="GET", body=None, timeout=120):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(DASH + path, data=data, method=method,
headers={"Content-Type": "application/json"})
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, json.loads(r.read().decode())
except urllib.error.HTTPError as e:
return e.code, {"error": e.read().decode("utf-8", "replace")[:300]}
except Exception as e:
return 0, {"error": repr(e)[:200]}
def call(name, args):
if name == "logicc_status":
c, s = dash("/api/status")
if c != 200:
return {"dashboard": "DOWN (%s)" % c, "detail": s}
return {"bank": s.get("bank"), "gateway_up": (s.get("gateway") or {}).get("up"),
"models": (s.get("gateway") or {}).get("models"),
"mail_pool_left": s.get("pool_left"), "disk_free_gb": s.get("disk_free_gb"),
"pc": s.get("pc"), "services": s.get("services"),
"wave": s.get("wave"), "captcha": s.get("captcha")}
if name == "pc_stats":
c, s = dash("/api/status")
return {"pc": s.get("pc"), "disk_free_gb": s.get("disk_free_gb")} if c == 200 else s
if name == "list_services":
c, s = dash("/api/status")
return s.get("services") if c == 200 else s
if name == "bank_list":
c, b = dash("/api/bank")
if c == 200 and isinstance(b, list):
lim = int(args.get("limit", 50))
return {"count": len(b), "rows": b[-lim:]}
return b
if name == "wave_start":
c, r = dash("/api/wave/start", "POST", {"n": int(args.get("n", 5))}, timeout=30)
return r
if name == "wave_stop":
c, r = dash("/api/wave/stop", "POST", {}, timeout=30)
return r
if name == "gateway_import":
c, r = dash("/api/gateway/import", "POST", {}, timeout=300)
return r
if name == "chat":
c, r = dash("/api/chat/test", "POST",
{"model": args.get("model", "gpt-6-luna"),
"prompt": args.get("prompt", "say FARM-OK")}, timeout=200)
return r
return {"error": "unknown tool: %s" % name}
def send(msg):
sys.stdout.write(json.dumps(msg) + "\n")
sys.stdout.flush()
def main():
for line in sys.stdin:
line = line.strip()
if not line:
continue
try:
req = json.loads(line)
except Exception:
continue
rid = req.get("id")
method = req.get("method", "")
if method == "initialize":
send({"jsonrpc": "2.0", "id": rid, "result": {
"protocolVersion": "2024-11-05",
"capabilities": {"tools": {}},
"serverInfo": {"name": "logicc-farm", "version": "1.1.0"}}})
elif method == "notifications/initialized":
pass
elif method == "tools/list":
send({"jsonrpc": "2.0", "id": rid, "result": {"tools": TOOLS}})
elif method == "tools/call":
p = req.get("params") or {}
name = p.get("name", "")
args = p.get("arguments") or {}
try:
out = call(name, args)
except Exception as e:
out = {"error": repr(e)[:300]}
send({"jsonrpc": "2.0", "id": rid, "result": {
"content": [{"type": "text", "text": json.dumps(out, ensure_ascii=False)}],
"isError": bool(isinstance(out, dict) and out.get("error"))}})
elif method == "ping":
send({"jsonrpc": "2.0", "id": rid, "result": {}})
elif rid is not None:
send({"jsonrpc": "2.0", "id": rid,
"error": {"code": -32601, "message": "method not found: %s" % method}})
if __name__ == "__main__":
main()
+1
View File
@@ -0,0 +1 @@
curl_cffi>=0.7
+123
View File
@@ -0,0 +1,123 @@
# -*- coding: utf-8 -*-
"""
start_all.py — one-click запуск всего стека Logicc farm:
1. dashboard :8560 (control plane + Web UI)
2. gateway :18789 (OpenAI-compat LLM endpoint, если node доступен и logicc2api рядом)
3. проверка captcha-sidecar :8877 (внешний процесс, только ping)
Работает у всех: пути из config.json / env (LG_HOME, LG_GW_DIR, LG_DASH_PORT).
Запуск: python start_all.py (Windows: pythonw start_all.py без консоли)
Стоп: python start_all.py --stop
"""
import json
import os
import subprocess
import sys
import time
import urllib.request
HERE = os.path.dirname(os.path.abspath(__file__))
DETACHED = 0x00000008 | 0x00000200 if os.name == "nt" else 0 # DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP
def cfg():
try:
return json.load(open(os.path.join(HERE, "config.json"), encoding="utf-8"))
except Exception:
return {}
def ping(url, timeout=3):
try:
with urllib.request.urlopen(url, timeout=timeout) as r:
return r.status < 500
except Exception as e:
return getattr(e, "code", 0) is not None and getattr(e, "code", 0) < 500
def py():
return sys.executable
def start_dashboard():
port = os.environ.get("LG_DASH_PORT", "8560")
if ping("http://127.0.0.1:%s/api/status" % port):
print("[dashboard] already UP :%s" % port)
return
log = open(os.path.join(HERE, "dash.log"), "ab")
subprocess.Popen([py(), os.path.join(HERE, "dashboard.py")],
stdout=log, stderr=log, cwd=HERE, creationflags=DETACHED,
env={**os.environ, "PYTHONPATH": ""})
for _ in range(15):
time.sleep(1)
if ping("http://127.0.0.1:%s/api/status" % port):
print("[dashboard] UP http://127.0.0.1:%s" % port)
return
print("[dashboard] FAILED — see dash.log")
def start_gateway():
gw_dir = os.environ.get("LG_GW_DIR", "")
if not gw_dir:
cand = os.path.join(os.path.dirname(HERE), "logicc2api")
gw_dir = cand if os.path.isdir(cand) else ""
if not gw_dir:
print("[gateway] logicc2api dir not found — skip (set LG_GW_DIR)")
return
if ping("http://127.0.0.1:18789/health"):
print("[gateway] already UP :18789")
return
try:
log = open(os.path.join(gw_dir, "gw.log"), "ab")
subprocess.Popen(["node", "server.mjs", "18789"], stdout=log, stderr=log,
cwd=gw_dir, creationflags=DETACHED)
for _ in range(10):
time.sleep(1)
if ping("http://127.0.0.1:18789/health"):
print("[gateway] UP http://127.0.0.1:18789/v1 (OpenAI-compat)")
return
print("[gateway] FAILED — see gw.log")
except FileNotFoundError:
print("[gateway] node not installed — skip")
def check_sidecar():
ok = ping("http://127.0.0.1:8877/health")
print("[sidecar] free captcha :8877 %s" % ("UP" if ok else "DOWN (2captcha fallback only)"))
def stop_all():
import ctypes
killed = []
if os.name == "nt":
out = subprocess.run(
["powershell", "-NoProfile", "-Command",
"Get-CimInstance Win32_Process -Filter \"Name like 'python%' or Name='node.exe'\" | "
"Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress"],
capture_output=True, text=True, timeout=60).stdout
try:
rows = json.loads(out or "[]")
if isinstance(rows, dict):
rows = [rows]
except Exception:
rows = []
for p in rows:
cl = (p.get("CommandLine") or "")
if any(k in cl for k in ("dashboard.py", "server.mjs", "logicc_reg.py")) and "start_all" not in cl:
try:
ctypes.windll.kernel32.TerminateProcess(
ctypes.windll.kernel32.OpenProcess(1, False, p["ProcessId"]), 1)
killed.append(p["ProcessId"])
except Exception:
pass
print("stopped pids:", killed or "none")
if __name__ == "__main__":
if "--stop" in sys.argv:
stop_all()
else:
start_dashboard()
start_gateway()
check_sidecar()
print("\nUI: http://127.0.0.1:8560 | LLM: http://127.0.0.1:18789/v1 | MCP: python mcp_server.py")