#!/usr/bin/env python3 # через mk_daemon = функции grok_bot), капча на создание/reveal, экономика v3 (траты из logs). import asyncio import calendar import hashlib import hmac import html as html_mod import importlib.util import json import logging import math import os import random import secrets import sqlite3 import re import sys import time from contextlib import closing from urllib.parse import parse_qsl from aiohttp import ClientError, ClientSession, ClientTimeout, web BASE = os.path.dirname(os.path.abspath(__file__)) APP_ROOT = os.environ.get("IISHKO_APP_ROOT", os.path.dirname(BASE)) sys.path.insert(0, APP_ROOT) import reminders as reminder_store import neurolab import community_economy import quest_economy import rankings import daily_checkin import key_issue_guard import model_uptime import base64 import file_intake from assistant_runtime import AssistantError, AssistantRuntime, UpstreamError from support_store import NotificationError, SupportError, SupportOutbox, SupportStore, safe_request_id import entry_telemetry import entry_admin import miniapp_guard import gateway_commerce import commerce_access import community_board import account_balances from account_limits import account_uid sys.path.insert(0, os.path.normpath(os.path.join(APP_ROOT, os.pardir, "gateway"))) from gateway_providers import ProviderRegistry try: from model_advisories import for_model as provider_moderation_for_model except ImportError: # Cosmetic advisory must not prevent a partial deployment from booting. def provider_moderation_for_model(_model_id): return None # [MODELMETA 2026-10-28] vendor-reference limits live in a static JSON file; a missing or # broken module/file must never keep the Mini App from booting, so enrichment is optional. try: import model_metadata except Exception: # pragma: no cover - deployment without the reference file model_metadata = None def _model_metadata_rows(model_ids): """id -> vendor-reference metadata, or None when no reference is available.""" if model_metadata is None: return None try: reference = model_metadata.for_models(model_ids) except Exception: return None return reference or None log = logging.getLogger("iishko-webapp") with open(os.environ.get("GROK_BOT_CONFIG", "/opt/grok-bot/config.json"), encoding="utf-8") as config_file: CFG = json.load(config_file) BOT_TOKEN = CFG["bot_token"] BOT_DB = os.environ.get("IISHKO_BOT_DB") or os.environ.get("GROK_BOT_DB", "/opt/grok-bot/bot.db") UPTIME_DB = os.environ.get("GROK_UPTIME_DB", os.path.join(os.path.dirname(BOT_DB), "model_uptime.db")) NEWAPI_DB = CFG.get("newapi_db", "/opt/grok-gateway/new-api/one-api.db") QUOTA_PER_USD = 500000 ADMIN_IDS = {int(value) for value in os.environ.get("IISHKO_ADMIN_IDS", "").split(",") if value.strip().isdigit()} ADMIN_IDS.update(value for value in CFG.get("admin_ids", []) if type(value) is int and value > 0) REF_NEW_ID_MIN = 9_000_000_000 PUBLIC_BASE = CFG.get("public_base", "https://api.your-domain.com").rstrip("/") + "/v1" BADGES = {1: ("\U0001f949", "Новичок", 0, 0), 2: ("\U0001f948", "Актив", 5, 7), 3: ("\U0001f947", "Профи", 15, 21), 4: ("\U0001f48e", "Легенда", 40, 48)} RANK_REFS = {2: 2, 3: 5, 4: 10} MK_CAP = {1: 2, 2: 3, 3: 4, 4: 6} # зеркало ботовского MK_CAP RANK_WEEK = {1: 500, 2: 1000, 3: 2000, 4: 5000} # единый источник недельного порога def _ranks_detail(): out = [] for lvl in sorted(BADGES): em, name, rep_req, days_req = BADGES[lvl] out.append({"rank": lvl, "emoji": em, "name": name, "days_req": days_req, "refs_req": RANK_REFS.get(lvl, 0), "rep_req": rep_req, "weekly_credit_usd": RANK_WEEK.get(lvl, 500), "keys_cap": MK_CAP.get(lvl, 2)}) return out DICE_BONUS = {1: 5_000_000, 2: 8_000_000, 3: 10_000_000, 4: 12_000_000, 5: 15_000_000, 6: 20_000_000} WHEEL = [(10, 400), (25, 250), (50, 150), (100, 100), (200, 70), (500, 25), (1000, 5)] TIER_MODELS = {1: ['glm-5.3', 'glm-5.3-prime', 'qwen-plus', 'qwen-max', 'qwen3.8-flash', 'qwen3.8-27b', 'qwen3.8-max', 'qwen3.8-max-0902', 'deepseek-v4.1-flash-1017', 'kimi-k3', 'qwen3-vl-plus'], 2: ['deepseek-v4-pro', 'qwen3.7-max', 'gpt-5.6-luna', 'gpt-5.6-terra', 'gpt-6-luna', 'grok-4.6', 'grok-4.7', 'grok-composer-2.5-fast', 'MiniMax-M2.7-highspeed', 'gemini-auto', 'LongCat-2.0', 'cx/gpt-6-luna', 'Atria-Dawn-Preview', 'Qwen3.8-Flash-Next', 'SenseNova-6.8-Flash-Lite', 'claude-sonnet-4.5'], 3: ['kimi/kimi-k3.1-pro', 'kimi/kimi-k3.1-pro-highspeed', 'gpt-5.6-sol', 'gpt-6-astra', 'kimi-k2.7-code', 'MiniMax-M2.7-highspeed', 'gemini-auto', 'LongCat-2.0', 'cx/gpt-6-luna', 'Atria-Dawn-Preview', 'Qwen3.8-Flash-Next', 'SenseNova-6.8-Flash-Lite', 'gpt-6-luna', 'grok-4.6', 'grok-4.7', 'claude-sonnet-4.5'], 4: ['claude-opus-5.5', 'claude-opus-5', 'claude-opus-4-5-token', 'claude-fable-5.1', 'gpt-5.5', 'claude-opus-4-6', 'MiniMax-M2.7-highspeed', 'gemini-auto', 'LongCat-2.0', 'cx/gpt-6-luna', 'Atria-Dawn-Preview', 'Qwen3.8-Flash-Next', 'SenseNova-6.8-Flash-Lite', 'gpt-6-luna', 'grok-4.6', 'grok-4.7', 'claude-sonnet-4.5']} TIER_TITLES = {1: ('🥉', 'Новичок'), 2: ('🥈', 'Актив'), 3: ('🥇', 'Профи'), 4: ('💎', 'Легенда')} MODEL_DESCS = {'glm-5.3': 'GLM 5.3 · диалоги, редактура и задачи по коду', 'qwen3.7-max': 'Qwen 3.7 Max · анализ задач, тексты и код', 'glm-5.3-prime': 'GLM 5.3 Prime · разбор задач и составление инструкций', 'deepseek-v4-pro': 'DeepSeek V4 Pro · разбор решений, анализ и код', 'glm-5.3-flash': 'GLM 5.3 Flash · вопросы, диалоги и черновики', 'qwen3.8-max-0902': 'Qwen 3.8 Max 0902 · разбор задач, тексты и код', 'qwen3.8-27b': 'Qwen 3.8 27B · вопросы, планы и черновики', 'qwen-plus': 'Qwen Plus · диалоги, тексты и объяснения', 'qwen3.8-flash': 'Qwen 3.8 Flash · повседневные вопросы и редактура', 'qwen-max': 'Qwen Max · анализ задач, тексты и код', 'qwen3-vl-plus': 'Qwen VL Plus · вопросы, описания и объяснения', 'deepseek-v4.1-flash-1017': 'DeepSeek V4.1 Flash 1017 · разбор кода и анализ задач', 'deepseek-v4-flash': 'DeepSeek V4 Flash · вопросы, объяснения и код', 'qwen3.8-max': 'Qwen 3.8 Max · анализ задач, тексты и код', 'kimi-k3': 'Kimi K3 · работа с текстом, планы и код', 'kimi/kimi-k3.1-pro': 'Kimi K3.1 Pro · анализ текста, планы и разбор кода', 'kimi/kimi-k3.1-pro-highspeed': 'Kimi K3.1 Pro Highspeed · анализ текста, планы и разбор кода', 'grok-4.6': 'Grok 4.6 · диалоги, идеи и задачи по коду', 'grok-4.7': 'Grok 4.7 · обсуждение идей, тексты и код', 'grok-composer-2.5-fast': 'Grok Composer 2.5 Fast · написание и редактирование текстов', 'claude-opus-5-5': 'Claude Opus 5.5 · разбор задач, инструкции и код', 'claude-opus-4-6': 'Claude Opus 4.6 · разбор задач, инструкции и код', 'claude-fable-5-1': 'Claude Fable 5.1 · тексты, сценарии и редактура', 'gpt-5.6-luna': 'GPT-5.6 Luna · диалоги, редактура и задачи по коду', 'gpt-6-luna': 'GPT-6 Luna · диалоги, редактура и код', 'gpt-5.6-terra': 'GPT-5.6 Terra · диалоги, объяснения и задачи по коду', 'gpt-5.6-sol': 'GPT-5.6 Sol · анализ задач, тексты и код', 'gpt-6.1-sol': 'GPT-6.1 Sol · разбор решений, тексты и код', 'gpt-5.5': 'GPT-5.5 · диалоги, тексты и задачи по коду', 'wanx2.1-t2i-turbo': 'Wanx 2.1 Turbo · изображения по текстовому описанию', 'wan2.2-t2i-flash': 'Wan 2.2 Flash · изображения по текстовому описанию', 'wan2.6-t2v': 'Wan 2.6 · видео по текстовому описанию', 'grok-imagine-image': 'Grok Imagine · изображения по текстовому описанию', 'grok-imagine-image-2.0': 'Grok Imagine 2.0 · изображения по текстовому описанию', 'gpt-image-2.5': 'GPT Image 2.5 · изображения по текстовому описанию', 'kimi-k2.7-code': 'Kimi K2.7 Code · генерация и правка кода', 'MiniMax-M2.7-highspeed': 'MiniMax 2.7 Highspeed · быстрые диалоги и код', 'gemini-auto': 'Gemini Auto · авто-выбор канала, диалоги и тексты', 'LongCat-2.0': 'LongCat 2.0 · диалоги, пересказ и черновики', 'cx/gpt-6-luna': 'GPT-6 Luna (канал cx) · тексты, разбор и код', 'Atria-Dawn-Preview': 'Atria Dawn Preview · экспериментальные диалоги', 'Qwen3.8-Flash-Next': 'Qwen 3.8 Flash Next · быстрые ответы и код', 'SenseNova-6.8-Flash-Lite': 'SenseNova 6.8 Flash Lite · лёгкие быстрые ответы', 'claude-sonnet-4.5': 'Claude Sonnet 4.5 · диалоги, тексты и код', 'claude-opus-5': 'Claude Opus 5 · сложные задачи и код', 'claude-opus-5.5': 'Claude Opus 5.5 · разбор задач, инструкции и код', 'claude-opus-4-5-token': 'Claude Opus 4.5 (token-канал) · длинные задачи и код', 'claude-fable-5.1': 'Claude Fable 5.1 · тексты, сценарии и редактура', 'gpt-6-astra': 'GPT-6 Astra · сложные диалоги, разбор и код'} # [HIDDEN 2310] публичные алиасы codai* не показываем в Mini App: в шлюзе за ними может # стоять другой upstream (codai -> claude). Это ТОЛЬКО презентация списков — авторизацию # шлюза (token_limits / abilities по группам) отдельно согласует владелец; webapp здесь # ничего не «закрывает» и модели не подменяет. _HIDDEN_PUBLIC_PREFIXES = ("codai",) def _is_hidden_public_alias(name): return isinstance(name, str) and name.lower().startswith(_HIDDEN_PUBLIC_PREFIXES) def _con(path, timeout=15): c = sqlite3.connect(path, timeout=timeout) c.row_factory = sqlite3.Row return c class DbBusy(Exception): """[BUSY] SQLite BUSY/LOCKED — отличаем от прочего, чтобы не молчать и не висеть.""" def _is_busy(e): msg = str(e).lower() return "busy" in msg or "locked" in msg def _db_busy(): """[BUSY] вместо бесконечного ожидания/ложных нулей — честные 503.""" return web.json_response( {"error": "db_busy", "msg": "База занята — попробуй ещё раз через пару секунд"}, status=503) def _bearer(request): auth = request.headers.get("Authorization", "") return auth[7:].strip() if auth.lower().startswith("bearer ") else "" def verify_init(init_data): """Bounded Telegram HMAC validation; preserve the existing 24-hour launch session.""" if not isinstance(init_data, str) or not init_data or len(init_data) > 8192: return None try: if len(init_data.encode("utf-8")) > 8192: return None pairs = parse_qsl(init_data, strict_parsing=True, keep_blank_values=True, max_num_fields=32, encoding="utf-8", errors="strict") data = dict(pairs) if len(data) != len(pairs) or any(len(k) > 64 or len(v) > 4096 for k, v in pairs): return None signature = data.pop("hash", None) if not isinstance(signature, str) or re.fullmatch(r"[0-9a-fA-F]{64}", signature) is None: return None if "user" not in data or re.fullmatch(r"[1-9][0-9]{0,11}", data.get("auth_date", "")) is None: return None check = "\n".join("%s=%s" % (key, data[key]) for key in sorted(data)) secret = hmac.new(b"WebAppData", BOT_TOKEN.encode(), hashlib.sha256).digest() expected = hmac.new(secret, check.encode(), hashlib.sha256).hexdigest() if not hmac.compare_digest(expected, signature.lower()): return None auth_date, now = int(data["auth_date"]), time.time() if auth_date > now + 60 or now - auth_date > 86400: return None user = json.loads(data["user"]) uid = user.get("id") if isinstance(user, dict) else None # int(True), int(1.5) and int("123") must never become a different signed identity. return uid if type(uid) is int and 0 < uid <= 2**63 - 1 else None except (ValueError, TypeError, UnicodeError, RecursionError, OverflowError): return None def refs_weighted(con, uid): row = con.execute( "SELECT COALESCE(SUM(CASE WHEN tg_id>=? THEN 0.5 ELSE 1.0 END),0) " "FROM users WHERE referred_by=? AND ref_awarded=1", (REF_NEW_ID_MIN, uid)).fetchone() return float(row[0] or 0) def rank_of(u, refs): """badge_of replica: дни обязательны + (рефы ИЛИ репа); badge_lock = пол.""" if u["tg_id"] in ADMIN_IDS or u["admin"]: return 4 rep = u["rep"] or 0 days = max(0, (int(time.time()) - int(u["created"] or 0)) // 86400) if u["created"] else 0 lvl = 1 for l in (2, 3, 4): _, _, rep_req, days_req = BADGES[l] if days >= days_req and (refs >= RANK_REFS[l] or (rep_req and rep >= rep_req)): lvl = l lock = int(u["badge_lock"] or 0) until = int(u["badge_until"] or 0) if lock and (until == 0 or time.time() < until): lvl = max(lvl, min(4, max(1, lock))) return lvl def today_msk(): return time.strftime("%Y-%m-%d", time.gmtime(int(time.time()) + 3 * 3600)) def msk_midnight_ts(): return calendar.timegm(time.strptime(today_msk(), "%Y-%m-%d")) - 3 * 3600 def balance_cents(uid): w = _wallet(uid, allow_paused=True) return max(0, (w[1] * 100) // QUOTA_PER_USD) if w else 0 def _account_balances(uid, user=None): if user is None: with_user = _con(BOT_DB) try: row = with_user.execute("SELECT * FROM users WHERE tg_id=?", (uid,)).fetchone() user = dict(row) if row is not None else {} finally: with_user.close() con = _con(NEWAPI_DB) try: return account_balances.snapshot(con, uid, user, QUOTA_PER_USD) finally: con.close() def _wallet(uid, allow_paused=False): # paused-токен показывает деньги, но не становится мишенью mint/burn — # мутационные пути по умолчанию остаются гейтнуты на status=1 (трата/реактивация запрещены). names = [] con = _con(BOT_DB) try: u = con.execute("SELECT token_name FROM users WHERE tg_id=?", (int(uid),)).fetchone() finally: con.close() if u and u["token_name"] and account_uid(u["token_name"]) == int(uid): names.append(u["token_name"]) d = "tg%d" % int(uid) if d not in names: names.append(d) con = _con(NEWAPI_DB) try: con.execute("PRAGMA busy_timeout=15000") for nm in names: if allow_paused: r = con.execute("SELECT id, remain_quota FROM tokens WHERE name=? AND status IN (1,2) " "AND deleted_at IS NULL " "ORDER BY remain_quota DESC LIMIT 1", (nm,)).fetchone() else: r = con.execute("SELECT id, remain_quota FROM tokens WHERE name=? AND status=1 AND deleted_at IS NULL " "ORDER BY remain_quota DESC LIMIT 1", (nm,)).fetchone() if r: return (int(r[0]), int(r[1])) return None finally: con.close() def mint(uid, units, type_): units = int(units) if units <= 0: return 0 w = _wallet(uid) if not w: return 0 con = _con(NEWAPI_DB) con.execute("PRAGMA busy_timeout=15000") try: con.execute("UPDATE tokens SET remain_quota=remain_quota+? WHERE id=?", (units, w[0])) con.commit() finally: con.close() con = _con(BOT_DB) con.execute("PRAGMA busy_timeout=15000") try: con.execute("INSERT INTO econ_tx (src,dst,units,type,ts) VALUES (0,?,?,?,?)", (int(uid), units, type_, int(time.time()))) con.commit() finally: con.close() _econ_invalidate(int(uid)) return units def ledger_count(uid, type_, since_ts=None): con = _con(BOT_DB) try: if since_ts is None: n = con.execute("SELECT COUNT(*) FROM econ_tx WHERE dst=? AND type=?", (uid, type_)).fetchone()[0] else: n = con.execute("SELECT COUNT(*) FROM econ_tx WHERE dst=? AND type=? AND ts>=?", (uid, type_, int(since_ts))).fetchone()[0] return int(n) finally: con.close() # ---------- задания ---------- def task_defs(con, uid): u = con.execute("SELECT token_name, chat_count, img_count, last_checkin FROM users WHERE tg_id=?", (uid,)).fetchone() refs = con.execute("SELECT COUNT(*) FROM users WHERE referred_by=? AND ref_awarded=1", (uid,)).fetchone()[0] mid = msk_midnight_ts() has_key = bool(u and u["token_name"]) chat_n = int(u["chat_count"] or 0) if u else 0 img_n = int(u["img_count"] or 0) if u else 0 daily_done = bool(u and u["last_checkin"] == today_msk()) if u else False spin_done = ledger_count(uid, "web:spin", mid) > 0 defs = [ ("key", "Получи API-ключ", "Забери ключ здесь — вкладка «Ключи»", 1.0, has_key, False, "web:task:key"), ("chat1", "Первый чат", "Отправь один запрос любой модели", 1.0, chat_n >= 1, False, "web:task:chat1"), ("img1", "Первая картинка", "Сгенерируй одно изображение", 1.0, img_n >= 1, False, "web:task:img1"), ("ref1", "Первый реферал", "Пригласи одного друга", 2.0, refs >= 1, False, "web:task:ref1"), ("ref5", "Пятёрка своих", "Пригласи 5 друзей", 10.0, refs >= 5, False, "web:task:ref5"), ("daily", "Ежедневный кубик", "Брось кубик сегодня", 0.5, daily_done, True, "web:task:daily"), ("spin", "Крутни колесо", "Одно вращение колеса сегодня", 0.25, spin_done, True, "web:task:spin"), ] out = [] for tid, title, desc, reward, done, repeatable, txtype in defs: claimed = ledger_count(uid, txtype, mid if repeatable else None) > 0 out.append({"id": tid, "title": title, "desc": desc, "reward": reward, "done": bool(done), "claimed": bool(claimed), "repeatable": repeatable, "txtype": txtype}) return out TASK_BY_ID = None # заполняется в рантайме из task_defs # ---------- [V3] капча (SVG-арифметика, one-time, 5 мин) ---------- def _captcha_init(): con = _con(BOT_DB) try: con.execute("PRAGMA busy_timeout=15000") con.execute("CREATE TABLE IF NOT EXISTS wa_captcha (id TEXT PRIMARY KEY, uid INTEGER NOT NULL, " "ans INTEGER NOT NULL, expires INTEGER NOT NULL, used INTEGER NOT NULL DEFAULT 0)") con.execute("CREATE INDEX IF NOT EXISTS wa_captcha_uid ON wa_captcha(uid)") con.execute("DELETE FROM wa_captcha WHERE expires<=?", (int(time.time()),)) con.commit() finally: con.close() def _device_init(): con = _con(BOT_DB) con.execute("PRAGMA busy_timeout=15000") con.execute("CREATE TABLE IF NOT EXISTS wa_devices (uid INTEGER NOT NULL, device TEXT NOT NULL, " "first INTEGER NOT NULL, last INTEGER NOT NULL, PRIMARY KEY (uid, device))") con.execute("CREATE TABLE IF NOT EXISTS wa_key_dev (name TEXT PRIMARY KEY, uid INTEGER, " "device TEXT, created INTEGER)") con.execute("DELETE FROM wa_devices WHERE last < ?", (int(time.time()) - 30 * 86400,)) con.commit() con.close() def _device_track(uid, dev): con = _con(BOT_DB) con.execute("PRAGMA busy_timeout=15000") try: now = int(time.time()) con.execute("INSERT INTO wa_devices (uid, device, first, last) VALUES (?,?,?,?) " "ON CONFLICT(uid, device) DO UPDATE SET last=?", (uid, dev, now, now, now)) con.commit() finally: con.close() def _captcha_svg(expr_parts): """[WACAP 21.10] expr_parts: список (char, color). Размер глифа подбирается под ширину — выражение влезает ЦЕЛИКОМ (раньше '19 − 18 = ?' обрезалось: 8 глифов × ~38px > 276px, tail '= ?' не рисовался — «капчу не видно»). Джиттер мягче, шум тоньше, системные шрифты (Unbounded в SVG не грузится). [WACAP2 21.10] H=116 совпадает с CSS-коробкой (.cap-svg svg aspect-ratio:300/116): раньше viewBox был 300×92, картинка влезала в бокс 278×116 по «meet» и получала пустые полосы сверху/снизу — визуально «капча мелкая и кривая». Глиф крупнее (до 46px) и центруется по baseline, а не прижимается к низу коробки.""" W, H = 300, 116 n = max(1, len(expr_parts)) size = min(46, max(24, (W - 44) // n - 4)) step = size + 6 s = ['' % (W, H, W, H), '' % (W, H)] for _ in range(2): x1, y1 = random.randint(0, W), random.randint(0, H) x2, y2 = random.randint(0, W), random.randint(0, H) s.append('' % (x1, y1, x2, y2)) for _ in range(10): s.append('' % ( random.randint(0, W), random.randint(0, H))) x = max(14, (W - n * step) // 2) for ch, col in expr_parts: y = H // 2 + (size * 36) // 100 + random.randint(-3, 3) rot = random.randint(-8, 8) s.append('%s' % ( x + size // 2, y, size, col, rot, x + size // 2, y, html_mod.escape(ch))) x += step s.append('') return "".join(s) def captcha_new(uid): a = random.randint(3, 19) if random.random() < 0.5: b = random.randint(2, 15) ans = a + b op = "+" else: b = random.randint(1, max(1, a - 1)) ans = a - b op = "\u2212" expr = "%d %s %d = ?" % (a, op, b) parts = [] for ch in expr: if ch == " ": continue col = "#ff6b35" if ch in "+\u2212=?" else random.choice(["#f5f5f2", "#ddd", "#f0a582"]) parts.append((ch, col)) svg = _captcha_svg(parts) cid = secrets.token_hex(16) con = _con(BOT_DB) try: now = int(time.time()) con.execute("PRAGMA busy_timeout=15000") con.execute("BEGIN IMMEDIATE") con.execute("DELETE FROM wa_captcha WHERE expires<=? OR uid=?", (now, uid)) if con.execute("SELECT COUNT(*) FROM wa_captcha").fetchone()[0] >= 20000: raise AssistantError(503, "captcha_unavailable", "Капча сейчас недоступна. Попробуй позже.") con.execute("INSERT INTO wa_captcha (id,uid,ans,expires,used) VALUES (?,?,?,?,0)", (cid, uid, ans, now + 300)) con.commit() finally: con.close() return {"id": cid, "svg": svg} def captcha_check(uid, cid, ans): if type(uid) is not int or not 0 < uid <= 2**63 - 1 or not isinstance(cid, str) or not 1 <= len(cid) <= 32: return False con = _con(BOT_DB) try: con.execute("PRAGMA busy_timeout=15000") con.execute("BEGIN IMMEDIATE") row = con.execute("SELECT ans,expires,used FROM wa_captcha WHERE id=? AND uid=?", (cid, uid)).fetchone() if row is None or row["used"]: return False # Exactly one attempt, including malformed guesses; wrong-account attempts cannot burn it. con.execute("UPDATE wa_captcha SET used=1 WHERE id=? AND uid=?", (cid, uid)) value = None if type(ans) is int and -9999 <= ans <= 9999: value = ans elif isinstance(ans, str) and len(ans) <= 8 and re.fullmatch(r"[+-]?[0-9]{1,4}", ans.strip()): value = int(ans.strip()) ok = row["expires"] > int(time.time()) and value is not None and row["ans"] == value con.commit() return ok except (sqlite3.Error, ValueError, TypeError): return False finally: con.close() async def api_captcha(req): return web.json_response(await asyncio.to_thread(captcha_new, req["uid"])) # ---------- [V3] mk_daemon (мутации через grok_bot) ---------- class MkDaemon: def __init__(self): self.proc = None self._logf = None self.lock = asyncio.Lock() async def _spawn(self): env = dict(os.environ) env["PYTHONPATH"] = env.get("IISHKO_RUNTIME_PATHS", "") env.setdefault("IISHKO_APP_ROOT", APP_ROOT) env.setdefault("GROK_BOT_DB", BOT_DB) env.setdefault("GROK_BOT_CFG", env.get("GROK_BOT_CONFIG", os.path.join(APP_ROOT, "config.json"))) # [FIX-2410] fd лог-файла держим в self и закрываем в _reap/_cleanup: # раньше каждый респавн протекал открытым дескриптором. if self._logf is not None: try: self._logf.close() except OSError: pass log_path = os.environ.get("IISHKO_KEY_DAEMON_LOG") self._logf = open(log_path, "ab") if log_path else None self.proc = await asyncio.create_subprocess_exec( sys.executable, os.path.join(BASE, "mk_daemon.py"), cwd=BASE, env=env, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=self._logf or sys.stderr) async def _reap(self): # [FIX-2410] единый путь остановки демона: kill + await proc.wait() + закрытие лог-fd. proc, self.proc = self.proc, None logf, self._logf = self._logf, None if proc is not None: try: if proc.returncode is None: proc.kill() await proc.wait() except ProcessLookupError: pass except Exception: log.exception("mk daemon stop failed") if logf is not None: try: logf.close() except OSError: pass async def call(self, cmd, timeout=90, **kw): # захват lock ограничен 5с, дальше быстрый отказ с busy-флагом. # На таймауте захвата демон не трогаем; внутренний wait_for(timeout) ответа демона сохранён. try: await asyncio.wait_for(self.lock.acquire(), 5) except asyncio.TimeoutError: return {"ok": False, "busy": True, "err": "Сервис ключей занят, повтори через пару секунд"} try: try: if self.proc is None or self.proc.returncode is not None: await self._spawn() payload = json.dumps(dict(cmd=cmd, **kw), ensure_ascii=False) + "\n" self.proc.stdin.write(payload.encode()) await self.proc.stdin.drain() line = await asyncio.wait_for(self.proc.stdout.readline(), timeout) if not line: raise ConnectionError("key daemon EOF") result = json.loads(line.decode()) if not isinstance(result, dict): raise ValueError("invalid daemon result") return result except BaseException as error: await self._reap() if isinstance(error, (asyncio.CancelledError, KeyboardInterrupt, SystemExit)): raise # No automatic retry: the first command may already have committed. return {"ok": False, "uncertain": True, "err": "Нет подтверждения. Проверь операцию с тем же номером."} finally: self.lock.release() MK = MkDaemon() def _mask(key): return (key[:6] + "\u2026" + key[-4:]) if key and len(key) > 12 else None KEYS_CAP_SOURCE = os.path.join(APP_ROOT, "econ_cap.py") def _keys_cap_policy(): """Read the direct-API limiter's literal policy, never import/run its production code.""" import ast try: with open(KEYS_CAP_SOURCE, encoding="utf-8") as source: tree = ast.parse(source.read()) values = {} for node in tree.body: if isinstance(node, ast.Assign): for target in node.targets: if isinstance(target, ast.Name) and target.id in ("DAILY_USD_CAP", "OWNER_UID"): values[target.id] = ast.literal_eval(node.value) caps, owner = values["DAILY_USD_CAP"], values["OWNER_UID"] if not isinstance(caps, dict) or not all( type(rank) is int and rank in caps and type(caps[rank]) in (int, float) and math.isfinite(caps[rank]) and caps[rank] >= 0 for rank in range(5)): return None if not isinstance(owner, (str, int)) or isinstance(owner, bool) or not re.fullmatch( r"[1-9][0-9]*", str(owner)): return None return caps, str(owner) except (OSError, UnicodeError, SyntaxError, ValueError, TypeError, KeyError, OverflowError, RecursionError): return None def _keys_readonly(path): from pathlib import Path con = sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True, timeout=15) con.row_factory = sqlite3.Row return con def _keys_limits(uid, rank, cap, user, now): # the configured account-shared budget; econ_cap currently skips token-status writes. limits = {"keys_cap": cap, "weekly_credit_usd": RANK_WEEK.get(rank, 500), "direct_api_daily_usd": None, "direct_api_daily_unlimited": False, "direct_api_daily_reset_at": (now + 10800) // 86400 * 86400 - 10800 + 86400, "direct_api_daily_scope": "account_shared"} policy = _keys_cap_policy() if policy is None: return limits caps, owner = policy if str(uid) == owner: limits["direct_api_daily_unlimited"] = True return limits if not {"badge_lock", "badge_until", "rank_cache"}.issubset(user.keys()): return limits try: until = int(user["badge_until"] or 0) locked = int(user["badge_lock"] or 0) if not until or until > now else 0 effective = max(locked, int(user["rank_cache"] or 0)) if effective >= 0: limits["direct_api_daily_usd"] = caps[min(effective, 4)] except (TypeError, ValueError, OverflowError): pass return limits def _keys_usage_snapshot(uid, rank, cap, names, now): con = _keys_readonly(BOT_DB) try: user = con.execute("SELECT * FROM users WHERE tg_id=?", (uid,)).fetchone() finally: con.close() if user is None: return None limits = _keys_limits(uid, rank, cap, user, now) periods = (("day", (now + 10800) // 86400 * 86400 - 10800), ("week", now - 7 * 86400), ("month", now - 30 * 86400)) usage = {name: {period: {"from_ts": start, "to_ts": now, "quota": 0, "usd": 0.0, "requests": 0, "tokens": 0, "known_tokens": 0, "unknown_token_requests": 0, "tokens_complete": True} for period, start in periods} for name in names} gw = _keys_readonly(NEWAPI_DB) try: gw.execute("BEGIN") columns = {row["name"] for row in gw.execute("PRAGMA table_info(logs)")} if not {"token_name", "quota", "created_at", "type"}.issubset(columns): raise sqlite3.OperationalError("saved request logs unavailable") if names: token_fields = ",".join( (field if field in columns else "NULL") + " AS " + field for field in ("prompt_tokens", "completion_tokens")) fields, args = ["token_name"], [] for period, start in periods: for expression, field in ( ("COALESCE(quota,0)", "quota"), ("1", "requests"), ("COALESCE(prompt_tokens,0)+COALESCE(completion_tokens,0)", "known_tokens"), ("CASE WHEN prompt_tokens IS NULL OR completion_tokens IS NULL THEN 1 ELSE 0 END", "unknown_token_requests")): fields.append("SUM(CASE WHEN created_at>=? THEN " + expression + " ELSE 0 END) AS " + period + "_" + field) args.append(start) # New API user_id is shared: only the daemon's exact returned names are authoritative. source = ("(SELECT token_name,quota,created_at," + token_fields + " FROM logs INDEXED BY idx_logs_token_name WHERE token_name IN (" + ",".join("?" for _ in names) + ") AND type=2 AND created_at>=? AND created_at<=?)") rows = gw.execute("SELECT " + ",".join(fields) + " FROM " + source + " GROUP BY token_name", (*args, *names, periods[-1][1], now)).fetchall() for row in rows: for period, _ in periods: total = usage[row["token_name"]][period] for field in ("quota", "requests", "known_tokens", "unknown_token_requests"): total[field] = int(row[period + "_" + field] or 0) total["usd"] = total["quota"] / float(QUOTA_PER_USD) total["tokens_complete"] = total["unknown_token_requests"] == 0 total["tokens"] = total["known_tokens"] if total["tokens_complete"] else None finally: gw.close() return {"usage_meta": {"source": "saved_request_logs", "currency": "USD", "quota_per_usd": QUOTA_PER_USD, "timezone": "Europe/Moscow", "as_of": now}, "limits": limits, "usage": usage} async def api_keys(req): uid = req["uid"] res = await MK.call("list", uid=uid) if not res.get("ok"): return _keys_response(res) keys = res.get("keys") if (type(res.get("uid")) is not int or res["uid"] != uid or not isinstance(keys, list) or any(not isinstance(key, dict) or not isinstance(key.get("name"), str) or not key["name"] for key in keys) or type(res.get("cap")) is not int or res["cap"] < 0): return web.json_response({"error": "keys_unavailable", "msg": "Не удалось подтвердить список ключей"}, status=503) names = tuple(dict.fromkeys(key["name"] for key in keys)) try: snapshot = await asyncio.to_thread( _keys_usage_snapshot, uid, req["rank"], res["cap"], names, int(time.time())) except sqlite3.Error: return _db_busy() if snapshot is None: return web.json_response({"error": "not_found"}, status=404) res = dict(res, rank=req["rank"], endpoint=PUBLIC_BASE, usage_meta=snapshot["usage_meta"], limits=snapshot["limits"], keys=[dict(key, usage=snapshot["usage"][key["name"]]) for key in keys]) return web.json_response(res) def _keys_response(res): if res.get("ok"): return web.json_response(res) if res.get("busy"): return web.json_response({"error": "busy", "msg": res.get("err", "Сервис ключей занят, повтори через пару секунд")}, status=503, headers={"Retry-After": "2"}) rejected = res.get("operation_rejected") is True body = {"error": "keys" if rejected else "uncertain", "msg": res.get("err", "Операция не подтверждена")} if rejected: body["operation_rejected"] = True return web.json_response(body, status=400 if rejected else 503) def _keys_error(message, error="bad_request"): return web.json_response({"error": error, "msg": message, "operation_rejected": True}, status=400) async def _keys_body(req, mutation=False): try: body = await req.json() except (ValueError, UnicodeError, RecursionError): return None, _keys_error("Ожидается JSON-объект") if not isinstance(body, dict): return None, _keys_error("Ожидается JSON-объект") if mutation and (not isinstance(body.get("request_id"), str) or not re.fullmatch(r"[A-Za-z0-9_-]{12,96}", body["request_id"])): return None, _keys_error("Обнови Mini App: нужен номер операции", "request_id_required") return body, None async def _captcha_gate(req, body=None): if body is None: body, error = await _keys_body(req) if error is not None: return False, body, error cid, ans = body.get("cid"), body.get("ans") if not isinstance(cid, str) or not 1 <= len(cid) <= 32: return False, body, _keys_error("Проверь ответ капчи", "captcha") if not await asyncio.to_thread(captcha_check, req["uid"], cid, ans): return False, body, _keys_error("Капча неверная или истекла — попробуй ещё", "captcha") return True, body, None def _key_device_check(uid, dev): con = _con(BOT_DB) try: count = con.execute("SELECT COUNT(DISTINCT uid) FROM wa_key_dev WHERE device=? AND uid!=? AND created>=?", (dev, uid, int(time.time()) - 14 * 86400)).fetchone()[0] return count < 3 finally: con.close() def _key_device_record(uid, dev, name): con = _con(BOT_DB) try: con.execute("INSERT OR REPLACE INTO wa_key_dev(name,uid,device,created) VALUES (?,?,?,?)", (name, uid, dev, int(time.time()))) con.commit() finally: con.close() async def api_keys_create(req): body, error = await _keys_body(req, mutation=True) if error is not None: return error # Replaying a committed create must not require reusing a consumed captcha. previous = await MK.call("replay", uid=req["uid"], action="create", request_id=body["request_id"]) if not previous.get("ok") or previous.get("found") is not False: return _keys_response(previous) signals = key_issue_guard.context(BOT_TOKEN, req["uid"], req.get("device"), req.remote, req.headers) if signals is None: return _keys_error("Для выдачи ключа открой Mini App заново и разреши хранение данных", "device_required") retry = await asyncio.to_thread(key_issue_guard.attempt, BOT_DB, signals) if retry: return web.json_response({"error": "issuance_rate", "operation_rejected": True, "msg": "Слишком много попыток выдачи ключей. Подожди и повтори.", "retry_after": retry}, status=429, headers={"Retry-After": str(retry)}) ok, _, error = await _captcha_gate(req, body) if not ok: return error res = await MK.call("create", uid=req["uid"], request_id=body["request_id"], issue_device=signals["device"]) if res.get("ok"): _econ_invalidate(req["uid"]) return _keys_response(res) async def api_keys_reveal(req): body, error = await _keys_body(req) if error is not None: return error n = body.get("n") if type(n) is not int or not -1 <= n <= 1000000: return _keys_error("Некорректный номер ключа") ok, _, error = await _captcha_gate(req, body) if not ok: return error return _keys_response(await MK.call("reveal", uid=req["uid"], n=n)) async def _key_mutation(req, action): body, error = await _keys_body(req, mutation=True) if error is not None: return error n = body.get("n") if type(n) is not int or not (0 <= n <= 1000000) or (action in ("del", "transfer") and n == 0): return _keys_error("Проверь номер ключа") params = {"n": n} if action == "transfer": usd, direction = body.get("usd"), body.get("dir") if type(usd) not in (int, float) or not math.isfinite(usd) or direction not in ("to", "from"): return _keys_error("Проверь сумму и направление перевода") if not (1 <= usd <= 1000 or usd == 0 and direction == "from"): return _keys_error("Перевод: от 1 до 1000; возврат всего остатка: 0") params.update(usd=usd, direction=direction) res = await MK.call(action, uid=req["uid"], request_id=body["request_id"], **params) if res.get("ok"): _econ_invalidate(req["uid"]) return _keys_response(res) async def api_keys_lock(req): return await _key_mutation(req, "lock") async def api_keys_transfer(req): return await _key_mutation(req, "transfer") async def api_keys_del(req): return await _key_mutation(req, "del") async def api_keys_return_all(req): body, error = await _keys_body(req, mutation=True) if error is not None: return error if set(body) - {"request_id"}: return _keys_error("Возврат всех остатков принимает только request_id") result = await MK.call("return_all", uid=req["uid"], request_id=body["request_id"]) if result.get("ok"): _econ_invalidate(req["uid"]) return _keys_response(result) # ---------- [V3] экономика ---------- def _quests_build(uid): lvl = quest_economy.earned_rank(BOT_DB, uid, BADGES, RANK_REFS, REF_NEW_ID_MIN) data = quest_economy.snapshot(BOT_DB, NEWAPI_DB, uid, lvl) data["rank_name"] = BADGES.get(lvl, BADGES[1])[1] return data def _quest_claim(uid, qid): lvl = quest_economy.earned_rank(BOT_DB, uid, BADGES, RANK_REFS, REF_NEW_ID_MIN) credited, result = quest_economy.claim_daily( BOT_DB, NEWAPI_DB, uid, qid, lvl, allow_checkin=(qid == "checkin")) data = _quests_build(uid) data["claim"] = {"result": result, "credited_usd": credited / float(QUOTA_PER_USD)} return data, result async def api_quests(req): try: data = await asyncio.to_thread(_quests_build, req["uid"]) return web.json_response(data, headers={"Cache-Control": "no-store"}) except sqlite3.Error: log.exception("quests snapshot failed uid=%s", req["uid"]) return web.json_response({"error": "quests_unavailable"}, status=503) async def api_quest_claim(req): body = await _json_body(req) qid = body.get("quest") if qid not in ("msgs", "quiz", "checkin"): return web.json_response({"error": "unknown_quest"}, status=400) try: data, result = await asyncio.to_thread(_quest_claim, req["uid"], qid) if result == "error": return web.json_response({"error": "quest_claim_failed"}, status=503) return web.json_response(data, headers={"Cache-Control": "no-store"}) except sqlite3.Error: log.exception("quest claim failed uid=%s quest=%s", req["uid"], qid) return web.json_response({"error": "quest_claim_failed"}, status=503) _ECON_CACHE = {} # [FIX-2410] Track generations only while builds are in flight; no per-user # history survives the last waiter. The lock also covers mint's worker thread. import threading as _econ_threading _ECON_CACHE_LOCK = _econ_threading.Lock() _ECON_BUILDS = {} def _econ_invalidate(uid): with _ECON_CACHE_LOCK: _ECON_CACHE.pop(uid, None) state = _ECON_BUILDS.get(uid) if state is not None: state[0] = object() async def api_econ(req): uid = req["uid"] now = int(time.time()) with _ECON_CACHE_LOCK: cached = _ECON_CACHE.get(uid) if cached and now - cached[0] < 60: return web.json_response(cached[1]) state = _ECON_BUILDS.setdefault(uid, [object(), 0]) state[1] += 1 try: # [FIX-2410] Retry once if a committed mutation overtakes the read. # Never publish (or return) a snapshot known to have been invalidated. for attempt in range(2): now = int(time.time()) with _ECON_CACHE_LOCK: generation = state[0] # [ECONFIX 19.10] Heavy SQLite stays outside the event loop. data = await asyncio.to_thread(_econ_build, uid, now) if data is None: return web.json_response({"error": "not_found"}, status=404) with _ECON_CACHE_LOCK: if generation is not state[0]: continue # [FIX-2410] Evict oldest insertion, keeping the 1024-entry cap. if uid not in _ECON_CACHE and len(_ECON_CACHE) >= 1024: _ECON_CACHE.pop(next(iter(_ECON_CACHE)), None) _ECON_CACHE[uid] = (now, data) return web.json_response(data) return _db_busy() except sqlite3.Error as error: log.warning("economy snapshot unavailable: %s", type(error).__name__) return _db_busy() finally: with _ECON_CACHE_LOCK: state[1] -= 1 if not state[1]: _ECON_BUILDS.pop(uid, None) def _econ_scope(uid, user, gw): canonical = "tg%d" % int(uid) main = user["token_name"] or None names = {main} if main else set() canonical_bound = main == canonical saved_key = user["api_key"] if "api_key" in user.keys() else None if not canonical_bound and saved_key: key = saved_key[3:] if saved_key.startswith("sk-") else saved_key canonical_bound = gw.execute( "SELECT 1 FROM tokens WHERE name=? AND key IN (?,?) LIMIT 1", (canonical, key, "sk-" + key)).fetchone() is not None if canonical_bound: names.add(canonical) if not main: main = canonical names.add("pm%d" % int(uid)) prefix = canonical + "-k" # Names alone are authoritative here; New API user_id is shared by all bot users. exact = sorted(name for name in names if not re.fullmatch(re.escape(prefix) + r"[0-9]+", name)) return {"main": main, "canonical": canonical if canonical_bound else None, "exact": exact, "extra_prefix": prefix} def _econ_extra_sql(column, prefix): return ("(%s>=? AND %s=?" if start is not None else "") times = (now, start) if start is not None else (now,) names = scope["exact"] exact = "token_name IN (%s)" % ",".join("?" for _ in names) extra, extra_args = _econ_extra_sql("token_name", scope["extra_prefix"]) # Disjoint indexed branches avoid both adjacent UID prefixes and a full log scan. source = ("(SELECT %s FROM logs INDEXED BY idx_logs_token_name WHERE %s AND %s " "UNION ALL SELECT %s FROM logs INDEXED BY idx_logs_token_name WHERE %s AND %s)" % (fields, exact, bounds, fields, extra, bounds)) return source, (*names, *times, *extra_args, *times) def _econ_usage_period(gw, scope, columns, start, now): source, args = _econ_log_source(scope, now, columns, start) rows = gw.execute( "SELECT CASE WHEN model_name IS NULL OR TRIM(model_name)='' THEN NULL ELSE model_name END model," "COALESCE(SUM(quota),0) quota,COUNT(*) requests," "SUM(COALESCE(prompt_tokens,0)+COALESCE(completion_tokens,0)) known_tokens," "SUM(CASE WHEN prompt_tokens IS NULL OR completion_tokens IS NULL THEN 1 ELSE 0 END) unknown_tokens " "FROM " + source + " GROUP BY model ORDER BY quota DESC,model", args).fetchall() models = [] for row in rows: unknown = int(row["unknown_tokens"]) known = int(row["known_tokens"]) quota = int(row["quota"]) models.append({"model": row["model"], "quota": quota, "usd": quota / float(QUOTA_PER_USD), "requests": int(row["requests"]), "tokens": None if unknown else known, "known_tokens": known, "unknown_token_requests": unknown, "tokens_complete": not unknown}) quota = sum(row["quota"] for row in models) known = sum(row["known_tokens"] for row in models) unknown = sum(row["unknown_token_requests"] for row in models) return {"from_ts": start, "to_ts": now, "quota": quota, "usd": quota / float(QUOTA_PER_USD), "requests": sum(row["requests"] for row in models), "tokens": None if unknown else known, "known_tokens": known, "unknown_token_requests": unknown, "tokens_complete": not unknown, "models": models} def _econ_build(uid, now): mid = (now + 10800) // 86400 * 86400 - 10800 week = now - 7 * 86400 d14 = now - 14 * 86400 d30 = now - 30 * 86400 con = _con(BOT_DB) try: u = con.execute("SELECT * FROM users WHERE tg_id=?", (uid,)).fetchone() if u is None: return None rows = con.execute( "SELECT (ts+10800)/86400 d, SUM(units) u FROM econ_tx " "WHERE dst=? AND src=0 AND ts>=? AND ts<=? GROUP BY d", (uid, d14, now)).fetchall() mint_days = {int(x["d"]): int(x["u"] or 0) for x in rows} tx_rows = con.execute("SELECT id, src, dst, units, type, ts FROM econ_tx " "WHERE src=? OR dst=? ORDER BY id DESC LIMIT 40", (uid, uid)).fetchall() finally: con.close() gw = _con(NEWAPI_DB) try: gw.execute("BEGIN") scope = _econ_scope(uid, u, gw) r = gw.execute("SELECT COALESCE(SUM(remain_quota),0) FROM tokens " "WHERE name=? AND deleted_at IS NULL", (scope["main"],)).fetchone() bal = int(r[0] or 0) extra, args = _econ_extra_sql("name", scope["extra_prefix"]) r = gw.execute( "SELECT COALESCE(SUM(remain_quota),0),COUNT(*) FROM tokens " "WHERE (" + extra + " OR name=?) AND name!=? AND deleted_at IS NULL", (*args, scope["canonical"], scope["main"] or "")).fetchone() extras_bal, extras_n = int(r[0] or 0), int(r[1] or 0) columns = {row["name"] for row in gw.execute("PRAGMA table_info(logs)")} source, args = _econ_log_source(scope, now, columns) spent_total = int(gw.execute("SELECT COALESCE(SUM(quota),0) FROM " + source, args).fetchone()[0]) model_usage = {"source": "saved_request_logs", "currency": "USD", "quota_per_usd": QUOTA_PER_USD, "as_of": now, "timezone": "Europe/Moscow"} for period, start in (("day", mid), ("week", week), ("month", d30)): model_usage[period] = _econ_usage_period(gw, scope, columns, start, now) source, args = _econ_log_source(scope, now, columns, d14) rows = gw.execute("SELECT (created_at+10800)/86400 d,SUM(quota) q,COUNT(*) n FROM " + source + " GROUP BY d ORDER BY d", args).fetchall() spend_days = {int(x["d"]): (int(x["q"] or 0), int(x["n"])) for x in rows} models_top = [{"model": row["model"], "usd": row["usd"], "n": row["requests"]} for row in model_usage["month"]["models"]] finally: gw.close() days = [] for i in range(13, -1, -1): dnum = (now + 10800) // 86400 - i dstr = time.strftime("%d.%m", time.gmtime(dnum * 86400 - 10800)) sq, sn = spend_days.get(dnum, (0, 0)) days.append({"d": dstr, "spend_usd": sq / float(QUOTA_PER_USD), "requests": sn, "mint_usd": mint_days.get(dnum, 0) / float(QUOTA_PER_USD)}) tx = [] for r in tx_rows: t = r["type"] or "" out = r["src"] == uid direction = "out" if out else "in" if t.startswith("web:ktr_from"): direction = "in" elif t.startswith("web:ktr_to"): direction = "out" tx.append({"type": t, "amount_usd": (r["units"] * 100 // QUOTA_PER_USD) / 100.0, "direction": direction, "peer": r["dst"] if out else r["src"], "ts": r["ts"]}) return { "balance_usd": bal / float(QUOTA_PER_USD), "extras_n": extras_n, "extras_usd": extras_bal / float(QUOTA_PER_USD), "spent_total_usd": spent_total / float(QUOTA_PER_USD), "spent_today_usd": model_usage["day"]["usd"], "spent_week_usd": model_usage["week"]["usd"], "req_today": model_usage["day"]["requests"], "req_30d": model_usage["month"]["requests"], "days": days, "models_top": models_top, "tx": tx, "model_usage": model_usage, } # ---------- v2 endpoints ---------- def _me_sync(uid): # [FIX-2410] sync sqlite вынесен из event loop (как _econ_build + to_thread) con = _con(BOT_DB) try: u = con.execute("SELECT * FROM users WHERE tg_id=?", (uid,)).fetchone() if not u: return {"error": "not_found"}, 404 refs = refs_weighted(con, uid) lvl = rank_of(u, refs) em, name, rep_req, days_req = BADGES[lvl] days = max(0, (int(time.time()) - int(u["created"] or 0)) // 86400) if u["created"] else 0 nxt = BADGES.get(lvl + 1) progress = None if nxt: _, nname, nrep, ndays = nxt progress = {"next": nname, "days": days, "days_req": ndays, "refs": refs, "refs_req": RANK_REFS[lvl + 1], "rep": u["rep"] or 0, "rep_req": nrep} refs_count = con.execute("SELECT COUNT(*) FROM users WHERE referred_by=? AND ref_awarded=1", (uid,)).fetchone()[0] try: balances = _account_balances(uid, dict(u)) except Exception: log.exception("api_me: чтение баланса не удалось") return {"error": "db_busy"}, 503 return { "uid": uid, "username": u["username"], "rank": lvl, "rank_name": name, "rank_emoji": em, "balance_usd": balances["main_balance_usd"], **balances, "points": u["points"] or 0, "rep": u["rep"] or 0, "days": days, "refs": refs, "refs_count": refs_count, "chat_count": u["chat_count"] or 0, "img_count": u["img_count"] or 0, "created": u["created"], "last_active": u["last_active"], "chat_model": u["chat_model"], "vip": u["vip"] or 0, "ref_link": "https://t.me/iishkogatewaybot?start=ref%d" % uid, "progress": progress, "keys_cap": MK_CAP.get(lvl, 2), "weekly_credit_usd": RANK_WEEK.get(lvl, 500), "ranks_detail": _ranks_detail(), }, 200 finally: con.close() async def api_me(req): # [FIX-2410] translate DB open/read failures at the HTTP boundary. try: data, status = await asyncio.to_thread(_me_sync, req["uid"]) except sqlite3.Error: log.exception("api_me: database unavailable") return _db_busy() return web.json_response(data, status=status) # [MSTATUS 1910] синхронизация TIER_MODELS/MODEL_DESCS/TIER_TITLES с АКТИВНЫМ ботом + live-статусы моделей import threading as _ms_threading import urllib.request as _ms_urlreq import urllib.error as _ms_urlerr # [CATLIVE 2310] источник каталога — iishko_bot.py (grok_bot.py в проде не запускается). # IISHKO_BOT_SOURCE/IISHKO_APP_ROOT задают тот же путь для портов и тестов. BOT_SOURCE = str(commerce_access._source()) CATALOG_TTL = 20.0 def _ms_load_bot_consts(path=None): """AST-читает каталог активного бота и возвращает (consts, error). Прежний молчаливый return {} скрывал, что webapp остался на устаревшем списке рангов.""" import ast try: with open(path or BOT_SOURCE, encoding="utf-8") as bot_source: tree = ast.parse(bot_source.read()) except Exception as error: return {}, type(error).__name__ out = {} for node in tree.body: if isinstance(node, ast.Assign): for tgt in node.targets: if isinstance(tgt, ast.Name) and tgt.id in ('TIER_MODELS', 'MODEL_DESCS', 'TIER_TITLES', 'MEDIA_MODELS'): try: out[tgt.id] = ast.literal_eval(node.value) except Exception: pass if not out.get('TIER_MODELS'): return out, "TIER_MODELS_NOT_FOUND" return out, None _CATALOG = {"source": "fallback", "loaded_at": 0.0, "error": "", "mtime": None, "next_try": 0.0} _MEDIA_MODELS = {} _MEDIA_CACHE = {"key": None, "until": 0.0, "configured": {}, "error": None, "checked_at": None} _MEDIA_CACHE_LOCK = _ms_threading.Lock() _MEDIA_CACHE_TTL = 20.0 def _media_manifest(value): """Accept only a bounded literal discovery manifest; never import the bot.""" if not isinstance(value, dict) or not 1 <= len(value) <= 64: return {} for name, item in value.items(): if not isinstance(name, str) or not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._/-]{0,127}", name): return {} if not isinstance(item, dict) or item.get("kind") not in ("image", "video"): return {} if (type(item.get("bot_supported")) is not bool or type(item.get("default")) is not bool or not isinstance(item.get("desc"), str) or not 1 <= len(item["desc"]) <= 300 or item.get("configured_via") not in ("gateway", "direct") or item.get("selection_mode") != ("exact" if item["kind"] == "image" else "preference")): return {} if item["bot_supported"]: encoded = base64.urlsafe_b64encode(name.encode("utf-8")).decode("ascii").rstrip("=") if len("media_" + item["kind"] + "_" + encoded) > 64: return {} return value def _media_catalog_snapshot(): manifest = _MEDIA_MODELS gateway_ids = tuple(name for name, item in manifest.items() if item["configured_via"] == "gateway") key = (NEWAPI_DB, gateway_ids) with _MEDIA_CACHE_LOCK: if _MEDIA_CACHE["key"] != key or time.monotonic() >= _MEDIA_CACHE["until"]: configured = dict.fromkeys(gateway_ids) error, checked_at, con = None, None, None if gateway_ids: try: from pathlib import Path con = sqlite3.connect(Path(NEWAPI_DB).resolve().as_uri() + "?mode=ro", uri=True, timeout=0.25) con.execute("PRAGMA query_only=ON") deadline = time.monotonic() + 0.25 con.set_progress_handler(lambda: int(time.monotonic() >= deadline), 1000) rows = con.execute( "SELECT DISTINCT a.model FROM abilities AS a " "JOIN channels AS c ON c.id=a.channel_id " "WHERE a.enabled=1 AND c.status=1 AND a.model IN (" + ",".join("?" for _ in gateway_ids) + ") LIMIT ?", (*gateway_ids, len(gateway_ids))).fetchall() present = {row[0] for row in rows} configured = {name: name in present for name in gateway_ids} checked_at = int(time.time()) except (sqlite3.Error, OSError, TypeError, ValueError): error = "configured_state_unavailable" finally: if con is not None: con.close() _MEDIA_CACHE.update(key=key, until=time.monotonic() + _MEDIA_CACHE_TTL, configured=configured, error=error, checked_at=checked_at) states = dict(_MEDIA_CACHE["configured"]) meta = {"catalog": "bot" if manifest else "unavailable", "configured_source": "gateway_abilities", "configured_status": "ok" if gateway_ids and not _MEDIA_CACHE["error"] else "unknown", "configured_error": _MEDIA_CACHE["error"] if manifest else "catalog_unavailable", "checked_at": _MEDIA_CACHE["checked_at"], "cache_seconds": int(_MEDIA_CACHE_TTL), "generation_probed": False} media = {"image": [], "video": []} for name, item in manifest.items(): launch_url = None if item["bot_supported"]: encoded = base64.urlsafe_b64encode(name.encode("utf-8")).decode("ascii").rstrip("=") launch_url = "https://t.me/iishkogatewaybot?start=media_" + item["kind"] + "_" + encoded media[item["kind"]].append({ "name": name, "kind": item["kind"], "desc": item["desc"], "bot_supported": item["bot_supported"], "configured": states.get(name), "health": "unknown", "selection_mode": item["selection_mode"], "default": item["default"], "launch_url": launch_url}) return media, meta def _catalog_with_media(): media, meta = _media_catalog_snapshot() _CATALOG.update(media=media, media_meta=meta) return _CATALOG def _refresh_bot_catalog(force=False): """Перечитывает каталог активного бота, когда его исходник изменился: бот правят на лету, а webapp без рестарта отдавал снимок литералов этого файла. При ошибке держит последний хороший каталог — устаревшие литералы не подменяют живой список молча.""" global TIER_MODELS, MODEL_DESCS, TIER_TITLES, _MEDIA_MODELS now = time.time() if not force and now < _CATALOG["next_try"]: # отрицательный кэш: не парсить бота на каждый запрос return _catalog_with_media() try: mtime = os.path.getmtime(BOT_SOURCE) except OSError as error: _CATALOG["error"] = type(error).__name__ _CATALOG["next_try"] = now + CATALOG_TTL log.warning("бот-каталог недоступен (%s): держим источник %s", _CATALOG["error"], _CATALOG["source"]) return _catalog_with_media() if _CATALOG["source"] == "bot" and mtime == _CATALOG["mtime"] and not force: return _catalog_with_media() consts, error = _ms_load_bot_consts() if error: _CATALOG["error"] = error _CATALOG["next_try"] = now + CATALOG_TTL log.warning("бот-каталог не обновлён (%s): держим источник %s", error, _CATALOG["source"]) return _catalog_with_media() TIER_MODELS = consts['TIER_MODELS'] if consts.get('MODEL_DESCS'): MODEL_DESCS = consts['MODEL_DESCS'] if consts.get('TIER_TITLES'): TIER_TITLES = consts['TIER_TITLES'] _MEDIA_MODELS = _media_manifest(consts.get('MEDIA_MODELS')) _CATALOG.update(source="bot", loaded_at=now, error="", mtime=mtime, next_try=now + CATALOG_TTL) return _catalog_with_media() # [KEYGATE 2810] живой каталог бота может содержать только плоские tier-имена, тогда как # ACL и ранги не переписываются, видимость плоских имён не меняется. _SLASH_RANK_TWINS = { "kimi/kimi-k3.1-pro": "kimi-k3.1-pro", "kimi/kimi-k3.1-pro-highspeed": "kimi-k3.1-pro-highspeed", } def _model_min_rank(name, tiers=None): """Ранг модели по живому каталогу; None = в каталоге её нет (алиасы/снятые имена). Точное совпадение всегда в приоритете; для канонических slash-имён Kimi 3.1 ранг берётся у их плоского двойника, если точного тира в живом каталоге нет.""" tiers = TIER_MODELS if tiers is None else tiers ranks = [rank for rank, group in tiers.items() if name in group] if ranks: return min(ranks) twin = _SLASH_RANK_TWINS.get(name) if twin: twin_ranks = [rank for rank, group in tiers.items() if twin in group] if twin_ranks: return min(twin_ranks) return None def _rank_name(rank): """Название ранга без 500 на случай нового тира в активном боте.""" for table in (BADGES, TIER_TITLES): label = (table.get(rank) or (None, None))[1] if label: return label return "ранг %s" % rank _refresh_bot_catalog() if _CATALOG["source"] != "bot": log.warning("каталог активного бота не прочитан (%s): webapp на резервном списке", _CATALOG["error"]) _MS = {"data": {}, "ts": 0, "order": []} def _ms_key(): try: con = _con(NEWAPI_DB) r = con.execute("SELECT key FROM tokens WHERE user_id=1 AND status=1 AND deleted_at IS NULL ORDER BY id LIMIT 1").fetchone() con.close() return ("sk-" + r["key"] if not r["key"].startswith("sk-") else r["key"]) if r and r["key"] else None except Exception: return None # [PRICES 2010] per-1M-token pricing from new-api ModelRatio/CompletionRatio options _PRICES = {"data": {}, "ts": 0.0} def _load_prices(): import sqlite3 as _sq, json as _js con = _sq.connect(NEWAPI_DB, timeout=15) try: mr = _js.loads(con.execute("SELECT value FROM options WHERE key='ModelRatio'").fetchone()[0]) row = con.execute("SELECT value FROM options WHERE key='CompletionRatio'").fetchone() cr = _js.loads(row[0]) if row else {} finally: con.close() out = {} for m, r in mr.items(): try: r = float(r) except (TypeError, ValueError): continue p_in = r * 1_000_000 / QUOTA_PER_USD # $ per 1M input tokens p_out = r * float(cr.get(m, 1) or 1) * 1_000_000 / QUOTA_PER_USD out[m] = {"p_in": round(p_in, 4), "p_out": round(p_out, 4)} return out def _prices(): if time.time() - _PRICES["ts"] > 600: try: _PRICES["data"] = _load_prices() _PRICES["ts"] = time.time() except Exception: pass return _PRICES["data"] # [UPTIME 2310] статус модели = результат РЕАЛЬНОЙ пробы /chat/completions, не «маршрутизуемость» # из конфига. Цикл просыпается каждую минуту и ПОПЫТАЕТСЯ проверить каждую модель каталога: # ограниченная concurrency (_MS_CONCURRENCY параллельных проб) + жёсткий deadline цикла # Если модель не успела пройти проверку за deadline — её данные честно стареют (checked_at), # экран показывает «Не проверена», в api_models отдаётся coverage; фиктивного «Работает» нет. _MS_CADENCE = 60.0 # цикл проб просыпается раз в минуту _MS_CYCLE_DEADLINE = 50.0 # бюджет цикла < каденса: циклы не наслаиваются _MS_CONCURRENCY = 4 # одновременно не больше N проб: щадим и шлюз, и кредит _MS_PROBE_TIMEOUT = 18.0 # верхняя граница одной пробы (влезает в deadline по остатку) _MS_STALE_AFTER = int(2 * _MS_CADENCE) # старше 2 циклов без проверки = «Не проверена» (UNKNOWN) _ms_cycle_lock = _ms_threading.Lock() from concurrent.futures import ThreadPoolExecutor as _MsExecutor, wait as _ms_futures_wait _MS_POOL = _MsExecutor(max_workers=_MS_CONCURRENCY, thread_name_prefix="ms-probe") def _ms_probe_once(key, model, timeout=18): body = json.dumps({"model": model, "messages": [{"role": "user", "content": "hi"}], "max_tokens": 5}).encode() t0 = time.monotonic() rq = _ms_urlreq.Request(PUBLIC_BASE + "/chat/completions", data=body, headers={"Content-Type": "application/json", "Authorization": "Bearer " + key}) try: with _ms_urlreq.urlopen(rq, timeout=timeout) as resp: # [PROBE3 2310] аргумент, не литерал 18 data = json.loads(resp.read()) ch0 = (data.get("choices") or [{}])[0] content = (ch0.get("message") or {}).get("content") rcontent = (ch0.get("message") or {}).get("reasoning_content") # Preserve the production fix: short reasoning probes can exhaust the output budget. ok = (isinstance(content, str) and bool(content.strip())) or (isinstance(rcontent, str) and bool(rcontent.strip())) or ch0.get("finish_reason") == "length" return {"up": 1 if ok else None, "status": "up" if ok else "unknown", "ms": int((time.monotonic() - t0) * 1000), "checked_at": int(time.time())} except _ms_urlerr.HTTPError as ex: if ex.code in (401, 402, 403): return {"up": None, "status": "unknown", "http_status": ex.code, "checked_at": int(time.time())} busy = ex.code == 429 or ex.code >= 500 return {"up": None if busy else 0, "status": "busy" if busy else "down", "http_status": ex.code, "checked_at": int(time.time())} except Exception: return {"up": None, "status": "unknown", "checked_at": int(time.time())} def _ms_probe_timeout(left): return _MS_PROBE_TIMEOUT if left is None else max(1.0, min(_MS_PROBE_TIMEOUT, left)) class _ProbeExpired(Exception): """[PROBE3 2310] deadline цикла уже истёк: проба не стартует — ни запроса, ни кредита.""" def _ms_probe_one(key, model, deadline=None): # [PROBE2 2010] down только после 2 подряд фейлов (фикс ложных 429/burst). # [UPTIME 2310] ретрай обязан влезать в deadline цикла: без запаса возвращаем первый # результат как есть — «не успели проверить» честнее лишней пробы. # [PROBE3 2310] раньше просроченная проба всё равно стреляла запросом (max(1.0, left)): # кредит тратился ПОСЛЕ истечения бюджета цикла. Теперь — отказ до любого запроса. def left(): return None if deadline is None else deadline - time.monotonic() spare = left() if spare is not None and spare <= 0: raise _ProbeExpired() r = _ms_probe_once(key, model, _ms_probe_timeout(spare)) if r.get("up") or r.get("http_status") in (401, 402, 403): return r spare = left() if spare is not None and spare <= 1.6: return r time.sleep(1.5 if spare is None else min(1.5, spare - 0.1)) spare = left() if spare is not None and spare <= 0: return r return _ms_probe_once(key, model, _ms_probe_timeout(spare)) def _ms_model_order(): """Живой каталог тиров без дублей и скрытых публичных алиасов (их никто не видит — тратить на них проб-кредит нечестно).""" names, seen = [], set() for tier in sorted(TIER_MODELS): for m in TIER_MODELS.get(tier, []): if m not in seen and not _is_hidden_public_alias(m): seen.add(m) names.append(m) return names def _ms_cycle(): """Один цикл: попытка проверить КАЖДУЮ модель каталога за deadline с ограниченной concurrency. В историю пишутся только пробы, реально завершившиеся до deadline; не успевшие модели сохраняют свой старый checked_at и после _MS_STALE_AFTER честно показываются «Не проверена». Возврат — coverage-слепок цикла.""" if not _ms_cycle_lock.acquire(blocking=False): return {"fresh": 0, "total": 0, "skipped_busy": True} try: _refresh_bot_catalog() # [CATLIVE 2310] пробы идут по живому каталогу, не по снимку импорта order = _ms_model_order() if order != _MS["order"]: _MS["order"] = list(order) key = _ms_key() fresh = {} if key and order: deadline = time.monotonic() + _MS_CYCLE_DEADLINE futures = {m: _MS_POOL.submit(_ms_probe_one, key, m, deadline) for m in order} _ms_futures_wait(set(futures.values()), timeout=max(0.0, deadline - time.monotonic())) # стартовавшие ограничены urlopen-timeout по остатку и ретрай-гвардом ≤1.6с: # хвост < deadline + ~1с при каденсе 60с, новый цикл наслаивания не даёт. for fut in futures.values(): if not fut.done(): fut.cancel() for m, fut in futures.items(): if fut.done() and not fut.cancelled(): try: fresh[m] = fut.result() except Exception: pass # не прошедшая проба = не свежая: модель остаётся со своим возрастом order_set = set(order) data = {m: v for m, v in (_MS.get("data") or {}).items() if m in order_set} data.update(fresh) _MS["data"] = data if fresh: _MS["ts"] = time.time() try: model_uptime.record_batch(UPTIME_DB, fresh) except Exception: log.exception("Model history persistence failed") return {"fresh": len(fresh), "total": len(order)} finally: _ms_cycle_lock.release() def _ms_loop(): while True: started = time.monotonic() try: _ms_cycle() except Exception: log.exception("Model probe cycle failed") # старт-к-старту = max(каденс, длительность цикла): циклы не наслаиваются, # даже если цикл упёрся в deadline time.sleep(max(0.0, _MS_CADENCE - (time.monotonic() - started))) async def api_models(req): await asyncio.to_thread(_refresh_bot_catalog) # [CATLIVE 2310] каталог = активный бот prices = await asyncio.to_thread(_prices) statuses = _MS.get("data") or {} now = int(time.time()) # [HIDDEN 2310] публичные алиасы codai* в списки не отдаём (см. _is_hidden_public_alias) names = [m for m in dict.fromkeys(m for group in TIER_MODELS.values() for m in group) if not _is_hidden_public_alias(m)] uptime = await asyncio.to_thread(model_uptime.history, UPTIME_DB, names) models = [] for name in names: status = statuses.get(name) or {} min_rank = _model_min_rank(name) or 1 models.append({"name": name, "desc": MODEL_DESCS.get(name, ""), "available": req["rank"] >= min_rank, "min_rank": min_rank, "rank_name": _rank_name(min_rank), **status, **prices.get(name, {}), "uptime": uptime["models"].get(name)}) # [MODELMETA 2026-10-28] vendor reference for the catalogue row (context window / # maximum output as advertised by the vendor, gateway_verified=false). Additive only: # the visible list, ranks and availability above stay exactly as filtered. reference = _model_metadata_rows([m["name"] for m in models]) if reference is not None: for row in models: row["model_metadata"] = reference[row["name"]] for row in models: row["provider_moderation"] = provider_moderation_for_model(row["name"]) # [UPTIME 2310] coverage: сколько моделей реально проверено в свежем окне. Не успевшие # за deadline видны как «Не проверена» (status отсутствует/устарел) — фиктивного «Работает» нет. checked = sum(1 for m in models if now - int(m.get("checked_at") or 0) <= _MS_STALE_AFTER) return web.json_response({"models": models, "total": len(models), "available_count": sum(m["available"] for m in models), "access": "ranked", "user_rank": req["rank"], "ranks": [{"rank": rank, "name": _rank_name(rank), "models_count": sum(m["min_rank"] <= rank for m in models)} for rank in sorted(TIER_MODELS)], "status_ts": _MS.get("ts", 0), "status_stale_after": _MS_STALE_AFTER, "status_checked": checked, "probe_cadence": int(_MS_CADENCE), "probe_deadline": int(_MS_CYCLE_DEADLINE), "probe_concurrency": _MS_CONCURRENCY, "history_hours": uptime["hours"], "history_generated_at": uptime["generated_at"], "catalog": _CATALOG["source"], "media": _CATALOG.get("media", {"image": [], "video": []}), "media_meta": _CATALOG.get("media_meta", { "catalog": "unavailable", "configured_status": "unknown", "generation_probed": False})}) async def api_top(req): # [RANKS 2810] one public leaderboard endpoint: kind=referrals|requests|tokens|models, # period=day|week|month (all only for referrals). Sync sqlite stays off the event loop; # bad parameters are 400 and database faults are an honest 503, never zero rows. kind = req.query.get("kind") period = req.query.get("period") limit = req.query.get("limit") try: data = await asyncio.to_thread( rankings.top, BOT_DB, NEWAPI_DB, kind, period, None, limit) except ValueError as exc: return web.json_response({"error": "bad_request", "msg": str(exc)}, status=400) except sqlite3.Error: log.exception("api_top: database unavailable") return _db_busy() return web.json_response(data) def _tx_sync(uid): # [FIX-2410] sync sqlite вынесен из event loop con = _con(BOT_DB) try: rows = con.execute( "SELECT id, src, dst, units, type, ts FROM econ_tx WHERE src=? OR dst=? ORDER BY id DESC LIMIT 50", (uid, uid)).fetchall() finally: con.close() out = [] for r in rows: t = r["type"] or "" direction = "out" if r["src"] == uid else "in" if t.startswith("web:ktr_from"): direction = "in" elif t.startswith("web:ktr_to"): direction = "out" out.append({"type": t, "amount_usd": (r["units"] * 100 // QUOTA_PER_USD) / 100.0, "direction": direction, "peer": r["dst"] if r["src"] == uid else r["src"], "ts": r["ts"]}) return {"tx": out}, 200 async def api_tx(req): # [FIX-2410] translate DB open/read failures at the HTTP boundary. try: data, status = await asyncio.to_thread(_tx_sync, req["uid"]) except sqlite3.Error: log.exception("api_tx: database unavailable") return _db_busy() return web.json_response(data, status=status) LEGACY_REQS = 142_595 # [MAXROWID-FIX 23.10] синхрон с grok_bot._gateway_stats (LEGACY_REQS) def _global_sync(): # [FIX-2410] sync sqlite вынесен из event loop con = _con(BOT_DB) # [FIX-2410] close the BOT connection even when a SELECT fails. try: users = con.execute("SELECT COUNT(*) FROM users").fetchone()[0] active = con.execute("SELECT COUNT(*) FROM users WHERE last_active>?", (int(time.time()) - 86400,)).fetchone()[0] finally: con.close() models = len({m for t in TIER_MODELS.values() for m in t}) gw = _con(NEWAPI_DB) try: # [MAXROWID-FIX 23.10] MAX(rowid) = high-water mark вместе с удалёнными строками # (ретенция съела 1.62M строк) -> завышало счётчик на ~1.1M. Считаем реальные billing-события. requests = int(gw.execute("SELECT COALESCE(SUM(count),0) FROM quota_data").fetchone()[0] or 0) + LEGACY_REQS finally: gw.close() return {"users": users, "active24": active, "models": models, "requests": requests}, 200 async def api_global(req): # [FIX-2410] translate DB open/read failures at the HTTP boundary. try: data, status = await asyncio.to_thread(_global_sync) except sqlite3.Error: log.exception("api_global: database unavailable") return _db_busy() return web.json_response(data, status=status) def _daily_status_sync(uid): rank = quest_economy.earned_rank(BOT_DB, uid, BADGES, RANK_REFS, REF_NEW_ID_MIN) return daily_checkin.status(BOT_DB, NEWAPI_DB, uid, rank=rank) def _daily_claim_sync(uid): rank = quest_economy.earned_rank(BOT_DB, uid, BADGES, RANK_REFS, REF_NEW_ID_MIN) return daily_checkin.claim(BOT_DB, NEWAPI_DB, uid, rank, source="miniapp") def _daily_http_status(data): if data.get("ok"): return 200 error = data.get("error") if error in ("blocked", "user"): return 403 if error == "wallet": return 409 if error == "bad_input": return 400 return 503 async def api_bonus(req): try: data = await asyncio.to_thread(_daily_status_sync, req["uid"]) except sqlite3.Error: log.exception("api_bonus: database unavailable") return _db_busy() return web.json_response(data, status=_daily_http_status(data), headers={"Cache-Control": "no-store"}) async def api_daily(req): try: body = await req.json() except (ValueError, UnicodeError, RecursionError): raise web.HTTPBadRequest(text='{"error":"bad_request"}', content_type="application/json") from None if not isinstance(body, dict): raise web.HTTPBadRequest(text='{"error":"bad_request"}', content_type="application/json") # The authenticated account and earned rank are server-authoritative. # No client-provided face, uid or amount participates in a payout. try: data = await asyncio.to_thread(_daily_claim_sync, req["uid"]) except sqlite3.Error: log.exception("api_daily: database unavailable") return _db_busy() return web.json_response(data, status=_daily_http_status(data), headers={"Cache-Control": "no-store"}) async def api_retired_bonus(req): return web.json_response({ "error": "retired", "msg": "Старые игры и задания заменены «Нейролабом». Перезапусти Mini App и открой расследование.", }, status=410) def _key_sync(uid): # [FIX-2410] sync sqlite вынесен из event loop; молчаливый fallback -> честный 503 con = _con(BOT_DB) # [FIX-2410] close the BOT connection even when its SELECT fails. try: u = con.execute("SELECT token_name, key_locked, created FROM users WHERE tg_id=?", (uid,)).fetchone() finally: con.close() key = None remain = 0 gw = _con(NEWAPI_DB) try: names = [] if u and u["token_name"]: names.append(u["token_name"]) d = "tg%d" % int(uid) if d not in names: names.append(d) for nm in names: r = gw.execute("SELECT `key`, remain_quota FROM tokens WHERE name=? AND deleted_at IS NULL " "ORDER BY id DESC LIMIT 1", (nm,)).fetchone() if r: key, remain = r[0], int(r[1]) break except Exception: # [FIX-2410] было: except Exception: pass (молчаливый fallback) log.exception("api_key: чтение NEWAPI_DB не удалось") return {"error": "db_busy"}, 503 finally: gw.close() masked = _mask(key) return { "has_key": bool(key), "masked": masked, "token_name": (u["token_name"] if u else None), "key_locked": int(u["key_locked"] or 0) if u else 0, "remain_usd": remain / float(QUOTA_PER_USD), "base_url": PUBLIC_BASE, "reveal_note": "Полный ключ — во вкладке «Ключи» через капчу", }, 200 async def api_key(req): # [FIX-2410] includes primary BOT_DB and NEWAPI_DB connection failures. try: data, status = await asyncio.to_thread(_key_sync, req["uid"]) except sqlite3.Error: log.exception("api_key: database unavailable") return _db_busy() return web.json_response(data, status=status) def _boards_sync(): # [FIX-2410] sync sqlite вынесен из event loop; молчаливый fallback -> честный 503 con = _con(BOT_DB) try: def uname_of(uid): u = con.execute("SELECT username FROM users WHERE tg_id=?", (uid,)).fetchone() return rankings.public_user(uid, u["username"] if u else None) rich = [] gw = _con(NEWAPI_DB) try: # Authorized wallets are the same set the spend guard accepts (status 1 or 4, try: rows = gw.execute( "SELECT name, MAX(COALESCE(remain_quota,0)) q FROM tokens " "WHERE (name GLOB 'tg[0-9]*' OR name GLOB 'pm[0-9]*' OR name GLOB 'sol[0-9]*') " "AND status IN (1,4) AND COALESCE(deleted_at,0)=0 " "GROUP BY name").fetchall() finally: gw.close() wallets = {} for r in rows: uid = rankings.account_uid(r["name"]) if uid is None: continue wallets[uid] = wallets.get(uid, 0) + int(r["q"] or 0) for i, (uid, quota) in enumerate(sorted( wallets.items(), key=lambda kv: (-kv[1], kv[0]))[:12]): rich.append({"pos": i + 1, "user": uname_of(uid), "usd": quota / float(QUOTA_PER_USD)}) except Exception: # [FIX-2410] было: except Exception: pass (молчаливый fallback) log.exception("api_boards: чтение NEWAPI_DB не удалось") return {"error": "db_busy"}, 503 week = int(time.time()) - 7 * 86400 casino = [] rows = con.execute( "SELECT src, COUNT(*) n FROM econ_tx WHERE ts>=? AND src!=0 AND " "(type LIKE 'cas:%' OR type LIKE 'duel:%' OR type LIKE 'jpot%') " "GROUP BY src ORDER BY n DESC LIMIT 12", (week,)).fetchall() for i, r in enumerate(rows): casino.append({"pos": i + 1, "user": uname_of(r["src"]), "n": r["n"]}) return {"rich": rich, "casino": casino}, 200 finally: con.close() async def api_boards(req): # [FIX-2410] includes primary BOT_DB and NEWAPI_DB connection failures. try: data, status = await asyncio.to_thread(_boards_sync) except sqlite3.Error: log.exception("api_boards: database unavailable") return _db_busy() return web.json_response(data, status=status) # Stateless assistant and game progress share authenticated identity, not owner credentials. # 98.9% uptime за последние сутки. В авто-режиме он остаётся после Opus, чтобы дешёвые модели шли первыми. AGENT_MODELS_WA = ["grok-4.7", "kimi-k3", "claude-opus-5-5", "claude-sonnet-5", "kimi/kimi-k3.1-pro", "kimi/kimi-k3.1-pro-highspeed", "deepseek-v4.1-flash-1017", "glm-5.3-flash", "qwen3.8-max-0902", "qwen-plus", "gpt-5.6-luna", "gpt-5.6-terra", "gpt-5.6-sol", "gpt-6.1-sol", "gpt-6.1-sol-thinking", "gpt-5.5", "gpt-5.5-pro"] def _agent_pool(): """Модели агента = список рантайма, пересечённый с живым каталогом активного бота. Имена, отсутствующие в действующих тирах бота, не предлагаются и не подставляются. [HIDDEN 2310] публичные алиасы codai* не предлагаются ни одному рангу: за ними в шлюзе может стоять другой upstream. Скрытие — только списки; авторизацию шлюза (token_limits/ abilities) согласует владелец, webapp подмены моделей не делает.""" return [m for m in AGENT_MODELS_WA if _model_min_rank(m) is not None and not _is_hidden_public_alias(m)] def _agent_models_for(rank): try: rank = max(1, int(rank)) except (TypeError, ValueError): rank = 1 return [m for m in _agent_pool() if _model_min_rank(m) <= rank] def _agent_key_limits_error(): return AssistantError(503, "key_limits_unavailable", "Не удалось проверить доступные модели твоего API-ключа. Попробуй позже.") def _agent_key_model_limits(uid): try: key = _ASSISTANT.user_key(uid) except sqlite3.Error: raise _agent_key_limits_error() from None if not isinstance(key, str) or not key: raise _agent_key_limits_error() plain = key[3:] if key.startswith("sk-") else key try: with closing(_ASSISTANT.connect(_ASSISTANT.newapi_db)) as con: rows = con.execute( "SELECT model_limits_enabled,model_limits FROM tokens " "WHERE key IN (?,?) AND status=1 AND deleted_at IS NULL LIMIT 2", (plain, key)).fetchall() except sqlite3.Error: raise _agent_key_limits_error() from None if len(rows) != 1: raise AssistantError(403, "key_ambiguous", "Не удалось однозначно определить API-ключ. Создай новый ключ во вкладке «Ключи».") enabled, limits = rows[0][0], rows[0][1] if isinstance(enabled, bool): enabled = bool(enabled) elif type(enabled) is int and enabled in (0, 1): enabled = bool(enabled) else: raise _agent_key_limits_error() if not enabled: return None if not isinstance(limits, str): raise _agent_key_limits_error() return frozenset(name.strip() for name in limits.split(",") if name.strip()) def _agent_models_for_key(ranked, limits): if limits is None: return list(ranked) return [name for name in ranked if name in limits] def _agent_key_reject_details(uid, operation_id): """[KEYGATE 2810] Pre-admission 403 до _ASSISTANT.chat: операция точно не стартовала. UI вправе показать «не допущено» (state=not_found, uncertain=False), но только если этот operation_id ещё не регистрировался и не завершался: повтор с тем же id мог уже выполнить действия. Тогда не утверждаем not_found — остаётся обычный rejected.""" details = {"operation_id": operation_id} try: operations = getattr(_ASSISTANT, "operations", None) finished = getattr(_ASSISTANT, "finished", None) if not isinstance(operations, dict) or not isinstance(finished, dict): return details current = operations.get(uid) if current is not None and getattr(current, "operation_id", None) == operation_id: return details if (uid, operation_id) in finished: return details except Exception: return details details.update(state="not_found", uncertain=False, side_effect_started=False) return details _agent_base = CFG.get("newapi_url", "http://127.0.0.1:48000").rstrip("/") if not _agent_base.endswith("/v1"): _agent_base += "/v1" _ASSISTANT = AssistantRuntime( BOT_DB, NEWAPI_DB, _agent_base, AGENT_MODELS_WA, reminder_store, os.environ.get("GROK_SANDBOX_CONFIG", os.path.join(BASE, os.pardir, "sandbox.json"))) _SUPPORT = SupportStore(os.environ.get("GROK_SUPPORT_DB", os.path.join(os.path.dirname(BOT_DB), "support.db"))) _NPC_BUSY = set() _NPC_RATE = {} async def _json_body(req): try: body = await req.json() except (ValueError, UnicodeDecodeError, RecursionError): raise AssistantError(400, "bad_json", "Не удалось прочитать запрос. Ожидается JSON-объект.") from None if not isinstance(body, dict): raise AssistantError(400, "invalid_body", "Ожидается JSON-объект.") return body async def api_agent_models(req): # Health and entitlement are separate. A temporary outage must not silently change a saved selection. catalog = await asyncio.to_thread(_refresh_bot_catalog) rank = max(1, int(req.get("rank") or 1)) locked = [{"name": name, "min_rank": _model_min_rank(name), "rank_name": _rank_name(_model_min_rank(name))} for name in _agent_pool() if _model_min_rank(name) > rank] ranked = _agent_models_for(rank) limits = await asyncio.to_thread(_agent_key_model_limits, req["uid"]) models = _agent_models_for_key(ranked, limits) key_unavailable = ([{"name": name, "reason": "key_model_limit"} for name in ranked if name not in limits] if limits is not None else []) # [SANDBOX 2310] честный текущий флаг, а не «активна навсегда после первого exec». payload = {"models": models, "auto": True, "user_rank": rank, "locked": locked, "catalog": catalog["source"], "key_unavailable": key_unavailable, "sandbox_enabled": os.environ.get("IISHKO_SANDBOX_ENABLED") == "1"} # [MODELMETA 2026-10-28] vendor reference keyed by the allowed ids only (same list the reference = _model_metadata_rows(models) if reference is not None: payload["model_metadata"] = reference if not models: payload["msg"] = ("На твоём текущем API-ключе нет ни одной доступной модели — создай новый ключ " "во вкладке «Ключи» или напиши в поддержку." if key_unavailable else "Сейчас нет доступных моделей — обнови экран позже.") return web.json_response(payload) async def api_agent_history(req): await asyncio.to_thread(_ASSISTANT.user, req["uid"]) messages, generation = await asyncio.to_thread(_ASSISTANT.history, req["uid"]) return web.json_response({"messages": messages, "generation": generation, "persistent": False}) async def api_agent_history_clear(req): await asyncio.to_thread(_ASSISTANT.user, req["uid"]) await asyncio.to_thread(_ASSISTANT.clear_history, req["uid"]) return web.json_response({"ok": True}) async def _agent_with_attachment(body, attachment): """Вложение Mini App: base64 -> текст через file_intake (без диска/БД/сети). Возвращает (body, info). Текст добавляется к последнему user-сообщению.""" if not isinstance(attachment, dict): raise AssistantError(400, "bad_attachment", "Вложение повреждено — прикрепи файл заново.") name = str(attachment.get("name") or "file")[:120] raw = attachment.get("data") if not isinstance(raw, str) or not raw: raise AssistantError(400, "bad_attachment", "Пустое вложение — прикрепи файл заново.") if len(raw) > 12 * 1024 * 1024: raise AssistantError(400, "file_too_big", "Файл больше 8 МБ — пришли меньший.") try: # [P2-7 2610] base64-decode тяжёлого вложения — в thread, не в event loop data = await asyncio.to_thread(base64.b64decode, raw, validate=True) except Exception: raise AssistantError(400, "bad_attachment", "Не удалось прочитать вложение.") from None messages = body.get("messages") if not isinstance(messages, list) or not messages or len(messages) > 20 or not all(isinstance(m, dict) for m in messages): raise AssistantError(400, "invalid_messages", "Ожидается список сообщений диалога.") messages = [dict(message) for message in messages] res = await asyncio.to_thread(file_intake.extract, name, data) if not res.ok: raise AssistantError(400, "file_extract", "Не смог прочитать файл: " + (res.reason or "неподдерживаемый формат")) last_len = 0 for m in reversed(messages): if m.get("role") == "user": last_len = len(str(m.get("content") or "")) break budget = max(0, 11000 - last_len) if budget < 500: raise AssistantError(400, "file_context_too_long", "Вопрос слишком длинный для вложения — сократи текст запроса.") text = res.text[:budget] truncated = bool(res.truncated) or len(text) < len(res.text) info = {"name": name, "chars": len(text), "truncated": truncated} note = "\n\n[Вложение «%s»: %d символов%s]\n%s" % ( name, info["chars"], ", текст обрезан" if truncated else "", text) for m in reversed(messages): if m.get("role") == "user": m["content"] = str(m.get("content") or "") + note break else: messages.append({"role": "user", "content": note}) return dict(body, messages=messages), info async def api_agent_chat(req): # [RANKGATE 2310] модель вне ранга = честная ошибка, тихой подмены нет. # [AUTO 2310] «Авто» — интент рантайма «быстрый старт»: короткий fast-таймаут и собственный # резолв в первый кандидат. Раньше шлюз слепо заменял авто на allowed[0] и этим убивал # fast-режим. Политика рангов сохранена: если кандидат рантайма этому ранку запрещён, # авто честно резолвится в первый разрешённый — запрещённых моделей в авто нет. body = await _json_body(req) operation_id = _ASSISTANT.operation_id(body.get("operation_id"), generate=True) req["agent_operation_id"] = operation_id body = dict(body, operation_id=operation_id) attachment = body.pop("attachment", None) file_info = None if attachment is not None: guard = req.app.get("miniapp_guard") retry = guard.take(req["uid"], "files") if guard is not None else 0 if retry: return guard.response(retry, operation_id=operation_id) body, file_info = await _agent_with_attachment(body, attachment) await asyncio.to_thread(_refresh_bot_catalog) rank = max(1, int(req.get("rank") or 1)) allowed = _agent_models_for(rank) if not allowed: raise AssistantError(503, "catalog_unavailable", "Каталог моделей сейчас не загружен. Обнови экран позже.") model = body.get("model", "auto") if not isinstance(model, str): raise AssistantError(400, "invalid_model", "Выбери модель из списка.") if model != "auto" and model not in allowed: min_rank = _model_min_rank(model) if min_rank is None: raise AssistantError(400, "invalid_model", "Этой модели нет в активном каталоге — выбери из списка.") if min_rank > rank: raise AssistantError(403, "model_rank", "%s откроется с ранга %s. Автоматической замены нет — выбери модель из списка." % (model, _rank_name(min_rank))) raise AssistantError(400, "invalid_model", "Выбери модель из списка.") # проверяем ACL до провайдера/инструментов, тихой подмены нет. limits = await asyncio.to_thread(_agent_key_model_limits, req["uid"]) if model == "auto": candidates = _agent_models_for_key(allowed, limits) if not candidates: raise AssistantError(403, "model_key_access", "На твоём текущем API-ключе нет доступных моделей — выбери модель из списка " "или создай новый ключ во вкладке «Ключи».", **_agent_key_reject_details(req["uid"], operation_id)) body = dict(body, model="auto", candidates=candidates) elif limits is not None and model not in limits: raise AssistantError(403, "model_key_access", "%s недоступна на твоём текущем API-ключе — выбери другую модель из списка. " "Автоматической замены нет." % model, **_agent_key_reject_details(req["uid"], operation_id)) result = await _ASSISTANT.chat( req["uid"], body, alive=lambda: req.transport is not None and not req.transport.is_closing()) # [SANDBOX 2310] реальный uid/путь песочницы наружу не отдаём — в UI достаточно result = dict(result) result.pop("workspace", None) result["sandbox_enabled"] = os.environ.get("IISHKO_SANDBOX_ENABLED") == "1" if file_info: result["file"] = file_info return web.json_response(result) async def api_agent_cancel(req): body = await _json_body(req) operation_id = body.get("operation_id") if operation_id is not None: operation_id = _ASSISTANT.operation_id(operation_id) req["agent_operation_id"] = operation_id return web.json_response(_ASSISTANT.cancel(req["uid"], operation_id)) async def _support_body(req): limit = 32 * 1024 if req.content_length is not None and req.content_length > limit: raise SupportError(413, "support_body_too_large", "Обращение слишком большое.") raw = bytearray() async for chunk in req.content.iter_chunked(4096): raw.extend(chunk) if len(raw) > limit: raise SupportError(413, "support_body_too_large", "Обращение слишком большое.") try: body = json.loads(raw) except (ValueError, UnicodeDecodeError, RecursionError): raise SupportError(400, "bad_json", "Не удалось прочитать обращение.") from None if not isinstance(body, dict): raise SupportError(400, "invalid_body", "Ожидается JSON-объект.") return body async def api_support_post(req): body = await _support_body(req) if req.app.get("support_worker") is None: raise SupportError(503, "support_unavailable", "Обращение пока не сохранено. Попробуй позже с тем же ID.") try: ticket = await asyncio.to_thread(_SUPPORT.submit, req["uid"], body.get("request_id"), body.get("message"), body.get("context")) except (sqlite3.Error, OSError): raise SupportError(503, "support_unavailable", "Обращение пока не сохранено. Попробуй позже с тем же ID.") from None worker = req.app.get("support_worker") if worker is not None: worker.wake.set() return web.json_response({"ok": True, "ticket": ticket, "request_id": body["request_id"]}) async def api_support_get(req): if req.app.get("support_worker") is None: raise SupportError(503, "support_unavailable", "Не удалось загрузить сохранённые обращения.") try: tickets = await asyncio.to_thread(_SUPPORT.list_receipts, req["uid"]) except (sqlite3.Error, OSError): raise SupportError(503, "support_unavailable", "Не удалось загрузить сохранённые обращения.") from None return web.json_response({"tickets": tickets}) async def _support_notify(admin_id, text, reply_markup=None): if os.environ.get("IISHKO_NOTIFICATIONS_ENABLED", "1") == "0": raise NotificationError(retryable=False) payload = {"chat_id": admin_id, "text": text, "disable_web_page_preview": True} if reply_markup: payload["reply_markup"] = reply_markup try: timeout = ClientTimeout(total=10, connect=3) async with ClientSession(timeout=timeout) as session: async with session.post("https://api.telegram.org/bot" + BOT_TOKEN + "/sendMessage", json=payload) as response: status = response.status raw = await response.content.read(8192) try: result = json.loads(raw) except (ValueError, UnicodeDecodeError, RecursionError): result = {} if status == 200 and isinstance(result, dict) and result.get("ok") is True: return retry_after = 0 if status == 429 and isinstance(result, dict): parameters = result.get("parameters") if isinstance(parameters, dict): retry_after = parameters.get("retry_after", 0) error = NotificationError(retryable=status not in (400, 401, 403, 404), retry_after=retry_after) # Only a structured rejection is safe to retry; transport errors and 5xx may have sent. error.delivery_rejected = status == 429 and isinstance(result, dict) and result.get("ok") is False raise error except (ClientError, asyncio.TimeoutError): # ClientError text may include the bot token in a URL; never retain or log it. raise NotificationError() from None def _entry_keyboard(alert_id): """Operator actions for one entry-network alert. The bot owns the callbacks (eb:*).""" return {"inline_keyboard": [ [{"text": "🚫 Забанить сеть", "callback_data": "eb:ban:%d" % alert_id}, {"text": "♻️ Разбанить", "callback_data": "eb:unban:%d" % alert_id}], [{"text": "🏷 Тег", "callback_data": "eb:tag:%d" % alert_id}, {"text": "👥 Аккаунты сети", "callback_data": "eb:net:%d" % alert_id}], ]} async def _entry_notify(admin_id, text, claim): """Entry alert delivery: same transport as support, plus the ban/tag keyboard.""" try: keyboard = _entry_keyboard(int(claim["alert_id"])) except (KeyError, TypeError, ValueError): keyboard = None await _support_notify(admin_id, text, keyboard) async def _support_lifecycle(app): app["support_worker"] = None app["support_task"] = None try: await asyncio.to_thread(_SUPPORT.init_db) except (sqlite3.Error, OSError) as error: log.error("support storage unavailable error=%s", type(error).__name__) yield return worker = SupportOutbox(_SUPPORT, lambda: ADMIN_IDS, _support_notify) app["support_worker"] = worker task = None if (os.environ.get("IISHKO_SUPPORT_DELIVERY_ENABLED", "1") != "0" and os.environ.get("IISHKO_NOTIFICATIONS_ENABLED", "1") != "0"): task = asyncio.create_task(worker.run(), name="iishko-support-outbox") app["support_task"] = task try: yield finally: worker.stop() if task is not None: try: await asyncio.wait_for(asyncio.shield(task), timeout=12) except asyncio.TimeoutError: task.cancel() await asyncio.gather(task, return_exceptions=True) async def api_access_entry(req): limit = 1024 if req.content_length is not None and req.content_length > limit: return web.json_response({"error": "entry_body_too_large", "msg": "Запрос входа слишком большой."}, status=413) raw = bytearray() async for chunk in req.content.iter_chunked(1024): raw.extend(chunk) if len(raw) > limit: return web.json_response({"error": "entry_body_too_large", "msg": "Запрос входа слишком большой."}, status=413) try: body = json.loads(raw) except (ValueError, UnicodeError, RecursionError): body = None if (not isinstance(body, dict) or set(body) - {"session"} or ("session" in body and (not isinstance(body["session"], str) or re.fullmatch(r"[A-Za-z0-9_.:-]{1,96}", body["session"]) is None))): return web.json_response({"error": "invalid_entry", "msg": "Ожидается только необязательная метка сессии."}, status=400) store = req.app.get("entry_store") try: if store is None: raise entry_telemetry.EntryError() await asyncio.to_thread(store.record, req["uid"], entry_telemetry.trusted_ip(req.remote, req.headers)) except entry_telemetry.EntryError as error: return web.json_response({"error": error.code, "msg": error.message}, status=error.status) except (sqlite3.Error, OSError): return web.json_response({"error": "entry_unavailable", "msg": "Не удалось сохранить вход. Попробуй позже."}, status=503) worker = req.app.get("entry_worker") if worker is not None: worker.wake.set() return web.json_response({"ok": True}) async def _entry_retention(store): # Local-only housekeeping remains active while delivery is disabled; idle data still expires. while True: await asyncio.sleep(3600) try: await asyncio.to_thread(store.prune) except (sqlite3.Error, OSError) as error: log.warning("entry retention unavailable error=%s", type(error).__name__) async def _entry_lifecycle(app): app["entry_store"], app["entry_worker"], app["entry_task"], app["entry_prune_task"] = None, None, None, None try: try: from entry_geo import lookup_ip except ImportError: lookup_ip = None explicit_key = os.environ.get("IISHKO_ENTRY_HMAC_KEY") if explicit_key is not None and len(explicit_key.encode("utf-8")) < 32: raise ValueError("entry_hmac_key_too_short") ranges = os.environ.get("IISHKO_ENTRY_SHARED_EGRESS_CIDRS", "") if len(ranges) > 4096: raise ValueError("entry_shared_ranges_limit") store = entry_telemetry.EntryTelemetry( BOT_DB, explicit_key if explicit_key is not None else BOT_TOKEN, ADMIN_IDS, lookup=lookup_ip, shared_cidrs=[item.strip() for item in ranges.split(",") if item.strip()]) await asyncio.to_thread(store.init_db) except (sqlite3.Error, OSError, ValueError) as error: log.error("entry storage unavailable error=%s", type(error).__name__) yield return try: await asyncio.to_thread(entry_admin.init_db) except (sqlite3.Error, OSError): log.error("entry tag storage unavailable") # Tags are operator notes on a network hash; they ride inside every alert for that hash. worker = entry_telemetry.EntryOutbox(store, _entry_notify, tags=entry_admin.tags) app["entry_store"], app["entry_worker"] = store, worker task = None if entry_telemetry.delivery_enabled(): task = asyncio.create_task(worker.run(), name="iishko-entry-outbox") app["entry_task"] = task retention_task = asyncio.create_task(_entry_retention(store), name="iishko-entry-retention") app["entry_prune_task"] = retention_task try: yield finally: worker.stop() retention_task.cancel() await asyncio.gather(retention_task, return_exceptions=True) if task is not None: try: await asyncio.wait_for(asyncio.shield(task), timeout=12) except asyncio.TimeoutError: task.cancel() await asyncio.gather(task, return_exceptions=True) async def _agent_shutdown(app): await _ASSISTANT.close() async def api_reminders(req): await asyncio.to_thread(_ASSISTANT.user, req["uid"]) rows = await asyncio.to_thread(reminder_store.list_reminders, BOT_DB, req["uid"]) return web.json_response({"reminders": rows}) async def api_reminders_create(req): await asyncio.to_thread(_ASSISTANT.user, req["uid"]) body = await _json_body(req) try: row = await asyncio.to_thread( reminder_store.create_reminder, BOT_DB, req["uid"], body.get("text"), body.get("due_at")) except (ValueError, TypeError): raise AssistantError(400, "invalid_reminder", "Укажи текст до 1000 символов и время от 30 секунд до года вперёд; максимум 100 активных напоминаний.") from None return web.json_response({"ok": True, "reminder": row}) async def api_reminders_cancel(req): await asyncio.to_thread(_ASSISTANT.user, req["uid"]) body = await _json_body(req) reminder_id = body.get("id") if isinstance(reminder_id, bool) or not isinstance(reminder_id, int) or reminder_id <= 0: raise AssistantError(400, "invalid_reminder", "Некорректный номер напоминания.") cancelled = await asyncio.to_thread(reminder_store.cancel_reminder, BOT_DB, req["uid"], reminder_id) if not cancelled: raise AssistantError(404, "not_found", "Напоминание не найдено или уже отправляется.") return web.json_response({"ok": True, "status": "cancelled"}) async def api_neurolab(req): return web.json_response(await asyncio.to_thread(neurolab.game_state, BOT_DB, req["uid"])) async def api_neurolab_action(req): body = await _json_body(req) return web.json_response(await asyncio.to_thread(neurolab.game_action, BOT_DB, req["uid"], body)) async def api_neurolab_talk(req): body = await _json_body(req) uid, model = req["uid"], body.get("model", "auto") if not isinstance(model, str) or model not in ("auto", *_agent_models_for(req.get("rank"))): raise AssistantError(400, "invalid_model", "Выбери доступную модель или режим «Авто».") if uid in _NPC_BUSY: raise AssistantError(409, "talk_busy", "Персонаж ещё отвечает. Дождись реплики.") now = time.time() for owner in [owner for owner, stamps in _NPC_RATE.items() if not stamps or now - stamps[-1] >= 60]: _NPC_RATE.pop(owner, None) stamps = [stamp for stamp in _NPC_RATE.get(uid, []) if now - stamp < 60] if len(stamps) >= 8: raise AssistantError(429, "talk_rate", "Дай персонажу немного времени: не больше 8 реплик в минуту.", retry_after=max(1, math.ceil(stamps[0] + 60 - now))) _NPC_RATE[uid] = stamps + [now] _NPC_BUSY.add(uid) try: context = await asyncio.to_thread( neurolab.talk_context, BOT_DB, uid, body.get("character_id"), body.get("text")) reply, source, actual_model = context["reply"], "script", None # The canonical engine owns facts, progress and rewards. A model can voice only the supplied facts. try: key = await asyncio.to_thread(_ASSISTANT.user_key, uid) candidate = "glm-5.3-flash" if model == "auto" else model voiced = await asyncio.wait_for( _ASSISTANT.complete(candidate, [{"role": "system", "content": context["system"]}, {"role": "user", "content": context["prompt"]}], key, fast=True, max_tokens=400), timeout=10) voiced = voiced.strip()[:1200] if voiced and req.transport is not None and not req.transport.is_closing(): stored = await asyncio.to_thread( neurolab.save_talk_reply, BOT_DB, uid, context["character_id"], voiced, context["revision"]) if stored: reply, source, actual_model = voiced, "model", candidate except (AssistantError, UpstreamError, asyncio.TimeoutError, ClientError): pass state = await asyncio.to_thread(neurolab.game_state, BOT_DB, uid) if state.get("revision") == context["revision"]: for character in state.get("characters", []): if character["id"] == context["character_id"]: character["transcript"] = [{"role": "user", "content": context["prompt"]}, {"role": "assistant", "content": reply}] return web.json_response({"reply": reply, "source": source, "model": actual_model, "character_id": context["character_id"], "state": state}) finally: _NPC_BUSY.discard(uid) def _rank_for(uid): con = _con(BOT_DB) try: u = con.execute("SELECT * FROM users WHERE tg_id=?", (uid,)).fetchone() return rank_of(u, refs_weighted(con, uid)) if u else 1 finally: con.close() @web.middleware async def request_id_mw(req, handler): request_id = safe_request_id(req.headers.get("X-Request-ID")) req["request_id"] = request_id try: response = await handler(req) except web.HTTPException as error: response = error except Exception as error: if not req.path.startswith("/api/"): raise # [P0-REVIEW 2710] body из замыкания недоступен — собираем payload явно payload = {"error": "internal", "msg": "Внутренняя ошибка сервера"} if req.get("agent_operation_id"): payload.update(operation_id=req["agent_operation_id"], state="failed", uncertain=True) response = web.json_response(payload, status=500) response.headers["X-Request-ID"] = request_id if req.path.startswith("/api/"): response.headers.setdefault("Cache-Control", "no-store") return response @web.middleware async def auth_mw(req, handler): if req.path.startswith("/api/"): guard = req.app.get("miniapp_guard") uid = verify_init(req.headers.get("X-Init-Data", "")) if not uid: retry = (guard.reject_auth(entry_telemetry.trusted_ip(req.remote, req.headers) or req.remote) if guard is not None else 0) if retry: return guard.response(retry) return web.json_response({"error": "unauthorized"}, status=401) req["uid"] = uid retry = guard.check(uid, req.method, req.path) if guard is not None else 0 if retry: return guard.response(retry) device = req.headers.get("X-Device-Id", "").strip() req["device"] = device if re.fullmatch(r"[a-f0-9]{32}", device) else "" if req["device"] and req.path not in ("/api/models", "/api/access/entry"): try: await asyncio.to_thread(_device_track, uid, key_issue_guard.opaque(BOT_TOKEN, "key-device", req["device"])) except Exception: pass try: # [AUDIT 21.10] синхронный SQLite вынесен из event loop (раньше каждый /api/* блокировал цикл) req["rank"] = await asyncio.to_thread(_rank_for, uid) except sqlite3.OperationalError as e: # [FIX-2410] fail-closed: без данных о ранге не даём blanket rank=1 — честный 503 log.warning("auth_mw: rank lookup failed: %s", type(e).__name__) return _db_busy() except Exception as e: # [FIX-2410] было: req["rank"] = 1 (тихое занижение ранга при недоступных данных) log.warning("auth_mw: rank lookup failed: %s", type(e).__name__) return web.json_response({"error": "db_busy"}, status=503) try: resp = await handler(req) except (AssistantError, SupportError, neurolab.GameError) as error: details = dict(error.details) if isinstance(getattr(error, "details", None), dict) else {} if req.get("agent_operation_id"): details.setdefault("operation_id", req["agent_operation_id"]) details.setdefault("state", "failed" if error.status >= 500 else "rejected") details.setdefault("uncertain", error.status >= 500) headers = {} if error.status == 429: retry = details.get("retry_after", 60) if type(retry) not in (int, float) or not math.isfinite(retry) or retry <= 0: retry = 60 retry = max(1, min(86400, math.ceil(retry))) details["retry_after"] = retry headers["Retry-After"] = str(retry) resp = web.json_response({"error": error.code, "msg": error.message, **details}, status=error.status, headers=headers) except sqlite3.OperationalError as error: if not _is_busy(error): raise resp = _db_busy() # [AUDIT 21.10] API не кэшируется (раньше Cache-Control отсутствовал вообще) resp.headers.setdefault("Cache-Control", "no-store") return resp return await handler(req) async def index(req): return web.FileResponse(os.path.join(BASE, "static", "index.html"), headers={ "Cache-Control": "no-store, must-revalidate", "Pragma": "no-store"}) async def _cleanup(app): # [FIX-2410] ждём смерть proc (раньше kill без wait) и закрываем log fd (утечка на каждый респавн) try: await MK._reap() except Exception: log.exception("mk daemon cleanup failed") async def api_community(req): try: data = await asyncio.to_thread(community_economy.snapshot, BOT_DB, req["uid"], ADMIN_IDS) return web.json_response(data, headers={"Cache-Control": "no-store"}) except community_economy.EconomyError as error: return web.json_response({"error": error.code, "message": error.message}, status=error.status) async def api_community_action(req): try: body = await _json_body(req) data = await asyncio.to_thread(community_economy.act, BOT_DB, req["uid"], body, ADMIN_IDS) return web.json_response(data, headers={"Cache-Control": "no-store"}) except community_economy.EconomyError as error: return web.json_response({"error": error.code, "message": error.message, "operation_rejected": True}, status=error.status) def _feature_error(error): return web.json_response({"error": error.code, "msg": error.message, "operation_rejected": bool(getattr(error, "operation_rejected", False))}, status=error.status) def _feature_user(uid): con = _con(BOT_DB) try: return gateway_commerce._user(con, uid) finally: con.close() def _sync_commerce_models(uid): user = _feature_user(uid) base = set(commerce_access.base_models(BOT_DB, uid)) active = gateway_commerce.entitlements(BOT_DB, uid)["models"] managed = {item["model"] for item in gateway_commerce.managed_model_passes(BOT_DB, uid)} con = _con(NEWAPI_DB) try: con.execute("BEGIN IMMEDIATE") rows, ambiguous = account_balances.owned_rows(con, uid, user) if ambiguous: raise ValueError("ambiguous account credentials") for row in rows: if not row["model_limits_enabled"] or row["unlimited_quota"]: continue current = [name for name in (row["model_limits"] or "").split(",") if name] scoped = list(dict.fromkeys([name for name in current if name not in managed or name in base] + active)) con.execute("UPDATE tokens SET model_limits=? WHERE id=?", (",".join(scoped), row["id"])) con.commit() except BaseException: con.rollback() raise finally: con.close() async def api_commerce(req): try: result = await asyncio.to_thread(gateway_commerce.snapshot, BOT_DB, req["uid"], CFG.get("commerce_offers", []), os.environ.get("CRYPTOPAY_TOKEN") or CFG.get("cryptopay_token", "")) return web.json_response(result) except gateway_commerce.CommerceError as error: return _feature_error(error) async def api_commerce_action(req): body, error = await _keys_body(req) if error is not None: return error try: base, available_models = (), None if body.get("action") in ("purchase", "buy"): base = await asyncio.to_thread(commerce_access.base_models, BOT_DB, req["uid"]) available_models = await asyncio.to_thread(commerce_access.public_models) result = await gateway_commerce.act(BOT_DB, req["uid"], body, CFG.get("commerce_offers", []), os.environ.get("CRYPTOPAY_TOKEN") or CFG.get("cryptopay_token", ""), base_models=base, available_models=available_models) if result.get("action") == "purchase": try: await asyncio.to_thread(_sync_commerce_models, req["uid"]) except (sqlite3.Error, ValueError, OSError): result["upstream_access_pending"] = True result["msg"] = "Покупка сохранена; доступ к модели ожидает синхронизации." return web.json_response(result) except gateway_commerce.CommerceError as error: return _feature_error(error) async def api_activities(req): try: result = await asyncio.to_thread(community_board.snapshot, BOT_DB, req["uid"], admins=ADMIN_IDS) return web.json_response(result) except community_board.BoardError as error: return _feature_error(error) async def api_activities_action(req): body, error = await _keys_body(req) if error is not None: return error try: result = await asyncio.to_thread(community_board.act, BOT_DB, req["uid"], body, admins=ADMIN_IDS) return web.json_response(result) except community_board.BoardError as error: return _feature_error(error) _REGISTRY_CACHE = {"path": None, "mtime": None, "registry": None} def _get_registry(): """ProviderRegistry с mtime-кэшем: файл парсится один раз, не на каждый запрос (P1-7).""" path = os.environ.get("IISHKO_PROVIDERS_FILE") or "" try: mtime = os.path.getmtime(path) if path else None except OSError: mtime = None if _REGISTRY_CACHE["registry"] is None or _REGISTRY_CACHE["path"] != path or _REGISTRY_CACHE["mtime"] != mtime: _REGISTRY_CACHE.update(path=path, mtime=mtime, registry=ProviderRegistry.from_file(path or None)) return _REGISTRY_CACHE["registry"] def _provider_snapshot(uid, model): user = _feature_user(uid) registry = _get_registry() con = _con(NEWAPI_DB) try: rows, ambiguous = account_balances.owned_rows(con, uid, user) if ambiguous: raise ValueError("ambiguous account credentials") main = next((row for row in rows if row["name"] == "tg%d" % uid), None) if main is None: main = next((row for row in rows if row["name"] == user.get("token_name")), None) group = main["group"] if main is not None else "default" finally: con.close() return registry.catalog(NEWAPI_DB, model, group or "default") async def api_providers(req): model = req.query.get("model", "") if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}", model): return _keys_error("Укажи точный идентификатор модели", "invalid_model") try: result = await asyncio.to_thread(_provider_snapshot, req["uid"], model) return web.json_response(result) except gateway_commerce.CommerceError as error: return _feature_error(error) except (OSError, ValueError): return web.json_response({"error": "providers_unavailable", "msg": "Каталог провайдеров временно недоступен", "operation_rejected": True}, status=503) def create_app(): _captcha_init() _device_init() _ASSISTANT.init_db() neurolab.init_db(BOT_DB) community_economy.init_db(BOT_DB) gateway_commerce.init_db(BOT_DB) community_board.init_db(BOT_DB) app = web.Application(middlewares=[request_id_mw, auth_mw], client_max_size=16 * 1024 * 1024) app["miniapp_guard"] = miniapp_guard.MiniappGuard(BOT_TOKEN) app.cleanup_ctx.append(_support_lifecycle) app.cleanup_ctx.append(_entry_lifecycle) app.on_shutdown.append(_agent_shutdown) app.router.add_get("/api/community", api_community) app.router.add_post("/api/community/action", api_community_action) app.router.add_get("/api/commerce", api_commerce) app.router.add_post("/api/commerce/action", api_commerce_action) app.router.add_get("/api/activities", api_activities) app.router.add_post("/api/activities/action", api_activities_action) app.router.add_get("/api/providers", api_providers) app.on_cleanup.append(_cleanup) app.router.add_get("/", index) app.router.add_static("/static/", os.path.join(BASE, "static")) app.router.add_get("/api/me", api_me) app.router.add_post("/api/access/entry", api_access_entry) app.router.add_get("/api/models", api_models) app.router.add_get("/api/top", api_top) app.router.add_get("/api/tx", api_tx) app.router.add_get("/api/global", api_global) app.router.add_get("/api/bonus", api_bonus) app.router.add_post("/api/daily", api_daily) app.router.add_post("/api/spin", api_retired_bonus) app.router.add_post("/api/task", api_retired_bonus) app.router.add_get("/api/key", api_key) app.router.add_get("/api/boards", api_boards) # v3 app.router.add_get("/api/captcha", api_captcha) app.router.add_get("/api/keys", api_keys) app.router.add_post("/api/keys/create", api_keys_create) app.router.add_post("/api/keys/reveal", api_keys_reveal) app.router.add_post("/api/keys/lock", api_keys_lock) app.router.add_post("/api/keys/transfer", api_keys_transfer) app.router.add_post("/api/keys/return_all", api_keys_return_all) app.router.add_post("/api/keys/del", api_keys_del) app.router.add_get("/api/econ", api_econ) app.router.add_get("/api/quests", api_quests) app.router.add_post("/api/quests/claim", api_quest_claim) app.router.add_get("/api/agent_models", api_agent_models) app.router.add_post("/api/agent_chat", api_agent_chat) app.router.add_post("/api/agent_cancel", api_agent_cancel) app.router.add_post("/api/support", api_support_post) app.router.add_get("/api/support", api_support_get) app.router.add_get("/api/agent_history", api_agent_history) app.router.add_post("/api/agent_history/clear", api_agent_history_clear) app.router.add_get("/api/reminders", api_reminders) app.router.add_post("/api/reminders/create", api_reminders_create) app.router.add_post("/api/reminders/cancel", api_reminders_cancel) app.router.add_get("/api/neurolab", api_neurolab) app.router.add_post("/api/neurolab/action", api_neurolab_action) app.router.add_post("/api/neurolab/talk", api_neurolab_talk) app.router.add_get("/healthz", lambda r: web.Response(text="ok")) return app def main(): app = create_app() _ms_threading.Thread(target=_ms_loop, daemon=True).start() # [MSTATUS 1910] web.run_app(app, host=os.environ.get("IISHKO_WEBAPP_HOST", "127.0.0.1"), port=int(os.environ.get("IISHKO_WEBAPP_PORT", "8850")), print=None) if __name__ == "__main__": main()