logicc-farm: pure-HTTP Clerk autoreg + OpenAI-compat gateway combo
This commit is contained in:
@@ -0,0 +1,58 @@
|
|||||||
|
# logicc-farm — авторег + gateway для app.logicc.com
|
||||||
|
|
||||||
|
Полный комбо-набор для Logicc (Clerk-based AI-платформа): массовая регистрация аккаунтов через чистый HTTP и OpenAI-совместимый gateway с пулом аккаунтов.
|
||||||
|
|
||||||
|
## Что внутри
|
||||||
|
|
||||||
|
```
|
||||||
|
autoreg/logicc_reg.py — авторегистратор (чистый stdlib Python, 0 зависимостей)
|
||||||
|
gateway/ — logicc2api (MIT, JamesZhaoY) — OpenAI-compat прокси с пулом аккаунтов
|
||||||
|
```
|
||||||
|
|
||||||
|
## Как работает авторег
|
||||||
|
|
||||||
|
Logicc использует Clerk (`clerk.logicc.com`) для аутентификации. Весь флоу реверснут в чистые HTTP-запросы, браузер не нужен:
|
||||||
|
|
||||||
|
1. **Turnstile** (sitekey `0x4AAAAAAAWXJGBD7bONzLBd`) решается через 2captcha (`method=turnstile`, ~10с, ~$0.002/шт)
|
||||||
|
2. `POST /v1/client/sign_ups` — email + password + captcha_token → `su_*` sign-up id
|
||||||
|
3. Код подтверждения читается с почты по IMAP (t-online работает; доставка кода занимает до 5-6 минут — таймаут 540с)
|
||||||
|
4. `POST /v1/client/sign_ups/{su_id}/attempt_first_factor` (`strategy=email_code`) → сессия
|
||||||
|
5. Из cookie-jar забираются `__client` + `session_id` + JWT — это готовые креды для gateway
|
||||||
|
|
||||||
|
Важно: Clerk банит temporary-email домены (`temporary email services are not allowed`), поэтому нужны реальные почтовые ящики (t-online и подобные).
|
||||||
|
|
||||||
|
### Запуск
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# env-переменные (опционально):
|
||||||
|
# LG_POOL — файл почты, формат email:password построчно
|
||||||
|
# LG_KEYS — JSON с ключами 2captcha: [{"key": "...", "label": "..."}]
|
||||||
|
python autoreg/logicc_reg.py 5 # зарегистрировать 5 аккаунтов
|
||||||
|
```
|
||||||
|
|
||||||
|
Результат — `autoreg/logicc_bank.jsonl`, каждая строка:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"email": "...", "password": "***", "client_cookie": "...", "session_id": "sess_...", "jwt": "...", "status": "complete"}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Gateway
|
||||||
|
|
||||||
|
`gateway/` = [logicc2api](https://github.com/JamesZhaoY/logicc2api) (MIT). Поднимает OpenAI-совместимый `/v1/chat/completions` + `/v1/models`, пул до 200 аккаунтов, round-robin, cooldown на 429/401, авто-обновление `__client` cookie.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd gateway && npm install && node server.mjs
|
||||||
|
# или docker compose up -d
|
||||||
|
```
|
||||||
|
|
||||||
|
Импорт аккаунтов из банка: консоль гейтвея принимает batch-import JSON —
|
||||||
|
`[{"name": "acc1", "token": "<jwt>"}]` (JWT-only) или `[{"clientCookie": "...", "sessionId": "sess_..."}]`.
|
||||||
|
|
||||||
|
Защита `/v1/*` — `LOGICC_API_KEY` в `.env`.
|
||||||
|
|
||||||
|
## Дисклеймер
|
||||||
|
|
||||||
|
Материалы для исследования API-аутентификации Clerk. Используйте на свой страх и риск.
|
||||||
|
|
||||||
|
---
|
||||||
|
[AlStack](https://t.me/AlStack) — больше разборов и тулкитов
|
||||||
Binary file not shown.
@@ -0,0 +1,347 @@
|
|||||||
|
# logicc_reg.py N — mass autoreg app.logicc.com via pure-HTTP Clerk API + free Turnstile sidecar
|
||||||
|
import json, os, random, re, ssl, sys, time, urllib.parse, urllib.request, http.cookiejar
|
||||||
|
import imaplib, email as emaillib
|
||||||
|
from email.header import decode_header
|
||||||
|
|
||||||
|
BASE_CLERK = "https://clerk.logicc.com"
|
||||||
|
SITEKEY = "0x4AAAAAAAWXJGBD7bONzLBd"
|
||||||
|
PAGE = "https://accounts.logicc.com/sign-up"
|
||||||
|
SIDE = os.environ.get("SIDE", "http://127.0.0.1:8877/solve")
|
||||||
|
JSV = "5.56.0"
|
||||||
|
|
||||||
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
|
POOL = os.environ.get("LG_POOL", r"C:/Users/User/Desktop/avtoreg/working_mails.txt")
|
||||||
|
BANK = os.path.join(HERE, "logicc_bank.jsonl")
|
||||||
|
STATE = os.path.join(HERE, "state.json")
|
||||||
|
|
||||||
|
VD = "https://api.voidash.com"
|
||||||
|
VD_DOMAINS = ["voidash.bond", "govno.eu.cc", "musor.eu.cc", "pomoi.eu.cc", "voidash.cyou"]
|
||||||
|
|
||||||
|
def vd_json(method, path, body=None, sk=None, timeout=30):
|
||||||
|
url = VD + path
|
||||||
|
data = json.dumps(body).encode() if body is not None else None
|
||||||
|
req = urllib.request.Request(url, data=data, method=method, headers={
|
||||||
|
"User-Agent": UA, "Accept": "application/json",
|
||||||
|
**({"Content-Type": "application/json"} if data else {}),
|
||||||
|
**({"Authorization": "Bearer " + sk} if sk else {}),
|
||||||
|
})
|
||||||
|
resp = urllib.request.urlopen(req, timeout=timeout)
|
||||||
|
return json.loads(resp.read().decode())
|
||||||
|
|
||||||
|
def create_inbox():
|
||||||
|
dom = random.choice(VD_DOMAINS)
|
||||||
|
try:
|
||||||
|
j = vd_json("POST", "/api/v1/inboxes", {"domain": dom})
|
||||||
|
except Exception as e:
|
||||||
|
log("voidash create err:", str(e)[:120]); return None, None
|
||||||
|
sk = j.get("session_key")
|
||||||
|
inbox = j.get("inbox", j)
|
||||||
|
addr = inbox.get("address") if isinstance(inbox, dict) else None
|
||||||
|
return addr, sk
|
||||||
|
|
||||||
|
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36"
|
||||||
|
|
||||||
|
FIRST = ["James","Oliver","Liam","Noah","Emma","Ava","Sophia","Mia","Lucas","Henry","Jack","Leo","Anna","Marie","Paul","Felix","Nina","Clara","Max","Oscar"]
|
||||||
|
LAST = ["Meyer","Schmidt","Fischer","Weber","Wagner","Becker","Hoffmann","Schulz","Koch","Richter","Klein","Wolf","Neumann","Braun","Kruger","Hartmann","Lange","Werner","Krause","Lehmann"]
|
||||||
|
|
||||||
|
def log(*a):
|
||||||
|
print(time.strftime("%H:%M:%S"), *a, flush=True)
|
||||||
|
|
||||||
|
def load_state():
|
||||||
|
if os.path.exists(STATE):
|
||||||
|
return json.load(open(STATE, encoding="utf-8"))
|
||||||
|
return {"idx": 0}
|
||||||
|
|
||||||
|
def save_state(st):
|
||||||
|
tmp = STATE + ".tmp"
|
||||||
|
json.dump(st, open(tmp, "w"), indent=1)
|
||||||
|
os.replace(tmp, STATE)
|
||||||
|
|
||||||
|
def load_pool():
|
||||||
|
out = []
|
||||||
|
for line in open(POOL, encoding="utf-8"):
|
||||||
|
line = line.strip()
|
||||||
|
if not line or line.startswith("#") or ":" not in line:
|
||||||
|
continue
|
||||||
|
em, pw = line.split(":", 1)
|
||||||
|
if "-" in em.split("@")[0]: # dash-alias dead for delivery
|
||||||
|
continue
|
||||||
|
out.append((em, pw))
|
||||||
|
return out
|
||||||
|
|
||||||
|
KEY_FILE = os.environ.get("LG_KEYS", "C:/Users/User/tmp/captcha_keys_2captcha.json")
|
||||||
|
_tc_key = None
|
||||||
|
|
||||||
|
def post_form(url, data, timeout=60):
|
||||||
|
req = urllib.request.Request(url, data=urllib.parse.urlencode(data).encode(),
|
||||||
|
headers={"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
"User-Agent": UA})
|
||||||
|
return urllib.request.urlopen(req, timeout=timeout).read().decode()
|
||||||
|
|
||||||
|
def load_2c_key():
|
||||||
|
global _tc_key
|
||||||
|
if _tc_key:
|
||||||
|
return _tc_key
|
||||||
|
d = json.load(open(KEY_FILE))
|
||||||
|
ks = d["keys"] if isinstance(d, dict) else d
|
||||||
|
best, best_bal = None, -1e9
|
||||||
|
for k in ks:
|
||||||
|
try:
|
||||||
|
out = post_form("https://api.2captcha.com/res.php",
|
||||||
|
{"key": k["key"], "action": "getbalance", "json": 1}, timeout=30)
|
||||||
|
bal = float(json.loads(out).get("request", -1))
|
||||||
|
except Exception:
|
||||||
|
bal = -1.0
|
||||||
|
log("2captcha key", k.get("label"), "balance $%.3f" % bal)
|
||||||
|
if bal > best_bal:
|
||||||
|
best, best_bal = k["key"], bal
|
||||||
|
if best_bal < 0.05:
|
||||||
|
raise RuntimeError("all 2captcha keys empty (best $%.3f)" % best_bal)
|
||||||
|
_tc_key = best
|
||||||
|
return best
|
||||||
|
|
||||||
|
def solve_2captcha():
|
||||||
|
key = load_2c_key()
|
||||||
|
try:
|
||||||
|
out = post_form("https://api.2captcha.com/in.php",
|
||||||
|
{"key": key, "method": "turnstile", "sitekey": SITEKEY,
|
||||||
|
"pageurl": PAGE, "json": 1}, timeout=60)
|
||||||
|
d = json.loads(out)
|
||||||
|
if d.get("errorId"):
|
||||||
|
log("2c in err:", out[:150]); return ""
|
||||||
|
tid = d["request"]
|
||||||
|
except Exception as e:
|
||||||
|
log("2c in exc:", str(e)[:120]); return ""
|
||||||
|
deadline = time.time() + 240
|
||||||
|
while time.time() < deadline:
|
||||||
|
time.sleep(10)
|
||||||
|
try:
|
||||||
|
d = json.loads(post_form("https://api.2captcha.com/res.php",
|
||||||
|
{"key": key, "action": "get", "id": tid, "json": 1}, timeout=30))
|
||||||
|
st = d.get("status")
|
||||||
|
if st == 1 or st == "success":
|
||||||
|
r = d.get("request")
|
||||||
|
if isinstance(r, dict):
|
||||||
|
return r.get("token") or ""
|
||||||
|
return str(r)
|
||||||
|
if isinstance(st, str) and st.startswith("ERROR"):
|
||||||
|
log("2c fatal:", st); return ""
|
||||||
|
if st == 0 and isinstance(d.get("request"), str) and d["request"].startswith("ERROR"):
|
||||||
|
log("2c fatal:", d["request"]); return ""
|
||||||
|
except Exception as e:
|
||||||
|
log("2c poll err:", str(e)[:80])
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def solve_sidecar():
|
||||||
|
try:
|
||||||
|
p = {"type": "turnstile", "url": PAGE, "sitekey": SITEKEY, "real_page": True}
|
||||||
|
req = urllib.request.Request(SIDE, data=json.dumps(p).encode(),
|
||||||
|
headers={"Content-Type": "application/json"})
|
||||||
|
r = json.loads(urllib.request.urlopen(req, timeout=300).read())
|
||||||
|
tok = r.get("token") or ""
|
||||||
|
if tok:
|
||||||
|
return tok
|
||||||
|
log("sidecar empty:", str(r)[:120])
|
||||||
|
except Exception as e:
|
||||||
|
log("sidecar err:", str(e)[:120])
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def solve_turnstile():
|
||||||
|
# sidecar cloakbrowser gives 408 on this sitekey (clicked→timeout); 2captcha solves in ~10s
|
||||||
|
return solve_2captcha()
|
||||||
|
|
||||||
|
def clerk_post(jar, path, fields):
|
||||||
|
url = BASE_CLERK + path
|
||||||
|
if "?" in url:
|
||||||
|
url += "&_clerk_js_version=" + JSV
|
||||||
|
else:
|
||||||
|
url += "?_clerk_js_version=" + JSV
|
||||||
|
data = urllib.parse.urlencode(fields).encode()
|
||||||
|
req = urllib.request.Request(url, data=data, headers={
|
||||||
|
"User-Agent": UA,
|
||||||
|
"Content-Type": "application/x-www-form-urlencoded",
|
||||||
|
"Origin": "https://accounts.logicc.com",
|
||||||
|
"Referer": PAGE,
|
||||||
|
"Accept": "*/*",
|
||||||
|
})
|
||||||
|
op = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
|
||||||
|
resp = op.open(req, timeout=60)
|
||||||
|
body = resp.read().decode("utf-8", "replace")
|
||||||
|
return resp, json.loads(body)
|
||||||
|
|
||||||
|
def imap_wait_code(user, pw, since_ts, timeout=540):
|
||||||
|
deadline = time.time() + timeout
|
||||||
|
conn = None
|
||||||
|
while time.time() < deadline:
|
||||||
|
try:
|
||||||
|
if conn is None:
|
||||||
|
conn = imaplib.IMAP4_SSL("secureimap.t-online.de", 993, timeout=30)
|
||||||
|
conn.login(user, pw)
|
||||||
|
for folder in ("INBOX", "INBOX.Spam"):
|
||||||
|
try:
|
||||||
|
conn.select(folder)
|
||||||
|
except Exception:
|
||||||
|
continue
|
||||||
|
typ, data = conn.search(None, "ALL")
|
||||||
|
ids = data[0].split()[-30:]
|
||||||
|
for i in reversed(ids):
|
||||||
|
typ, md = conn.fetch(i, "(RFC822)")
|
||||||
|
raw = md[0][1]
|
||||||
|
msg = emaillib.message_from_bytes(raw)
|
||||||
|
dh = msg.get("Date")
|
||||||
|
if dh:
|
||||||
|
try:
|
||||||
|
mt = emaillib.parsedate_to_datetime(dh).timestamp()
|
||||||
|
if mt < since_ts - 120:
|
||||||
|
continue
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
|
subj = str(msg.get("Subject") or "")
|
||||||
|
frm = str(msg.get("From") or "")
|
||||||
|
if "logicc" not in (subj + frm).lower() and "verif" not in subj.lower() and "code" not in subj.lower():
|
||||||
|
continue
|
||||||
|
body = ""
|
||||||
|
if msg.is_multipart():
|
||||||
|
for part in msg.walk():
|
||||||
|
ct = part.get_content_type()
|
||||||
|
if ct == "text/plain":
|
||||||
|
body += part.get_payload(decode=True).decode("utf-8", "replace")
|
||||||
|
elif ct == "text/html" and not body:
|
||||||
|
body += part.get_payload(decode=True).decode("utf-8", "replace")
|
||||||
|
else:
|
||||||
|
body = msg.get_payload(decode=True).decode("utf-8", "replace")
|
||||||
|
m = re.search(r"\b(\d{6})\b", re.sub(r"<[^>]+>", " ", body))
|
||||||
|
if m:
|
||||||
|
try: conn.logout()
|
||||||
|
except Exception: pass
|
||||||
|
return m.group(1)
|
||||||
|
time.sleep(15)
|
||||||
|
except Exception as e:
|
||||||
|
log("imap err:", str(e)[:100])
|
||||||
|
try: conn and conn.logout()
|
||||||
|
except Exception: pass
|
||||||
|
conn = None
|
||||||
|
time.sleep(10)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def vd_wait_code(sk, timeout=240):
|
||||||
|
deadline = time.time() + timeout
|
||||||
|
while time.time() < deadline:
|
||||||
|
try:
|
||||||
|
j = vd_json("GET", "/api/v1/messages", sk=sk)
|
||||||
|
for msg in j.get("messages", []):
|
||||||
|
subj = (msg.get("subject") or "")
|
||||||
|
frm = (msg.get("from") or "") if isinstance(msg.get("from"), str) else json.dumps(msg.get("from") or "")
|
||||||
|
if "logicc" not in (subj + frm).lower() and "verif" not in subj.lower() and "code" not in subj.lower():
|
||||||
|
continue
|
||||||
|
raw = (msg.get("html") or "") + (msg.get("text") or "") + (msg.get("body") or "")
|
||||||
|
txt = re.sub(r"<[^>]+>", " ", raw)
|
||||||
|
m = re.search(r"\b(\d{6})\b", txt)
|
||||||
|
if m:
|
||||||
|
return m.group(1)
|
||||||
|
m = re.search(r"\b(\d{4,8})\b", txt)
|
||||||
|
if m:
|
||||||
|
return m.group(1)
|
||||||
|
except Exception as e:
|
||||||
|
log("vd poll err:", str(e)[:100])
|
||||||
|
time.sleep(8)
|
||||||
|
return ""
|
||||||
|
|
||||||
|
def register(em, pw):
|
||||||
|
jar = http.cookiejar.CookieJar()
|
||||||
|
tok = solve_turnstile()
|
||||||
|
if not tok:
|
||||||
|
return {"email": em, "err": "no_turnstile"}
|
||||||
|
first = random.choice(FIRST); last = random.choice(LAST)
|
||||||
|
password = "Lg" + "".join(random.choices("abcdefghijklmnopqrstuvwxyz", k=6)) + str(random.randint(10, 99)) + "!"
|
||||||
|
t0 = time.time()
|
||||||
|
d2 = None
|
||||||
|
try:
|
||||||
|
_, d = clerk_post(jar, "/v1/client/sign_ups", {
|
||||||
|
"email_address": em, "password": password,
|
||||||
|
"first_name": first, "last_name": last,
|
||||||
|
"captcha_token": tok,
|
||||||
|
"unsafe_metadata": "{}",
|
||||||
|
})
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
body = e.read().decode("utf-8", "replace")
|
||||||
|
return {"email": em, "err": f"signup_http_{e.code}", "body": body[:500]}
|
||||||
|
su = d.get("sign_up") or (d.get("response") or {})
|
||||||
|
su_id = su.get("id") or ""
|
||||||
|
status = su.get("status")
|
||||||
|
if not su_id:
|
||||||
|
return {"email": em, "err": "no_su_id", "body": json.dumps(d)[:500]}
|
||||||
|
log("su_id", su_id, "status", status)
|
||||||
|
if status == "complete":
|
||||||
|
pass # no email verification needed
|
||||||
|
else:
|
||||||
|
code = imap_wait_code(em, pw, t0, timeout=540)
|
||||||
|
if not code:
|
||||||
|
return {"email": em, "err": "no_code", "su_id": su_id, "password": password}
|
||||||
|
log("code", code)
|
||||||
|
try:
|
||||||
|
_, d2 = clerk_post(jar, f"/v1/client/sign_ups/{su_id}/attempt_first_factor",
|
||||||
|
{"strategy": "email_code", "code": code})
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
return {"email": em, "err": f"verify_http_{e.code}", "body": e.read().decode("utf-8","replace")[:500], "su_id": su_id}
|
||||||
|
# harvest session + cookies
|
||||||
|
client = (d2 or d).get("client") or {}
|
||||||
|
su_out = (d2 or d).get("response") or (d2 or d).get("sign_up") or {}
|
||||||
|
sess_id = ""
|
||||||
|
jwt = ""
|
||||||
|
sessions = client.get("sessions") or []
|
||||||
|
if sessions:
|
||||||
|
sess_id = sessions[0].get("id") or ""
|
||||||
|
jwt = sessions[0].get("token") or ""
|
||||||
|
if not sess_id:
|
||||||
|
m = re.search(r"sess_[A-Za-z0-9]+", json.dumps(d2 or d))
|
||||||
|
sess_id = m.group(0) if m else ""
|
||||||
|
cclient = ""; csession = ""
|
||||||
|
for c in jar:
|
||||||
|
if c.name == "__client":
|
||||||
|
cclient = c.value
|
||||||
|
elif c.name == "__session":
|
||||||
|
csession = c.value
|
||||||
|
if not jwt and csession:
|
||||||
|
jwt = csession
|
||||||
|
rec = {"email": em, "password": password, "first": first, "last": last,
|
||||||
|
"client_cookie": cclient, "session_id": sess_id, "jwt": jwt,
|
||||||
|
"su_id": su_id, "status": su_out.get("status") if isinstance(su_out, dict) else "",
|
||||||
|
"ts": int(time.time())}
|
||||||
|
if not cclient or not sess_id:
|
||||||
|
rec["err"] = "no_creds"
|
||||||
|
return rec
|
||||||
|
|
||||||
|
def main():
|
||||||
|
n = int(sys.argv[1]) if len(sys.argv) > 1 else 1
|
||||||
|
pool = load_pool()
|
||||||
|
st = load_state()
|
||||||
|
used = set()
|
||||||
|
if os.path.exists(BANK):
|
||||||
|
for line in open(BANK, encoding="utf-8"):
|
||||||
|
try: used.add(json.loads(line)["email"])
|
||||||
|
except Exception: pass
|
||||||
|
ok = fail = 0
|
||||||
|
for i in range(n):
|
||||||
|
while st["idx"] < len(pool) and pool[st["idx"]][0] in used:
|
||||||
|
st["idx"] += 1
|
||||||
|
if st["idx"] >= len(pool):
|
||||||
|
log("pool exhausted"); break
|
||||||
|
em, pw = pool[st["idx"]]
|
||||||
|
st["idx"] += 1
|
||||||
|
save_state(st)
|
||||||
|
log(f"[{i+1}/{n}] reg {em}")
|
||||||
|
rec = register(em, pw)
|
||||||
|
with open(BANK, "a", encoding="utf-8") as f:
|
||||||
|
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
|
||||||
|
if rec.get("client_cookie") and rec.get("session_id"):
|
||||||
|
ok += 1
|
||||||
|
log("OK", rec["session_id"])
|
||||||
|
else:
|
||||||
|
fail += 1
|
||||||
|
log("FAIL", rec.get("err"), str(rec.get("body", ""))[:200])
|
||||||
|
time.sleep(random.randint(20, 40))
|
||||||
|
log(f"DONE ok={ok} fail={fail}")
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Only application sources enter the build context. Excludes credentials and data.
|
||||||
|
**
|
||||||
|
!Dockerfile
|
||||||
|
!package.json
|
||||||
|
!server.mjs
|
||||||
|
!pool.mjs
|
||||||
|
!LICENSE
|
||||||
|
!public/
|
||||||
|
!public/**
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
data/
|
||||||
|
.backup/
|
||||||
|
.playwright-cli/
|
||||||
|
node_modules/
|
||||||
|
*.log
|
||||||
|
.env*
|
||||||
|
.DS_Store
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# 免责声明与使用责任说明
|
||||||
|
|
||||||
|
适用项目:logicc2api
|
||||||
|
|
||||||
|
**使用前请仔细阅读,尤其是“无担保与责任限制”部分。本说明用于提示使用风险与责任边界,须在适用法律允许的范围内解释和适用,不构成对任何违法行为的授权或免责。**
|
||||||
|
|
||||||
|
## 一、项目性质与许可
|
||||||
|
|
||||||
|
logicc2api 是用于接口适配与本地账户管理的软件工具。项目中的 Logicc、OpenAI 等名称、商标及接口名称仅用于描述服务或兼容性,不应据此认定相关权利人对本项目提供了授权、认证、合作或背书。本项目不代表上述服务提供方作出承诺。
|
||||||
|
|
||||||
|
本项目依照 [MIT License](LICENSE) 提供。软件的使用、复制、修改、分发及商业使用权利以该许可证为准;本说明不另行增加“仅限学习”“禁止商用”等许可限制。MIT 许可不授予用户访问第三方账户、模型、数据或服务的额外权利,也不免除用户对第三方依法承担的义务。
|
||||||
|
|
||||||
|
## 二、合法使用与账户授权
|
||||||
|
|
||||||
|
用户应在适用法律及有效授权范围内使用本项目,并自行核实第三方服务对接口访问、自动化调用、账户共享、转售、调用频率和配额的相关约定。软件具备某项技术能力,不等于第三方服务允许该用途。
|
||||||
|
|
||||||
|
用户应确保所使用的账户、Cookie、Session ID、JWT、API Key 及输入数据来源合法,且拥有相应使用权限。不得利用本项目从事未经授权的账户访问、凭据窃取、非法获取或披露数据、侵犯他人权益、干扰服务正常运行等违法行为。
|
||||||
|
|
||||||
|
用户对自己控制的账户、部署方式、调用行为及内容传播依法承担相应责任;作者、贡献者及版权持有人的责任依适用法律和其实际行为认定。
|
||||||
|
|
||||||
|
## 三、第三方服务、费用与内容风险
|
||||||
|
|
||||||
|
第三方服务的接口、模型、价格、配额、访问规则及服务条款可能发生变化,也可能出现限流、会话失效、账户限制或服务中断。作者及贡献者不承诺上游服务持续可用、账号不受限制或本项目始终兼容。
|
||||||
|
|
||||||
|
真实请求可能消耗第三方服务配额或产生费用;具体计费和账户处理以用户与服务提供方之间的有效约定为准。本项目不承诺免费、无限调用,也不保证费用或用量统计完整准确。
|
||||||
|
|
||||||
|
生成内容可能存在事实错误、不完整信息或侵权风险。用户应根据具体用途进行核验,并自行确认使用、发布或传播相关内容所需的权限;模型输出不构成作者或贡献者提供的专业意见或结果保证。
|
||||||
|
|
||||||
|
## 四、凭据、数据与部署责任
|
||||||
|
|
||||||
|
用户应妥善保管凭据、配置、日志和备份,采取与部署环境相适应的访问控制措施。项目文档说明,本地状态文件可能以明文保存账户凭据;不得将其随源码、截图或问题报告公开。
|
||||||
|
|
||||||
|
本地运行不代表请求数据仅保留在本机。调用上游服务时,相关输入可能发送至所配置的第三方服务。用户应事先核实数据处理规则,确认拥有上传、处理及必要传输的合法依据,并避免提交无权披露的个人信息或商业秘密。
|
||||||
|
|
||||||
|
对外提供服务、共享部署或二次分发的运营者,应依法履行其自身的安全、隐私、内容管理及告知义务,不得以本说明替代其对最终用户承担的责任。
|
||||||
|
|
||||||
|
## 五、无担保与责任限制
|
||||||
|
|
||||||
|
**在适用法律允许的范围内,本软件及相关文档按“现状”提供,不附带明示或默示担保,包括适销性、特定用途适用性及不侵权担保。作者、贡献者及版权持有人不保证软件无错误、无漏洞、持续可用或满足特定业务需求。**
|
||||||
|
|
||||||
|
**在适用法律允许免除或限制责任的范围内,作者、贡献者及版权持有人不对因使用或无法使用本软件而产生的损失承担责任,包括数据丢失、凭据泄露、账户限制、服务中断、业务损失或预期收益损失。具体适用仍以 MIT 许可及适用法律为准。**
|
||||||
|
|
||||||
|
**上述条款不排除或限制法律规定不得排除或限制的责任。适用中华人民共和国法律时,造成对方人身损害,或者因故意、重大过失造成对方财产损失等依法不得免责的情形,不适用上述免责约定。**
|
||||||
|
|
||||||
|
本说明不因用户下载、浏览或使用项目,就当然排除用户的法定权利;相关条款是否纳入合同及其效力,须依据适用法律和具体事实判断。部分条款被认定无效时,其余条款在法律允许的范围内继续适用。
|
||||||
|
|
||||||
|
## 六、反馈与版本
|
||||||
|
|
||||||
|
如发现可能涉及权利侵害或文档问题,可通过[项目 Issues](https://github.com/JamesZhaoY/logicc2api/issues)提供不含敏感信息的说明。请勿在公开反馈中提交有效凭据、个人信息或未脱敏的请求数据。
|
||||||
|
|
||||||
|
本说明的修订记录以仓库版本记录为准;后续修订不当然追溯适用于修订前的行为,也不改变第三方服务条款或既有 MIT 许可所授予的权利。
|
||||||
|
|
||||||
|
法律参考:涉及中华人民共和国法律的免责及格式条款边界,可参见[《中华人民共和国民法典》第四百九十六条、第四百九十七条及第五百零六条(中国网信网)](https://www.cac.gov.cn/2020-06/01/c_15925617772683192.htm)。此处列示参考依据,不表示所有使用场景均适用同一法域。
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
FROM node:24-alpine
|
||||||
|
|
||||||
|
ENV NODE_ENV=production \
|
||||||
|
PORT=18789 \
|
||||||
|
LOGICC_HOST=0.0.0.0 \
|
||||||
|
LOGICC_DATA_FILE=/app/data/state.json
|
||||||
|
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package.json server.mjs pool.mjs LICENSE ./
|
||||||
|
COPY public ./public
|
||||||
|
RUN mkdir -p /app/data && chown node:node /app/data
|
||||||
|
|
||||||
|
USER node
|
||||||
|
EXPOSE 18789
|
||||||
|
|
||||||
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=5s --retries=3 \
|
||||||
|
CMD ["node", "--input-type=module", "-e", "const response = await fetch('http://127.0.0.1:' + process.env.PORT + '/health'); if (!response.ok) process.exit(1);"]
|
||||||
|
|
||||||
|
CMD ["node", "server.mjs"]
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 JamesZhaoY
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
# logicc2api
|
||||||
|
|
||||||
|
**English** · [简体中文](README.zh-CN.md)
|
||||||
|
|
||||||
|
> **Disclaimer:** Please read the [disclaimer and usage responsibilities (Simplified Chinese)](DISCLAIMER.md) before use. It covers account authorization, third-party service risks, data handling, and limitations of liability. The [MIT License](LICENSE) continues to govern the software license.
|
||||||
|
|
||||||
|
A local OpenAI-compatible adapter for [Logicc](https://app.logicc.com), with account pool management and a web console. It converts Logicc's AI SDK v6 event stream into OpenAI Chat Completions responses and shows account health, traffic, latency, and request history in one place.
|
||||||
|
|
||||||
|
Built with Node.js and plain HTML/CSS/JavaScript. **No runtime dependencies, database setup, or frontend build step.** The web interface is currently in Simplified Chinese; documentation is available in English and Chinese.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
| Area | What it provides |
|
||||||
|
| --- | --- |
|
||||||
|
| OpenAI-compatible API | Model listing and streaming/non-streaming Chat Completions |
|
||||||
|
| Account pool | Add, edit, remove, enable/disable, search, and bulk-import accounts |
|
||||||
|
| Credential refresh | On-demand Clerk JWT refresh, shared concurrent refreshes, and persistence of rotated client cookies |
|
||||||
|
| Scheduling | Prefer the least-busy accounts, round-robin between ties, and cool down failing accounts |
|
||||||
|
| Dashboard | Request trends, success rate, time to first text, and account availability |
|
||||||
|
| Models and logs | Live model discovery, observed model latency, request details, filters, and CSV export |
|
||||||
|
| Playground | Send a real streaming request, choose an upstream tool, and stop the local request |
|
||||||
|
| Local storage | Keep configuration and request metadata across restarts; credentials are omitted from management responses |
|
||||||
|
|
||||||
|
The console polls local state every five seconds. Account checks and model synchronization fetch the upstream model list; the playground sends real generation requests and uses your upstream quota.
|
||||||
|
|
||||||
|
## Quick start
|
||||||
|
|
||||||
|
Requires **Node.js 22 or newer** and a Logicc account/session you can use. For a container-based setup without installing Node.js on the host, see [Docker deployment](#docker-deployment).
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/JamesZhaoY/logicc2api.git
|
||||||
|
cd logicc2api
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
There is no dependency installation step. You can also run `node server.mjs` directly.
|
||||||
|
|
||||||
|
1. Open **<http://127.0.0.1:18789/>**.
|
||||||
|
2. Go to **号池管理 → 添加账户** (Account pool → Add account), enter your credentials, and click **检测** (Check).
|
||||||
|
3. Point your client at **`http://127.0.0.1:18789/v1`**. Unless you configure `LOGICC_API_KEY`, use any non-empty API key, such as `local`.
|
||||||
|
|
||||||
|
To select a different port:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node server.mjs 18790
|
||||||
|
```
|
||||||
|
|
||||||
|
Native startup binds to `127.0.0.1` by default. Command-line port selection takes precedence over `PORT`.
|
||||||
|
|
||||||
|
## Docker deployment
|
||||||
|
|
||||||
|
Requires Docker Engine with the Compose plugin, or Docker Desktop. The repository includes a [Dockerfile](Dockerfile) and [compose.yaml](compose.yaml); the image is built locally from source.
|
||||||
|
|
||||||
|
### Start with Docker Compose
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/JamesZhaoY/logicc2api.git
|
||||||
|
cd logicc2api
|
||||||
|
docker compose up -d --build --wait
|
||||||
|
```
|
||||||
|
|
||||||
|
If you already cloned the repository, run the last command from its root directory. Open **<http://127.0.0.1:18789/>**, add an account, and use **`http://127.0.0.1:18789/v1`** as your client's Base URL.
|
||||||
|
|
||||||
|
The image uses Node.js 24 Alpine and runs as the non-root `node` user. Inside the container, `LOGICC_HOST=0.0.0.0` allows Docker's port forwarding to reach the server. Compose publishes the port only on the host's `127.0.0.1`. The image health check calls `/health`; a healthy container means the service is running, not that an upstream account has passed a check.
|
||||||
|
|
||||||
|
### Change the port or API key
|
||||||
|
|
||||||
|
Create a local `.env` file next to `compose.yaml`, for example:
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
LOGICC_PORT=18790
|
||||||
|
LOGICC_API_KEY=replace-with-your-own-key
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d --wait
|
||||||
|
```
|
||||||
|
|
||||||
|
Then use `http://127.0.0.1:18790/` and supply the configured Bearer key for `/v1/*`. Both variables are optional; the defaults are port `18789` and no API key requirement. Use another port if a native instance already occupies `18789`. Keep the settings in `.env` so subsequent Compose commands use the same configuration. Compose reads these values through [environment interpolation](https://docs.docker.com/compose/how-tos/environment-variables/variable-interpolation/); the file is ignored by Git and excluded from the image build.
|
||||||
|
|
||||||
|
`LOGICC_PORT` changes the container port and published port together because the server validates the HTTP Host port. When writing a custom `docker run` command, keep the two ports equal and set `PORT` inside the container if changing the default. An API key protects `/v1/*`; it does not add an admin login to the console.
|
||||||
|
|
||||||
|
### Data, logs, and upgrades
|
||||||
|
|
||||||
|
Compose stores `/app/data` in the named volume `logicc2api_logicc-data` (or `<project-name>_logicc-data` when using `-p`). Accounts, request records, and rotated credentials survive container recreation. The image build excludes your local `data/`, `.env`, logs, and backups; an existing native installation is not imported automatically. Add your accounts through the console when starting a fresh container.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Status and logs
|
||||||
|
docker compose ps
|
||||||
|
docker compose logs -f --tail=100 logicc2api
|
||||||
|
|
||||||
|
# Update source and rebuild; retain the same data volume
|
||||||
|
git pull --ff-only
|
||||||
|
docker compose up -d --build --wait
|
||||||
|
|
||||||
|
# Stop and remove containers while keeping account data
|
||||||
|
docker compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
Do not add `--volumes` / `-v` to `docker compose down` unless you intend to delete the account data. Named volume behavior is documented in [Docker's volume guide](https://docs.docker.com/engine/storage/volumes/).
|
||||||
|
|
||||||
|
For deployment on a remote server, access the local-only console through an SSH tunnel from your computer:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ssh -N -L 18789:127.0.0.1:18789 your-user@your-server
|
||||||
|
```
|
||||||
|
|
||||||
|
Then open `http://127.0.0.1:18789/` on your computer. Adjust both port numbers if you configured another port. The existing local-origin checks remain in effect; public-domain hosting requires a separate authentication/access design.
|
||||||
|
|
||||||
|
## Account credentials
|
||||||
|
|
||||||
|
The account form accepts any of the following:
|
||||||
|
|
||||||
|
| Input | Behavior |
|
||||||
|
| --- | --- |
|
||||||
|
| `__client` Cookie + Session ID | Obtain fresh session JWTs on demand |
|
||||||
|
| `__client` Cookie + Session JWT | Read the Session ID from the JWT's `sid` claim, then refresh on demand |
|
||||||
|
| Session JWT only | Use it until it expires; replace it manually or push a new JWT through `/__set_token` |
|
||||||
|
|
||||||
|
For your logged-in account, open browser DevTools → Application → Cookies → `clerk.logicc.com` and copy the **value** of `__client`. A Session ID starts with `sess_`. A Session JWT can be obtained in the Logicc page's console:
|
||||||
|
|
||||||
|
```js
|
||||||
|
await window.Clerk.session.getToken({ skipCache: true })
|
||||||
|
```
|
||||||
|
|
||||||
|
The `__session` cookie contains a short-lived session JWT; it is not the same credential as `__client`. A session can be revoked or signed out, so automatic refresh does not imply permanent access.
|
||||||
|
|
||||||
|
When editing an account, leaving a credential field blank preserves its saved value. Changing the client cookie or Session ID clears the cached JWT. Disabling or removing an account affects the local pool; it does not delete the upstream account.
|
||||||
|
|
||||||
|
### Bulk import
|
||||||
|
|
||||||
|
Paste a JSON array or upload a JSON file in **批量导入** (Bulk import):
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"name": "Work account",
|
||||||
|
"clientCookie": "YOUR_CLIENT_COOKIE",
|
||||||
|
"sessionId": "sess_YOUR_SESSION_ID",
|
||||||
|
"enabled": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
`{ "accounts": [...] }` is also accepted. JWT-only entries use `name` and `token`. The pool holds up to 200 accounts. Duplicate Session IDs are rejected, and the whole batch is validated before any account is added.
|
||||||
|
|
||||||
|
## API usage
|
||||||
|
|
||||||
|
### List models
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://127.0.0.1:18789/v1/models \
|
||||||
|
-H 'Authorization: Bearer local'
|
||||||
|
```
|
||||||
|
|
||||||
|
Available models are read from the selected upstream account rather than hardcoded.
|
||||||
|
|
||||||
|
### Generate a response
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://127.0.0.1:18789/v1/chat/completions \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-H 'Authorization: Bearer local' \
|
||||||
|
-d '{
|
||||||
|
"model": "default",
|
||||||
|
"messages": [{"role": "user", "content": "Say hello in one sentence."}]
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### Stream a response
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -N http://127.0.0.1:18789/v1/chat/completions \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-H 'Authorization: Bearer local' \
|
||||||
|
-d '{
|
||||||
|
"model": "default",
|
||||||
|
"stream": true,
|
||||||
|
"stream_options": {"include_usage": true},
|
||||||
|
"messages": [{"role": "user", "content": "Say hello in one sentence."}]
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
Omitting `model`, or using `default`, selects the upstream default model (or the first available model). Streaming responses use `chat.completion.chunk` and end with `[DONE]`. Set `stream: false`, or omit it, for a complete JSON response.
|
||||||
|
|
||||||
|
Upstream token usage is converted when available. When it is absent, API responses use zero counters for compatibility; the console marks usage as unavailable rather than estimating it.
|
||||||
|
|
||||||
|
### Tool mapping and compatibility limits
|
||||||
|
|
||||||
|
- `reasoning_effort` is forwarded to the upstream API.
|
||||||
|
- Function names `web_search` / `web-search` map to the upstream `web-search` tool; `image_generation` / `image-generation` map to `image-generation`. These invoke upstream built-in tools when available for the account/model.
|
||||||
|
- Other function definitions are added to the prompt as a JSON Schema convention. **Standard OpenAI `tool_calls` execution is not implemented.** Upstream tool events appear as text markers such as `[tool:web-search]`.
|
||||||
|
- Each request creates a new upstream chat. Conversation messages are combined into one prompt; native upstream multi-turn state is not preserved.
|
||||||
|
- Attachments are not forwarded. Image-tool output is displayed as text in the playground.
|
||||||
|
- This adapter implements `/v1/models` and `/v1/chat/completions`; it does not implement the entire OpenAI API.
|
||||||
|
|
||||||
|
## Scheduling and refresh behavior
|
||||||
|
|
||||||
|
- Enabled, eligible accounts with the fewest in-flight requests are preferred. Ties use round-robin selection, and one account handles the entire chat request.
|
||||||
|
- HTTP 429 triggers a 60-second cooldown; 401/403 trigger five minutes; upstream server errors trigger 15 seconds. Later requests skip cooling accounts.
|
||||||
|
- An eligible account can participate again when its cooldown ends. Checking or updating an account also allows recovery. A failed request is not replayed on a different account.
|
||||||
|
- A JWT with fewer than ten seconds remaining is refreshed on demand. An upstream 401 triggers a forced refresh and one retry.
|
||||||
|
- Concurrent refreshes for the same account share one operation. New `__client` values returned by Clerk are persisted.
|
||||||
|
- Clerk refresh uses `POST /v1/client/sessions/{sid}/tokens`.
|
||||||
|
|
||||||
|
## Configuration and data
|
||||||
|
|
||||||
|
| Environment variable | Purpose |
|
||||||
|
| --- | --- |
|
||||||
|
| `PORT` | Listening port; default `18789` |
|
||||||
|
| `LOGICC_HOST` | Bind address; native default `127.0.0.1`, container default `0.0.0.0` |
|
||||||
|
| `LOGICC_DATA_FILE` | State path; default `data/state.json` in the project directory |
|
||||||
|
| `LOGICC_API_KEY` | Optional Bearer key required for `/v1/*` |
|
||||||
|
| `LOGICC_API_BASE` | Upstream base URL; default `https://app.logicc.com/api` |
|
||||||
|
| `LOGICC_CLERK_BASE` | Clerk base URL; default `https://clerk.logicc.com` |
|
||||||
|
| `LOGICC_CLIENT_COOKIE` | Import a default account into an empty pool |
|
||||||
|
| `LOGICC_SESSION_ID` | Session ID for the environment-imported account; alternatively read from a JWT |
|
||||||
|
| `LOGICC_TOKEN` | Initial JWT for the environment-imported account |
|
||||||
|
| `LOGICC_TOKEN_FILE` | External JWT file for the environment-imported account |
|
||||||
|
| `LOGICC_TOKEN_CMD` | External JWT refresh command for that account; configured only through the process environment |
|
||||||
|
|
||||||
|
Native Node.js startup does not load `.env` files automatically. Export variables in your shell or, on a compatible Node.js version, start with `node --env-file=.env server.mjs`. Docker Compose reads `.env` for the `LOGICC_PORT` and `LOGICC_API_KEY` mappings above; `LOGICC_PORT` is a Compose setting, not a native server setting. Other environment variables must be explicitly added to the Compose service if needed.
|
||||||
|
|
||||||
|
Existing saved accounts take precedence over initial environment credentials, so old environment values do not overwrite rotated cookies. If you use an external refresh command or token file, keep providing its configuration when starting the service.
|
||||||
|
|
||||||
|
`data/state.json` contains credentials, the cached model catalog, cooldowns, and at most 2,000 recent request metadata records. Writes use a temporary file plus rename, with a requested file mode of `0600`. The file is **plaintext**, and filesystem permission enforcement depends on the platform. Runtime data, environment files, logs, backups, and browser test artifacts are excluded from Git.
|
||||||
|
|
||||||
|
The dashboard summarizes retained chat records from the previous 24 hours. Model discovery and account checks appear in logs but are excluded from chat metrics. The log page displays the latest 200 records. First-text latency includes credential refresh, chat creation, and network time. Prompts and generated answers are not stored in request logs.
|
||||||
|
|
||||||
|
The console is intended for a **single local process**, with no separate admin login. Management requests require the local origin/Host checks and `X-Logicc-Admin: 1`; `LOGICC_API_KEY` protects `/v1/*`, not the console. The compatibility endpoint `POST /__set_token` accepts a raw JWT, optionally with `?account_id=<id>`, and permits the Logicc page origin. JWTs are matched to accounts by Session ID.
|
||||||
|
|
||||||
|
Do not run multiple instances against the same state file. Use separate `LOGICC_DATA_FILE` paths and ports for independent instances.
|
||||||
|
|
||||||
|
## Development and tests
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm test
|
||||||
|
```
|
||||||
|
|
||||||
|
Tests use Node's built-in test runner and a local mock upstream. They cover account CRUD and atomic import, credential masking and file permissions, scheduling and cooldowns, forced refresh and cookie rotation, concurrent refreshes, JSON/SSE conversion, tool forwarding, usage and failure statistics, origin restrictions, and malformed input. They do not need real credentials or consume upstream quota.
|
||||||
|
|
||||||
|
```text
|
||||||
|
server.mjs HTTP routes, upstream requests, and protocol conversion
|
||||||
|
pool.mjs Account storage, credential refresh, scheduling, and metrics
|
||||||
|
public/ Web console, served without a build step
|
||||||
|
test/adapter.test.mjs Integration and protocol checks
|
||||||
|
Dockerfile Non-root container image and service health check
|
||||||
|
compose.yaml Local port mapping and persistent account data
|
||||||
|
```
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
[MIT](LICENSE) © 2026 JamesZhaoY.
|
||||||
@@ -0,0 +1,253 @@
|
|||||||
|
# logicc2api
|
||||||
|
|
||||||
|
[English](README.md) · **简体中文**
|
||||||
|
|
||||||
|
> **免责声明:** 使用前请阅读[《免责声明与使用责任说明》](DISCLAIMER.md),了解账户授权、第三方服务风险、数据处理及责任限制。软件许可继续适用 [MIT License](LICENSE)。
|
||||||
|
|
||||||
|
为 [Logicc](https://app.logicc.com) 提供 OpenAI 兼容接口的本地代理,内置号池管理和 Web 控制台。将 Logicc 的 AI SDK v6 数据流转换成 OpenAI Chat Completions 响应,集中查看账户状态、流量、模型延迟和请求日志。
|
||||||
|
|
||||||
|
使用 Node.js 与原生 HTML/CSS/JavaScript 实现。**零运行时依赖,无需数据库,无需前端构建。** 当前页面为简体中文,同时提供中英文介绍文档。
|
||||||
|
|
||||||
|
## 功能
|
||||||
|
|
||||||
|
| 模块 | 功能说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| OpenAI 兼容接口 | 模型列表、流式及非流式 Chat Completions |
|
||||||
|
| 号池管理 | 账户增删改、启停、搜索、JSON 批量导入 |
|
||||||
|
| 凭据刷新 | 按需刷新 Clerk JWT、合并同账户的并发刷新、保存轮换后的 Cookie |
|
||||||
|
| 账户调度 | 最低并发优先,同等并发轮询,异常账户自动冷却 |
|
||||||
|
| 运行看板 | 请求趋势、成功率、首字延迟和账户可用性 |
|
||||||
|
| 模型与日志 | 实时同步模型、统计实际延迟、查看请求详情、筛选和导出 CSV |
|
||||||
|
| 请求测试 | 发送真实流式请求、选择上游内置工具、停止本地请求 |
|
||||||
|
| 本地存储 | 重启后保留配置和请求元数据,管理接口不返回原始凭据 |
|
||||||
|
|
||||||
|
页面每 5 秒读取本地状态;自动刷新不会调用上游。账号检测和模型同步仅获取模型列表;请求测试会生成内容并消耗上游额度。
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
需要 **Node.js 22 或更新版本**,以及可使用的 Logicc 账户与会话。如果不想在宿主机安装 Node.js,可使用下方的 [Docker 部署](#docker-部署)。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/JamesZhaoY/logicc2api.git
|
||||||
|
cd logicc2api
|
||||||
|
npm start
|
||||||
|
```
|
||||||
|
|
||||||
|
无需安装依赖,也可以直接执行 `node server.mjs`。
|
||||||
|
|
||||||
|
1. 打开 **<http://127.0.0.1:18789/>**。
|
||||||
|
2. 进入 **号池管理 → 添加账户**,填写凭据后点击 **检测**。
|
||||||
|
3. 在客户端中设置 Base URL 为 **`http://127.0.0.1:18789/v1`**。未配置 `LOGICC_API_KEY` 时,API Key 填任意非空字符串,例如 `local`。
|
||||||
|
|
||||||
|
自定义端口:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node server.mjs 18790
|
||||||
|
```
|
||||||
|
|
||||||
|
直接使用 Node.js 启动时默认监听 `127.0.0.1`,命令行端口优先于环境变量 `PORT`。
|
||||||
|
|
||||||
|
## Docker 部署
|
||||||
|
|
||||||
|
需要安装带 Compose 插件的 Docker Engine,或 Docker Desktop。仓库已提供 [Dockerfile](Dockerfile) 和 [compose.yaml](compose.yaml),镜像从源码在本机构建。
|
||||||
|
|
||||||
|
### 使用 Docker Compose 启动
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone https://github.com/JamesZhaoY/logicc2api.git
|
||||||
|
cd logicc2api
|
||||||
|
docker compose up -d --build --wait
|
||||||
|
```
|
||||||
|
|
||||||
|
如果已经克隆仓库,在项目根目录执行最后一条命令即可。启动后打开 **<http://127.0.0.1:18789/>**,在号池中添加账户,客户端 Base URL 填 **`http://127.0.0.1:18789/v1`**。
|
||||||
|
|
||||||
|
镜像基于 Node.js 24 Alpine,使用非 root 的 `node` 用户运行。容器内设置 `LOGICC_HOST=0.0.0.0`,使 Docker 端口转发可以连接服务;Compose 只把端口发布到宿主机的 `127.0.0.1`。镜像通过 `/health` 检查服务是否存活;容器显示 healthy 不代表上游账户已经通过连接检测。
|
||||||
|
|
||||||
|
### 修改端口或设置 API Key
|
||||||
|
|
||||||
|
在 `compose.yaml` 同级创建本地 `.env` 文件,例如:
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
LOGICC_PORT=18790
|
||||||
|
LOGICC_API_KEY=replace-with-your-own-key
|
||||||
|
```
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose up -d --wait
|
||||||
|
```
|
||||||
|
|
||||||
|
之后访问 `http://127.0.0.1:18790/`,调用 `/v1/*` 时携带配置的 Bearer Key。两个变量均可省略,默认端口为 `18789`、不要求 API Key。如果本机原有 Node.js 服务已占用 `18789`,请选择其他端口。把配置保存在 `.env` 中,可以保证后续 Compose 命令使用同一组设置。Compose 通过[环境变量插值](https://docs.docker.com/compose/how-tos/environment-variables/variable-interpolation/)读取配置;该文件被 Git 忽略,也不会进入镜像构建。
|
||||||
|
|
||||||
|
由于服务会校验 HTTP Host 中的端口,`LOGICC_PORT` 会同步调整容器内和宿主机端口。自行编写 `docker run` 命令时,也应保持两侧端口一致;修改默认端口时需设置容器内的 `PORT`。API Key 仅保护 `/v1/*`,不会为控制台增加管理员登录。
|
||||||
|
|
||||||
|
### 数据、日志与更新
|
||||||
|
|
||||||
|
Compose 将 `/app/data` 保存到命名卷 `logicc2api_logicc-data`;使用 `-p` 自定义项目名时,卷名为 `<项目名>_logicc-data`。容器重建后,账户、请求记录和轮换后的凭据仍会保留。镜像构建会排除本地 `data/`、`.env`、日志和备份,不会自动导入原有 Node.js 实例的数据;新容器请通过控制台添加账户。
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 查看状态和日志
|
||||||
|
docker compose ps
|
||||||
|
docker compose logs -f --tail=100 logicc2api
|
||||||
|
|
||||||
|
# 更新源码并重建,继续使用原有数据卷
|
||||||
|
git pull --ff-only
|
||||||
|
docker compose up -d --build --wait
|
||||||
|
|
||||||
|
# 停止并移除容器,保留号池数据
|
||||||
|
docker compose down
|
||||||
|
```
|
||||||
|
|
||||||
|
只有确定要删除号池数据时,才给 `docker compose down` 添加 `--volumes` / `-v`。命名卷行为可参考 [Docker 数据卷文档](https://docs.docker.com/engine/storage/volumes/)。
|
||||||
|
|
||||||
|
部署在远程服务器时,可在自己的电脑上通过 SSH 隧道访问仅限本机的控制台:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
ssh -N -L 18789:127.0.0.1:18789 your-user@your-server
|
||||||
|
```
|
||||||
|
|
||||||
|
然后在电脑上打开 `http://127.0.0.1:18789/`。如果修改了端口,请同步调整两处端口号。现有本机来源检查仍然生效;公网域名访问需要另行设计身份认证和访问控制。
|
||||||
|
|
||||||
|
## 账户凭据
|
||||||
|
|
||||||
|
添加账户时支持以下任一种组合:
|
||||||
|
|
||||||
|
| 输入 | 行为 |
|
||||||
|
| --- | --- |
|
||||||
|
| `__client` Cookie + Session ID | 按需获取新的 Session JWT |
|
||||||
|
| `__client` Cookie + Session JWT | 从 JWT 的 `sid` 中读取 Session ID,再按需刷新 |
|
||||||
|
| 仅 Session JWT | 有效期内可用;到期后手动替换,或通过 `/__set_token` 推送新 JWT |
|
||||||
|
|
||||||
|
在已登录 Logicc 的浏览器中,打开开发者工具 → Application → Cookies → `clerk.logicc.com`,复制 `__client` 的 **Value**。Session ID 以 `sess_` 开头。也可在 Logicc 页面的 Console 获取 Session JWT:
|
||||||
|
|
||||||
|
```js
|
||||||
|
await window.Clerk.session.getToken({ skipCache: true })
|
||||||
|
```
|
||||||
|
|
||||||
|
`__session` Cookie 保存的是短期 Session JWT,与 `__client` 不是同一种凭据。会话被注销、撤销等情况仍需更新凭据,自动刷新不代表永久有效。
|
||||||
|
|
||||||
|
编辑时留空的凭据字段会保留已有值。更换客户端 Cookie 或 Session ID 会清除旧 JWT 缓存。启停和移除仅作用于本地号池,不会删除上游账户。
|
||||||
|
|
||||||
|
### 批量导入
|
||||||
|
|
||||||
|
在 **批量导入** 中粘贴 JSON 数组或上传 JSON 文件:
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"name": "工作账户",
|
||||||
|
"clientCookie": "YOUR_CLIENT_COOKIE",
|
||||||
|
"sessionId": "sess_YOUR_SESSION_ID",
|
||||||
|
"enabled": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
也支持 `{ "accounts": [...] }`。仅使用 JWT 时,每项填写 `name` 和 `token`。号池最多 200 个账户,相同 Session ID 不重复导入;整批校验通过后保存,校验失败不会部分写入。
|
||||||
|
|
||||||
|
## API 调用
|
||||||
|
|
||||||
|
### 获取模型列表
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://127.0.0.1:18789/v1/models \
|
||||||
|
-H 'Authorization: Bearer local'
|
||||||
|
```
|
||||||
|
|
||||||
|
模型列表从选中的上游账户获取,不在代码中固定。
|
||||||
|
|
||||||
|
### 非流式响应
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl http://127.0.0.1:18789/v1/chat/completions \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-H 'Authorization: Bearer local' \
|
||||||
|
-d '{
|
||||||
|
"model": "default",
|
||||||
|
"messages": [{"role": "user", "content": "用一句话打个招呼。"}]
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### 流式响应
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl -N http://127.0.0.1:18789/v1/chat/completions \
|
||||||
|
-H 'Content-Type: application/json' \
|
||||||
|
-H 'Authorization: Bearer local' \
|
||||||
|
-d '{
|
||||||
|
"model": "default",
|
||||||
|
"stream": true,
|
||||||
|
"stream_options": {"include_usage": true},
|
||||||
|
"messages": [{"role": "user", "content": "用一句话打个招呼。"}]
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
`model` 省略或为 `default` 时,选择上游默认模型,没有默认项则使用第一个模型。流式返回 `chat.completion.chunk`,以 `[DONE]` 结束;省略 `stream` 或设为 `false` 则返回完整 JSON。
|
||||||
|
|
||||||
|
上游提供 token 用量时会转换返回;未提供时,API 兼容响应的计数填零,控制台明确显示用量不可用,不估算用量。
|
||||||
|
|
||||||
|
### 工具映射与兼容范围
|
||||||
|
|
||||||
|
- `reasoning_effort` 透传给上游。
|
||||||
|
- 函数名 `web_search` / `web-search` 映射到上游内置工具 `web-search`;`image_generation` / `image-generation` 映射到 `image-generation`。实际可用性取决于账户和模型。
|
||||||
|
- 其他函数定义以 JSON Schema 约定加入提示词,**尚未实现标准 OpenAI `tool_calls` 执行协议**。上游工具事件以 `[tool:web-search]` 等文本标记呈现。
|
||||||
|
- 每次请求新建上游聊天,多轮消息合并为单条提示词,不保留上游原生多轮会话状态。
|
||||||
|
- 附件未透传;图片工具输出在测试页面中以文本形式展示。
|
||||||
|
- 实现了 `/v1/models` 和 `/v1/chat/completions`,并非完整 OpenAI API。
|
||||||
|
|
||||||
|
## 调度与刷新行为
|
||||||
|
|
||||||
|
- 从已启用、符合调度条件的账户中,优先选择正在处理请求数最少的账户;同等并发采用轮询。同一次聊天固定使用一个账户。
|
||||||
|
- HTTP 429 冷却 60 秒,401 / 403 冷却 5 分钟,上游服务错误冷却 15 秒。后续请求跳过冷却账户。
|
||||||
|
- 冷却结束后,符合条件的账户可参与下一次请求;也可主动检测或更新账户。失败的单次请求不会跨账户重放。
|
||||||
|
- JWT 剩余寿命少于 10 秒时按需刷新;上游返回 401 时强制刷新并重试一次。
|
||||||
|
- 同一账户的并发刷新会合并;Clerk 返回新 `__client` Cookie 时自动保存。
|
||||||
|
- Clerk 刷新端点为 `POST /v1/client/sessions/{sid}/tokens`。
|
||||||
|
|
||||||
|
## 配置与数据
|
||||||
|
|
||||||
|
| 环境变量 | 用途 |
|
||||||
|
| --- | --- |
|
||||||
|
| `PORT` | 监听端口,默认 `18789` |
|
||||||
|
| `LOGICC_HOST` | 监听地址;Node.js 直接启动默认 `127.0.0.1`,容器内默认 `0.0.0.0` |
|
||||||
|
| `LOGICC_DATA_FILE` | 数据文件路径,默认项目目录下 `data/state.json` |
|
||||||
|
| `LOGICC_API_KEY` | 可选,配置后 `/v1/*` 必须携带对应 Bearer Key |
|
||||||
|
| `LOGICC_API_BASE` | 上游基址,默认 `https://app.logicc.com/api` |
|
||||||
|
| `LOGICC_CLERK_BASE` | Clerk 基址,默认 `https://clerk.logicc.com` |
|
||||||
|
| `LOGICC_CLIENT_COOKIE` | 号池为空时导入默认账户 |
|
||||||
|
| `LOGICC_SESSION_ID` | 环境变量导入账户的 Session ID,也可从 JWT 中读取 |
|
||||||
|
| `LOGICC_TOKEN` | 环境变量导入账户的初始 JWT |
|
||||||
|
| `LOGICC_TOKEN_FILE` | 环境变量导入账户使用的外部 JWT 文件 |
|
||||||
|
| `LOGICC_TOKEN_CMD` | 该账户的外部 JWT 刷新命令,仅从进程环境读取,页面不可配置 |
|
||||||
|
|
||||||
|
直接使用 Node.js 启动时,程序不自动加载 `.env` 文件。请在 shell 中导出环境变量,或在支持的 Node.js 版本中使用 `node --env-file=.env server.mjs` 启动。Docker Compose 会读取 `.env` 并映射上文的 `LOGICC_PORT` 和 `LOGICC_API_KEY`;`LOGICC_PORT` 仅用于 Compose,不是 Node.js 服务直接读取的变量。如需其他环境变量,应显式添加到 Compose 服务配置中。
|
||||||
|
|
||||||
|
已有账户数据优先于初始环境凭据,避免旧环境变量覆盖已轮换的 Cookie。使用外部刷新命令或 JWT 文件的账户,重启时仍需提供相应配置。
|
||||||
|
|
||||||
|
`data/state.json` 保存账户凭据、缓存模型目录、冷却时间及最多 2,000 条请求元数据。采用临时文件写入后重命名,文件请求权限为 `0600`;其中凭据为 **明文**,权限保护效果取决于操作系统。运行数据、环境文件、日志、备份和浏览器测试产物均排除在 Git 之外。
|
||||||
|
|
||||||
|
看板统计保留记录中最近 24 小时的聊天请求。模型同步与账号检测显示在日志中,不计入聊天指标。日志页展示最近 200 条记录。首字延迟包含凭据刷新、建立聊天和网络传输耗时;请求日志不保存提示词与生成的回答。
|
||||||
|
|
||||||
|
控制台面向 **单进程本机使用**,没有单独的管理员登录系统。管理请求需要通过本机来源/Host 检查并带有 `X-Logicc-Admin: 1`;`LOGICC_API_KEY` 仅保护 `/v1/*`。兼容入口 `POST /__set_token` 接收原始 JWT,可附加 `?account_id=<id>`,允许 Logicc 页面来源访问,并按 JWT 的 Session ID 匹配账户。
|
||||||
|
|
||||||
|
不要让多个实例同时写入同一数据文件。独立实例请分别配置端口和 `LOGICC_DATA_FILE`。
|
||||||
|
|
||||||
|
## 开发与验证
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm test
|
||||||
|
```
|
||||||
|
|
||||||
|
使用 Node 内置测试框架和本机模拟上游,覆盖账户增删改与整批导入、凭据脱敏和文件权限、轮询与冷却、强制刷新与 Cookie 轮换、并发刷新合并、JSON/SSE 转换、工具透传、用量与错误统计、来源限制和异常输入。测试无需真实凭据,不消耗上游额度。
|
||||||
|
|
||||||
|
```text
|
||||||
|
server.mjs HTTP 路由、上游调用和协议转换
|
||||||
|
pool.mjs 账户存储、凭据刷新、调度和统计
|
||||||
|
public/ 无需构建的 Web 控制台
|
||||||
|
test/adapter.test.mjs 集成与协议测试
|
||||||
|
Dockerfile 非 root 容器镜像和健康检查
|
||||||
|
compose.yaml 本机端口映射与号池数据持久化
|
||||||
|
```
|
||||||
|
|
||||||
|
## 许可证
|
||||||
|
|
||||||
|
[MIT](LICENSE) © 2026 JamesZhaoY。
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
name: logicc2api
|
||||||
|
|
||||||
|
services:
|
||||||
|
logicc2api:
|
||||||
|
build: .
|
||||||
|
image: logicc2api:local
|
||||||
|
init: true
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
PORT: "${LOGICC_PORT:-18789}"
|
||||||
|
LOGICC_API_KEY: "${LOGICC_API_KEY:-}"
|
||||||
|
ports:
|
||||||
|
# Keep both ports equal because the server validates the Host header port.
|
||||||
|
- "127.0.0.1:${LOGICC_PORT:-18789}:${LOGICC_PORT:-18789}"
|
||||||
|
volumes:
|
||||||
|
- logicc-data:/app/data
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
logicc-data:
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1,93 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<style data-replay-app-styles=""></style>
|
||||||
|
<link rel="icon" type="image/x-icon" sizes="128x128" href="/favicon.ico" />
|
||||||
|
<link rel="apple-touch-icon" href="/apple-touch-icon.png" />
|
||||||
|
<link rel="manifest" href="/manifest.webmanifest" />
|
||||||
|
<meta
|
||||||
|
name="viewport"
|
||||||
|
content="width=device-width, initial-scale=1.0, viewport-fit=cover, interactive-widget=resizes-content"
|
||||||
|
/>
|
||||||
|
<meta name="color-scheme" content="light dark" />
|
||||||
|
<meta name="theme-color" content="#ffffff" />
|
||||||
|
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||||
|
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
|
||||||
|
<meta name="apple-mobile-web-app-title" content="Logicc" />
|
||||||
|
<meta name="description" content="Logicc platform for using LLMs" />
|
||||||
|
<title>Logicc</title>
|
||||||
|
<script>
|
||||||
|
;(() => {
|
||||||
|
const theme = document.cookie
|
||||||
|
.split(';')
|
||||||
|
.map((part) => part.trim())
|
||||||
|
.find((part) => part.startsWith('theme='))
|
||||||
|
?.slice('theme='.length)
|
||||||
|
const preference = themePreferenceFromCookie(theme)
|
||||||
|
const colorScheme = preference === 'system' ? 'light dark' : preference
|
||||||
|
|
||||||
|
document.documentElement.dataset.theme = preference
|
||||||
|
document.documentElement.style.colorScheme = colorScheme
|
||||||
|
document.querySelector('meta[name="color-scheme"]')?.setAttribute('content', colorScheme)
|
||||||
|
|
||||||
|
function themePreferenceFromCookie(theme) {
|
||||||
|
try {
|
||||||
|
const value = theme ? decodeURIComponent(theme) : 'system'
|
||||||
|
|
||||||
|
return ['light', 'dark', 'system'].includes(value) ? value : 'system'
|
||||||
|
} catch {
|
||||||
|
return 'system'
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})()
|
||||||
|
</script>
|
||||||
|
<script type="module" crossorigin src="/assets/index-B7U_cYvM.js"></script>
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/rolldown-runtime-hePW80VL.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/runtime-config-CJnnGQ74.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/routing-lLhVIQGT.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/react-vendor-D-TB5cQ4.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/auth-vendor-CEJ-YKG6.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/common-BtBGZBqa.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/errors-CoomhO-H.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/instrumentation-qBd5fRAt.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/router-query-vendor-W4Ul0azN.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/floating-ui-vendor-CoYIENW2.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/ui-i18n-vendor-C0_uJjaz.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/organizations-Bz38DqXd.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/use-backend-client-BMxX6z3G.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/users-BEbTi5Fn.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/clerk-config-BfWMmGLg.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/blocks-BHa7WPWG.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/chevron-down-BMQ8Lgm3.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/chevron-right-DI74p8Ds.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/plus-CjpO3L00.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/x-9Br-gtnB.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/app-icons-zS04Yl7E.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/bundle-mjs-BCZgiF-g.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/button-r8bdE7LE.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/dropdown-menu-DHnKE6JX.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/toast-CIMRyI3i.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/loading-skeleton-Djdt7pSc.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/brand-icons-yw3iEAU9.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/control-styles-CuzqHx5_.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/checkbox-Biu6GESp.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/input-D_KHk4j9.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/settings-permissions-CkWhlgKX.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/assistant-icons-BAs_Ss69.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/use-chat-access-BtE_Ircb.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/middleware-DwWjLaW1.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/input-limits-CoHORidU.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/dialog-BTL9ZA9t.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/confirmation-dialog-uSUCgV-l.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/use-debounce-IbTK28v9.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/user-group-search-C2RwoXuV.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/explore-plans-icons-MCT8N59E.js">
|
||||||
|
<link rel="modulepreload" crossorigin href="/assets/scroll-area-Svz3RfjI.js">
|
||||||
|
<link rel="stylesheet" crossorigin href="/assets/index-Bya5XM1J.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="root"></div>
|
||||||
|
<script src="/runtime-config.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"name": "logicc2api",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"description": "Local OpenAI-compatible adapter for Logicc with account pool management and a web console.",
|
||||||
|
"license": "MIT",
|
||||||
|
"author": "JamesZhaoY",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://github.com/JamesZhaoY/logicc2api.git"
|
||||||
|
},
|
||||||
|
"homepage": "https://github.com/JamesZhaoY/logicc2api#readme",
|
||||||
|
"bugs": {
|
||||||
|
"url": "https://github.com/JamesZhaoY/logicc2api/issues"
|
||||||
|
},
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"start": "node server.mjs",
|
||||||
|
"test": "node --test test/*.test.mjs"
|
||||||
|
},
|
||||||
|
"engines": { "node": ">=22" }
|
||||||
|
}
|
||||||
@@ -0,0 +1,294 @@
|
|||||||
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import { existsSync, mkdirSync, readFileSync, writeFileSync, renameSync, chmodSync } from 'node:fs';
|
||||||
|
import { dirname } from 'node:path';
|
||||||
|
import { exec } from 'node:child_process';
|
||||||
|
import { promisify } from 'node:util';
|
||||||
|
|
||||||
|
export class HttpError extends Error {
|
||||||
|
constructor(status, message) { super(message); this.status = status; }
|
||||||
|
}
|
||||||
|
|
||||||
|
export function claims(token) {
|
||||||
|
try {
|
||||||
|
const payload = JSON.parse(Buffer.from(token.split('.')[1], 'base64url'));
|
||||||
|
return payload && typeof payload === 'object' && !Array.isArray(payload) ? payload : {};
|
||||||
|
}
|
||||||
|
catch { return {}; }
|
||||||
|
}
|
||||||
|
export const fresh = token => Number(claims(token).exp) > Date.now() / 1000 + 10;
|
||||||
|
export function safeError(error) {
|
||||||
|
return String(error?.message || error).replace(/eyJ[\w-]+\.[\w-]+\.[\w-]+/g, '[凭据已隐藏]').slice(0, 350);
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanSecret(value, field) {
|
||||||
|
if (typeof value !== 'string' || value.length > 20000) throw new HttpError(400, `${field} 格式不正确`);
|
||||||
|
const text = value.trim().replace(/^(['"])(.*)\1$/, '$2').replace(/^__client=/, '');
|
||||||
|
if (text && !/^[\w.~+/=-]+$/.test(text)) throw new HttpError(400, `${field} 请填写凭据值,不要填写完整 Cookie 请求头`);
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class AccountPool {
|
||||||
|
constructor(file, env = process.env) {
|
||||||
|
this.file = file;
|
||||||
|
this.env = env;
|
||||||
|
this.cursor = 0;
|
||||||
|
this.runtime = new Map();
|
||||||
|
this.startedAt = Date.now();
|
||||||
|
this.data = { version: 1, accounts: [], requests: [], models: [], modelsUpdatedAt: null };
|
||||||
|
if (existsSync(file)) {
|
||||||
|
this.data = JSON.parse(readFileSync(file, 'utf8'));
|
||||||
|
if (this.data.version !== 1 || !['accounts', 'requests', 'models'].every(k => Array.isArray(this.data[k]))) {
|
||||||
|
throw new Error('号池数据格式不正确,请检查数据文件;原文件未被覆盖。');
|
||||||
|
}
|
||||||
|
chmodSync(file, 0o600);
|
||||||
|
}
|
||||||
|
if (!this.data.accounts.length && (env.LOGICC_CLIENT_COOKIE || env.LOGICC_TOKEN || env.LOGICC_TOKEN_CMD || env.LOGICC_TOKEN_FILE)) {
|
||||||
|
let token = env.LOGICC_TOKEN || '';
|
||||||
|
try { token ||= readFileSync(env.LOGICC_TOKEN_FILE || '/tmp/logicc-token.txt', 'utf8').trim(); } catch {}
|
||||||
|
this.data.accounts.push({
|
||||||
|
id: randomUUID(), name: '默认账户', enabled: true, legacy: true,
|
||||||
|
clientCookie: env.LOGICC_CLIENT_COOKIE || '', token,
|
||||||
|
sessionId: env.LOGICC_SESSION_ID || claims(token).sid || '',
|
||||||
|
createdAt: Date.now(), updatedAt: Date.now(), lastCheckedAt: null, lastError: null,
|
||||||
|
});
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
save() {
|
||||||
|
mkdirSync(dirname(this.file), { recursive: true, mode: 0o700 });
|
||||||
|
const temp = `${this.file}.tmp`;
|
||||||
|
writeFileSync(temp, JSON.stringify(this.data, null, 2), { mode: 0o600 });
|
||||||
|
chmodSync(temp, 0o600);
|
||||||
|
renameSync(temp, this.file);
|
||||||
|
}
|
||||||
|
|
||||||
|
runtimeFor(id) {
|
||||||
|
if (!this.runtime.has(id)) this.runtime.set(id, { inFlight: 0, refresh: null, cooldownUntil: this.data.accounts.find(a => a.id === id)?.cooldownUntil || 0 });
|
||||||
|
return this.runtime.get(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
account(id) {
|
||||||
|
const account = this.data.accounts.find(a => a.id === id);
|
||||||
|
if (!account) throw new HttpError(404, '账户不存在');
|
||||||
|
return account;
|
||||||
|
}
|
||||||
|
|
||||||
|
status(account) {
|
||||||
|
if (!account.enabled) return 'disabled';
|
||||||
|
if (this.runtimeFor(account.id).cooldownUntil > Date.now()) return 'cooling';
|
||||||
|
if (!fresh(account.token) && !account.clientCookie && !(account.legacy && this.env.LOGICC_TOKEN_CMD)) return 'expired';
|
||||||
|
if (account.lastError) return 'retry';
|
||||||
|
return account.lastCheckedAt ? 'ready' : 'pending';
|
||||||
|
}
|
||||||
|
|
||||||
|
publicAccount(account) {
|
||||||
|
const runtime = this.runtimeFor(account.id);
|
||||||
|
const records = this.data.requests.filter(r => r.accountId === account.id && r.kind === 'chat');
|
||||||
|
const success = records.filter(r => r.status === 'success');
|
||||||
|
return {
|
||||||
|
id: account.id, name: account.name, enabled: account.enabled, sessionId: account.sessionId,
|
||||||
|
hasClientCookie: Boolean(account.clientCookie), hasToken: Boolean(account.token),
|
||||||
|
tokenExpiresAt: claims(account.token).exp ? claims(account.token).exp * 1000 : null,
|
||||||
|
createdAt: account.createdAt, updatedAt: account.updatedAt,
|
||||||
|
lastCheckedAt: account.lastCheckedAt, lastError: account.lastError,
|
||||||
|
status: this.status(account), inFlight: runtime.inFlight, cooldownUntil: runtime.cooldownUntil,
|
||||||
|
requests: records.length, successRate: records.length ? success.length / records.length * 100 : null,
|
||||||
|
avgLatency: success.length ? success.reduce((s, r) => s + r.durationMs, 0) / success.length : null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
normalize(input, existing) {
|
||||||
|
if (!input || typeof input !== 'object' || Array.isArray(input)) throw new HttpError(400, '账户必须是 JSON 对象');
|
||||||
|
const account = existing ? { ...existing } : {
|
||||||
|
id: randomUUID(), name: '', enabled: true, clientCookie: '', token: '', sessionId: '',
|
||||||
|
createdAt: Date.now(), lastCheckedAt: null, lastError: null,
|
||||||
|
};
|
||||||
|
if ('name' in input) {
|
||||||
|
if (typeof input.name !== 'string' || !input.name.trim() || input.name.trim().length > 80) throw new HttpError(400, '账户名称需要 1–80 个字符');
|
||||||
|
account.name = input.name.trim();
|
||||||
|
}
|
||||||
|
if (!account.name) throw new HttpError(400, '请填写账户名称');
|
||||||
|
if ('enabled' in input) {
|
||||||
|
if (typeof input.enabled !== 'boolean') throw new HttpError(400, 'enabled 必须为布尔值');
|
||||||
|
account.enabled = input.enabled;
|
||||||
|
}
|
||||||
|
for (const field of ['clientCookie', 'token']) {
|
||||||
|
if (field in input) {
|
||||||
|
const secret = cleanSecret(input[field], field);
|
||||||
|
if (secret) { account[field] = secret; account.lastError = null; account.lastCheckedAt = null; }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (input.token) {
|
||||||
|
const decoded = claims(account.token);
|
||||||
|
if (typeof decoded.sid !== 'string' || !/^sess_[a-zA-Z0-9_-]{1,150}$/.test(decoded.sid) || !Number.isFinite(decoded.exp) || account.token.split('.').length !== 3) throw new HttpError(400, 'Session JWT 需要包含有效的 sid 和 exp');
|
||||||
|
if (input.sessionId && input.sessionId !== decoded.sid) throw new HttpError(400, 'Session ID 与 JWT 中的 sid 不一致');
|
||||||
|
account.sessionId = decoded.sid;
|
||||||
|
}
|
||||||
|
if ('sessionId' in input && input.sessionId !== '') {
|
||||||
|
if (typeof input.sessionId !== 'string' || !/^sess_[a-zA-Z0-9_-]{1,150}$/.test(input.sessionId)) throw new HttpError(400, 'Session ID 应以 sess_ 开头');
|
||||||
|
account.sessionId = input.sessionId;
|
||||||
|
}
|
||||||
|
if (existing && !input.token && (account.sessionId !== existing.sessionId || account.clientCookie !== existing.clientCookie)) {
|
||||||
|
account.token = '';
|
||||||
|
account.lastError = null;
|
||||||
|
account.lastCheckedAt = null;
|
||||||
|
}
|
||||||
|
if (!account.clientCookie && !account.token && !(account.legacy && this.env.LOGICC_TOKEN_CMD)) throw new HttpError(400, '请填写 __client Cookie 或 Session JWT');
|
||||||
|
if (account.clientCookie && !account.sessionId) throw new HttpError(400, '__client Cookie 需要同时填写 Session ID 或含 sid 的 Session JWT');
|
||||||
|
account.updatedAt = Date.now();
|
||||||
|
return account;
|
||||||
|
}
|
||||||
|
|
||||||
|
addMany(inputs) {
|
||||||
|
if (!Array.isArray(inputs) || !inputs.length || inputs.length > 200 || this.data.accounts.length + inputs.length > 200) throw new HttpError(400, '号池最多 200 个账户,请导入非空数组');
|
||||||
|
const accounts = inputs.map(input => this.normalize(input));
|
||||||
|
const seen = new Set(this.data.accounts.map(a => a.sessionId).filter(Boolean));
|
||||||
|
for (const account of accounts) {
|
||||||
|
if (account.sessionId && seen.has(account.sessionId)) throw new HttpError(409, `账户「${account.name}」的 Session 已存在,整批未导入`);
|
||||||
|
if (account.sessionId) seen.add(account.sessionId);
|
||||||
|
}
|
||||||
|
this.data.accounts.push(...accounts);
|
||||||
|
this.save();
|
||||||
|
return accounts.map(a => this.publicAccount(a));
|
||||||
|
}
|
||||||
|
|
||||||
|
update(id, input) {
|
||||||
|
const current = this.account(id);
|
||||||
|
if (this.runtimeFor(id).inFlight || this.runtimeFor(id).refresh) throw new HttpError(409, '账户正在处理请求,请完成后再修改');
|
||||||
|
const updated = this.normalize(input, current);
|
||||||
|
if (this.data.accounts.some(a => a.id !== id && a.sessionId && a.sessionId === updated.sessionId)) throw new HttpError(409, '此 Session 已在号池中');
|
||||||
|
Object.assign(current, updated);
|
||||||
|
this.runtimeFor(id).cooldownUntil = 0;
|
||||||
|
current.cooldownUntil = 0;
|
||||||
|
this.save();
|
||||||
|
return this.publicAccount(current);
|
||||||
|
}
|
||||||
|
|
||||||
|
remove(id) {
|
||||||
|
const account = this.account(id);
|
||||||
|
const runtime = this.runtimeFor(id);
|
||||||
|
if (runtime.inFlight || runtime.refresh) throw new HttpError(409, '账户正在处理请求,请完成后再删除');
|
||||||
|
this.data.accounts.splice(this.data.accounts.indexOf(account), 1);
|
||||||
|
this.runtime.delete(id);
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
acquire() {
|
||||||
|
const candidates = this.data.accounts.filter(a => a.enabled && this.runtimeFor(a.id).cooldownUntil <= Date.now() &&
|
||||||
|
(fresh(a.token) || (a.clientCookie && a.sessionId) || (a.legacy && (this.env.LOGICC_TOKEN_FILE || this.env.LOGICC_TOKEN_CMD))));
|
||||||
|
if (!candidates.length) throw new HttpError(503, '没有可用账户,请在控制台添加、启用或检测账户');
|
||||||
|
// ponytail: 单进程内按最低并发数轮询;多实例部署时再使用共享调度器。
|
||||||
|
const min = Math.min(...candidates.map(a => this.runtimeFor(a.id).inFlight));
|
||||||
|
const available = candidates.filter(a => this.runtimeFor(a.id).inFlight === min);
|
||||||
|
const account = available[this.cursor++ % available.length];
|
||||||
|
this.runtimeFor(account.id).inFlight++;
|
||||||
|
return account;
|
||||||
|
}
|
||||||
|
|
||||||
|
release(account) { this.runtimeFor(account.id).inFlight = Math.max(0, this.runtimeFor(account.id).inFlight - 1); }
|
||||||
|
|
||||||
|
async tokenFor(account, force = false) {
|
||||||
|
if (!force && fresh(account.token)) return account.token;
|
||||||
|
const runtime = this.runtimeFor(account.id);
|
||||||
|
if (runtime.refresh) return runtime.refresh;
|
||||||
|
runtime.refresh = this.refreshToken(account, force);
|
||||||
|
try { return await runtime.refresh; } finally { runtime.refresh = null; }
|
||||||
|
}
|
||||||
|
|
||||||
|
async refreshToken(account, force) {
|
||||||
|
const previous = account.token;
|
||||||
|
if (account.legacy) {
|
||||||
|
try {
|
||||||
|
const token = readFileSync(this.env.LOGICC_TOKEN_FILE || '/tmp/logicc-token.txt', 'utf8').trim();
|
||||||
|
if (fresh(token) && (!force || token !== previous) && (!account.sessionId || claims(token).sid === account.sessionId)) {
|
||||||
|
account.token = token; this.save(); return token;
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
if (this.env.LOGICC_TOKEN_CMD) {
|
||||||
|
let stdout;
|
||||||
|
try { ({ stdout } = await promisify(exec)(this.env.LOGICC_TOKEN_CMD, { timeout: 15000, maxBuffer: 65536 })); }
|
||||||
|
catch { throw new HttpError(401, '外部 JWT 刷新命令执行失败,请在本机检查命令配置'); }
|
||||||
|
const token = stdout.trim();
|
||||||
|
if (!fresh(token) || (account.sessionId && claims(token).sid !== account.sessionId)) throw new HttpError(401, '刷新命令返回的 JWT 已过期或不属于此账户');
|
||||||
|
account.token = token; this.save(); return token;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!account.clientCookie || !account.sessionId) throw new HttpError(401, 'Session JWT 已过期,请更新 JWT 或配置 __client Cookie 与 Session ID');
|
||||||
|
const base = (this.env.LOGICC_CLERK_BASE || 'https://clerk.logicc.com').replace(/\/+$/, '');
|
||||||
|
const response = await fetch(`${base}/v1/client/sessions/${encodeURIComponent(account.sessionId)}/tokens`, {
|
||||||
|
method: 'POST', headers: { Cookie: `__client=${account.clientCookie}`, Origin: 'https://app.logicc.com' },
|
||||||
|
signal: AbortSignal.timeout(20000), redirect: 'error',
|
||||||
|
});
|
||||||
|
// Clerk 若轮换客户端凭据,保存响应中的新值,重启后仍使用新值。
|
||||||
|
for (const cookie of response.headers.getSetCookie()) {
|
||||||
|
const match = cookie.match(/^__client=([^;]+)/);
|
||||||
|
if (match) { account.clientCookie = cleanSecret(match[1], '__client'); this.save(); }
|
||||||
|
}
|
||||||
|
if (!response.ok) throw new HttpError(response.status, `凭据刷新失败(HTTP ${response.status}),请更新 __client Cookie / Session ID`);
|
||||||
|
const data = await response.json();
|
||||||
|
if (!fresh(data.jwt) || claims(data.jwt).sid !== account.sessionId) throw new HttpError(401, '上游没有返回属于此账户的有效 Session JWT');
|
||||||
|
account.token = data.jwt;
|
||||||
|
this.save();
|
||||||
|
return account.token;
|
||||||
|
}
|
||||||
|
|
||||||
|
healthy(account) {
|
||||||
|
account.lastError = null;
|
||||||
|
account.lastCheckedAt = Date.now();
|
||||||
|
this.runtimeFor(account.id).cooldownUntil = 0;
|
||||||
|
account.cooldownUntil = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
failed(account, error) {
|
||||||
|
account.lastError = safeError(error);
|
||||||
|
account.lastCheckedAt = Date.now();
|
||||||
|
const status = error.status || 502;
|
||||||
|
if ([401, 403, 429].includes(status) || status >= 500) {
|
||||||
|
const cooldown = status === 429 ? 60000 : [401, 403].includes(status) ? 300000 : 15000;
|
||||||
|
this.runtimeFor(account.id).cooldownUntil = Date.now() + cooldown;
|
||||||
|
account.cooldownUntil = this.runtimeFor(account.id).cooldownUntil;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
record(record) {
|
||||||
|
this.data.requests.unshift({ id: randomUUID(), ...record });
|
||||||
|
// ponytail: 本地控制台保留最近 2,000 条元数据,规模扩大后再换 SQLite。
|
||||||
|
this.data.requests.length = Math.min(this.data.requests.length, 2000);
|
||||||
|
this.save();
|
||||||
|
}
|
||||||
|
|
||||||
|
snapshot() {
|
||||||
|
const now = Date.now();
|
||||||
|
const records = this.data.requests.filter(r => r.kind === 'chat' && r.startedAt > now - 86400000);
|
||||||
|
const success = records.filter(r => r.status === 'success');
|
||||||
|
const firstTokens = success.filter(r => r.ttftMs != null);
|
||||||
|
const accounts = this.data.accounts.map(a => this.publicAccount(a));
|
||||||
|
const start = Math.floor(now / 3600000) * 3600000 - 23 * 3600000;
|
||||||
|
const trend = Array.from({ length: 24 }, (_, i) => ({ time: start + i * 3600000, success: 0, error: 0 }));
|
||||||
|
for (const record of records) {
|
||||||
|
const bucket = trend[Math.floor((record.startedAt - start) / 3600000)];
|
||||||
|
if (bucket) bucket[record.status === 'success' ? 'success' : 'error']++;
|
||||||
|
}
|
||||||
|
const modelStats = [...new Set(records.map(r => r.model).filter(Boolean))].map(model => {
|
||||||
|
const requests = records.filter(r => r.model === model);
|
||||||
|
const ok = requests.filter(r => r.status === 'success');
|
||||||
|
const ttfts = ok.filter(r => r.ttftMs != null);
|
||||||
|
return { model, requests: requests.length, successRate: ok.length / requests.length * 100,
|
||||||
|
avgLatency: ok.length ? ok.reduce((sum, r) => sum + r.durationMs, 0) / ok.length : null,
|
||||||
|
avgTtft: ttfts.length ? ttfts.reduce((sum, r) => sum + r.ttftMs, 0) / ttfts.length : null };
|
||||||
|
}).sort((a, b) => b.requests - a.requests);
|
||||||
|
return {
|
||||||
|
startedAt: this.startedAt, now, accounts, trend, modelStats,
|
||||||
|
requests: this.data.requests.slice(0, 200), models: this.data.models, modelsUpdatedAt: this.data.modelsUpdatedAt,
|
||||||
|
stats: { requests: records.length, successes: success.length, failures: records.length - success.length,
|
||||||
|
successRate: records.length ? success.length / records.length * 100 : null,
|
||||||
|
avgTtft: firstTokens.length ? firstTokens.reduce((s, r) => s + r.ttftMs, 0) / firstTokens.length : null,
|
||||||
|
avgLatency: success.length ? success.reduce((s, r) => s + r.durationMs, 0) / success.length : null,
|
||||||
|
active: accounts.reduce((sum, a) => sum + a.inFlight, 0),
|
||||||
|
available: accounts.filter(a => ['ready', 'pending', 'retry'].includes(a.status)).length,
|
||||||
|
retained: this.data.requests.length,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,274 @@
|
|||||||
|
const paths = {
|
||||||
|
overview:'M3 3h7v7H3zm11 0h7v7h-7zM3 14h7v7H3zm11 0h7v7h-7z',
|
||||||
|
accounts:'M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2m20 0v-2a4 4 0 0 0-3-3.87M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8m8-7.87a4 4 0 0 1 0 7.75',
|
||||||
|
models:'m12 2 9 5-9 5-9-5 9-5zm-9 10 9 5 9-5M3 17l9 5 9-5',
|
||||||
|
logs:'M5 3h14v18H5zM8 7h8M8 11h8M8 15h5',
|
||||||
|
play:'m8 4 13 8-13 8V4Z',code:'m8 6-6 6 6 6m8-12 6 6-6 6m-3-15-2 18',
|
||||||
|
refresh:'M20 7a9 9 0 0 0-15-3L2 7m0-5v5h5m-3 10a9 9 0 0 0 15 3l3-3m0 5v-5h-5',
|
||||||
|
plus:'M12 5v14M5 12h14',arrow:'M4 12h16m-6-6 6 6-6 6',
|
||||||
|
clock:'M12 8v5l3 2m7-3a10 10 0 1 1-20 0 10 10 0 0 1 20 0',
|
||||||
|
check:'m5 12 4 4L19 6',chart:'M4 3v17h17M8 15l4-5 4 2 5-7',
|
||||||
|
close:'m6 6 12 12M6 18 18 6',search:'M21 21l-5-5m2-6a8 8 0 1 1-16 0 8 8 0 0 1 16 0',
|
||||||
|
upload:'M12 16V3m-5 5 5-5 5 5M4 15v6h16v-6',download:'M12 3v13m-5-5 5 5 5-5M4 17v4h16v-4',
|
||||||
|
lock:'M6 10h12v11H6zM8 10V6a4 4 0 0 1 8 0v4',
|
||||||
|
copy:'M9 9h12v12H9zM15 9V3H3v12h6',activity:'M2 12h5l3-8 4 16 3-8h5',
|
||||||
|
settings:'M3 7h18M7 3v8M3 17h18m-6-4v8',
|
||||||
|
};
|
||||||
|
const icon = name => `<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="${paths[name] || paths.overview}"/></svg>`;
|
||||||
|
document.querySelectorAll('[data-icon]').forEach(el => el.innerHTML = icon(el.dataset.icon));
|
||||||
|
const $ = selector => document.querySelector(selector);
|
||||||
|
const esc = value => String(value ?? '').replace(/[&<>"']/g, char => ({'&':'&','<':'<','>':'>','"':'"',"'":'''}[char]));
|
||||||
|
const n = value => Number(value || 0).toLocaleString('zh-CN');
|
||||||
|
const duration = value => value == null ? '—' : value < 1000 ? `${Math.round(value)} ms` : `${(value / 1000).toFixed(2)} s`;
|
||||||
|
const percent = value => value == null ? '—' : `${value.toFixed(1)}%`;
|
||||||
|
const time = value => value ? new Date(value).toLocaleTimeString('zh-CN', {hour12:false}) : '尚未检测';
|
||||||
|
const date = value => value ? new Date(value).toLocaleString('zh-CN', {hour12:false}) : '—';
|
||||||
|
const ago = value => !value ? '尚未检测' : Date.now()-value < 60000 ? '刚刚' : Date.now()-value < 3600000 ? `${Math.floor((Date.now()-value)/60000)} 分钟前` : date(value);
|
||||||
|
const shortSid = value => value ? `${value.slice(0,10)}…${value.slice(-4)}` : '外部刷新';
|
||||||
|
const titles = {overview:'代理概览',accounts:'号池管理',models:'模型与性能',logs:'请求日志',playground:'请求测试',connect:'API 接入'};
|
||||||
|
const statuses = {ready:'可用',pending:'未检测',retry:'待重试',cooling:'冷却中',error:'异常',expired:'已过期',disabled:'已停用',success:'成功',cancelled:'已取消'};
|
||||||
|
const badge = (status, title='') => `<span class="badge ${esc(status)}" title="${esc(title)}">${statuses[status] || esc(status)}</span>`;
|
||||||
|
let state, page = location.hash.slice(1) || 'overview', busyCount = 0, loading = false;
|
||||||
|
let accountQuery = '', accountFilter = 'all', logQuery = '', logFilter = 'all', logPage = 0;
|
||||||
|
let deleteId, playController, playStarted;
|
||||||
|
const busyAccounts = new Set();
|
||||||
|
|
||||||
|
async function api(path, { method = 'GET', body } = {}) {
|
||||||
|
const response = await fetch(`/api${path}`, {method, headers:{'X-Logicc-Admin':'1',...(body !== undefined || method === 'POST' ? {'Content-Type':'application/json'} : {})},body:body !== undefined ? JSON.stringify(body) : method === 'POST' ? '{}' : undefined, signal:AbortSignal.timeout(35000)});
|
||||||
|
const result = await response.json();
|
||||||
|
if (!response.ok) throw new Error(result.error?.message || `HTTP ${response.status}`);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
function toast(message, error = false) {
|
||||||
|
const element = document.createElement('div');
|
||||||
|
element.className = `toast${error?' error':''}`;
|
||||||
|
element.textContent = message;
|
||||||
|
$('#toasts').append(element);
|
||||||
|
while ($('#toasts').children.length > 3) $('#toasts').firstElementChild.remove();
|
||||||
|
setTimeout(() => element.remove(), 5000);
|
||||||
|
}
|
||||||
|
function errorAt(id, message) { const el = $(id); el.textContent = message; el.hidden = !message; }
|
||||||
|
async function reload(force = false) {
|
||||||
|
if (loading) return;
|
||||||
|
loading = true;
|
||||||
|
try {
|
||||||
|
state = await api('/state');
|
||||||
|
$('#connection-error').hidden = true;
|
||||||
|
$('#connection-state').innerHTML = '<span class="status-dot"></span>代理运行中';
|
||||||
|
$('#sidebar-status').textContent = '本地服务在线';
|
||||||
|
$('#sidebar-dot').classList.remove('offline');
|
||||||
|
$('#sidebar-address').textContent = new URL(state.service.baseUrl).host;
|
||||||
|
$('#nav-count').textContent = state.accounts.length;
|
||||||
|
$('#last-updated').textContent = `上次同步 ${time(Date.now())}`;
|
||||||
|
if (force || (!busyCount && !$('dialog[open]') && !$('details.menu[open]') && !['INPUT','TEXTAREA','SELECT'].includes(document.activeElement?.tagName))) render();
|
||||||
|
} catch (error) {
|
||||||
|
$('#connection-error').textContent = `连接失败:${error.message}。请确认代理仍在运行;5 秒后自动重试。`;
|
||||||
|
$('#connection-error').hidden = false;
|
||||||
|
$('#connection-state').innerHTML = '<span class="status-dot offline"></span>连接已断开';
|
||||||
|
$('#sidebar-status').textContent = '服务连接中断';
|
||||||
|
$('#sidebar-dot').classList.add('offline');
|
||||||
|
if (!state) $('#main').innerHTML = empty('无法连接代理','请检查启动服务的终端,或点击右上角刷新按钮重试。','activity');
|
||||||
|
} finally { loading = false; }
|
||||||
|
}
|
||||||
|
function heading(title, subtitle, actions = '', eyebrow = 'WORKSPACE / LOCAL') {
|
||||||
|
return `<div class="page-heading"><div><div class="eyebrow">${eyebrow}</div><h1>${title}</h1><p>${subtitle}</p></div><div class="heading-actions">${actions}</div></div>`;
|
||||||
|
}
|
||||||
|
const addButton = `<button class="button primary" data-action="add">${icon('plus')}添加账户</button>`;
|
||||||
|
const importButton = `<button class="button secondary" data-action="import">${icon('upload')}批量导入</button>`;
|
||||||
|
const empty = (title, description, symbol = 'accounts', action = '') => `<div class="empty-state">${icon(symbol)}<h3>${title}</h3><p>${description}</p>${action}</div>`;
|
||||||
|
function metric(label,value,foot,symbol) { return `<div class="metric"><div class="metric-head">${label}${icon(symbol)}</div><div class="metric-value">${value}</div><div class="metric-foot">${foot}</div></div>`; }
|
||||||
|
function render() {
|
||||||
|
if (!state) return;
|
||||||
|
if (!titles[page]) page = 'overview';
|
||||||
|
$('#breadcrumb-page').textContent = titles[page];
|
||||||
|
document.title = `${titles[page]} · Logicc`;
|
||||||
|
document.querySelectorAll('[data-page]').forEach(link => { link.classList.toggle('active',link.dataset.page === page); if(link.dataset.page === page) link.setAttribute('aria-current','page'); else link.removeAttribute('aria-current'); });
|
||||||
|
if (page === 'playground' && $('#play-form')) return;
|
||||||
|
$('#main').innerHTML = ({overview:overviewPage,accounts:accountsPage,models:modelsPage,logs:logsPage,playground:playgroundPage,connect:connectPage})[page]();
|
||||||
|
}
|
||||||
|
function chart() {
|
||||||
|
const max = Math.max(2, ...state.trend.map(b => b.success+b.error));
|
||||||
|
const plot = {x:30,y:10,w:578,h:120};
|
||||||
|
const grid = [0,.5,1].map(f => `<line class="grid" x1="30" y1="${10+120*f}" x2="618" y2="${10+120*f}"/><text x="0" y="${13+120*f}">${Math.round(max*(1-f))}</text>`).join('');
|
||||||
|
const bars = state.trend.map((bucket,i) => {
|
||||||
|
const x = plot.x+i*24.5;
|
||||||
|
const h = bucket.success/max*120, e=bucket.error/max*120;
|
||||||
|
return `<g><title>${time(bucket.time)} · 成功 ${bucket.success} / 异常 ${bucket.error}</title><rect class="bar" x="${x}" y="${130-h}" width="13" height="${h}" rx="2"/><rect class="bar-error" x="${x}" y="${130-h-e}" width="13" height="${e}" rx="2"/></g>`;
|
||||||
|
}).join('');
|
||||||
|
const labels = [0,4,8,12,16,20,23].map(i=>`<text x="${plot.x+i*24.5}" y="155" text-anchor="middle">${new Date(state.trend[i].time).getHours().toString().padStart(2,'0')}:00</text>`).join('');
|
||||||
|
return `<div class="chart-wrap"><svg class="chart" viewBox="0 0 630 165" preserveAspectRatio="none" role="img" aria-label="过去 24 小时按小时统计的聊天请求:成功 ${state.stats.successes},异常或取消 ${state.stats.failures}">${grid}${bars}<line class="baseline" x1="30" y1="131" x2="618" y2="131"/>${labels}</svg>${!state.stats.requests?'<div class="chart-empty"><strong>等待第一条请求</strong><span>接入客户端后,流量将在这里显示</span></div>':''}</div>`;
|
||||||
|
}
|
||||||
|
function overviewPage() {
|
||||||
|
const s=state.stats, total=state.accounts.length, available=s.available;
|
||||||
|
const trouble=state.accounts.filter(a=>['error','cooling','expired'].includes(a.status)).length;
|
||||||
|
const disabled=state.accounts.filter(a=>a.status==='disabled').length;
|
||||||
|
return heading('让每一次请求,都有迹可循。','账号、模型与流量,在一个地方掌握。',`<a class="button secondary" href="#connect">${icon('code')}接入 API</a>${addButton}`,'LOGICC / PROXY OVERVIEW') +
|
||||||
|
`<section class="metrics" aria-label="过去24小时运行指标">${metric('可调度账户',`${n(available)}<small>/ ${n(total)}</small>`,`<span class="positive">${available?'调度池已就绪':'等待添加账户'}</span>`,'accounts')}${metric('请求总量',n(s.requests),`过去 24 小时 · ${n(s.active)} 个处理中`,'chart')}${metric('请求成功率',percent(s.successRate),`${n(s.successes)} 次成功 · ${n(s.failures)} 次异常 / 取消`,'check')}${metric('平均首字延迟',s.avgTtft == null?'—':`${(s.avgTtft/1000).toFixed(2)}<small>s</small>`,'首次文本输出 · 含代理开销','clock')}</section>
|
||||||
|
<div class="dashboard-grid"><section class="panel"><div class="panel-heading"><div><h2>请求流量</h2><p>流量趋势与请求结果</p></div><div><span class="range-label">近 24 小时</span></div></div>${chart()}<div class="table-footer"><div class="legend"><span><i></i>成功请求</span><span><i class="error"></i>异常 / 取消</span></div><span>按小时汇总 · 本地时间</span></div></section>
|
||||||
|
<section class="panel health-panel"><div class="panel-heading"><div><h2>号池状态</h2><p>当前账户可用性</p></div>${icon('accounts')}</div><div class="health-content"><div class="health-ring"><svg viewBox="0 0 110 110" aria-hidden="true"><circle class="ring-base" cx="55" cy="55" r="46"/><circle class="ring-progress" cx="55" cy="55" r="46" stroke-dasharray="${total?available/total*289:0} 289"/></svg><div class="ring-center"><strong>${total?Math.round(available/total*100):0}<span>%</span></strong><span>可调度</span></div></div><div class="health-list"><div><i class="tiny-square"></i>可调度<b>${available.toString().padStart(2,'0')}</b></div><div><i class="tiny-square warn"></i>待处理<b>${trouble.toString().padStart(2,'0')}</b></div><div><i class="tiny-square off"></i>已停用<b>${disabled.toString().padStart(2,'0')}</b></div></div></div><div class="health-footer">${icon('settings')}低并发优先轮询 · 异常自动冷却</div></section></div>
|
||||||
|
<section class="panel table-panel"><div class="panel-heading"><div><h2>账户池 <span class="subtle-text">/ ${total.toString().padStart(2,'0')}</span></h2><p>集中管理凭据与调度状态</p></div><a class="text-button" href="#accounts">管理全部${icon('arrow')}</a></div>${accountTable(state.accounts.slice(0,4),true)}<div class="table-footer"><span>${icon('lock')}凭据保存在本机,页面仅显示状态</span><span>${total} 个账户</span></div></section>
|
||||||
|
<section class="panel table-panel section-gap"><div class="panel-heading"><div><h2>最近请求</h2><p>查看每次调用的响应与耗时</p></div><a class="text-button" href="#logs">全部日志${icon('arrow')}</a></div>${logTable(state.requests.slice(0,4))}</section>`;
|
||||||
|
}
|
||||||
|
function accountTable(accounts,compact=false) {
|
||||||
|
if (!accounts.length) return empty(state.accounts.length?'没有匹配的账户':'添加你的第一个账户',state.accounts.length?'试试其他名称、Session ID 或状态。':'添加凭据后检测连接,即可通过 OpenAI 兼容接口发送请求。','accounts',state.accounts.length?'':addButton);
|
||||||
|
return `<div class="table-wrap"><table><thead><tr><th>账户</th><th>状态</th><th>认证方式</th><th>请求 / 成功率</th>${compact?'':'<th>上次检测</th>'}<th>操作</th></tr></thead><tbody>${accounts.map((a,i)=>`<tr><td><div class="account-name"><span class="account-avatar">${String(state.accounts.indexOf(a)+1).padStart(2,'0')}</span><div><strong>${esc(a.name)}</strong><small title="${esc(a.sessionId)}">${esc(shortSid(a.sessionId))}</small></div></div></td><td>${badge(a.status,a.lastError || '')}${a.inFlight?`<div class="subtle-text">${a.inFlight} 个处理中</div>`:''}</td><td><span>${a.hasClientCookie?'Client 自动刷新':'Session JWT'}</span>${!compact?`<div class="subtle-text">${a.hasToken&&a.tokenExpiresAt?`JWT ${a.tokenExpiresAt>Date.now()?'有效至 '+time(a.tokenExpiresAt):'待刷新'}`:'按需获取 JWT'}</div>`:''}</td><td><span class="mono">${n(a.requests)}</span><span class="subtle-text"> / ${percent(a.successRate)}</span></td>${compact?'':`<td><span class="subtle-text">${ago(a.lastCheckedAt)}</span>${a.lastError?`<div class="error-text" title="${esc(a.lastError)}">${esc(a.lastError)}</div>`:''}</td>`}<td><div class="row-actions"><button class="text-button" data-action="check" data-id="${a.id}" ${busyAccounts.has(a.id)?'disabled':''}>${busyAccounts.has(a.id)?'检测中…':'检测'}</button><details class="menu"><summary aria-label="${esc(a.name)} 更多操作">⋯</summary><div class="menu-items"><button data-action="edit" data-id="${a.id}">编辑账户</button><button data-action="refresh-token" data-id="${a.id}">刷新凭据</button><button data-action="toggle" data-id="${a.id}">${a.enabled?'暂停调度':'启用账户'}</button><button class="delete" data-action="delete" data-id="${a.id}">移除账户</button></div></details></div></td></tr>`).join('')}</tbody></table></div>`;
|
||||||
|
}
|
||||||
|
function accountsPage() {
|
||||||
|
return heading('号池管理','管理账户凭据,让请求在可用账户间有序分配。',`${importButton}${addButton}`,'WORKSPACE / ACCOUNTS')+
|
||||||
|
`<div class="toolbar"><div class="search-box">${icon('search')}<input id="account-search" aria-label="搜索账户" placeholder="搜索名称或 Session ID…" value="${esc(accountQuery)}"></div><div class="filter-group"><select id="account-filter" aria-label="筛选账户状态">${[['all','全部状态'],['ready','可用'],['pending','未检测'],['cooling','冷却中'],['error','异常 / 过期'],['disabled','已停用']].map(([v,l])=>`<option value="${v}" ${v===accountFilter?'selected':''}>${l}</option>`).join('')}</select><button class="button secondary" data-action="check-all">${icon('activity')}检测全部</button></div></div><section class="panel table-panel"><div id="accounts-table">${filteredAccounts()}</div><div class="table-footer"><span>${icon('settings')}低并发优先轮询 · 凭据错误冷却 5 分钟</span><span>${state.accounts.length} / 200 个账户</span></div></section><p class="security-caption">检测仅获取模型列表,不生成回答。停用账户保留配置;移除账户会删除本地凭据。</p>`;
|
||||||
|
}
|
||||||
|
function filteredAccounts() {
|
||||||
|
const query=accountQuery.toLowerCase();
|
||||||
|
return accountTable(state.accounts.filter(a=>(`${a.name} ${a.sessionId}`.toLowerCase().includes(query)) && (accountFilter==='all' || (accountFilter==='error'?['error','expired'].includes(a.status):a.status===accountFilter))));
|
||||||
|
}
|
||||||
|
function modelsPage() {
|
||||||
|
const maxLatency=Math.max(1,...state.modelStats.map(m=>m.avgTtft || 0));
|
||||||
|
return heading('模型与性能','查看上游可用模型,以及真实调用产生的性能数据。',`<button class="button primary" data-action="sync-models">${icon('refresh')}同步模型</button>`,'WORKSPACE / MODELS')+
|
||||||
|
`<section class="panel table-panel"><div class="panel-heading"><div><h2>模型目录 <span class="subtle-text">/ ${state.models.length.toString().padStart(2,'0')}</span></h2><p>${state.modelsUpdatedAt?'最近同步 '+date(state.modelsUpdatedAt):'连接账户后,从上游同步模型目录'}</p></div><span class="range-label">性能 · 近 24 小时</span></div>${!state.models.length?empty('模型目录尚未同步','先在号池中添加并检测账户,或点击「同步模型」。','models'):`<div class="table-wrap"><table><thead><tr><th>模型 ID</th><th>提供方</th><th>调用次数</th><th>成功率</th><th>平均首字延迟</th><th>平均总耗时</th><th></th></tr></thead><tbody>${state.models.map(m=>{const s=state.modelStats.find(s=>s.model===m.id);return `<tr><td><div class="model-name">${esc(m.id)}</div>${m.name!==m.id?`<div class="subtle-text">${esc(m.name)}</div>`:''}</td><td>${esc(m.provider)}</td><td class="mono">${s?n(s.requests):'0'}</td><td>${percent(s?.successRate)}</td><td><div class="latency-bar"><span class="mono">${duration(s?.avgTtft)}</span>${s?.avgTtft!=null?`<span class="latency-track"><i style="width:${s.avgTtft/maxLatency*100}%"></i></span>`:''}</div></td><td class="mono">${duration(s?.avgLatency)}</td><td><button class="text-button" data-action="try-model" data-model="${esc(m.id)}">测试${icon('arrow')}</button></td></tr>`;}).join('')}</tbody></table></div>`}<div class="table-footer"><span>延迟来自本机代理真实请求,包含刷新、建会话与传输开销</span><span>无调用时显示 —</span></div></section><div class="notice"><strong>能力说明</strong><br>支持流式与非流式文本响应,内置搜索与图片工具可透传。自定义函数采用提示词约定,尚不支持标准 tool_calls;当前多轮消息会合并为单条提示词。</div>`;
|
||||||
|
}
|
||||||
|
const kindLabel = kind => ({chat:'聊天请求',models:'模型列表',check:'账户检测'}[kind] || kind);
|
||||||
|
function logTable(records) {
|
||||||
|
if (!records.length) return empty('暂无请求记录','账号检测、模型同步和客户端调用完成后,记录会显示在这里。','logs');
|
||||||
|
return `<div class="table-wrap"><table><thead><tr><th>时间</th><th>账户 / 请求</th><th>模型</th><th>首字延迟</th><th>总耗时</th><th>结果</th><th></th></tr></thead><tbody>${records.map(r=>`<tr><td><div class="mono">${time(r.startedAt)}</div><div class="subtle-text">${new Date(r.startedAt).toLocaleDateString('zh-CN')}</div></td><td><div>${esc(r.accountName || '未分配账户')}</div><div class="subtle-text">${kindLabel(r.kind)}${r.stream?' · 流式':''}</div></td><td class="model-name">${esc(r.model || '—')}</td><td class="mono">${duration(r.ttftMs)}</td><td class="mono">${duration(r.durationMs)}</td><td>${badge(r.status,r.error || '')}</td><td><button class="row-detail" data-action="log-detail" data-id="${r.id}">详情</button></td></tr>`).join('')}</tbody></table></div>`;
|
||||||
|
}
|
||||||
|
function filteredLogs() {
|
||||||
|
const query=logQuery.toLowerCase();
|
||||||
|
return state.requests.filter(r=>(`${r.model || ''} ${r.accountName || ''} ${r.error || ''} ${kindLabel(r.kind)}`.toLowerCase().includes(query))&&(logFilter==='all'||r.status===logFilter));
|
||||||
|
}
|
||||||
|
function logsContent() {
|
||||||
|
const records=filteredLogs(), pages=Math.max(1,Math.ceil(records.length/15));
|
||||||
|
logPage=Math.min(logPage,pages-1);
|
||||||
|
return `${logTable(records.slice(logPage*15,logPage*15+15))}<div class="table-footer"><span>当前 ${records.length} 条 · 展示最近 200 条</span><div class="pagination"><button data-action="prev-logs" ${!logPage?'disabled':''}>上一页</button><span>${logPage+1} / ${pages}</span><button data-action="next-logs" ${logPage===pages-1?'disabled':''}>下一页</button></div></div>`;
|
||||||
|
}
|
||||||
|
function logsPage() {
|
||||||
|
return heading('请求日志','从一次请求,追溯账户、模型与响应状态。',`<button class="button secondary" data-action="export-logs">${icon('download')}导出当前结果</button>`,'WORKSPACE / REQUEST LOGS')+
|
||||||
|
`<div class="toolbar"><div class="search-box">${icon('search')}<input id="log-search" aria-label="搜索请求日志" placeholder="搜索模型、账户或错误…" value="${esc(logQuery)}"></div><select id="log-filter" aria-label="筛选请求结果">${[['all','全部结果'],['success','成功'],['error','异常'],['cancelled','已取消']].map(([v,l])=>`<option value="${v}" ${v===logFilter?'selected':''}>${l}</option>`).join('')}</select></div><section class="panel table-panel" id="logs-content">${logsContent()}</section><p class="security-caption">仅保存请求元数据,不记录提示词、回答或凭据。数据文件最多保留 2,000 条;指标按保留记录中的近 24 小时计算。</p>`;
|
||||||
|
}
|
||||||
|
function connectPage() {
|
||||||
|
const base=state.service.baseUrl;
|
||||||
|
const model=state.models[0]?.id || 'default';
|
||||||
|
const snippet=`curl ${base}/chat/completions \\\n -H 'Content-Type: application/json' \\\n -H 'Authorization: Bearer ${state.service.apiKeyRequired?'YOUR_API_KEY':'local'}' \\\n -d '${JSON.stringify({model,stream:true,messages:[{role:'user',content:'你好,请简单介绍自己。'}]})}'`;
|
||||||
|
return heading('连接你的客户端','通过 OpenAI 兼容协议,将客户端接入 Logicc 号池。','','DEVELOPER / API ACCESS')+
|
||||||
|
`<div class="integration-grid"><section class="panel integration-panel"><h2>OpenAI 兼容接口</h2><p>在客户端的自定义服务中填写以下 Base URL。</p><div class="copy-field"><code class="mono">${esc(base)}</code><button class="text-button" data-action="copy-url">${icon('copy')}复制</button></div><div class="info-rows"><div><span>API Key</span><b>${state.service.apiKeyRequired?'使用启动时配置的 LOGICC_API_KEY':'任意非空字符串,例如 local'}</b></div><div><span>模型列表</span><b class="mono">GET /v1/models</b></div><div><span>聊天补全</span><b class="mono">POST /v1/chat/completions</b></div></div><div class="section-title"><h2>快速测试</h2><span>cURL / Streaming</span></div><div class="code-block"><button class="code-copy" data-action="copy-code">复制</button><pre id="curl-snippet">${esc(snippet)}</pre></div></section><div><section class="panel integration-panel"><h2>连接信息</h2><div class="info-rows"><div><span>服务范围</span><b>仅本机 · 127.0.0.1</b></div><div><span>上游服务</span><b>app.logicc.com</b></div><div><span>账户调度</span><b>低并发优先轮询</b></div><div><span>速率限制</span><b>429 后冷却 60 秒</b></div><div><span>凭据异常</span><b>401 / 403 后冷却 5 分钟</b></div><div><span>请求记录</span><b>最多 2,000 条</b></div></div></section><div class="notice"><strong>关于凭据刷新</strong><br>__client Cookie + Session ID 可按需获取短期 JWT。客户端凭据失效时,在号池中更新后重新检测即可。<br><br>检测和实际请求会更新账户状态;控制台自动刷新只读取本地数据。</div></div></div>`;
|
||||||
|
}
|
||||||
|
function playgroundPage() {
|
||||||
|
return heading('发起一次真实请求','直接验证号池、模型与流式响应;测试会消耗上游额度。','','WORKSPACE / PLAYGROUND')+
|
||||||
|
`<div class="playground-grid"><form class="panel form-panel" id="play-form"><label>模型<select name="model" required>${state.models.length?state.models.map(m=>`<option value="${esc(m.id)}">${esc(m.id)}</option>`).join(''):'<option value="default">default · 上游默认模型</option>'}</select></label><label>提示词<textarea name="prompt" required placeholder="输入你想发送给模型的消息…">用一句话介绍你自己。</textarea></label>${state.service.apiKeyRequired?'<label>代理 API Key<input type="password" name="apiKey" required autocomplete="off" placeholder="本次请求使用,不保存"></label>':''}<label>内置工具<select name="tool"><option value="">不指定</option><option value="web_search">网页搜索</option><option value="image_generation">图片生成(仅透传)</option></select></label><div class="heading-actions"><button type="submit" class="button primary" id="play-submit">${icon('play')}发送请求</button><button type="button" class="button secondary" data-action="stop-play" id="play-stop" hidden>停止</button></div><p class="field-hint">账户由调度池分配,结果会记录到请求日志。图片工具返回内容以文本形式展示。</p></form><section class="panel output-panel"><div class="panel-heading"><div><h2>模型响应</h2><p>STREAMING RESPONSE</p></div><span class="range-label" id="play-status">等待发送</span></div><pre id="play-output" class="output-placeholder" aria-live="polite">在左侧输入消息,查看实时响应。</pre><div class="output-meta" id="play-meta">连接本地 OpenAI 兼容接口</div></section></div>`;
|
||||||
|
}
|
||||||
|
function openAccount(id) {
|
||||||
|
const form=$('#account-form'); form.reset();
|
||||||
|
errorAt('#account-error','');
|
||||||
|
const account=id?state.accounts.find(a=>a.id===id):null;
|
||||||
|
form.elements.id.value=id || '';
|
||||||
|
form.elements.name.value=account?.name || '';
|
||||||
|
form.elements.sessionId.value=account?.sessionId || '';
|
||||||
|
form.elements.enabled.checked=account?account.enabled:true;
|
||||||
|
form.elements.clientCookie.placeholder=account?.hasClientCookie?'已保存 · 留空保留原凭据':'粘贴 clerk.logicc.com 的 __client 值';
|
||||||
|
form.querySelector('details').open=false;
|
||||||
|
$('#account-dialog-title').textContent=account?'编辑账户':'添加账户';
|
||||||
|
$('#account-dialog').showModal();
|
||||||
|
form.elements.name.focus();
|
||||||
|
}
|
||||||
|
async function checkAccount(id, refresh=false, silent=false) {
|
||||||
|
busyAccounts.add(id);busyCount++;
|
||||||
|
try {
|
||||||
|
const result=await api(`/accounts/${id}/${refresh?'refresh':'check'}`,{method:'POST'});
|
||||||
|
if(!silent)toast(`账户可用 · 已同步 ${result.models} 个模型`);
|
||||||
|
return true;
|
||||||
|
} catch(error) { if(!silent)toast(error.message,true); return false; }
|
||||||
|
finally { busyAccounts.delete(id);busyCount--; }
|
||||||
|
}
|
||||||
|
async function copy(text) { try { await navigator.clipboard.writeText(text);toast('已复制到剪贴板'); } catch {toast('复制失败,请手动选择文本复制',true);} }
|
||||||
|
|
||||||
|
$('#account-form').addEventListener('submit',async event=>{
|
||||||
|
event.preventDefault(); const form=event.currentTarget,button=form.querySelector('[type=submit]');button.disabled=true;errorAt('#account-error','');
|
||||||
|
const values=Object.fromEntries(new FormData(form)); const id=values.id;delete values.id;values.enabled=form.elements.enabled.checked;
|
||||||
|
if (!values.token.trim()) delete values.token;
|
||||||
|
if (!values.clientCookie.trim()) delete values.clientCookie;
|
||||||
|
try {await api(id?`/accounts/${id}`:'/accounts',{method:id?'PATCH':'POST',body:values});form.reset();$('#account-dialog').close();toast(id?'账户已更新':'账户已添加,可以检测连接');await reload(true);}
|
||||||
|
catch(error){errorAt('#account-error',error.message);}finally{button.disabled=false;}
|
||||||
|
});
|
||||||
|
$('#import-file').addEventListener('change',async event=>{
|
||||||
|
const file=event.target.files[0];if(!file)return;
|
||||||
|
if(file.size>1048576){errorAt('#import-error','文件不能超过 1 MB');return;}
|
||||||
|
$('#import-form').elements.accounts.value=await file.text();
|
||||||
|
});
|
||||||
|
$('#import-form').addEventListener('submit',async event=>{
|
||||||
|
event.preventDefault();const form=event.currentTarget,button=form.querySelector('[type=submit]');button.disabled=true;errorAt('#import-error','');
|
||||||
|
try {let body;try{body=JSON.parse(form.elements.accounts.value);}catch{throw new Error('JSON 格式不正确,请检查引号和逗号');}const result=await api('/accounts/import',{method:'POST',body});form.reset();$('#import-dialog').close();toast(`成功导入 ${result.accounts.length} 个账户`);await reload(true);}
|
||||||
|
catch(error){errorAt('#import-error',error.message);}finally{button.disabled=false;}
|
||||||
|
});
|
||||||
|
$('#confirm-form').addEventListener('submit',async event=>{
|
||||||
|
event.preventDefault();const button=event.currentTarget.querySelector('[type=submit]');button.disabled=true;errorAt('#confirm-error','');
|
||||||
|
try{await api(`/accounts/${deleteId}`,{method:'DELETE'});$('#confirm-dialog').close();toast('账户已移除');await reload(true);}catch(error){errorAt('#confirm-error',error.message);}finally{button.disabled=false;}
|
||||||
|
});
|
||||||
|
document.addEventListener('input',event=>{
|
||||||
|
if(event.target.id==='account-search'){accountQuery=event.target.value;$('#accounts-table').innerHTML=filteredAccounts();}
|
||||||
|
if(event.target.id==='log-search'){logQuery=event.target.value;logPage=0;$('#logs-content').innerHTML=logsContent();}
|
||||||
|
});
|
||||||
|
document.addEventListener('change',event=>{
|
||||||
|
if(event.target.id==='account-filter'){accountFilter=event.target.value;$('#accounts-table').innerHTML=filteredAccounts();}
|
||||||
|
if(event.target.id==='log-filter'){logFilter=event.target.value;logPage=0;$('#logs-content').innerHTML=logsContent();}
|
||||||
|
});
|
||||||
|
document.addEventListener('click',async event=>{
|
||||||
|
const close=event.target.closest('[data-close]');if(close){$(`#${close.dataset.close}`).close();return;}
|
||||||
|
const button=event.target.closest('[data-action]');if(!button || button.disabled)return;
|
||||||
|
const {action,id}=button.dataset;
|
||||||
|
button.closest('details')?.removeAttribute('open');
|
||||||
|
try {
|
||||||
|
if(action==='add')return openAccount();
|
||||||
|
if(action==='edit')return openAccount(id);
|
||||||
|
if(action==='import'){errorAt('#import-error','');$('#import-form').reset();return $('#import-dialog').showModal();}
|
||||||
|
if(action==='delete'){deleteId=id;errorAt('#confirm-error','');$('#confirm-message').textContent=`将移除「${state.accounts.find(a=>a.id===id).name}」及其本地凭据。已有请求记录会保留。`;return $('#confirm-dialog').showModal();}
|
||||||
|
if(action==='log-detail'){
|
||||||
|
const r=state.requests.find(r=>r.id===id);
|
||||||
|
$('#request-detail').innerHTML=`<dl class="details-list">${[['请求 ID',r.id],['开始时间',date(r.startedAt)],['请求类型',kindLabel(r.kind)],['账户',r.accountName || '未分配'],['模型',r.model || '—'],['首字延迟',duration(r.ttftMs)],['总耗时',duration(r.durationMs)],['结果',statuses[r.status]],['Token 用量',r.usage?`${r.usage.prompt_tokens} 输入 / ${r.usage.completion_tokens} 输出`:'上游未提供'],...(r.error?[['错误',r.error]]:[])].map(([label,value])=>`<div><dt>${label}</dt><dd class="${label==='错误'?'error-detail':''}">${esc(value)}</dd></div>`).join('')}</dl>`;return $('#detail-dialog').showModal();
|
||||||
|
}
|
||||||
|
if(action==='copy-url')return copy(state.service.baseUrl);
|
||||||
|
if(action==='copy-code')return copy($('#curl-snippet').textContent);
|
||||||
|
if(action==='prev-logs'||action==='next-logs'){logPage+=action==='next-logs'?1:-1;$('#logs-content').innerHTML=logsContent();return;}
|
||||||
|
if(action==='export-logs'){
|
||||||
|
const cell=value=>`"${String(value??'').replace(/^[=+@-]/,"'").replace(/"/g,'""')}"`;
|
||||||
|
const csv=[['时间','类型','账户','模型','结果','首字延迟(ms)','耗时(ms)','错误'],...filteredLogs().map(r=>[date(r.startedAt),kindLabel(r.kind),r.accountName,r.model,statuses[r.status],r.ttftMs,r.durationMs,r.error])].map(row=>row.map(cell).join(',')).join('\r\n');
|
||||||
|
const url=URL.createObjectURL(new Blob(['\ufeff'+csv],{type:'text/csv;charset=utf-8'}));const link=document.createElement('a');link.href=url;link.download=`logicc-requests-${new Date().toISOString().slice(0,10)}.csv`;link.click();setTimeout(()=>URL.revokeObjectURL(url),1000);return;
|
||||||
|
}
|
||||||
|
if(action==='try-model'){location.hash='playground';page='playground';render();$('#play-form').elements.model.value=button.dataset.model;return;}
|
||||||
|
if(action==='stop-play'){playController?.abort();return;}
|
||||||
|
button.disabled=true;busyCount++;
|
||||||
|
if(action==='check'||action==='refresh-token')await checkAccount(id,action==='refresh-token');
|
||||||
|
if(action==='toggle'){const a=state.accounts.find(a=>a.id===id);await api(`/accounts/${id}`,{method:'PATCH',body:{enabled:!a.enabled}});toast(a.enabled?'已暂停此账户调度':'账户已启用');}
|
||||||
|
if(action==='sync-models'){const result=await api('/models/refresh',{method:'POST'});toast(`已同步 ${result.models.length} 个模型`);}
|
||||||
|
if(action==='check-all'){
|
||||||
|
const accounts=state.accounts.filter(a=>a.enabled);let ok=0;
|
||||||
|
if(!accounts.length)toast('没有已启用的账户');
|
||||||
|
else{for(let i=0;i<accounts.length;i++){button.textContent=`检测 ${i+1} / ${accounts.length}`;if(await checkAccount(accounts[i].id,false,true))ok++;}toast(`检测完成:${ok} 个可用,${accounts.length-ok} 个异常`,ok!==accounts.length);}
|
||||||
|
}
|
||||||
|
await reload(true);
|
||||||
|
}catch(error){toast(error.message,true);}
|
||||||
|
finally{if(button.disabled){button.disabled=false;busyCount=Math.max(0,busyCount-1);}}
|
||||||
|
});
|
||||||
|
document.addEventListener('submit',async event=>{
|
||||||
|
if(event.target.id!=='play-form')return;
|
||||||
|
event.preventDefault();if(playController)return;
|
||||||
|
const form=event.target,output=$('#play-output'),status=$('#play-status'),meta=$('#play-meta'),submit=$('#play-submit'),stop=$('#play-stop');
|
||||||
|
playController=new AbortController();playStarted=performance.now();let first=null;
|
||||||
|
submit.disabled=true;stop.hidden=false;output.textContent='';output.classList.remove('output-placeholder');status.textContent='请求中';meta.textContent='正在等待模型响应…';
|
||||||
|
const data=new FormData(form),body={model:data.get('model'),stream:true,messages:[{role:'user',content:data.get('prompt')}]};
|
||||||
|
if(data.get('tool'))body.tools=[{type:'function',function:{name:data.get('tool')}}];
|
||||||
|
try{
|
||||||
|
const response=await fetch('/v1/chat/completions',{method:'POST',headers:{'Content-Type':'application/json',Authorization:`Bearer ${data.get('apiKey')||'local'}`},body:JSON.stringify(body),signal:playController.signal});
|
||||||
|
if(!response.ok){const result=await response.json();throw new Error(result.error?.message||`HTTP ${response.status}`);}
|
||||||
|
const reader=response.body.getReader(),decoder=new TextDecoder();let buffer='';
|
||||||
|
for(;;){const {value,done}=await reader.read();if(done)break;buffer+=decoder.decode(value,{stream:true});let index;
|
||||||
|
while((index=buffer.indexOf('\n\n'))!==-1){const frame=buffer.slice(0,index);buffer=buffer.slice(index+2);for(const line of frame.split('\n')){if(!line.startsWith('data:'))continue;const text=line.slice(5).trim();if(!text||text==='[DONE]')continue;const chunk=JSON.parse(text);if(chunk.error)throw new Error(chunk.error.message);const delta=chunk.choices?.[0]?.delta?.content;if(delta){first??=performance.now()-playStarted;output.textContent+=delta;status.textContent='接收中';}}}
|
||||||
|
}
|
||||||
|
status.textContent='已完成';meta.textContent=`首段文本 ${duration(first)} · 总耗时 ${duration(performance.now()-playStarted)}`;
|
||||||
|
if(!output.textContent)output.textContent='请求已完成,但上游未返回文本。';
|
||||||
|
}catch(error){const cancelled=error.name==='AbortError';status.textContent=cancelled?'已停止':'请求失败';meta.textContent=cancelled?'请求已由你停止':error.message;if(!output.textContent)output.textContent=cancelled?'请求已停止。':error.message;}
|
||||||
|
finally{playController=null;submit.disabled=false;stop.hidden=true;await reload();}
|
||||||
|
});
|
||||||
|
window.addEventListener('hashchange',()=>{if(playController)playController.abort();page=location.hash.slice(1)||'overview';render();$('#main').focus({preventScroll:true});window.scrollTo(0,0);});
|
||||||
|
$('#refresh').addEventListener('click',()=>reload(true));
|
||||||
|
for(const dialog of document.querySelectorAll('dialog'))dialog.addEventListener('click',event=>{if(event.target===dialog){const box=dialog.getBoundingClientRect();if(event.clientX<box.left||event.clientX>box.right||event.clientY<box.top||event.clientY>box.bottom)dialog.close();}});
|
||||||
|
await reload(true);
|
||||||
|
setInterval(()=>{if(!document.hidden)reload();},5000);
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40"><rect width="40" height="40" rx="10" fill="#25392e"/><path d="M11 10h8v20h-8zm11 12h8v8h-8z" fill="#edf3dc"/></svg>
|
||||||
|
After Width: | Height: | Size: 176 B |
@@ -0,0 +1,63 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||||
|
<meta name="color-scheme" content="light">
|
||||||
|
<meta name="theme-color" content="#f7f8f5">
|
||||||
|
<title>Logicc · 代理控制台</title>
|
||||||
|
<link rel="icon" href="/favicon.svg" type="image/svg+xml">
|
||||||
|
<link rel="stylesheet" href="/style.css">
|
||||||
|
<script type="module" src="/app.js"></script>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<a class="skip-link" href="#main">跳到主要内容</a>
|
||||||
|
<aside class="sidebar">
|
||||||
|
<a class="brand" href="#overview" aria-label="Logicc 控制台首页"><span class="brand-mark" aria-hidden="true"><i></i><i></i><i></i></span><span>logicc<span class="brand-dot">.</span></span></a>
|
||||||
|
<div class="workspace"><span class="workspace-symbol">L</span><div><strong>本地工作空间</strong><span>PROXY CONSOLE</span></div><span class="local-badge">LOCAL</span></div>
|
||||||
|
<div class="nav-label">工作空间</div>
|
||||||
|
<nav aria-label="主导航">
|
||||||
|
<a href="#overview" data-page="overview"><span data-icon="overview"></span>代理概览</a>
|
||||||
|
<a href="#accounts" data-page="accounts"><span data-icon="accounts"></span>号池管理<span id="nav-count" class="nav-count">—</span></a>
|
||||||
|
<a href="#models" data-page="models"><span data-icon="models"></span>模型与性能</a>
|
||||||
|
<a href="#logs" data-page="logs"><span data-icon="logs"></span>请求日志</a>
|
||||||
|
<a href="#playground" data-page="playground"><span data-icon="play"></span>请求测试</a>
|
||||||
|
</nav>
|
||||||
|
<div class="nav-label second-label">开发者</div>
|
||||||
|
<nav aria-label="开发者导航"><a href="#connect" data-page="connect"><span data-icon="code"></span>API 接入</a></nav>
|
||||||
|
<div class="sidebar-bottom"><div class="server-label"><span class="status-dot" id="sidebar-dot"></span><strong id="sidebar-status">正在连接代理</strong></div><span class="mono" id="sidebar-address">127.0.0.1:18789</span><div class="sidebar-footer"><span>Logicc Adapter</span><span>v1.0</span></div></div>
|
||||||
|
</aside>
|
||||||
|
<div class="app-shell">
|
||||||
|
<header class="topbar"><div class="breadcrumb">控制台<span>/</span><strong id="breadcrumb-page">代理概览</strong></div><div class="topbar-actions"><span id="connection-state" class="connection-state"><span class="status-dot"></span>连接中</span><span class="top-divider"></span><button id="refresh" class="icon-button" aria-label="刷新数据" title="刷新数据"><span data-icon="refresh"></span></button><span class="avatar" aria-label="本地用户">L</span></div></header>
|
||||||
|
<div id="connection-error" class="connection-error" role="alert" hidden></div>
|
||||||
|
<main id="main" tabindex="-1"><div class="loading-state"><span class="loader"></span><p>正在读取代理状态…</p></div></main>
|
||||||
|
<footer class="page-footer"><span><span class="tiny-dot"></span> 数据来自本地代理 · 每 5 秒更新</span><span id="last-updated">等待同步</span></footer>
|
||||||
|
</div>
|
||||||
|
<dialog id="account-dialog" class="modal"><form id="account-form">
|
||||||
|
<div class="modal-header"><div><div class="eyebrow">ACCOUNT POOL</div><h2 id="account-dialog-title">添加账户</h2></div><button type="button" class="icon-button" data-close="account-dialog" aria-label="关闭"><span data-icon="close"></span></button></div>
|
||||||
|
<p class="modal-description">使用 Clerk 客户端凭据自动刷新,或临时使用 Session JWT。</p>
|
||||||
|
<input type="hidden" name="id">
|
||||||
|
<label>账户名称 <span class="required">*</span><input name="name" required maxlength="80" placeholder="例如:日常使用 / 工作账户" autocomplete="off"></label>
|
||||||
|
<label>__client Cookie<input name="clientCookie" type="password" placeholder="粘贴 clerk.logicc.com 的 __client 值" autocomplete="new-password" spellcheck="false"></label>
|
||||||
|
<div class="field-hint">在浏览器开发者工具 → Application → Cookies → clerk.logicc.com 中获取。</div>
|
||||||
|
<label>Session ID<input name="sessionId" placeholder="sess_…" autocomplete="off" spellcheck="false" class="mono"></label>
|
||||||
|
<div class="field-hint">填写 Session ID,或在下方粘贴 Session JWT 自动读取 sid。</div>
|
||||||
|
<details class="token-details"><summary>使用 / 更新 Session JWT</summary><label>Session JWT<textarea name="token" rows="3" placeholder="eyJ…(短期有效)" autocomplete="off" spellcheck="false"></textarea></label><div class="field-hint">仅使用 JWT 时,过期后需重新更新。编辑时留空保留已有凭据。</div></details>
|
||||||
|
<label class="checkbox-label"><input name="enabled" type="checkbox" checked>加入调度池</label>
|
||||||
|
<p class="form-error" id="account-error" role="alert" hidden></p>
|
||||||
|
<div class="modal-footer"><span class="secret-note"><span data-icon="lock"></span>凭据仅保存在本机</span><button type="button" class="button secondary" data-close="account-dialog">取消</button><button type="submit" class="button primary">保存账户</button></div>
|
||||||
|
</form></dialog>
|
||||||
|
<dialog id="import-dialog" class="modal"><form id="import-form">
|
||||||
|
<div class="modal-header"><div><div class="eyebrow">BATCH IMPORT</div><h2>批量导入账户</h2></div><button type="button" class="icon-button" data-close="import-dialog" aria-label="关闭"><span data-icon="close"></span></button></div>
|
||||||
|
<p class="modal-description">导入 JSON 数组;相同 Session 不会重复加入。整批校验通过后保存。</p>
|
||||||
|
<label class="file-label">选择 JSON 文件<input id="import-file" type="file" accept=".json,application/json"></label>
|
||||||
|
<label>或粘贴 JSON<textarea name="accounts" class="mono" rows="9" required spellcheck="false" placeholder='[{"name":"工作账户","clientCookie":"…","sessionId":"sess_…"}]'></textarea></label>
|
||||||
|
<p class="field-hint">每项包含 name 与 clientCookie + sessionId,或 name 与 token。最多 200 个账户。</p>
|
||||||
|
<p id="import-error" class="form-error" role="alert" hidden></p>
|
||||||
|
<div class="modal-footer"><button type="button" class="button secondary" data-close="import-dialog">取消</button><button type="submit" class="button primary">导入账户</button></div>
|
||||||
|
</form></dialog>
|
||||||
|
<dialog id="confirm-dialog" class="modal small-modal"><form id="confirm-form"><div class="modal-header"><h2>移除账户</h2><button type="button" class="icon-button" data-close="confirm-dialog" aria-label="关闭"><span data-icon="close"></span></button></div><p id="confirm-message" class="modal-description"></p><p id="confirm-error" class="form-error" hidden role="alert"></p><div class="modal-footer"><button type="button" class="button secondary" data-close="confirm-dialog">取消</button><button type="submit" class="button danger">确认移除</button></div></form></dialog>
|
||||||
|
<dialog id="detail-dialog" class="modal"><div class="modal-header"><h2>请求详情</h2><button type="button" class="icon-button" data-close="detail-dialog" aria-label="关闭"><span data-icon="close"></span></button></div><div id="request-detail"></div></dialog>
|
||||||
|
<div id="toasts" class="toasts" aria-live="polite" aria-atomic="true"></div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
File diff suppressed because one or more lines are too long
@@ -0,0 +1 @@
|
|||||||
|
window.config = Object.freeze({"api":{"url":"https://app.logicc.com/api"},"app":{"env":"production","version":"chat-frontend@20261013.095124"},"clerk":{"publishableKey":"pk_live_Y2xlcmsubG9naWNjLmNvbSQ="},"sentry":{"dsn":"https://04737f497529e5bc4ca1fd63e6064bf2@sentry.dookapi.com/18"},"tolt":{"id":"pk_ETWwNqM84TFPzg75pfTMq8Q7"}})
|
||||||
@@ -0,0 +1,329 @@
|
|||||||
|
// Logicc → OpenAI adapter and local account-pool console. No runtime dependencies.
|
||||||
|
import { createServer } from 'node:http';
|
||||||
|
import { readFileSync } from 'node:fs';
|
||||||
|
import { fileURLToPath } from 'node:url';
|
||||||
|
import { dirname, resolve } from 'node:path';
|
||||||
|
import { timingSafeEqual } from 'node:crypto';
|
||||||
|
import { AccountPool, HttpError, claims, safeError } from './pool.mjs';
|
||||||
|
|
||||||
|
const ROOT = dirname(fileURLToPath(import.meta.url));
|
||||||
|
|
||||||
|
export async function* parseAiSdkStream(body) {
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
let buffer = '';
|
||||||
|
function parse(frame) {
|
||||||
|
const text = frame.split(/\r?\n/).filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart()).join('\n').trim();
|
||||||
|
if (!text || text === '[DONE]') return null;
|
||||||
|
try { return JSON.parse(text); } catch { throw new HttpError(502, '上游返回了无法解析的数据流'); }
|
||||||
|
}
|
||||||
|
for await (const chunk of body) {
|
||||||
|
buffer += decoder.decode(chunk, { stream: true });
|
||||||
|
let separator;
|
||||||
|
while ((separator = /\r?\n\r?\n/.exec(buffer))) {
|
||||||
|
const event = parse(buffer.slice(0, separator.index));
|
||||||
|
buffer = buffer.slice(separator.index + separator[0].length);
|
||||||
|
if (event) yield event;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
buffer += decoder.decode();
|
||||||
|
if (buffer.trim()) { const event = parse(buffer); if (event) yield event; }
|
||||||
|
}
|
||||||
|
|
||||||
|
function mapTools(tools) {
|
||||||
|
const builtins = { web_search: 'web-search', 'web-search': 'web-search', image_generation: 'image-generation', 'image-generation': 'image-generation' };
|
||||||
|
let forcedTool;
|
||||||
|
const custom = [];
|
||||||
|
for (const tool of tools || []) {
|
||||||
|
const name = tool?.function?.name ?? tool?.name;
|
||||||
|
if (Object.hasOwn(builtins, name)) forcedTool = builtins[name];
|
||||||
|
else if (tool?.function) custom.push(tool.function);
|
||||||
|
}
|
||||||
|
return { forcedTool, prompt: custom.length ? `\n\n[Tools available — if you need one, respond with a JSON block: {"tool_call": {"name": "<name>", "arguments": {...}}}]\n${JSON.stringify(custom)}` : '' };
|
||||||
|
}
|
||||||
|
|
||||||
|
function flattenMessages(messages) {
|
||||||
|
return messages.map(message => {
|
||||||
|
if (!message || typeof message.role !== 'string') throw new HttpError(400, 'messages 中的每条消息需要 role');
|
||||||
|
if (message.content != null && typeof message.content !== 'string' && !Array.isArray(message.content)) throw new HttpError(400, '消息 content 必须为文本或内容数组');
|
||||||
|
const content = typeof message.content === 'string' ? message.content : (message.content || []).filter(p => p?.type === 'text').map(p => p.text).join('\n');
|
||||||
|
return message.role === 'user' ? content : `[${message.role}]\n${content}`;
|
||||||
|
}).join('\n\n');
|
||||||
|
}
|
||||||
|
|
||||||
|
function readBody(req, limit = 1048576) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let size = 0;
|
||||||
|
const chunks = [];
|
||||||
|
req.on('data', chunk => {
|
||||||
|
size += chunk.length;
|
||||||
|
if (size > limit) { reject(new HttpError(413, '请求体过大')); return; }
|
||||||
|
chunks.push(chunk);
|
||||||
|
});
|
||||||
|
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
||||||
|
req.on('error', reject);
|
||||||
|
req.on('aborted', () => reject(new HttpError(400, '请求已中断')));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
async function readJson(req) {
|
||||||
|
const text = await readBody(req);
|
||||||
|
try { return JSON.parse(text || '{}'); } catch { throw new HttpError(400, '请求体不是有效 JSON'); }
|
||||||
|
}
|
||||||
|
function json(res, status, data) {
|
||||||
|
if (res.destroyed || res.writableEnded) return;
|
||||||
|
res.writeHead(status, { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store' });
|
||||||
|
res.end(JSON.stringify(data));
|
||||||
|
}
|
||||||
|
function usageOf(event) {
|
||||||
|
const usage = event.totalUsage || event.usage || event.messageMetadata?.usage;
|
||||||
|
if (!usage) return null;
|
||||||
|
const number = value => typeof value === 'number' && Number.isFinite(value) ? value : value?.total;
|
||||||
|
const input = number(usage.inputTokens) ?? usage.prompt_tokens;
|
||||||
|
const output = number(usage.outputTokens) ?? usage.completion_tokens;
|
||||||
|
if (!Number.isFinite(input) || !Number.isFinite(output)) return null;
|
||||||
|
return { prompt_tokens: input, completion_tokens: output, total_tokens: input + output };
|
||||||
|
}
|
||||||
|
|
||||||
|
export function createAdapter({ env = process.env, dataFile = env.LOGICC_DATA_FILE || resolve(ROOT, 'data/state.json') } = {}) {
|
||||||
|
const pool = new AccountPool(dataFile, env);
|
||||||
|
const apiBase = (env.LOGICC_API_BASE || 'https://app.logicc.com/api').replace(/\/+$/, '');
|
||||||
|
|
||||||
|
async function upstream(account, path, { method = 'GET', body, stream = false, signal } = {}, retry = true) {
|
||||||
|
const token = await pool.tokenFor(account);
|
||||||
|
const response = await fetch(`${apiBase}/${path}`, {
|
||||||
|
method, signal, redirect: 'error',
|
||||||
|
headers: { Authorization: `Bearer ${token}`, Accept: stream ? 'text/event-stream' : 'application/json',
|
||||||
|
...(stream ? { 'Stream-Response-Protocol': 'ai-sdk-v6' } : {}),
|
||||||
|
...(body !== undefined ? { 'Content-Type': 'application/json' } : {}) },
|
||||||
|
body: body === undefined ? undefined : JSON.stringify(body),
|
||||||
|
});
|
||||||
|
if (response.status === 401 && retry) {
|
||||||
|
await response.body?.cancel();
|
||||||
|
await pool.tokenFor(account, true);
|
||||||
|
return upstream(account, path, { method, body, stream, signal }, false);
|
||||||
|
}
|
||||||
|
if (!response.ok) {
|
||||||
|
await response.body?.cancel();
|
||||||
|
throw new HttpError(response.status, `上游 ${path.split('?')[0].startsWith('chats/') ? '聊天' : path.split('?')[0]} 请求失败(HTTP ${response.status})`);
|
||||||
|
}
|
||||||
|
return response;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function modelsFor(account, signal) {
|
||||||
|
const response = await upstream(account, 'models?language=en', { signal });
|
||||||
|
const data = await response.json();
|
||||||
|
const list = Array.isArray(data) ? data : data.models ?? data.data;
|
||||||
|
if (!Array.isArray(list)) throw new HttpError(502, '上游模型列表格式不正确');
|
||||||
|
const models = list.filter(m => typeof (m.id ?? m.modelId) === 'string').map(m => ({
|
||||||
|
id: m.id ?? m.modelId, name: typeof m.name === 'string' ? m.name : m.id ?? m.modelId,
|
||||||
|
provider: typeof m.provider === 'string' ? m.provider : typeof m.provider?.name === 'string' ? m.provider.name : 'logicc',
|
||||||
|
isDefault: Boolean(m.isDefault),
|
||||||
|
}));
|
||||||
|
if (!models.length) throw new HttpError(502, '上游没有返回可用模型');
|
||||||
|
pool.data.models = models;
|
||||||
|
pool.data.modelsUpdatedAt = Date.now();
|
||||||
|
return models;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function track(req, res, kind, operation, accountId) {
|
||||||
|
const trace = { kind, startedAt: Date.now(), model: null, ttftMs: null, status: 'success', stream: false, usage: null };
|
||||||
|
const controller = new AbortController();
|
||||||
|
const onClose = () => { if (!res.writableEnded) controller.abort(); };
|
||||||
|
res.on('close', onClose);
|
||||||
|
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(180000)]);
|
||||||
|
let account;
|
||||||
|
try {
|
||||||
|
account = accountId ? pool.account(accountId) : pool.acquire();
|
||||||
|
if (accountId) pool.runtimeFor(account.id).inFlight++;
|
||||||
|
trace.accountId = account.id;
|
||||||
|
trace.accountName = account.name;
|
||||||
|
const result = await operation(account, trace, signal);
|
||||||
|
pool.healthy(account);
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
if (signal.aborted) error = new HttpError(controller.signal.aborted ? 499 : 504, controller.signal.aborted ? '客户端已取消请求' : '上游请求超时');
|
||||||
|
trace.status = error.status === 499 ? 'cancelled' : 'error';
|
||||||
|
trace.error = safeError(error);
|
||||||
|
trace.httpStatus = error.status || 502;
|
||||||
|
if (account && error.status !== 499) pool.failed(account, error);
|
||||||
|
throw error;
|
||||||
|
} finally {
|
||||||
|
res.off('close', onClose);
|
||||||
|
trace.durationMs = Date.now() - trace.startedAt;
|
||||||
|
if (account) pool.release(account);
|
||||||
|
pool.record(trace);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function chat(req, res) {
|
||||||
|
const body = await readJson(req);
|
||||||
|
if (!body || typeof body !== 'object' || !Array.isArray(body.messages) || !body.messages.length) throw new HttpError(400, 'messages 需要非空数组');
|
||||||
|
if (body.tools !== undefined && !Array.isArray(body.tools)) throw new HttpError(400, 'tools 必须为数组');
|
||||||
|
if (body.model !== undefined && typeof body.model !== 'string') throw new HttpError(400, 'model 必须为字符串');
|
||||||
|
if (body.stream !== undefined && typeof body.stream !== 'boolean') throw new HttpError(400, 'stream 必须为布尔值');
|
||||||
|
const tools = mapTools(body.tool_choice === 'none' ? [] : body.tools);
|
||||||
|
const prompt = flattenMessages(body.messages) + tools.prompt;
|
||||||
|
if (!prompt.trim()) throw new HttpError(400, '消息内容不能为空');
|
||||||
|
await track(req, res, 'chat', async (account, trace, signal) => {
|
||||||
|
let model = body.model;
|
||||||
|
if (!model || model === 'default') {
|
||||||
|
const models = await modelsFor(account, signal);
|
||||||
|
model = (models.find(m => m.isDefault) || models[0]).id;
|
||||||
|
}
|
||||||
|
trace.model = model;
|
||||||
|
trace.stream = Boolean(body.stream);
|
||||||
|
const chatResponse = await upstream(account, 'chats', { method: 'POST', body: {}, signal });
|
||||||
|
const createdChat = await chatResponse.json();
|
||||||
|
const id = typeof createdChat === 'string' ? createdChat : createdChat.id;
|
||||||
|
if (typeof id !== 'string' || !id) throw new HttpError(502, '上游创建会话未返回 ID');
|
||||||
|
const response = await upstream(account, `chats/${encodeURIComponent(id)}`, {
|
||||||
|
method: 'POST', stream: true, signal,
|
||||||
|
body: { modelId: model, prompt, isVoicePrompt: false,
|
||||||
|
...(body.reasoning_effort ? { reasoningEffort: body.reasoning_effort } : {}),
|
||||||
|
...(tools.forcedTool ? { forcedTool: tools.forcedTool } : {}) },
|
||||||
|
});
|
||||||
|
const created = Math.floor(Date.now() / 1000);
|
||||||
|
const base = { id: `chatcmpl-${id}`, created, model };
|
||||||
|
const chunk = (delta, finishReason = null) => ({ ...base, object: 'chat.completion.chunk', choices: [{ index: 0, delta, finish_reason: finishReason }] });
|
||||||
|
const send = data => { if (!res.destroyed) res.write(`data: ${JSON.stringify(data)}\n\n`); };
|
||||||
|
let content = '';
|
||||||
|
let finished = false;
|
||||||
|
let finishReason = 'stop';
|
||||||
|
if (body.stream) {
|
||||||
|
res.writeHead(200, { 'Content-Type': 'text/event-stream; charset=utf-8', 'Cache-Control': 'no-cache', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });
|
||||||
|
res.flushHeaders();
|
||||||
|
send(chunk({ role: 'assistant' }));
|
||||||
|
}
|
||||||
|
for await (const event of parseAiSdkStream(response.body)) {
|
||||||
|
if (event.type === 'error') throw new HttpError(502, `上游流错误:${safeError(event.errorText || '未知错误')}`);
|
||||||
|
let delta = '';
|
||||||
|
if (event.type === 'text-delta' && event.delta) {
|
||||||
|
delta = event.delta;
|
||||||
|
trace.ttftMs ??= Date.now() - trace.startedAt;
|
||||||
|
} else if (event.type === 'tool-input-start') delta = `\n[tool:${event.toolName ?? 'unknown'}] `;
|
||||||
|
else if (event.type === 'tool-input-delta') delta = event.inputTextDelta || event.delta || '';
|
||||||
|
if (delta) { if (body.stream) send(chunk({ content: delta })); else content += delta; }
|
||||||
|
const usage = usageOf(event);
|
||||||
|
if (usage) trace.usage = usage;
|
||||||
|
if (event.type === 'finish') {
|
||||||
|
finished = true;
|
||||||
|
finishReason = ['stop', 'length', 'content_filter'].includes(event.finishReason) ? event.finishReason : 'stop';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!finished) throw new HttpError(502, '上游数据流提前结束,未收到 finish 事件');
|
||||||
|
const usage = trace.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
|
||||||
|
if (body.stream) {
|
||||||
|
send(chunk({}, finishReason));
|
||||||
|
if (body.stream_options?.include_usage) send({ ...base, object: 'chat.completion.chunk', choices: [], usage });
|
||||||
|
res.end('data: [DONE]\n\n');
|
||||||
|
} else {
|
||||||
|
json(res, 200, { ...base, object: 'chat.completion', choices: [{ index: 0, message: { role: 'assistant', content }, finish_reason: finishReason }], usage });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const assets = { '/': ['index.html', 'text/html'], '/app.js': ['app.js', 'text/javascript'], '/style.css': ['style.css', 'text/css'], '/favicon.svg': ['favicon.svg', 'image/svg+xml'] };
|
||||||
|
const server = createServer(async (req, res) => {
|
||||||
|
res.setHeader('X-Content-Type-Options', 'nosniff');
|
||||||
|
res.setHeader('Referrer-Policy', 'no-referrer');
|
||||||
|
res.setHeader('Content-Security-Policy', "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'");
|
||||||
|
try {
|
||||||
|
const host = req.headers.host || '';
|
||||||
|
const localPort = server.address()?.port;
|
||||||
|
if (![ `127.0.0.1:${localPort}`, `localhost:${localPort}`, `[::1]:${localPort}` ].includes(host)) throw new HttpError(403, '仅接受本机 Host');
|
||||||
|
const url = new URL(req.url, `http://${host}`);
|
||||||
|
const origin = req.headers.origin;
|
||||||
|
const bridge = url.pathname === '/__set_token' && origin === 'https://app.logicc.com';
|
||||||
|
if (origin && origin !== `http://${host}` && !bridge) throw new HttpError(403, '不允许此网页来源访问本机控制台');
|
||||||
|
if (req.headers['sec-fetch-site'] === 'cross-site' && !bridge) throw new HttpError(403, '不允许跨站访问');
|
||||||
|
if (bridge) {
|
||||||
|
res.setHeader('Access-Control-Allow-Origin', origin);
|
||||||
|
res.setHeader('Access-Control-Allow-Methods', 'POST, OPTIONS');
|
||||||
|
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
|
||||||
|
res.setHeader('Access-Control-Allow-Private-Network', 'true');
|
||||||
|
res.setHeader('Vary', 'Origin');
|
||||||
|
}
|
||||||
|
if (req.method === 'OPTIONS') { res.writeHead(204); res.end(); return; }
|
||||||
|
if (assets[url.pathname] && ['GET', 'HEAD'].includes(req.method)) {
|
||||||
|
const [file, type] = assets[url.pathname];
|
||||||
|
res.writeHead(200, { 'Content-Type': `${type}; charset=utf-8`, 'Cache-Control': 'no-cache' });
|
||||||
|
res.end(req.method === 'HEAD' ? undefined : readFileSync(resolve(ROOT, 'public', file)));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (url.pathname === '/health' && req.method === 'GET') return json(res, 200, { status: 'ok', uptime: Math.floor((Date.now() - pool.startedAt) / 1000) });
|
||||||
|
if (url.pathname.startsWith('/api/')) {
|
||||||
|
if (req.headers['x-logicc-admin'] !== '1') throw new HttpError(403, '控制台请求缺少 X-Logicc-Admin 请求头');
|
||||||
|
if (!['GET', 'DELETE'].includes(req.method) && !req.headers['content-type']?.startsWith('application/json')) throw new HttpError(415, '管理接口需要 application/json');
|
||||||
|
if (url.pathname === '/api/state' && req.method === 'GET') return json(res, 200, {
|
||||||
|
...pool.snapshot(), service: { baseUrl: `http://${host}/v1`, upstream: apiBase, apiKeyRequired: Boolean(env.LOGICC_API_KEY), strategy: 'least-busy-round-robin' },
|
||||||
|
});
|
||||||
|
if (url.pathname === '/api/accounts' && req.method === 'POST') {
|
||||||
|
const input = await readJson(req);
|
||||||
|
return json(res, 201, { account: pool.addMany([input])[0] });
|
||||||
|
}
|
||||||
|
if (url.pathname === '/api/accounts/import' && req.method === 'POST') {
|
||||||
|
const input = await readJson(req);
|
||||||
|
return json(res, 201, { accounts: pool.addMany(Array.isArray(input) ? input : input?.accounts) });
|
||||||
|
}
|
||||||
|
const match = /^\/api\/accounts\/([\w-]+)(?:\/(check|refresh))?$/.exec(url.pathname);
|
||||||
|
if (match) {
|
||||||
|
const [, id, action] = match;
|
||||||
|
if (req.method === 'PATCH' && !action) return json(res, 200, { account: pool.update(id, await readJson(req)) });
|
||||||
|
if (req.method === 'DELETE' && !action) { pool.remove(id); return json(res, 200, { ok: true }); }
|
||||||
|
if (req.method === 'POST' && action) {
|
||||||
|
const result = await track(req, res, 'check', async (account, trace, signal) => {
|
||||||
|
if (action === 'refresh') await pool.tokenFor(account, true);
|
||||||
|
const models = await modelsFor(account, signal);
|
||||||
|
return { models: models.length };
|
||||||
|
}, id);
|
||||||
|
return json(res, 200, { ...result, account: pool.publicAccount(pool.account(id)) });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (url.pathname === '/api/models/refresh' && req.method === 'POST') {
|
||||||
|
const models = await track(req, res, 'models', (account, _trace, signal) => modelsFor(account, signal));
|
||||||
|
return json(res, 200, { models, updatedAt: pool.data.modelsUpdatedAt });
|
||||||
|
}
|
||||||
|
throw new HttpError(404, '管理接口不存在');
|
||||||
|
}
|
||||||
|
if (url.pathname === '/__set_token' && req.method === 'POST') {
|
||||||
|
const token = (await readBody(req, 25000)).trim().replace(/^(['"])(.*)\1$/, '$2');
|
||||||
|
const sid = claims(token).sid;
|
||||||
|
const requested = url.searchParams.get('account_id');
|
||||||
|
const existing = requested ? pool.account(requested) : pool.data.accounts.find(a => a.sessionId === sid);
|
||||||
|
if (existing && existing.sessionId && existing.sessionId !== sid) throw new HttpError(400, 'JWT 不属于指定账户');
|
||||||
|
const account = existing ? pool.update(existing.id, { token }) : pool.addMany([{ name: '浏览器账户', token }])[0];
|
||||||
|
return json(res, 200, { ok: true, accountId: account.id, exp: claims(token).exp });
|
||||||
|
}
|
||||||
|
if (url.pathname.startsWith('/v1/') && env.LOGICC_API_KEY) {
|
||||||
|
const incoming = Buffer.from(req.headers.authorization || '');
|
||||||
|
const expected = Buffer.from(`Bearer ${env.LOGICC_API_KEY}`);
|
||||||
|
if (incoming.length !== expected.length || !timingSafeEqual(incoming, expected)) throw new HttpError(401, '代理 API Key 不正确');
|
||||||
|
}
|
||||||
|
if (url.pathname === '/v1/models' && req.method === 'GET') {
|
||||||
|
const models = await track(req, res, 'models', (account, _trace, signal) => modelsFor(account, signal));
|
||||||
|
return json(res, 200, { object: 'list', data: models.map(m => ({ id: m.id, object: 'model', created: 0, owned_by: m.provider })) });
|
||||||
|
}
|
||||||
|
if (url.pathname === '/v1/chat/completions' && req.method === 'POST') return await chat(req, res);
|
||||||
|
throw new HttpError(404, '接口不存在');
|
||||||
|
} catch (error) {
|
||||||
|
const message = safeError(error);
|
||||||
|
if (res.headersSent) {
|
||||||
|
if (!res.destroyed && !res.writableEnded) res.end(`data: ${JSON.stringify({ error: { message, type: 'adapter_error' } })}\n\ndata: [DONE]\n\n`);
|
||||||
|
} else json(res, error.status >= 400 && error.status <= 599 ? error.status : 502, { error: { message, type: 'adapter_error' } });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return { server, pool };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||||
|
const port = Number(process.argv[2] || process.env.PORT || 18789);
|
||||||
|
const host = process.env.LOGICC_HOST || '127.0.0.1';
|
||||||
|
const { server } = createAdapter();
|
||||||
|
server.listen(port, host, () => {
|
||||||
|
console.log(`Logicc console: http://127.0.0.1:${server.address().port}/`);
|
||||||
|
console.log(`OpenAI API: http://127.0.0.1:${server.address().port}/v1`);
|
||||||
|
});
|
||||||
|
for (const signal of ['SIGTERM', 'SIGINT']) process.on(signal, () => {
|
||||||
|
server.close(() => process.exit(0));
|
||||||
|
setTimeout(() => process.exit(0), 5000).unref();
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import test from 'node:test';
|
||||||
|
import assert from 'node:assert/strict';
|
||||||
|
import { createServer } from 'node:http';
|
||||||
|
import { once } from 'node:events';
|
||||||
|
import { mkdtempSync, readFileSync, statSync, rmSync } from 'node:fs';
|
||||||
|
import { tmpdir } from 'node:os';
|
||||||
|
import { join } from 'node:path';
|
||||||
|
import { AccountPool, claims } from '../pool.mjs';
|
||||||
|
import { createAdapter, parseAiSdkStream } from '../server.mjs';
|
||||||
|
|
||||||
|
const jwt = (sid, suffix='initial', exp=Math.floor(Date.now()/1000)+120) => `${Buffer.from('{"alg":"test"}').toString('base64url')}.${Buffer.from(JSON.stringify({sid,exp})).toString('base64url')}.${suffix}`;
|
||||||
|
const listen = async server => {server.listen(0,'127.0.0.1');await once(server,'listening');return `http://127.0.0.1:${server.address().port}`;};
|
||||||
|
const close = server => new Promise(resolve=>{server.closeAllConnections();server.close(resolve);});
|
||||||
|
async function harness(t,extra={}) {
|
||||||
|
const folder=mkdtempSync(join(tmpdir(),'logicc-test-'));
|
||||||
|
const hits=[], tokenCalls=[];
|
||||||
|
const mock=createServer(async(req,res)=>{
|
||||||
|
let text='';for await(const chunk of req)text+=chunk;
|
||||||
|
const sid=claims((req.headers.authorization||'').slice(7)).sid;
|
||||||
|
const body=text?JSON.parse(text):{};
|
||||||
|
hits.push({url:req.url,body,sid});
|
||||||
|
const respond=(status,data)=>{res.writeHead(status,{'Content-Type':'application/json'});res.end(JSON.stringify(data));};
|
||||||
|
if(req.url.includes('/tokens')){
|
||||||
|
tokenCalls.push(req.headers.cookie);
|
||||||
|
const session=req.url.split('/')[4];
|
||||||
|
if(session==='sess_bad')return respond(401,{error:'invalid'});
|
||||||
|
res.setHeader('Set-Cookie','__client=rotated_cookie; HttpOnly; Path=/');
|
||||||
|
return respond(200,{jwt:jwt(session,'refreshed')});
|
||||||
|
}
|
||||||
|
if(req.url.startsWith('/api/models')){
|
||||||
|
if(sid==='sess_old' && !req.headers.authorization.endsWith('refreshed'))return respond(401,{error:'revoked'});
|
||||||
|
if(sid==='sess_limited')return respond(429,{error:'limited'});
|
||||||
|
return respond(200,[{id:'test-fast',name:'Test Fast',provider:'test',isDefault:true},{id:'test-slow',provider:'test'}]);
|
||||||
|
}
|
||||||
|
if(req.url==='/api/chats')return respond(200,'a-mock-chat-id');
|
||||||
|
if(req.url.startsWith('/api/chats/')){
|
||||||
|
res.writeHead(200,{'Content-Type':'text/event-stream'});
|
||||||
|
if(body.prompt==='ERROR'){res.end('data: {"type":"error","errorText":"mock failure"}\n\n');return;}
|
||||||
|
res.write('data: {"type":"text-delta","delta":"你好"}\r\n\r\n');
|
||||||
|
if(body.prompt==='TRUNCATED'){res.end();return;}
|
||||||
|
if(body.forcedTool)res.write(`data: ${JSON.stringify({type:'tool-input-start',toolName:body.forcedTool})}\n\n`);
|
||||||
|
res.end('data: {"type":"text-delta","delta":",测试通过。"}\r\n\r\ndata: {"type":"finish","usage":{"inputTokens":5,"outputTokens":8}}\r\n\r\ndata: [DONE]\r\n\r\n');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
respond(404,{});
|
||||||
|
});
|
||||||
|
const upstream=await listen(mock);
|
||||||
|
const file=join(folder,'state.json');
|
||||||
|
const {server,pool}=createAdapter({dataFile:file,env:{LOGICC_API_BASE:`${upstream}/api`,LOGICC_CLERK_BASE:upstream,...extra}});
|
||||||
|
const base=await listen(server);
|
||||||
|
t.after(async()=>{await close(server);await close(mock);rmSync(folder,{recursive:true,force:true});});
|
||||||
|
const api=async(path,method='GET',body,headers={})=>{
|
||||||
|
const response=await fetch(base+path,{method,headers:{'X-Logicc-Admin':'1',...(body!==undefined?{'Content-Type':'application/json'}:{}),...headers},body:body===undefined?undefined:JSON.stringify(body)});
|
||||||
|
return {status:response.status,data:await response.json()};
|
||||||
|
};
|
||||||
|
const add=async(name,sid,extra={})=>(await api('/api/accounts','POST',{name,token:jwt(sid),...extra})).data.account;
|
||||||
|
return {base,api,pool,file,hits,tokenCalls,add};
|
||||||
|
}
|
||||||
|
|
||||||
|
test('account CRUD, atomic import, credential masking, persistence, validation',async t=>{
|
||||||
|
const {api,add,file}=await harness(t);
|
||||||
|
const a=await add('工作账户','sess_one',{clientCookie:'secret_cookie'});
|
||||||
|
assert.ok(a.id);assert.equal(a.hasClientCookie,true);assert.equal(a.token,undefined);
|
||||||
|
assert.equal((await api(`/api/accounts/${a.id}`,'PATCH',{name:'新名称',clientCookie:'',enabled:false})).data.account.enabled,false);
|
||||||
|
assert.equal(JSON.parse(readFileSync(file)).accounts[0].clientCookie,'secret_cookie');
|
||||||
|
await api(`/api/accounts/${a.id}`,'PATCH',{clientCookie:'replacement_cookie',sessionId:'sess_replaced'});
|
||||||
|
assert.equal(JSON.parse(readFileSync(file)).accounts[0].token,'');
|
||||||
|
assert.equal(statSync(file).mode & 0o777,0o600);
|
||||||
|
const imported=await api('/api/accounts/import','POST',[{name:'第二个',token:jwt('sess_two')},{name:'重复项',token:jwt('sess_replaced')}]);
|
||||||
|
assert.equal(imported.status,409);assert.equal((await api('/api/state')).data.accounts.length,1);
|
||||||
|
assert.equal((await api('/api/accounts/import','POST',[{name:'第二个',token:jwt('sess_two')}])).status,201);
|
||||||
|
const state=(await api('/api/state')).data;
|
||||||
|
assert.equal(state.accounts.length,2);assert.ok(!JSON.stringify(state).includes('secret_cookie'));assert.ok(!JSON.stringify(state).includes(jwt('sess_one')));
|
||||||
|
assert.equal((await api('/api/accounts','POST',{name:'Bad',token:'a.b.c'})).status,400);
|
||||||
|
assert.equal((await api('/api/accounts','POST',{name:'Bad',token:`a.${Buffer.from('null').toString('base64url')}.c`})).status,400);
|
||||||
|
assert.equal((await api('/api/accounts','POST',{name:'Bad',clientCookie:'x',sessionId:'../etc'})).status,400);
|
||||||
|
assert.equal((await api(`/api/accounts/${a.id}`,'DELETE')).status,200);
|
||||||
|
const reloaded=new AccountPool(file,{});assert.equal(reloaded.data.accounts.length,1);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('round-robin uses enabled accounts and 429 cools only the affected account',async t=>{
|
||||||
|
const {api,add,hits}=await harness(t);
|
||||||
|
await add('第一','sess_first');const second=await add('第二','sess_second');
|
||||||
|
await api('/v1/models');await api('/v1/models');await api('/v1/models');
|
||||||
|
assert.deepEqual(hits.filter(h=>h.url.startsWith('/api/models')).map(h=>h.sid),['sess_first','sess_second','sess_first']);
|
||||||
|
await api(`/api/accounts/${second.id}`,'PATCH',{enabled:false});
|
||||||
|
await api('/v1/models');assert.equal(hits.at(-1).sid,'sess_first');
|
||||||
|
const limited=await add('限流','sess_limited');
|
||||||
|
assert.equal((await api(`/api/accounts/${limited.id}/check`,'POST',{})).status,429);
|
||||||
|
assert.equal((await api('/api/state')).data.accounts.find(a=>a.id===limited.id).status,'cooling');
|
||||||
|
for(let i=0;i<3;i++)assert.equal((await api('/v1/models')).status,200);
|
||||||
|
assert.equal(hits.at(-1).sid,'sess_first');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('401 forces a different JWT, persists rotated cookie and joins concurrent refreshes',async t=>{
|
||||||
|
const {api,add,pool,file,tokenCalls}=await harness(t);
|
||||||
|
const a=await add('过期认证','sess_old',{clientCookie:'original_cookie'});
|
||||||
|
assert.equal((await api('/v1/models')).status,200);
|
||||||
|
assert.equal(tokenCalls.length,1);
|
||||||
|
const persisted=JSON.parse(readFileSync(file)).accounts[0];
|
||||||
|
assert.equal(persisted.clientCookie,'rotated_cookie');assert.ok(persisted.token.endsWith('refreshed'));
|
||||||
|
const account=pool.account(a.id);account.token=jwt('sess_old','expired',1);
|
||||||
|
await Promise.all([pool.tokenFor(account),pool.tokenFor(account),pool.tokenFor(account)]);
|
||||||
|
assert.equal(tokenCalls.length,2);
|
||||||
|
assert.equal(tokenCalls.at(-1),'__client=rotated_cookie');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('OpenAI JSON + SSE, UTF-8/CRLF, tools, usage and actual request statistics',async t=>{
|
||||||
|
const {api,add,base,hits}=await harness(t);await add('测试','sess_chat');
|
||||||
|
const completion=await api('/v1/chat/completions','POST',{messages:[{role:'user',content:'你好'}]});
|
||||||
|
assert.equal(completion.status,200);assert.equal(completion.data.choices[0].message.content,'你好,测试通过。');
|
||||||
|
assert.equal(completion.data.usage.total_tokens,13);
|
||||||
|
const response=await fetch(`${base}/v1/chat/completions`,{method:'POST',body:JSON.stringify({model:'test-fast',stream:true,stream_options:{include_usage:true},messages:[{role:'user',content:'工具测试'}],tools:[{type:'function',function:{name:'web_search'}}]})});
|
||||||
|
assert.equal(response.status,200);const text=await response.text();assert.ok(text.endsWith('data: [DONE]\n\n'));
|
||||||
|
const frames=text.split('\n\n').filter(f=>f.startsWith('data: {')).map(f=>JSON.parse(f.slice(6)));
|
||||||
|
assert.equal(frames[0].choices[0].delta.role,'assistant');assert.ok(frames.some(f=>f.choices[0]?.delta.content?.includes('[tool:web-search]')));
|
||||||
|
assert.equal(frames.at(-1).usage.total_tokens,13);assert.equal(hits.at(-1).body.forcedTool,'web-search');
|
||||||
|
const state=(await api('/api/state')).data;assert.equal(state.stats.requests,2);assert.equal(state.stats.successRate,100);assert.equal(state.modelStats[0].requests,2);assert.ok(state.stats.avgTtft>=0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('upstream stream errors and truncation are failures, including after response headers',async t=>{
|
||||||
|
const {api,add,base,pool}=await harness(t);const account=await add('错误测试','sess_error');
|
||||||
|
const bad=await api('/v1/chat/completions','POST',{model:'test-fast',messages:[{role:'user',content:'ERROR'}]});
|
||||||
|
assert.equal(bad.status,502);assert.match(bad.data.error.message,/mock failure/);
|
||||||
|
pool.runtimeFor(account.id).cooldownUntil=0;
|
||||||
|
const response=await fetch(`${base}/v1/chat/completions`,{method:'POST',body:JSON.stringify({model:'test-fast',stream:true,messages:[{role:'user',content:'TRUNCATED'}]})});
|
||||||
|
const text=await response.text();assert.ok(text.includes('"error"'));assert.ok(text.includes('[DONE]'));
|
||||||
|
const state=(await api('/api/state')).data;assert.equal(state.stats.requests,2);assert.equal(state.stats.failures,2);assert.equal(state.stats.successRate,0);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('local-origin boundary, API key, malformed JSON, oversized body, and empty pool',async t=>{
|
||||||
|
const {api,base}=await harness(t,{LOGICC_API_KEY:'only-test-key'});
|
||||||
|
assert.equal((await api('/v1/models')).status,401);
|
||||||
|
assert.equal((await api('/v1/models','GET',undefined,{Authorization:'Bearer only-test-key'})).status,503);
|
||||||
|
assert.equal((await fetch(base+'/api/state')).status,403);
|
||||||
|
assert.equal((await api('/api/state','GET',undefined,{Origin:'https://evil.example'})).status,403);
|
||||||
|
assert.equal((await api('/api/state','GET',undefined,{'Sec-Fetch-Site':'cross-site'})).status,403);
|
||||||
|
assert.equal((await fetch(base+'/api/accounts',{method:'POST',headers:{'X-Logicc-Admin':'1','Content-Type':'application/json'},body:'{'})).status,400);
|
||||||
|
assert.equal((await fetch(base+'/api/accounts',{method:'POST',headers:{'X-Logicc-Admin':'1','Content-Type':'application/json'},body:'x'.repeat(1048577)})).status,413);
|
||||||
|
assert.equal((await api('/api/accounts','POST',null)).status,400);
|
||||||
|
assert.equal((await fetch(base+'/__set_token',{method:'POST',headers:{Origin:'https://evil.example'},body:jwt('sess_test')})).status,403);
|
||||||
|
const bridge=await fetch(base+'/__set_token',{method:'POST',headers:{Origin:'https://app.logicc.com'},body:jwt('sess_bridge')});
|
||||||
|
assert.equal(bridge.status,200);assert.equal(bridge.headers.get('Access-Control-Allow-Origin'),'https://app.logicc.com');
|
||||||
|
});
|
||||||
|
|
||||||
|
test('SSE parser supports split multibyte text and unterminated final frames',async()=>{
|
||||||
|
const buffer=Buffer.from('data: {"type":"text-delta","delta":"中文"}\r\n\r\ndata: {"type":"finish"}');
|
||||||
|
async function* bytes(){for(const byte of buffer)yield new Uint8Array([byte]);}
|
||||||
|
const events=[];for await(const event of parseAiSdkStream(bytes()))events.push(event);
|
||||||
|
assert.deepEqual(events,[{type:'text-delta',delta:'中文'},{type:'finish'}]);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user