Files
LihonT/services/members/codegate.py
cheb0chik 3540ac84ea LihonT 2.3.0 (Serena): profile music, AI video dubbing, PiP & bg play, fonts, cleaner
- Shared moderated MP3 profile music (with floating mini-player and MediaSession controls, zero bubble when absent)
- AI video dubbing into Russian with burned-in ASS subtitles inside AgentChat (`services/members/dub.py`)
- Picture-in-Picture 9:16 and background audio playback (`PlayControl` + `play_patch.py`)
- System/custom .ttf fonts & emoji packs (`FontsAndEmoji`), account cleaner (`AccountCleaner`)
- Feed blacklist, muted sound restoration, OLED burn-in shift, A/B flag editor, presets, long comments
- Updated site homepage (`src/web/index.html`) for LihonT 2.3.0 Serena
2026-11-26 15:40:32 +03:00

408 lines
22 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""The gate of LihonC, the coding agent (LihonC IDE, код.нейронка.рус): the program on a person's computer sends one turn of its talk
here, this service asks the free models through the LihonC router (lihonc.py) and sends the answer back.
There is no sign-in (Russian law allows sign-in only through Russian services, and a free tool does not need it). Instead every call
carries two things the program makes itself: the installation (a random secret made at the first start) and the device (a hash of
stable facts of the computer: the raw facts never leave it). The address the call came from is the third. Each of the three has a
budget of tokens a day (the address a bigger one, many people share an address of a mobile operator), and the whole server has one too.
Going around the budget: a device that has used up its day and then comes from another address or with a new installation is warned
once ("the budget belongs to the device, another network does not help"); the second time the device, its installations and the
addresses it used that day are shut out (the device and installations for a week, the addresses for a day, so that neighbours behind
the same operator are not punished for long).
What is kept: counters and these hashes only (the address is kept as a salted hash), never the talk. The arena model (DeepSeek
through Coarena, which keeps what is sent to it) needs consent first, remembered per device. The keys of the providers live in this
service's environment.
"""
from __future__ import annotations
import hashlib
import json
import os
import re
import secrets
import time
try:
import lihonc
except ImportError: # imported as part of a package
from . import lihonc
MOSCOW = 3 * 3600
DEVICE_TOKENS = int(os.environ.get("CODE_DAILY_TOKENS", "500000")) # per device (and per installation) a day
ADDRESS_TOKENS = int(os.environ.get("CODE_ADDRESS_TOKENS", "2000000")) # per address a day: many people may share one
SERVER_TOKENS = int(os.environ.get("CODE_SERVER_TOKENS", "20000000")) # for everybody together a day
OWNER_TOKENS = 20_000_000
WEIGHT = {"low": 1.0, "medium": 1.5, "high": 3.0} # thinking harder costs more of the budget
BAN_DEVICE = 7 * 86400
BAN_ADDRESS = 86400
BODY = 2_500_000 # one turn with the whole talk so far and up to three small pictures
MAX_MESSAGES = 400
ROLES = ("system", "user", "assistant", "tool")
PASSED = ("messages", "tools", "tool_choice", "temperature", "max_tokens")
HEX64 = re.compile(r"[a-f0-9]{64}\Z")
class Who:
"""The three hashed names of one call."""
def __init__(self, installation: str, device: str, address: str):
self.installation = installation
self.device = device
self.address = address
def subjects(self):
return tuple(subject for subject in (self.installation, self.device, self.address) if subject)
class Stream:
"""An answer that is still being written: the server sends each event as it comes (server-sent events)."""
def __init__(self, events):
self.events = events
def __iter__(self):
return iter(self.events)
def close(self):
self.events.close()
class CodeGate:
def __init__(self, registry, keys: dict | None = None, router=None):
self.r = registry
self.router = router or lihonc.Router(keys if keys is not None else lihonc.load_keys(os.environ.get("LIHONC_KEYS_FILE")))
self.operations = {"code_status": self.status, "code_chat": self.chat, "code_consent": self.consent}
with self.r.connect() as db:
db.execute("CREATE TABLE IF NOT EXISTS code_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS code_use (subject TEXT NOT NULL, day TEXT NOT NULL, kind TEXT NOT NULL, "
"used INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(subject, day, kind))")
db.execute("CREATE TABLE IF NOT EXISTS code_seen (device TEXT NOT NULL, day TEXT NOT NULL, subject TEXT NOT NULL, "
"after_limit INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(device, day, subject))")
db.execute("CREATE TABLE IF NOT EXISTS code_strikes (device TEXT NOT NULL, day TEXT NOT NULL, strikes INTEGER NOT NULL, "
"PRIMARY KEY(device, day))")
db.execute("CREATE TABLE IF NOT EXISTS code_bans (subject TEXT PRIMARY KEY, until INTEGER NOT NULL, reason TEXT NOT NULL)")
db.execute("CREATE TABLE IF NOT EXISTS code_consents (device TEXT PRIMARY KEY, accepted_at INTEGER NOT NULL)")
row = db.execute("SELECT value FROM code_meta WHERE key='salt'").fetchone()
if row is None:
db.execute("INSERT INTO code_meta(key, value) VALUES('salt', ?)", (secrets.token_hex(16),))
row = db.execute("SELECT value FROM code_meta WHERE key='salt'").fetchone()
self.salt = row[0]
def call(self, operation, payload):
return self.operations[operation](payload)
# ---- who is calling ---------------------------------------------------------------------------------------------------
def _hash(self, kind: str, value: str) -> str:
return kind + ":" + hashlib.sha256((self.salt + kind + value).encode("utf-8")).hexdigest()[:32]
def _who(self, p) -> Who:
installation, device = p.get("installation"), p.get("device")
if not isinstance(installation, str) or not HEX64.fullmatch(installation):
raise ValueError("Invalid installation code")
if not isinstance(device, str) or not HEX64.fullmatch(device):
raise ValueError("Invalid device")
address = str(p.get("_ip") or "").strip()
# behind a proxy that hides the address every caller looks like this computer: then the address is not counted or banned,
# or one person could shut everybody out
local = not address or address in ("-", "::1", "localhost") or address.startswith("127.")
return Who(self._hash("i", installation), self._hash("d", device), None if local else self._hash("a", address))
def _owner(self, who: Who) -> bool:
owners = [value.strip() for value in os.environ.get("CODE_OWNER_DEVICES", "").split(",") if value.strip()]
return any(self._hash("d", value) == who.device for value in owners)
# ---- counters ---------------------------------------------------------------------------------------------------------
def _day(self) -> str:
return time.strftime("%Y-%m-%d", time.gmtime(self.r.clock() + MOSCOW))
def _now(self) -> int:
return int(self.r.clock())
def _used(self, subject: str, kind: str = "tokens") -> int:
with self.r.connect() as db:
row = db.execute("SELECT used FROM code_use WHERE subject=? AND day=? AND kind=?", (subject, self._day(), kind)).fetchone()
return row[0] if row else 0
def _server_used(self) -> int:
with self.r.connect() as db:
row = db.execute("SELECT COALESCE(SUM(used), 0) FROM code_use WHERE day=? AND kind='tokens' AND subject LIKE 'd:%'",
(self._day(),)).fetchone()
return row[0]
def _limit(self, who: Who) -> int:
return OWNER_TOKENS if self._owner(who) else DEVICE_TOKENS
def _spend(self, who: Who, tokens: int) -> None:
day = self._day()
with self.r.connect() as db:
old = time.strftime("%Y-%m-%d", time.gmtime(self.r.clock() + MOSCOW - 7 * 86400))
for table in ("code_use", "code_seen", "code_strikes"):
db.execute("DELETE FROM %s WHERE day < ?" % table, (old,))
for subject in who.subjects():
for kind, amount in (("tokens", tokens), ("calls", 1)):
db.execute("INSERT INTO code_use(subject, day, kind, used) VALUES(?,?,?,?) "
"ON CONFLICT(subject, day, kind) DO UPDATE SET used = used + excluded.used", (subject, day, kind, amount))
@staticmethod
def _tokens(completion: dict, body: dict) -> int:
usage = completion.get("usage") if isinstance(completion.get("usage"), dict) else {}
total = usage.get("total_tokens")
if isinstance(total, int) and total > 0:
return total
size = len(json.dumps(body.get("messages", []), ensure_ascii=False)) + len(json.dumps(completion.get("choices", []), ensure_ascii=False))
return max(1, size // 3) # a provider that does not say: about three characters a token
# ---- bans and going around the budget ---------------------------------------------------------------------------------
def _banned(self, who: Who) -> int:
with self.r.connect() as db:
marks = ",".join("?" * len(who.subjects()))
row = db.execute("SELECT MAX(until) FROM code_bans WHERE subject IN (%s) AND until > ?" % marks,
(*who.subjects(), self._now())).fetchone()
return row[0] or 0
def _remember(self, who: Who, over: bool) -> tuple[bool, bool]:
"""Notes the installation and the address of the device today. Returns (new installation, new address) among those seen
after the device used up its day, which is what going around looks like."""
day = self._day()
fresh = []
with self.r.connect() as db:
for subject in (who.installation, who.address):
if not subject:
fresh.append(False)
continue
row = db.execute("SELECT after_limit FROM code_seen WHERE device=? AND day=? AND subject=?", (who.device, day, subject)).fetchone()
known_after = db.execute("SELECT COUNT(*) FROM code_seen WHERE device=? AND day=? AND after_limit=1 AND subject LIKE ?",
(who.device, day, subject[:2] + "%")).fetchone()[0]
fresh.append(over and known_after > 0 and (row is None or row[0] == 0))
if row is None:
db.execute("INSERT INTO code_seen(device, day, subject, after_limit) VALUES(?,?,?,?)", (who.device, day, subject, 1 if over else 0))
elif over and row[0] == 0:
db.execute("UPDATE code_seen SET after_limit=1 WHERE device=? AND day=? AND subject=?", (who.device, day, subject))
return fresh[0], fresh[1]
def _strike(self, who: Who) -> int:
day = self._day()
with self.r.connect() as db:
db.execute("INSERT INTO code_strikes(device, day, strikes) VALUES(?,?,1) "
"ON CONFLICT(device, day) DO UPDATE SET strikes = strikes + 1", (who.device, day))
return db.execute("SELECT strikes FROM code_strikes WHERE device=? AND day=?", (who.device, day)).fetchone()[0]
def _ban(self, who: Who, reason: str) -> int:
"""Shuts out the device, every installation and address it used today. Returns when the device may come back."""
now, day = self._now(), self._day()
with self.r.connect() as db:
subjects = [row[0] for row in db.execute("SELECT subject FROM code_seen WHERE device=? AND day=?", (who.device, day))]
for subject in (set(subjects) | {who.device, who.installation, who.address}) - {None}:
until = now + (BAN_ADDRESS if subject.startswith("a:") else BAN_DEVICE)
db.execute("INSERT INTO code_bans(subject, until, reason) VALUES(?,?,?) "
"ON CONFLICT(subject) DO UPDATE SET until=MAX(until, excluded.until), reason=excluded.reason", (subject, until, reason))
return now + BAN_DEVICE
def unban(self, device_hash_prefix: str) -> int:
"""For the owner from the server's command line: lifts the bans of the device whose hash starts with this, and of the
installations and addresses it used. Returns how many devices were let back."""
if len(device_hash_prefix) < 6:
raise ValueError("Give at least six characters of the device hash")
with self.r.connect() as db:
devices = [row[0] for row in db.execute("SELECT subject FROM code_bans WHERE subject LIKE ?", ("d:" + device_hash_prefix + "%",))]
for device in devices:
linked = [row[0] for row in db.execute("SELECT DISTINCT subject FROM code_seen WHERE device=?", (device,))]
for subject in [device] + linked:
db.execute("DELETE FROM code_bans WHERE subject=?", (subject,))
return len(devices)
def _gate(self, who: Who):
"""None when the call may go on, else the error to answer with."""
until = self._banned(who)
if until:
return self._banned_error(who, until)
if self._owner(who):
self._remember(who, False)
return None
limit = self._limit(who)
over = self._used(who.device) >= limit or self._used(who.installation) >= limit
new_installation, new_address = self._remember(who, over)
if over:
if new_installation or new_address:
if self._strike(who) >= 2:
return self._banned_error(who, self._ban(who, "going around the daily budget"))
return self._error("device_limit", "Дневной лимит этого компьютера исчерпан. Он общий для устройства: другая сеть, VPN "
"или переустановка не помогут, а повторная попытка закроет доступ на неделю. Сброс в 00:00 по Москве.")
return self._error("daily_limit", "Дневной лимит (%d тыс. токенов) исчерпан. Сброс в 00:00 по Москве." % (limit // 1000))
if who.address and self._used(who.address) >= ADDRESS_TOKENS:
return self._error("address_limit", "С этого интернета сегодня уже потрачен общий лимит. Сброс в 00:00 по Москве.")
if self._server_used() >= SERVER_TOKENS:
return self._error("server_limit", "Бесплатный запас LihonC на сегодня закончился у всех. Сброс в 00:00 по Москве.")
return None
def _banned_error(self, who: Who, until: int) -> dict:
code = who.device[2:10]
return self._error("banned", "Доступ к LihonC закрыт до %s (МСК): обход лимитов. Если это ошибка, напиши в @lihont и пришли код "
"устройства %s." % (time.strftime("%d.%m %H:%M", time.gmtime(until + MOSCOW)), code), device_code=code)
def _consented(self, who: Who) -> bool:
with self.r.connect() as db:
return db.execute("SELECT 1 FROM code_consents WHERE device=?", (who.device,)).fetchone() is not None
# ---- operations -------------------------------------------------------------------------------------------------------
def status(self, p):
who = self._who(p)
until = self._banned(who)
return {"arena_consent": self._consented(who), "models": [lihonc.NAMES[lihonc.AUTO], lihonc.NAMES[lihonc.ARENA]],
"efforts": list(WEIGHT), "banned_until": until or None, "device_code": who.device[2:10] if until else None,
"today": {"tokens": self._used(who.device), "limit": self._limit(who), "calls": self._used(who.device, "calls")}}
def consent(self, p):
who = self._who(p)
with self.r.connect() as db:
if p.get("accept") is True:
db.execute("INSERT OR REPLACE INTO code_consents(device, accepted_at) VALUES(?,?)", (who.device, self._now()))
else:
db.execute("DELETE FROM code_consents WHERE device=?", (who.device,))
return {"arena_consent": p.get("accept") is True}
def chat(self, p):
who = self._who(p)
model = str(p.get("model") or "").strip().lower()
if model not in lihonc.NAMES:
raise ValueError("Unknown model")
messages = p.get("messages")
if not isinstance(messages, list) or not 0 < len(messages) <= MAX_MESSAGES:
raise ValueError("Bad messages")
for message in messages:
if not isinstance(message, dict) or message.get("role") not in ROLES:
raise ValueError("Bad messages")
if p.get("tools") is not None and not isinstance(p.get("tools"), list):
raise ValueError("Bad tools")
body = {name: p[name] for name in PASSED if name in p}
body["stream"] = False
effort = p.get("effort") if p.get("effort") in WEIGHT else "medium"
body["reasoning_effort"] = effort
stop = self._gate(who)
if stop is not None:
return stop
if model == lihonc.ARENA and not self._consented(who):
return self._error("arena_consent_required", lihonc.CONSENT_TEXT, switch_to=lihonc.NAMES[lihonc.AUTO])
fallback = p.get("fallback") == "auto"
target = model
if p.get("stream") is True:
while True:
opened = self._open_stream(target, body)
if opened is not None:
return Stream(self._events(who, target, model, effort, body, *opened))
if target == lihonc.ARENA and fallback:
target = lihonc.AUTO
continue
if target == lihonc.ARENA:
return self._error("arena_unavailable", lihonc.ARENA_DOWN, switch_to=lihonc.NAMES[lihonc.AUTO])
return self._error("all_providers_busy", lihonc.ALL_BUSY)
while True:
completion = self._ask(target, body)
if completion is not None:
self._spend(who, int(self._tokens(completion, body) * WEIGHT[effort])) # only answered calls are counted
return {"completion": completion, "model": lihonc.NAMES[target], "switched": target != model,
"left": max(0, self._limit(who) - self._used(who.device))}
if target == lihonc.ARENA:
if fallback:
target = lihonc.AUTO
continue
return self._error("arena_unavailable", lihonc.ARENA_DOWN, switch_to=lihonc.NAMES[lihonc.AUTO])
return self._error("all_providers_busy", lihonc.ALL_BUSY)
def _open_stream(self, alias: str, body: dict):
"""(response, first chunk) of the first provider of the chain that starts to answer; None when none does. Nothing has been
sent to the person yet, so a provider that fails at once is simply replaced by the next."""
streaming = dict(body, stream=True, stream_options={"include_usage": True})
for provider, upstream in self.router.chain(alias, streaming):
if not self.router.available(provider):
continue
try:
response = self.router.open(provider, upstream, streaming)
except lihonc.UpstreamError:
continue
first = None
try:
for raw in response:
line = raw.decode("utf-8", "replace").strip()
if not line.startswith("data:"):
continue
data = line[5:].strip()
if data == "[DONE]":
break
chunk = json.loads(data)
if isinstance(chunk, dict) and not chunk.get("error"):
first = chunk
break
except (ValueError, OSError):
first = None
if first is not None:
return response, first, provider
response.close()
self.router.cool(provider, 20.0)
return None
def _events(self, who: Who, target: str, asked: str, effort: str, body: dict, response, first: dict, provider: str = ""):
"""The events of one streamed answer; the budget is charged at the end, also when the person goes away in the middle."""
written, usage = 0, None
try:
chunk = first
while chunk is not None:
if isinstance(chunk.get("usage"), dict) and chunk["usage"].get("total_tokens"):
usage = chunk["usage"]["total_tokens"]
for choice in chunk.get("choices") or []:
written += len(json.dumps(choice.get("delta") or {}, ensure_ascii=False))
yield lihonc.rename(chunk, target)
chunk = None
for raw in response:
line = raw.decode("utf-8", "replace").strip()
if not line.startswith("data:"):
continue
data = line[5:].strip()
if data == "[DONE]":
break
try:
parsed = json.loads(data)
except ValueError:
continue
if isinstance(parsed, dict):
chunk = parsed
break
yield {"lihonc_done": True, "model": lihonc.NAMES[target], "switched": target != asked}
finally:
response.close()
tokens = usage or max(1, (len(json.dumps(body.get("messages", []), ensure_ascii=False)) + written) // 3)
self._spend(who, int(tokens * WEIGHT[effort]))
self.router.charge(provider, tokens)
def _ask(self, alias: str, body: dict):
"""The first answer of the chain of the alias, with our model name; None when every provider failed."""
for provider, upstream in self.router.chain(alias, body):
if not self.router.available(provider):
continue
try:
response = self.router.open(provider, upstream, body)
except lihonc.UpstreamError:
continue
try:
payload = json.loads(response.read().decode("utf-8"))
except (UnicodeDecodeError, ValueError, OSError):
self.router.cool(provider, 20.0)
continue
finally:
response.close()
if isinstance(payload, dict) and payload.get("choices") and not payload.get("error"):
self.router.charge(provider, self._tokens(payload, body))
return lihonc.rename(payload, alias)
return None
@staticmethod
def _error(kind: str, message: str, **extra) -> dict:
return {"error": {"type": kind, "message": message, **extra}}