IISHKO: Telegram bot, Mini App and gateway
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled

Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-30 21:51:30 +03:00
co-authored by Claude Opus 5.5
commit 0ee6fb843b
179 changed files with 59173 additions and 0 deletions
+401
View File
@@ -0,0 +1,401 @@
"""Public API boundary: authentication aliases and safe, actionable errors."""
import json
import re
import logging
_log = logging.getLogger("gwerr")
import os as _os
import sqlite3 as _sq
_NEWAPI_DB = _os.environ.get("GW_NEWAPI_DB", "/opt/grok-gateway/new-api/one-api.db")
# [POLICYMSG 2810] Вердикт модерации апстрима детерминирован: тот же текст на том же
# OpenAI «content_filter»). Прежняя формулировка «Повтори попытку или выбери другую
# модель» обещала то, чего повтор дать не может, и за 24 ч 2026-10-28 ушла юзерам
# Единственный источник текста — здесь; бот импортирует константу, чтобы не дрейфовать.
CONTENT_POLICY_USERMSG = (
"Провайдер этой модели отклонил запрос своим контент-фильтром. "
"Повтор тем же текстом не поможет: переформулируй запрос "
"или выбери модель другого семейства."
)
def key_from_headers(headers):
raw = ""
try:
for name, value in (headers or {}).items():
if str(name).lower() in ("authorization", "x-api-key", "api-key"):
raw = str(value or "").strip()
if raw:
break
except Exception:
return ""
if raw[:7].lower() == "bearer ":
raw = raw[7:].strip()
if raw.lower().startswith("sk-"):
raw = raw[3:]
return raw
def token_state(api_key):
if not api_key:
return None
try:
con = _sq.connect("file:" + _NEWAPI_DB + "?mode=ro", uri=True, timeout=3)
try:
row = con.execute(
'SELECT status, COALESCE(remain_quota,0), COALESCE(unlimited_quota,0) '
'FROM tokens WHERE "key"=? AND deleted_at IS NULL ORDER BY id DESC LIMIT 1',
(api_key,)).fetchone()
finally:
con.close()
except Exception:
return None
return (int(row[0] or 0), int(row[1] or 0), int(row[2] or 0)) if row else None
HOP_HEADERS = frozenset({"host", "connection", "proxy-connection", "keep-alive", "transfer-encoding", "upgrade", "te", "trailer", "content-length"})
def _bearer(value):
parts = value.split()
return "Bearer " + parts[1] if len(parts) == 2 and parts[0].casefold() == "bearer" else value.strip()
_QUOTA_CUR_RE = re.compile(r"(?:当前额度|用户剩余额度|剩余额度)[::\s]*[$$]?\s*(-?[0-9]+(?:\.[0-9]+)?)")
_QUOTA_NEED_RE = re.compile(r"(?:需要额度|需要预扣费额度)[::\s]*[$$]?\s*([0-9]+(?:\.[0-9]+)?)")
def _parse_quota_amounts(text):
"""(current, needed) в USD из «用户额度不足,当前额度: $X,需要额度: $Y»; None если формата нет."""
m_cur, m_need = _QUOTA_CUR_RE.search(text), _QUOTA_NEED_RE.search(text)
if not (m_cur and m_need):
return None
try:
return float(m_cur.group(1)), float(m_need.group(1))
except ValueError:
return None
def normalize_auth_headers(headers):
aliases = {"authorization", "x-api-key", "api-key"}
credentials = {
_bearer(value) if name.lower() == "authorization" else "Bearer " + value.strip()
for name, value in headers.items() if name.lower() in aliases and value.strip()
}
if len(credentials) > 1:
raise ValueError("conflicting authentication headers")
lower = {k.lower(): v for k, v in headers.items()}
connection = {v.strip().lower() for v in lower.get("connection", "").split(",")}
excluded = HOP_HEADERS | connection | aliases
result = {k: v for k, v in headers.items() if k.lower() not in excluded}
if credentials:
result["Authorization"] = credentials.pop()
return result
_MAX_ERROR_TEXT = 65536
_ESCAPED_OBJECT = re.compile(r'^\{\s*\\+"')
_PUBLIC_ID = re.compile(r"[A-Za-z0-9_-]{1,128}")
_PRIVATE_ID = re.compile(
r"^(?:sk[-_]|sess[-_]|gh[pousr]_|github_pat_|xox[baprs]-|AIza|AKIA|ASIA|eyJ|bearer$|basic$)"
r"|(?:localhost|internal)(?:$|[-_])", re.IGNORECASE)
_REQUEST_ID = re.compile(
r"""\brequest[ _-]id\s*:\s*([^\s)\]}"',;]+)(?=\s*(?:[)\]}"',;]|$))""",
re.IGNORECASE)
def _decode_error_value(value):
"""Decode bounded, complete JSON layers only; never unicode_escape UTF-8 prose."""
if isinstance(value, (bytes, bytearray)):
if len(value) > _MAX_ERROR_TEXT:
return None
value = value.decode("utf-8-sig", errors="replace")
for _ in range(6):
if not isinstance(value, str):
return value
if len(value) > _MAX_ERROR_TEXT:
return None
text = value.strip().lstrip("\ufeff")
if not text or text[0] not in ('{', '[', '"'):
return text
try:
value = json.loads(text)
except (ValueError, RecursionError):
# Some relays remove the outer quotes of a JSON-encoded object.
# Unwrap only if the whole string is itself valid escaped JSON.
if not (_ESCAPED_OBJECT.match(text) and text.endswith("}")):
return text
try:
value = json.loads('"' + text + '"')
except (ValueError, RecursionError):
return text
return value
def _error_details(raw):
"""Walk only error/message envelopes, not arbitrary upstream data or credentials."""
source, request_ids, gateway_ids, seen, codes = [], [], [], [], []
error_code = None
node = raw
for _ in range(8):
node = _decode_error_value(node)
if isinstance(node, dict):
if any(node is previous for previous in seen):
break
seen.append(node)
for field in ("code", "type"):
value = node.get(field)
if isinstance(value, str) and len(value) <= 256:
source.append(value)
codes.append(value.strip().lower())
code = node.get("code")
if isinstance(code, str) and code.strip() and len(code) <= 128:
error_code = code.strip().lower()
request_ids.insert(0, node.get("request_id"))
gateway_ids.insert(0, node.get("gateway_request_id"))
child = node.get("error")
if not isinstance(child, (dict, str, bytes, bytearray)) or not child:
child = node.get("message")
node = child
elif isinstance(node, str):
source.append(node)
break
else:
break
return " ".join(source), error_code, request_ids, gateway_ids, codes
def _public_id(value):
return (isinstance(value, str) and _PUBLIC_ID.fullmatch(value)
and not _PRIVATE_ID.search(value))
def public_json_dumps(value):
"""UTF-8 presentation for normalized error JSON; successful replies stay byte-exact."""
return json.dumps(value, ensure_ascii=False)
# content_policy_violation. Структурное поле code/type — сильное доказательство (проверяется
# до billing-прозы); упоминание «content_filter» как имени параметра (unsupported_parameter,
# перечисление supported-параметров с reasoning_effort) политикой не является.
_POLICY_CODE_RE = re.compile(
r"^(?:(?:input|output)[_-]?)?data[_-]?inspection[_-]?failed$"
r"|^content[_-]?filter$|^content[_-]?policy[_-]?violation$", re.IGNORECASE)
_POLICY_TOKEN = (r"(?:(?:input|output)[_-]?)?data[_-]?inspection[_-]?failed"
r"|content[_-]?policy[_-]?violation|content[_-]?filter")
_POLICY_STANDALONE_RE = re.compile(r"^(?:" + _POLICY_TOKEN + r")$", re.IGNORECASE)
_POLICY_PREFIX_RE = re.compile(r"(?:^|[^0-9a-z_-])(?:" + _POLICY_TOKEN + r")\s*[::]", re.IGNORECASE)
_POLICY_LABELED_RE = re.compile(
r"""(?:^|[\s"'({\[,;])(?:error[\s_-]*(?:code|type)|code|type|finish[\s_-]*reason|reason|status)"""
r"""["'\s]*[=:]["'\s]*(?:""" + _POLICY_TOKEN + r""")(?:$|[\s"'()\]},;:.!])""", re.IGNORECASE)
_POLICY_WEAK_RE = re.compile(r"(?:^|[^0-9a-z_-])content[_-]?filter(?:$|[^0-9a-z_-])", re.IGNORECASE)
_POLICY_PARAM_PROSE_RE = re.compile(
r"support\w*|invalid|unknown|unexpected|unrecogni[sz]ed|parameter\w*|allowed\s+values|deprecat\w*",
re.IGNORECASE)
def _policy_code_hit(value):
"""True only for an exact vendor moderation code/type, never for prose mentioning it."""
return isinstance(value, str) and bool(_POLICY_CODE_RE.match(value.strip()))
def _legacy_policy_text(text, error_code):
"""Узкая legacy-поддержка текста: standalone-точный код, вендорный префикс «Code: …»,
лейбл «code/type/finish_reason: X», либо слабый «content_filter» без структурного кода
и без параметрной прозы в окне вокруг упоминания."""
if not text:
return False
if _POLICY_STANDALONE_RE.match(text.strip().strip('"\'')):
return True
if _POLICY_PREFIX_RE.search(text) or _POLICY_LABELED_RE.search(text):
return True
if error_code:
return False
for match in _POLICY_WEAK_RE.finditer(text):
window = text[max(0, match.start() - 40):match.end() + 40]
if not _POLICY_PARAM_PROSE_RE.search(window):
return True
return False
def _category(status, text, path, user_balance=None, from_upstream=False, error_code=None, api_key=None, codes=None):
if (status == 503 and error_code == "upstream_auth_error") or (status == 401 and (
"channel error" in text or re.search(r"channel #\d+", text)
or "incorrect api key provided" in text)):
return 503, "upstream_auth_error", (
"Выбранная модель временно недоступна. Ваш API-ключ не отозван. "
"Повторите запрос позже."), True
# [POLICYCODE 2810] Структурный код/тип модерации провайдера сильнее billing-прозы в
if _policy_code_hit(error_code) or any(_policy_code_hit(value) for value in codes or ()):
return 400, "content_policy_violation", CONTENT_POLICY_USERMSG, False
billing = ("arrearage", "good standing", "余额不足", "无可用资源包", "请充值", "insufficient balance", "credit balance", "exceeded your current quota",
"free quota exhausted", "out of credits")
if (status == 503 and error_code == "upstream_billing_error") or any(marker in text for marker in billing):
return 503, "upstream_billing_error", "Выбранная модель временно недоступна. Это не означает обнуление вашего баланса. Повторите позже.", True
# [NOPOLICY 2810] Legacy-текст сужен до реальных форм кода вендора: standalone-код,
# префикс «DataInspectionFailed: …», лейбл «code/type/finish_reason: X», либо слабый
# «content_filter» без структурного кода и вне параметрной прозы. Произвольная проза
# с упоминанием параметра (unsupported_parameter, reasoning_effort) вердиктом не является.
if _legacy_policy_text(text, error_code):
return 400, "content_policy_violation", CONTENT_POLICY_USERMSG, False
if "unsupported model" in text and any(m in text for m in ("qwen-image", "wanx", "t2i")) and path.endswith("/chat/completions"):
return 400, "model_endpoint_mismatch", "Это модель изображений, а не чата. Используйте POST /v1/images/generations или выберите чат-модель.", False
# Local new-api pre-consume rejection names the caller token explicitly.
if error_code == "pre_consume_token_quota_failed":
return 402, "quota_precharge_insufficient", (
"Недостаточно API-кредита для предоплаты этого запроса. "
"Пополните баланс или сократите историю/контекст."), False
if any(marker in text for marker in (
"insufficient_quota", "insufficient_user_quota", "user quota", "user balance",
"token quota", "用户额度不足", "预扣费额度失败", "用户剩余额度")):
# [ERRCLASS-20261020] «用户额度不足,当前额度: $X,需要额度: $Y» идентичен от самого new-api
# это upstream, не юзер.
q = _parse_quota_amounts(text)
if q and user_balance is not None:
cur, need = q
if abs(cur - user_balance) > max(0.01, need * 0.02):
_log.warning("quota_classification code=upstream_billing_error reason=balance_mismatch")
return 503, "upstream_billing_error", "Выбранная модель временно недоступна. Это не означает обнуление вашего баланса. Повторите позже.", True
if "channel error" in text or re.search(r"channel #\d+", text):
_log.warning("quota_classification code=upstream_billing_error reason=channel")
return 503, "upstream_billing_error", "Выбранная модель временно недоступна. Это не означает обнуление вашего баланса. Повторите позже.", True
# неизвестна даже при отсутствии числовых сумм: не обвиняем кошелёк.
if user_balance is None and not (status == 402 and error_code == "insufficient_quota"):
_log.warning("quota_classification code=quota_precharge_insufficient reason=no_balance_hint")
return 402, "quota_precharge_insufficient", (
"Недостаточно квоты для этого запроса. Сначала проверьте баланс, "
"затем попробуйте другую модель или сократите контекст; "
"если не помогло — обратитесь в поддержку @iishkogatewaybot."), False
if q is None and user_balance is not None and user_balance > 0.0:
_log.warning("quota_classification code=upstream_billing_error reason=positive_balance")
return 503, "upstream_billing_error", "Выбранная модель временно недоступна. Это не означает обнуление вашего баланса. Повторите позже.", True
_log.warning("quota_classification code=insufficient_quota")
return 402, "insufficient_quota", "Для предоплаты этого запроса недостаточно API-кредита. Проверьте баланс в Mini App или сократите историю; это не означает обнуление баланса.", False
# ошибка падала в generic invalid_request "Проверьте название модели" — ложь + клиент не ретраил.
if (error_code in ("wallet_debt_outstanding", "wallet_debt", "wallet_suspended", "account_arrears")
or "未结清消费" in text or "钱包调用暂时暂停" in text or "wallet_debt" in text):
_log.warning("wallet_debt code=upstream_billing_error")
return 503, "upstream_billing_error", "Выбранная модель временно недоступна. Это не означает обнуление вашего баланса. Повторите позже.", True
if (error_code in ("insufficient_credits", "credit_limit_exceeded", "payment_required",
"openrouter_credits", "credits_exhausted")
or "never purchased credits" in text or "insufficient credits" in text
or "openrouter_credits" in text or "credit_limit_exceeded" in text):
_log.warning("upstream_credits code=upstream_billing_error")
return 503, "upstream_billing_error", "Выбранная модель временно недоступна. Это не означает обнуление вашего баланса. Повторите позже.", True
# neutral, non-retryable — attribution not proven (own token vs reseller)
if ((status == 402 and error_code == "quota_precharge_insufficient") or "need quota" in text
or "token remain quota" in text or "当前额度已用尽" in text or
("额度不足" in text and "用户额度不足" not in text)):
return 402, "quota_precharge_insufficient", (
"Недостаточно квоты для этого запроса. Сначала проверьте баланс, "
"затем попробуйте другую модель или сократите контекст; "
"если не помогло — обратитесь в поддержку @iishkogatewaybot."), False
if "maximum context length" in text or "context_length_exceeded" in text or "context window" in text:
return 400, "context_overflow", "Запрос превышает контекст модели. Начните новый диалог, сократите историю или выберите модель с большим контекстом.", False
if status == 413:
if from_upstream:
return 413, "upstream_request_too_large", (
"Выбранная модель отклонила размер запроса. "
"Сократите историю или крупный вывод инструментов. Контекст модели измеряется в токенах; "
"эта ошибка не означает лимит контекста 40 МБ."), False
return 413, "request_too_large", "Запрос слишком большой. Сократите контекст или размер вложения; максимальный размер запроса — 40 MB.", False
if status == 401:
# [AUTHTRUTH 2410] new-api отдаёт один и тот же "Invalid token" и для чужого/удалённого
_ts = token_state(api_key) if api_key else None
if _ts is not None:
_tstatus, _remain, _unlim = _ts
if _tstatus == 4 or (not _unlim and _remain <= 0):
_log.warning("auth_truth code=api_key_empty status=%s remain=%s", _tstatus, _remain)
return 402, "api_key_empty", (
"Ключ живой, но на нём нулевой баланс. Переведи кредит с основного ключа "
"в Mini App -> «Ключи» (или возьми новый ключ в @iishkogatewaybot)."), False
if _tstatus in (2, 3):
_log.warning("auth_truth code=api_key_disabled status=%s", _tstatus)
return 403, "api_key_disabled", (
"Ключ отключён или истёк его срок. Открой Mini App -> «Ключи» и включи его "
"или выпусти новый в @iishkogatewaybot."), False
return 401, "invalid_api_key", "API-ключ недействителен или отозван. Получите актуальный ключ в @iishkogatewaybot.", False
if status == 503 and error_code == "upstream_busy":
return 503, "upstream_busy", "Выбранная модель сейчас занята. Повторите немного позже.", True
if status == 429:
if from_upstream:
# Preserve overload semantics so SDKs apply Retry-After/backoff instead of
# treating a healthy gateway as unavailable.
return 429, "upstream_busy", "Выбранная модель сейчас занята. Повторите немного позже.", True
return 429, "rate_limit_exceeded", "Достигнут временный лимит ключа. Повторите запрос позже.", True
if status in (408, 504):
return 504, "upstream_timeout", "Выбранная модель не ответила вовремя. Повторите запрос позже.", True
if (status == 503 and error_code == "upstream_pool_empty") or "no available accounts" in text or "no available account" in text:
return 503, "upstream_pool_empty", "Выбранная модель сейчас недоступна. Повторите позже.", True
if status == 404 and (path.endswith(("/chat/completions", "/completions", "/embeddings", "/images/generations")) or "/v1beta/" in path):
# >5000×404 за 2ч, 0 успехов; glm-5.3 сессии клиентов ломались «Запрос отклонён»).
# Реально отсутствующая модель отдаётся new-api как 503 model_not_found, так что 404 на
return 503, "upstream_route_dead", (
"Маршрут выбранной модели временно недоступен. "
"Это проблема шлюза, а не вашего запроса. Повторите позже."), True
channel = "channel error" in text or re.search(r"channel #\d+", text)
permission = (error_code in ("model_not_allowed", "model_forbidden", "model_access_denied")
or "this token has no access to model" in text
or "not allowed for this key" in text or "model access denied" in text)
if (status == 503 and error_code == "upstream_model_denied") or (status == 403 and (
(channel and permission) or ("not allowed for this key" in text and "allowed:" in text))):
return 503, "upstream_model_denied", (
"Маршрут не разрешает выбранную модель. Это не означает недостаточный ранг "
"вашего ключа. Повторите позже."), True
# from_upstream denotes the local new-api hop too, not proven provider origin.
if status == 403 and (error_code in ("model_not_allowed", "model_forbidden", "model_access_denied")
or "this token has no access to model" in text):
code = error_code if error_code in ("model_not_allowed", "model_forbidden") else "model_access_denied"
return 403, code, (
"Запрошенная модель не разрешена этим API-ключом. Проверьте точное имя "
"в актуальном Mini App → «Модели»: старые имена могли быть сняты с обслуживания. "
"Если модель должна быть доступна, откройте /profile в @iishkogatewaybot "
"для синхронизации прав ключа."), False
if status == 403 and "address is blocked" in text and "authentication" in text:
return 503, "upstream_ip_blocked", (
"Маршрут выбранной модели временно заблокирован. Ваш API-ключ не отозван; "
"повторите запрос позже."), True
if status == 503 and ("failed to get available channel" in text or "no available channel" in text):
# This is a catalog/route absence, not a gateway outage. A 404 stops blind
# retries and tells clients to refresh /v1/models.
return 404, "model_unavailable", (
"У модели сейчас нет живого маршрута. Обновите список через /v1/models "
"и выберите доступную модель."), False
if status >= 500 or (status == 403 and channel):
return 503, "upstream_unavailable", "Выбранная модель временно недоступна. Повторите запрос позже.", True
if status == 403:
return 403, "request_forbidden", (
"Запрос запрещён. Причина не подтверждена: "
"это не обязательно ранг или баланс вашего ключа. "
"Передайте request_id в поддержку @iishkogatewaybot."), False
if "allowed values: ['text']" in text:
# «contents.parts.type is invalid, allowed values: ['text']». Старый fallback врал
# «проверьте название модели» — агент-клиенты ретраили и ломали сессию.
return 400, "vision_not_supported", (
"Выбранная модель не принимает изображения: её маршрут текстовый (allowed: text). "
"Уберите картинку из запроса и из истории сессии или выберите vision-модель. "
"В этом запросе другая модель не подставлялась."), False
return status, "invalid_request", "Запрос отклонён. Проверьте название модели (/v1/models), параметры запроса и маршрут. Если модель точно есть в списке — повторите через минуту или напишите в @iishkogatewaybot.", False
def public_error(status, raw, path, user_balance=None, from_upstream=False, api_key=None):
"""Safe error JSON from bytes/text or parsed envelopes; never echo upstream prose."""
if type(status) is not int or not 400 <= status <= 599:
status = 502
source, error_code, request_ids, gateway_ids, codes = _error_details(raw)
status, code, message, retryable = _category(
status, source.lower(), path if isinstance(path, str) else "",
user_balance=user_balance, from_upstream=from_upstream, error_code=error_code,
api_key=api_key, codes=codes)
category = "invalid_request_error" if status < 500 else "upstream_error"
result = {"error": {"message": message, "type": category, "code": code, "retryable": retryable}}
match = _REQUEST_ID.search(source)
if match:
request_ids.append(match.group(1))
for field, candidates in (("request_id", request_ids), ("gateway_request_id", gateway_ids)):
for value in candidates:
if _public_id(value):
result["error"][field] = value
break
return status, result
+291
View File
@@ -0,0 +1,291 @@
import asyncio
from collections import deque
from contextlib import closing
from dataclasses import dataclass
import hashlib
import hmac
import json
import math
import os
from pathlib import Path
import secrets
import sqlite3
import time
from urllib.parse import parse_qsl
from aiohttp import web
from gateway_policy import inspect_token, denial_response, GENERATION_PATHS
from gateway_usage import daily_snapshot, quota_headers
@dataclass(frozen=True)
class Admission:
allowed: bool
status: int
code: str
limit: int
remaining: int
retry_after: int = 0
class AdaptiveLimiter:
def __init__(self, rpm=120, fair_rpm=10, max_inflight=256,
per_key_inflight=8, max_keys=8192, pressure=.75, clock=time.monotonic):
for value in (rpm, fair_rpm, max_inflight, per_key_inflight, max_keys):
if type(value) is not int or value < 1:
raise ValueError('invalid admission configuration')
if fair_rpm > rpm or per_key_inflight > max_inflight or not 0 < pressure <= 1:
raise ValueError('invalid admission configuration')
self.rpm, self.fair_rpm = rpm, fair_rpm
self.max_inflight, self.per_key_inflight = max_inflight, per_key_inflight
self.max_keys, self.pressure, self.clock = max_keys, pressure, clock
self.keys = {}
self.inflight = 0
self.secret = secrets.token_bytes(32)
self.next_cleanup = 0.0
@classmethod
def from_env(cls):
return cls(rpm=int(os.getenv('IISHKO_BASE_RPM', '120')),
fair_rpm=int(os.getenv('IISHKO_FAIR_RPM', '10')),
max_inflight=int(os.getenv('IISHKO_MAX_INFLIGHT', '256')),
per_key_inflight=int(os.getenv('IISHKO_PER_KEY_INFLIGHT', '8')),
max_keys=int(os.getenv('IISHKO_LIMITER_MAX_KEYS', '8192')),
pressure=float(os.getenv('IISHKO_PRESSURE_THRESHOLD', '.75')))
def identity(self, raw_key, owner=None):
value = 'account:' + str(owner) if owner is not None else 'key:' + raw_key
return hmac.new(self.secret, value.encode(), hashlib.sha256).digest()
def admit(self, identity):
now = self.clock()
if now >= self.next_cleanup:
for key, state in list(self.keys.items()):
times, active = state
while times and times[0] <= now - 60:
times.popleft()
if not times and not active:
del self.keys[key]
self.next_cleanup = now + 1
state = self.keys.get(identity)
if state is None:
if len(self.keys) >= self.max_keys:
return Admission(False, 503, 'gateway_busy', self.rpm, 0, 2), lambda: None
state = self.keys[identity] = [deque(), 0]
times, active = state
while times and times[0] <= now - 60:
times.popleft()
limit = self.rpm
if self.inflight >= math.ceil(self.max_inflight * self.pressure) and len(times) >= self.fair_rpm:
limit = max(self.fair_rpm, self.rpm // 2)
remaining = max(0, limit - len(times))
if not remaining:
retry = max(1, math.ceil(times[0] + 60 - now))
return Admission(False, 429, 'adaptive_rate_limit', limit, 0, retry), lambda: None
if active >= self.per_key_inflight:
return Admission(False, 429, 'key_concurrency_limit', limit, remaining, 2), lambda: None
if self.inflight >= self.max_inflight:
return Admission(False, 503, 'gateway_busy', limit, remaining, 2), lambda: None
times.append(now)
state[1] += 1
self.inflight += 1
released = False
def release():
nonlocal released
if not released:
released = True
state[1] -= 1
self.inflight -= 1
return Admission(True, 200, '', limit, remaining - 1), release
def _owner(db, raw_key):
from gateway_policy import OWNER
with closing(sqlite3.connect(Path(db).resolve().as_uri() + '?mode=ro', uri=True, timeout=3)) as con:
rows = con.execute('SELECT name FROM tokens WHERE key=? AND deleted_at IS NULL LIMIT 2', (raw_key,)).fetchall()
if len(rows) != 1:
return None
match = OWNER.fullmatch(rows[0][0] or '')
return int(match[1]) if match else None
FORM_GENERATION = frozenset(('/v1/audio/transcriptions', '/v1/audio/translations'))
JSON_GENERATION = GENERATION_PATHS - FORM_GENERATION
_DAILY_CODES = frozenset(('daily_limit', 'daily_budget_exhausted'))
def _form_model(raw, *, multipart):
"""Bounded `model` field from an already-read form body; '' when absent."""
try:
if not multipart:
pairs = parse_qsl(raw.decode('utf-8', 'replace'), keep_blank_values=False, max_num_fields=64)
value = next((item for name, item in pairs if name == 'model'), '')
return value if 0 < len(value) <= 256 else ''
for marker in (b'name="model"', b"name='model'", b'name=model'):
start = 0
while True:
at = raw.find(marker, start)
if at < 0:
break
start = at + 1
if at and (raw[at - 1:at].isalnum() or raw[at - 1:at] in (b'_', b'-')):
continue # filename="model" is not the field
head = raw[at:at + 512]
separator = b'\r\n\r\n' if b'\r\n\r\n' in head else b'\n\n'
if separator not in head:
continue
value_at = at + head.index(separator) + len(separator)
lines = raw[value_at:value_at + 512].splitlines()
value = lines[0].strip().decode('utf-8', 'replace') if lines else ''
if 0 < len(value) <= 256:
return value
except (ValueError, UnicodeDecodeError):
return ''
return ''
async def _generation_model(request):
"""Model declared by a generation POST; ValueError when the body is unparseable.
The body is read once through request.read(), which caches the bytes for the
proxy. request.post() would consume the stream and leave the proxy with an
empty upload body, so multipart fields are read from those same bytes.
"""
raw = await request.read()
if not raw:
return ''
content_type = (request.content_type or '').lower()
if content_type.startswith('multipart/form-data'):
return _form_model(raw, multipart=True)
if content_type == 'application/x-www-form-urlencoded':
return _form_model(raw, multipart=False)
try:
payload = json.loads(raw)
except (ValueError, UnicodeDecodeError):
raise ValueError('invalid request body') from None
if not isinstance(payload, dict):
raise ValueError('invalid request body')
value = payload.get('model')
return value if isinstance(value, str) and value else ''
def _daily_limited(response):
"""A gateway 429 that resets at Moscow midnight, not a transport delay."""
if not isinstance(response, web.Response) or response.status != 429:
return False
if response.content_type != 'application/json':
return False
body = response.body
if not isinstance(body, (bytes, bytearray)) or len(body) > 8192:
return False
try:
payload = json.loads(body)
except (ValueError, TypeError):
return False
error = payload.get('error') if isinstance(payload, dict) else None
return isinstance(error, dict) and error.get('code') in _DAILY_CODES
def install(app, *, newapi_db, bot_db, limits, entitlement_reader=None, model_access=None,
limiter=None):
limiter = limiter or AdaptiveLimiter.from_env()
app['iishko_admission'] = limiter
def enrich(request, response):
if (isinstance(response, web.Response) and not response.prepared
and response.status >= 400 and response.content_type == 'application/json'
and isinstance(response.body, (bytes, bytearray))):
try:
payload = json.loads(response.body)
if isinstance(payload, dict) and isinstance(payload.get('error'), dict):
payload['error']['request_id'] = request['iishko_request_id']
payload['error']['gateway_status'] = 'degraded' if response.status >= 500 else 'operational'
response.body = json.dumps(payload, ensure_ascii=False).encode()
except (ValueError, TypeError):
pass
return response
@web.middleware
async def admission(request, handler):
if not request.path.startswith('/v1/'):
return await handler(request)
request['iishko_request_id'] = secrets.token_hex(16)
from gateway_errors import normalize_auth_headers
try:
normalized = normalize_auth_headers(request.headers)
auth = normalized.get('Authorization', '').split()
raw_key = auth[1] if len(auth) == 2 and auth[0].lower() == 'bearer' else ''
except ValueError:
return denial_response((400, 'conflicting_authentication', 'Use one API credential.'), request['iishko_request_id'])
if not raw_key:
return denial_response((401, 'missing_api_key', 'An API key is required.'), request['iishko_request_id'])
raw_key = raw_key.removeprefix('sk-')
request['iishko_raw_key'] = raw_key
generation = request.method == 'POST' and request.path.rstrip('/') in GENERATION_PATHS
# caller must not be able to buffer up to MAX_BODY bytes before being refused.
try:
verdict = await asyncio.to_thread(inspect_token, newapi_db, bot_db, raw_key, '',
model_access=model_access)
except (sqlite3.Error, OSError, ValueError, TypeError):
return denial_response((503, 'policy_unavailable', 'Access checks are temporarily unavailable. The request was not forwarded.'), request['iishko_request_id'])
if verdict:
return denial_response(verdict, request['iishko_request_id'])
if not generation:
return enrich(request, await handler(request))
path = request.path.rstrip('/')
try:
model = await _generation_model(request)
except ValueError:
return denial_response((400, 'invalid_request', 'A valid JSON request is required.'), request['iishko_request_id'])
if path in JSON_GENERATION and not model:
return denial_response((400, 'invalid_request', 'A model identifier is required.'), request['iishko_request_id'])
# Model-aware policy runs after the body is known; it is read-only and
# charges nothing, so the daily counter is still written exactly once.
try:
verdict = await asyncio.to_thread(inspect_token, newapi_db, bot_db, raw_key, model,
model_access=model_access)
if verdict:
return denial_response(verdict, request['iishko_request_id'])
owner = await asyncio.to_thread(_owner, newapi_db, raw_key)
except (sqlite3.Error, OSError, ValueError, TypeError):
return denial_response((503, 'policy_unavailable', 'Access checks are temporarily unavailable. The request was not forwarded.'), request['iishko_request_id'])
decision, release = limiter.admit(limiter.identity(raw_key, owner))
request['iishko_admission_result'] = decision
if not decision.allowed:
return denial_response((decision.status, decision.code, 'Gateway is busy. Retry after the specified delay.'), request['iishko_request_id'])
try:
return enrich(request, await handler(request))
finally:
release()
async def prepare(request, response):
if not request.path.startswith('/v1/'):
return
request_id = request.get('iishko_request_id', secrets.token_hex(16))
response.headers['X-Request-ID'] = request_id
response.headers['X-Gateway-Status'] = 'degraded' if response.status >= 500 else 'operational'
decision = request.get('iishko_admission_result')
if decision:
response.headers['X-RateLimit-Limit'] = str(decision.limit)
response.headers['X-RateLimit-Remaining'] = str(decision.remaining)
if decision.retry_after:
response.headers['Retry-After'] = str(decision.retry_after)
provider = request.get('iishko_provider')
if provider:
response.headers['X-Iishko-Provider'] = provider
raw_key = request.get('iishko_raw_key')
if raw_key:
try:
snapshot = await asyncio.to_thread(daily_snapshot, newapi_db, bot_db, raw_key,
limits=limits, entitlement_reader=entitlement_reader)
response.headers.update(quota_headers(snapshot))
if (response.status == 429 and not (decision and decision.retry_after)
and snapshot and snapshot.get('reset_at')
and (_daily_limited(response) or snapshot['remaining'] == 0)):
response.headers.setdefault('Retry-After', str(max(1, snapshot['reset_at'] - int(time.time()))))
except (sqlite3.Error, OSError, ValueError, TypeError):
response.headers['X-Iishko-Daily-Status'] = 'unavailable'
app.middlewares.insert(0, admission)
app.on_response_prepare.append(prepare)
return limiter
+161
View File
@@ -0,0 +1,161 @@
import asyncio
from contextlib import closing
import hmac
import ipaddress
import json
import logging
from pathlib import Path
import re
import sqlite3
import time
from aiohttp import web
log = logging.getLogger('gateway_policy')
OWNER = re.compile(r'(?:tg|pm|sol)([1-9][0-9]*)(?:-k[1-9][0-9]*)?\Z')
GENERATION_PATHS = frozenset(('/v1/chat/completions', '/v1/completions', '/v1/messages',
'/v1/responses', '/v1/images/generations', '/v1/images/edits',
'/v1/images/variations', '/v1/embeddings',
'/v1/audio/speech', '/v1/audio/transcriptions', '/v1/audio/translations'))
def _connect(path):
con = sqlite3.connect(Path(path).resolve().as_uri() + '?mode=ro', uri=True, timeout=10)
con.execute('PRAGMA query_only=ON')
return con
def inspect_token(newapi_db, bot_db, raw_key, model, now=None, model_access=None):
"""Return an explicit denial or None. All reads are WAL-consistent and query-only."""
now = int(time.time()) if now is None else now
with closing(_connect(newapi_db)) as con:
row = con.execute(
'SELECT t.id,t.name,t.status,t.expired_time,t.remain_quota,t.unlimited_quota,'
't.model_limits_enabled,t.model_limits,u.status FROM tokens t '
'JOIN users u ON u.id=t.user_id AND u.deleted_at IS NULL '
'WHERE t.key=? AND t.deleted_at IS NULL LIMIT 1', (raw_key,)).fetchone()
if not row:
return 401, 'invalid_api_key', 'API-ключ не найден. Актуальные ключи доступны в Mini App.'
tid, name, status, expired, remain, unlimited, limited, models, user_status = row
if user_status != 1:
return 403, 'account_disabled', 'Аккаунт API заблокирован. Обратитесь в поддержку.'
if status == 4 and not unlimited and (remain or 0) <= 0:
return 402, 'insufficient_quota', 'На ключе нет API-кредита. Переведите баланс в Mini App.'
if status != 1:
if status == 2 and con.execute(
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='wa_daily_cap_pauses'").fetchone():
paused = con.execute('SELECT 1 FROM wa_daily_cap_pauses WHERE tid=? AND name=?',
(tid, name)).fetchone()
if paused:
return 429, 'daily_budget_exhausted', ('Дневной бюджет API исчерпан. Баланс сохранён; '
'доступ восстановится после 00:00 МСК.')
return 403, 'api_key_disabled', 'API-ключ приостановлен. Проверьте его состояние в Mini App.'
if expired and expired > 0 and expired <= now:
return 401, 'api_key_expired', 'Срок действия API-ключа истёк.'
if not unlimited and (remain or 0) <= 0:
return 402, 'insufficient_quota', 'Недостаточно API-кредита. Проверьте баланс в Mini App.'
token_models = {m.strip() for m in (models or '').split(',') if m.strip()}
identity = OWNER.fullmatch(name or '')
allowed = not limited or model in token_models
if model and identity and model_access is not None:
allowed = model_access(int(identity[1]), model, token_models, allowed)
if model and not allowed:
return 403, 'model_access_denied', ('У ключа нет доступа к выбранной модели. Проверьте точное '
'имя в /v1/models, свой ранг и срок действия доступа в Mini App.')
match = OWNER.fullmatch(name or '')
if match:
with closing(_connect(bot_db)) as con:
user = con.execute('SELECT banned,api_blocked,api_block_reason FROM users WHERE tg_id=?',
(int(match[1]),)).fetchone()
if not user:
return 403, 'account_not_found', 'Аккаунт ключа не найден. Откройте бота и обратитесь в поддержку.'
if user[0]:
return 403, 'account_banned', 'Аккаунт заблокирован. Апелляция: @reformboss'
if user[1]:
return 403, 'access_blocked', user[2] or 'Доступ приостановлен. Откройте бота и выполните условия доступа.'
return None
def denial_response(denial, request_id=None):
status, code, message = denial
gateway_status = 'degraded' if status >= 500 else 'operational'
error = {'message': message, 'type': 'gateway_error',
'code': code, 'retryable': status in (429, 503, 504),
'gateway_status': gateway_status}
headers = {'Cache-Control': 'no-store', 'X-Gateway-Status': gateway_status}
if status in (503, 504):
headers['Retry-After'] = '2'
if request_id:
error['request_id'] = request_id
headers['X-Request-ID'] = request_id
return web.json_response({'error': error}, status=status, headers=headers)
def create_handler(newapi_db, bot_db, secret, consume=None, check_access=None, allowed_models=None,
quota_snapshot=None, model_access=None):
async def authorize(req):
request_id = req.headers.get('X-Request-ID', '')
if not re.fullmatch(r'[0-9a-f]{32}', request_id):
request_id = None
async def result(response, raw_key):
if quota_snapshot is not None:
try:
from gateway_usage import quota_headers
snapshot = await asyncio.to_thread(quota_snapshot, raw_key)
response.headers.update(quota_headers(snapshot))
if response.status == 429 and snapshot and snapshot.get('reset_at'):
response.headers['Retry-After'] = str(max(1, snapshot['reset_at'] - int(time.time())))
except (sqlite3.Error, ValueError, TypeError, OSError):
log.warning('daily_metadata_unavailable')
response.headers['X-Iishko-Daily-Status'] = 'unavailable'
return response
try:
local = ipaddress.ip_address(req.remote or '').is_loopback
except ValueError:
local = False
supplied = req.headers.get('X-Gateway-Policy-Token', '')
if not local or not secret or not hmac.compare_digest(supplied.encode(), secret.encode()):
return denial_response((403, 'policy_auth_failed', 'Internal authorization required.'), request_id)
if req.content_length and req.content_length > 16 * 1024:
return denial_response((413, 'invalid_policy_request', 'Policy payload too large.'), request_id)
try:
raw = bytearray()
async for chunk in req.content.iter_chunked(4096):
raw.extend(chunk)
if len(raw) > 16 * 1024:
return denial_response((413, 'invalid_policy_request', 'Policy payload too large.'), request_id)
payload = json.loads(raw)
if not isinstance(payload, dict):
raise ValueError('not an object')
path, method, model = (payload.get(k, '') for k in ('path', 'method', 'model'))
if not all(isinstance(v, str) for v in (path, method, model)):
raise ValueError('invalid fields')
if not path.startswith('/v1/') or method not in ('GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS') or len(model) > 4096:
raise ValueError('invalid policy scope')
auth = req.headers.get('Authorization', '').split()
if len(auth) != 2 or auth[0].lower() != 'bearer':
return denial_response((401, 'missing_api_key', 'An API key is required.'), request_id)
raw_key = auth[1].removeprefix('sk-')
verdict = await asyncio.to_thread(inspect_token, newapi_db, bot_db, raw_key, model,
model_access=model_access)
if verdict:
response = denial_response(verdict, request_id)
return await result(response, raw_key) if verdict[1] == 'daily_budget_exhausted' else response
if allowed_models is not None and model and model not in allowed_models:
return denial_response((404, 'model_not_found', 'Модель не входит в проверенный каталог. Список: /v1/models.'), request_id)
if check_access is not None:
blocked, reason = await check_access(raw_key)
if blocked:
return denial_response((403, 'access_blocked', reason), request_id)
if consume is not None and method == 'POST' and path in GENERATION_PATHS:
verdict = await asyncio.to_thread(consume, raw_key, model)
if verdict:
code = 'daily_limit' if verdict[0] == 429 else 'policy_unavailable'
return await result(denial_response((verdict[0], code, verdict[1]), request_id), raw_key)
return await result(web.Response(status=204, headers={'Cache-Control': 'no-store'}), raw_key)
except (ValueError, TypeError):
return denial_response((400, 'invalid_policy_request', 'Invalid policy payload.'), request_id)
except Exception:
log.exception('gateway_policy_unavailable')
return denial_response((503, 'policy_unavailable', 'Проверка доступа временно недоступна. Запрос провайдеру не отправлен.'), request_id)
return authorize
+105
View File
@@ -0,0 +1,105 @@
import asyncio
import json
import time
import aiohttp
from multidict import CIMultiDict
from gateway_providers import ProviderError, response_effort, safe_to_retry
MAX_REJECTION = 65536
def outcome_status(result, fallback):
"""Downstream status the success handler actually produced.
A 200 from upstream can still become an identity, payload, or validation
refusal downstream. Accounting must follow the bytes that left the gateway,
not the upstream status line, or a broken route is recorded as healthy.
Partial or broken streams remain visible only when the handler raises; a
prepared 2xx stream that ends short is not observable here.
"""
status = getattr(result, "status", None)
return status if type(status) is int and 100 <= status <= 599 else fallback
async def relay_selected(request, session, target, *, headers, body, registry, newapi_db,
raw_key, model, success, failure, retry_budget=30):
pinned = request.headers.get("X-Iishko-Provider") or None
try:
payload = json.loads(body) if body else {}
effort = response_effort(payload)
header_effort = request.headers.get("X-Iishko-Effort")
if header_effort and header_effort != effort:
raise ProviderError(400, "effort_requires_request_field", "Specify effort in the model request body; headers do not rewrite generation parameters.")
except (ValueError, TypeError, UnicodeDecodeError) as error:
if isinstance(error, ProviderError):
raise
raise ProviderError(400, "invalid_request", "Provider routing requires a JSON generation request.") from error
attempted = []
started = time.monotonic()
for attempt in range(2):
selection = asyncio.create_task(asyncio.to_thread(
registry.choose, newapi_db, raw_key, model,
pinned=pinned, effort=effort, exclude=tuple(attempted)))
try:
choice = await asyncio.shield(selection)
except asyncio.CancelledError:
def release_late(future):
try:
late_choice = future.result()
except (Exception, asyncio.CancelledError):
return
registry.abandon(late_choice)
selection.add_done_callback(release_late)
raise
attempted.append(choice.id)
finished = False
success_started = False
outgoing = CIMultiDict((k, v) for k, v in headers.items() if k.lower() not in (
"x-iishko-provider", "x-iishko-effort", "x-api-key", "api-key", "x-new-api-channel-id", "x-channel-id"))
try:
outgoing["Authorization"] = registry.pinned_authorization(raw_key, choice)
outgoing["Accept-Encoding"] = "identity"
async with session.request(request.method, target, headers=outgoing, data=body,
allow_redirects=False, auto_decompress=False,
skip_auto_headers={"Accept-Encoding"}) as response:
request["iishko_provider"] = choice.id
if response.status >= 400:
raw = bytearray()
async for chunk in response.content.iter_chunked(16384):
raw.extend(chunk)
if len(raw) > MAX_REJECTION:
raw = bytearray()
break
registry.complete(choice, response.status, retry_after=response.headers.get("Retry-After", 0))
finished = True
can_retry = (not pinned and attempt == 0 and time.monotonic() - started < retry_budget
and safe_to_retry(response.status, raw))
if can_retry:
continue
return await failure(response.status, bytes(raw), response.headers)
success_started = True
result = await success(response)
# [OUTCOME 2610] The route is credited with what the caller got,
# not with the upstream 200. No replay is possible after this
# point, and the lease is released exactly once below.
registry.complete(choice, outcome_status(result, response.status))
finished = True
return result
except asyncio.CancelledError:
raise
except (aiohttp.ClientError, asyncio.TimeoutError, ConnectionResetError) as error:
# The provider may already have accepted/billed the generation.
# Never replay an ambiguous connection failure on a reserve.
registry.complete(choice, 504 if isinstance(error, asyncio.TimeoutError) else 502)
finished = True
if success_started:
if request.transport is not None:
request.transport.close()
raise
return await failure(504 if isinstance(error, asyncio.TimeoutError) else 503, b"", {})
finally:
if not finished:
registry.abandon(choice)
raise ProviderError(503, "no_healthy_provider", "No healthy same-model provider is available.")
+295
View File
@@ -0,0 +1,295 @@
from contextlib import closing
from dataclasses import dataclass
import json
from pathlib import Path
import re
import sqlite3
import threading
import time
from request_effort import InvalidEffort, read_effort
_ID = re.compile(r"[a-z][a-z0-9_-]{0,47}\Z")
_SAFE_RETRIES = frozenset(("upstream_throttled", "overloaded_error", "server_overloaded",
"rate_limit_exceeded", "no_available_channel", "upstream_unavailable"))
# Evidence a method can support. A response model echo proves identity only, so
# it can never carry `operator_verified` (that would claim weights/provenance).
_EVIDENCE_STATUS = {"none": ("unverified",),
"response_model": ("identity_checked",),
"tool_roundtrip": ("identity_checked", "operator_verified"),
"official_route": ("operator_verified",),
"signed_attestation": ("operator_verified",)}
_EVIDENCE_FIELDS = frozenset(("status", "method", "checked_at", "reference"))
def public_verification(verification):
"""Project evidence for the public catalogue: method and timestamp only.
`reference` may name a private operator note, admin URL, or ticket that must
never leave the registry, so it is deliberately not projected.
"""
return {"status": verification["status"], "method": verification["method"],
"checked_at": verification["checked_at"]}
class ProviderError(ValueError):
def __init__(self, status, code, message):
super().__init__(message)
self.status, self.code, self.message = status, code, message
def _read(db):
con = sqlite3.connect(Path(db).resolve().as_uri() + "?mode=ro", uri=True, timeout=3)
con.row_factory = sqlite3.Row
con.execute("PRAGMA query_only=ON")
return con
def response_effort(payload):
"""Read policy metadata only. The generation bytes remain unchanged."""
try:
return read_effort(payload)
except InvalidEffort as error:
raise ProviderError(400, "invalid_effort", str(error)) from None
def safe_to_retry(status, raw):
"""Only an explicit overload rejection, never a timeout/ambiguous transport."""
if status not in (429, 503):
return False
try:
body = json.loads(raw)
error = body.get("error", {})
return isinstance(error, dict) and (error.get("code") or error.get("type")) in _SAFE_RETRIES
except (ValueError, TypeError, AttributeError, UnicodeDecodeError):
return False
@dataclass(frozen=True)
class ProviderChoice:
id: str
channel_id: int
model: str
probe: bool = False
class ProviderRegistry:
def __init__(self, config=None, *, clock=time.monotonic):
config = config or {}
if not isinstance(config, dict) or type(config.get("pinning_enabled", False)) is not bool:
raise ValueError("invalid provider configuration")
self.pinning_enabled = config.get("pinning_enabled", False)
self.clock = clock
self._lock = threading.Lock()
self._circuits = {}
self._round = {}
self._active = {}
self.providers = []
used_ids, used_channels = set(), set()
entries = config.get("providers", [])
if not isinstance(entries, list) or len(entries) > 128:
raise ValueError("invalid provider list")
for entry in entries:
if not isinstance(entry, dict):
raise ValueError("invalid provider entry")
pid, name = entry.get("id"), entry.get("name")
if not isinstance(pid, str) or not _ID.fullmatch(pid) or pid in used_ids:
raise ValueError("invalid or duplicate provider id")
if not isinstance(name, str) or not 1 <= len(name) <= 80:
raise ValueError("invalid provider display name")
channels, models = entry.get("channel_ids", []), entry.get("models", {})
if not isinstance(channels, list) or len(channels) > 512 or any(type(v) is not int or v < 1 for v in channels):
raise ValueError("invalid provider channel ids")
if len(channels) != len(set(channels)) or used_channels.intersection(channels):
raise ValueError("a channel cannot masquerade as independent reserve providers")
if not isinstance(models, dict) or len(models) > 1024:
raise ValueError("invalid provider models")
clean_models = {}
for model, capability in models.items():
if not isinstance(model, str) or not 1 <= len(model) <= 256 or not isinstance(capability, dict):
raise ValueError("invalid model capability")
effort = capability.get("effort_levels")
if effort is not None and (not isinstance(effort, list) or any(not isinstance(v, str) or not v or len(v) > 32 for v in effort)):
raise ValueError("invalid effort levels")
evidence = capability.get("verification", {})
if not isinstance(evidence, dict):
raise ValueError("invalid verification evidence")
if not set(evidence) <= _EVIDENCE_FIELDS:
raise ValueError("unknown verification evidence field")
status = evidence.get("status", "unverified")
method = evidence.get("method", "none")
if status not in ("unverified", "identity_checked", "operator_verified"):
raise ValueError("invalid verification status")
if not isinstance(method, str) or method not in _EVIDENCE_STATUS:
raise ValueError("invalid verification method")
if status not in _EVIDENCE_STATUS[method]:
raise ValueError("incoherent verification status and method")
checked = evidence.get("checked_at")
reference = evidence.get("reference")
if status == "unverified":
# Nothing was checked, so claiming a timestamp or a reference
# would be fabricated evidence rather than a downgrade.
if checked is not None or reference is not None:
raise ValueError("unverified evidence cannot carry proof fields")
elif (type(checked) is not int or checked <= 0
or not isinstance(reference, str) or not reference.strip()
or len(reference) > 200):
raise ValueError("verification requires a timestamp and evidence reference")
clean_models[model] = {"effort_levels": effort, "verification": {
"status": status, "method": method, "checked_at": checked,
# Kept privately for the operator; never projected publicly.
"reference": reference}}
priority = entry.get("priority", 0)
if type(priority) is not int or not -10000 <= priority <= 10000:
raise ValueError("invalid provider priority")
concurrency = entry.get("max_inflight", 32)
if type(concurrency) is not int or not 1 <= concurrency <= 4096 or type(entry.get("reserve", False)) is not bool:
raise ValueError("invalid provider capacity")
self.providers.append({"id": pid, "name": name, "channels": tuple(channels), "models": clean_models,
"priority": priority, "reserve": entry.get("reserve", False),
"max_inflight": concurrency})
used_ids.add(pid)
used_channels.update(channels)
self.providers.sort(key=lambda p: (p["reserve"], -p["priority"], p["id"]))
@classmethod
def from_file(cls, path):
if not path:
return cls()
with open(path, encoding="utf-8") as source:
return cls(json.load(source))
def _channels(self, con, provider, model, group):
if not provider["channels"]:
return []
marks = ",".join("?" for _ in provider["channels"])
rows = con.execute(
'SELECT DISTINCT c.id,c.model_mapping FROM channels c JOIN abilities a ON a.channel_id=c.id '
'WHERE c.status=1 AND a.enabled=1 AND a.model=? AND a."group"=? AND c.id IN (' + marks + ') ORDER BY c.id',
(model, group, *provider["channels"])).fetchall()
result = []
for row in rows:
try:
mapping = json.loads(row["model_mapping"] or "{}")
except (ValueError, TypeError):
continue
if not isinstance(mapping, dict) or mapping.get(model, model) != model:
continue
result.append(int(row["id"]))
return result
def catalog(self, db, model, group="default"):
result = []
with closing(_read(db)) as con:
for provider in self.providers:
cap = provider["models"].get(model)
if cap is None:
continue
channels = self._channels(con, provider, model, group)
with self._lock:
worst = 0
for cid in channels:
st = self._circuits.get((cid, model), {})
worst = max(worst, st.get("until", 0))
cooldown = max(0, int(worst - self.clock() + .999))
busy = self._active.get(provider["id"], 0) >= provider["max_inflight"]
levels = cap["effort_levels"]
result.append({"id": provider["id"], "name": provider["name"],
"available": bool(channels) and not cooldown and not busy and self.pinning_enabled,
"reserve": provider["reserve"], "effort": None if levels is None else bool(levels),
"effort_levels": levels or [], "verification": public_verification(cap["verification"]),
"cooldown_seconds": cooldown})
return {"model": model, "providers": result, "pinning_enabled": self.pinning_enabled,
"identity_notice": "Model name checks detect mismatches; they do not prove original weights or vendor provenance."}
def choose(self, db, raw_key, model, *, pinned=None, effort=None, exclude=()):
if not self.pinning_enabled:
raise ProviderError(503, "provider_selection_unavailable", "Provider selection has not been enabled by the operator.")
if pinned and (not isinstance(pinned, str) or not _ID.fullmatch(pinned)):
raise ProviderError(400, "invalid_provider", "Invalid provider id.")
with closing(_read(db)) as con:
token = con.execute('SELECT t."group",u.role FROM tokens t JOIN users u ON u.id=t.user_id '
'WHERE t.key=? AND t.deleted_at IS NULL AND t.status=1 AND u.status=1 AND u.deleted_at IS NULL',
(raw_key,)).fetchall()
if len(token) != 1 or int(token[0]["role"]) < 10:
raise ProviderError(503, "provider_selection_unavailable", "This New API installation cannot safely pin the authenticated token.")
group = token[0]["group"] or "default"
known = False
unsupported = False
for provider in self.providers:
if pinned and provider["id"] != pinned:
continue
cap = provider["models"].get(model)
if cap is None:
continue
known = True
if provider["id"] in exclude:
continue
if effort is not None and (cap["effort_levels"] is None or effort not in cap["effort_levels"]):
unsupported = True
continue
channels = self._channels(con, provider, model, group)
if not channels:
continue
with self._lock:
if self._active.get(provider["id"], 0) >= provider["max_inflight"]:
continue
live = [cid for cid in channels
if (lambda s: not s or s["failures"] < 3 or
(s["until"] <= self.clock() and not s.get("probe"))
)(self._circuits.get((cid, model)))]
if not live:
continue
probe_chan = None
for cid in live:
s = self._circuits.get((cid, model))
if s and s["failures"] >= 3 and s["until"] <= self.clock() and not s.get("probe"):
s["probe"] = True
probe_chan = cid
break
index = self._round.get(provider["id"], 0)
self._round[provider["id"]] = index + 1
self._active[provider["id"]] = self._active.get(provider["id"], 0) + 1
chosen = probe_chan if probe_chan is not None else live[index % len(live)]
return ProviderChoice(provider["id"], chosen, model, probe_chan is not None)
if pinned and not known:
raise ProviderError(400, "provider_model_unavailable", "The selected provider does not serve this exact model.")
if unsupported:
raise ProviderError(400, "effort_not_supported", "Effort support for this model/provider is unsupported or unverified.")
raise ProviderError(503, "no_healthy_provider", "No healthy same-model provider is available. Retry later.")
def complete(self, choice, status, *, retry_after=0):
with self._lock:
self._active[choice.id] = max(0, self._active.get(choice.id, 0) - 1)
key = (choice.channel_id, choice.model)
if 200 <= status < 400:
self._circuits.pop(key, None)
return
if status not in (401, 403, 404, 429, 500, 502, 503, 504):
if choice.probe:
self._circuits.pop(key, None)
return
state = self._circuits.setdefault(key, {"failures": 0, "until": 0})
state["failures"] += 1
state["probe"] = False
if status in (401, 403, 404):
state["failures"] = max(3, state["failures"])
if state["failures"] >= 3:
try:
delay = max(15, min(120, int(retry_after)))
except (ValueError, TypeError):
delay = 15
state["until"] = self.clock() + delay
def abandon(self, choice):
"""Release cancellation without claiming provider success or replaying."""
with self._lock:
self._active[choice.id] = max(0, self._active.get(choice.id, 0) - 1)
state = self._circuits.get((choice.channel_id, choice.model))
if state and choice.probe:
state["probe"] = False
@staticmethod
def pinned_authorization(raw_key, choice):
if not isinstance(raw_key, str) or not re.fullmatch(r"[A-Za-z0-9_]{1,256}", raw_key):
raise ProviderError(503, "provider_selection_unavailable", "The token format cannot safely select a New API channel.")
return "Bearer sk-" + raw_key + "-" + str(choice.channel_id)
+73
View File
@@ -0,0 +1,73 @@
"""Read-only account-wide daily request metadata shared by both API protocols."""
from contextlib import closing
from datetime import datetime, timedelta, timezone
from pathlib import Path
import re
import sqlite3
import time
_OWNER = re.compile(r"(?:tg|pm|sol)([1-9][0-9]*)(?:-k[1-9][0-9]*)?\Z")
DEFAULT_REQUEST_LIMITS = {0: 5000, 1: 5000, 2: 10000, 3: 20000, 4: 30000}
MSK = timezone(timedelta(hours=3))
def _read(path):
con = sqlite3.connect(Path(path).resolve().as_uri() + "?mode=ro", uri=True, timeout=3)
con.row_factory = sqlite3.Row
con.execute("PRAGMA query_only=ON")
return con
def daily_snapshot(newapi_db, bot_db, raw_key, *, now=None, limits=None, entitlement_reader=None):
now = int(time.time()) if now is None else int(now)
moment = datetime.fromtimestamp(now, MSK)
day = moment.date().isoformat()
reset = int(datetime.combine(moment.date() + timedelta(days=1), datetime.min.time(), MSK).timestamp())
with closing(_read(newapi_db)) as con:
tokens = con.execute("SELECT name FROM tokens WHERE key=? AND deleted_at IS NULL", (raw_key,)).fetchall()
if len(tokens) != 1:
return None
match = _OWNER.fullmatch(tokens[0]["name"] or "")
if not match:
return None
uid = int(match[1])
if uid > 9223372036854775807:
return None
with closing(_read(bot_db)) as con:
user = con.execute("SELECT * FROM users WHERE tg_id=?", (uid,)).fetchone()
if user is None:
return None
columns = set(user.keys())
if not {"quota_date", "chat_count", "rank_cache"}.issubset(columns):
raise sqlite3.DatabaseError("daily request counters are unavailable")
def value(key, default=0):
return user[key] if key in columns and user[key] is not None else default
unlimited = bool(value("vip") or value("admin") or int(value("unlim_until")) > now)
locked = int(value("badge_lock")) if not value("badge_until") or int(value("badge_until")) > now else 0
rank = min(4, max(0, locked, int(value("rank_cache", 1))))
configured = DEFAULT_REQUEST_LIMITS if limits is None else limits
base = configured.get(rank, configured.get(1, 5000))
if type(base) is not int or base < 0:
raise ValueError("invalid daily request limit")
used = max(0, int(value("chat_count"))) if value("quota_date") == day else 0
extra = 0
if entitlement_reader is not None:
extra = entitlement_reader(bot_db, uid, now=now).get("extra_requests", 0)
if type(extra) is not int or extra < 0:
raise ValueError("invalid extra request entitlement")
limit = base + extra
return {"scope": "account", "period": "day", "timezone": "Europe/Moscow", "date": day,
"limit": None if unlimited else limit, "used": used,
"remaining": None if unlimited else max(0, limit - used), "reset_at": reset,
"unlimited": unlimited, "extra_requests": extra,
"note": "Admission attempts count once before forwarding. Provider retries do not consume a second daily request. Model-specific and monetary budgets may also apply."}
def quota_headers(snapshot):
if snapshot is None:
return {}
return {"X-Iishko-Daily-Limit": "unlimited" if snapshot["unlimited"] else str(snapshot["limit"]),
"X-Iishko-Daily-Remaining": "unlimited" if snapshot["unlimited"] else str(snapshot["remaining"]),
"X-Iishko-Daily-Used": str(snapshot["used"]),
"X-Iishko-Daily-Reset": str(snapshot["reset_at"]),
"X-Iishko-Daily-Scope": "account", "X-Iishko-Daily-Timezone": "Europe/Moscow"}
File diff suppressed because it is too large Load Diff
+30
View File
@@ -0,0 +1,30 @@
"""Read-only provider moderation advisories, not routing or health verdicts."""
# are included: this is an advisory for some routes, never a DS-only claim.
MODELS = frozenset({
"qwen3.8-max",
"glm-5.3-prime",
"kimi-k2.7-code",
"qwen3-vl-plus",
"qwen3.8-flash",
"deepseek-v4.1-flash-1017",
"kimi-k3.1-pro",
"kimi-k3.1-pro-highspeed",
"qwen-max",
"qwen-plus",
"deepseek-v4-pro",
"glm-5.1",
"kimi/kimi-k3.1-pro",
"qwen3.8-max-0902",
})
LABEL = "Строгая модерация провайдера"
NOTICE = ("На части маршрутов действует контент-фильтр провайдера. "
"Отказ не означает недоступность модели; повтор того же текста может не помочь.")
def for_model(model_id):
"""Return a fresh presentation-only advisory, or None for an unlisted ID."""
if not isinstance(model_id, str) or model_id not in MODELS:
return None
return {"label": LABEL, "notice": NOTICE, "scope": "some_provider_routes",
"observed_at": "2026-10-28"}
+61
View File
@@ -0,0 +1,61 @@
"""Model identity rules: spelling aliases, never replacement models."""
import re
_CLAUDE_VERSION_FIRST = re.compile(r"claude-(\d+(?:-\d+)*)-(sonnet|opus|fable)")
_CLAUDE_SHORT_NAME = re.compile(r"(?:opus|sonnet|fable)-\d+(?:-\d+)*")
_CREATOR_PREFIXES = {
"openai": ("gpt-", "o1", "o3", "o4"),
"anthropic": ("claude-", "opus-", "sonnet-"),
"x-ai": ("grok-",), "xai": ("grok-",),
"z-ai": ("glm-", "cogview-"), "zhipu": ("glm-", "cogview-"),
"moonshotai": ("kimi-",), "moonshot": ("kimi-",),
"qwen": ("qwen",), "alibaba": ("qwen",),
"deepseek": ("deepseek-",), "deepseek-ai": ("deepseek-",),
}
_AGGREGATOR_PREFIXES = {"kr", "cx", "or", "openrouter", "pool", "modeloc", "auto", "kimi"}
class ModelIdentityError(RuntimeError):
"""A response names a different model than the one requested."""
terminal = True
status = 503
code = "model_identity_mismatch"
def __init__(self):
super().__init__("Выбранная модель сейчас недоступна. Повтори позже.")
def canonical_model(name):
if not isinstance(name, str) or not name.strip():
return ""
name = name.strip().lower()
if "/" in name:
creator, bare = name.split("/", 1)
if creator in _AGGREGATOR_PREFIXES or bare.startswith(_CREATOR_PREFIXES.get(creator, ("\0",))):
name = bare
name = name.replace("_", "-").replace(".", "-")
# Two documented spellings of the same Claude version.
match = _CLAUDE_VERSION_FIRST.fullmatch(name)
if match:
name = "claude-" + match[2] + "-" + match[1]
if _CLAUDE_SHORT_NAME.fullmatch(name):
name = "claude-" + name
# [YETA-UNC 23.10] unfiltered provider variant reported under base model name
if name.endswith("-uncensored"):
name = name[: -len("-uncensored")]
return name
def same_original_model(requested, actual):
requested = canonical_model(requested)
return bool(requested) and requested == canonical_model(actual)
def check_response_model(requested, response):
"""Check a declared response identity; absent optional model is not evidence."""
if isinstance(response, dict) and response.get("model") is not None:
if not same_original_model(requested, response["model"]):
raise ModelIdentityError()
+253
View File
@@ -0,0 +1,253 @@
#!/usr/bin/env python3
from __future__ import annotations
import json
import os
import stat
import threading
MAX_BYTES = 1024 * 1024
SPECS_NAME = "model_specs.json"
SCOPE_VENDOR = "vendor_reference"
SCOPE_UNKNOWN = "unknown"
DEFAULT_SOURCE = "https://openrouter.ai/api/v1/models"
_MAX_LIMIT = 1000000000
_ENTRY_FIELDS = ("source_model", "context_window", "max_input_tokens",
"max_output_tokens", "top_provider_context_window")
_LOCK = threading.Lock()
_CACHE = {"key": None, "specs": {}, "source": None, "scope": SCOPE_VENDOR,
"field_sources": {}, "notes": (), "bot_output_budget": None}
def candidate_paths():
"""Resolution order: explicit env override, module dir, canonical parent/bot, prod.
An explicit ``IISHKO_MODEL_SPECS`` is authoritative: when it is set, no other
location is consulted, so a missing/invalid/oversized override degrades to an
honest "unknown" reference instead of silently loading different numbers.
"""
override = os.environ.get("IISHKO_MODEL_SPECS")
if override is not None:
return [override] if override else []
here = os.path.dirname(os.path.abspath(__file__))
return [os.path.join(here, SPECS_NAME),
os.path.join(os.path.dirname(here), "bot", SPECS_NAME),
os.path.join(os.sep, "opt", "grok-bot", SPECS_NAME)]
def _positive_int(value):
if isinstance(value, bool) or not isinstance(value, int):
return None
return value if 0 < value <= _MAX_LIMIT else None
def _clean_entry(raw):
if not isinstance(raw, dict):
return None
source_model = raw.get("source_model")
if not isinstance(source_model, str) or not source_model.strip() or len(source_model) > 128:
return None
entry = {"source_model": source_model.strip()}
for field in _ENTRY_FIELDS[1:]:
value = raw.get(field)
if field == "max_input_tokens":
entry[field] = None # reference only: never inferred from context_window
continue
entry[field] = _positive_int(value)
return entry
def _clean_specs(document):
"""Return (models, header) from a parsed document, or ({}, header) when unusable."""
header = {"source": None, "scope": SCOPE_VENDOR, "field_sources": {}, "notes": (),
"bot_output_budget": None}
if not isinstance(document, dict):
return {}, header
source = document.get("source")
if isinstance(source, str) and 0 < len(source) <= 512:
header["source"] = source
scope = document.get("scope")
if isinstance(scope, str) and 0 < len(scope) <= 64:
header["scope"] = scope
field_sources = document.get("field_sources")
if isinstance(field_sources, dict):
header["field_sources"] = {k: v for k, v in field_sources.items()
if isinstance(k, str) and isinstance(v, str)}
notes = document.get("notes")
if isinstance(notes, list):
header["notes"] = tuple(n for n in notes if isinstance(n, str))
budget = document.get("bot_output_budget")
if isinstance(budget, dict):
header["bot_output_budget"] = {
"scope": budget.get("scope") if isinstance(budget.get("scope"), str) else "bot_runtime_local",
"not_a_vendor_limit": True,
"normal": _positive_int(budget.get("normal")),
"max": _positive_int(budget.get("max")),
}
models_raw = document.get("models")
if not isinstance(models_raw, dict):
return {}, header
models = {}
for name, raw in models_raw.items():
if not isinstance(name, str) or not 0 < len(name) <= 128:
continue
entry = _clean_entry(raw)
if entry is not None:
models[name] = entry
return models, header
def _stat_key(path):
try:
info = os.stat(path)
except OSError:
return None
if not stat.S_ISREG(info.st_mode) or info.st_size <= 0 or info.st_size > MAX_BYTES:
return None
return (os.path.realpath(path), info.st_mtime_ns, info.st_size)
def _load():
"""Populate the cache if the backing file changed. Never raises."""
key = None
raw = None
for path in candidate_paths():
key = _stat_key(path)
if key is None:
continue
try:
with open(path, "rb") as handle:
raw = handle.read(MAX_BYTES + 1)
except OSError:
key, raw = None, None
continue
break
with _LOCK:
if key is None:
_CACHE.update({"key": None, "specs": {}, "source": None, "scope": SCOPE_VENDOR,
"field_sources": {}, "notes": (), "bot_output_budget": None})
return
if _CACHE["key"] == key:
return
models, header = {}, {"source": None, "scope": SCOPE_VENDOR, "field_sources": {},
"notes": (), "bot_output_budget": None}
if raw is not None and len(raw) <= MAX_BYTES:
try:
document = json.loads(raw.decode("utf-8-sig"))
except (ValueError, UnicodeDecodeError):
document = None
models, header = _clean_specs(document)
_CACHE.update({"key": key, "specs": models, **header})
def reload():
"""Force the next lookup to re-read the file (deploy/tests)."""
with _LOCK:
_CACHE["key"] = None
def available():
"""True when a usable vendor reference is loaded."""
try:
_load()
return bool(_CACHE["specs"])
except Exception:
return False
def describe():
"""Header of the loaded reference; honest empty shape when nothing is loaded."""
try:
_load()
except Exception:
pass
with _LOCK:
return {
"scope": _CACHE["scope"] if _CACHE["specs"] else SCOPE_UNKNOWN,
"source": _CACHE["source"],
"gateway_verified": False,
"known_models": len(_CACHE["specs"]),
"field_sources": dict(_CACHE["field_sources"]),
"notes": list(_CACHE["notes"]),
"bot_output_budget": dict(_CACHE["bot_output_budget"] or {}) or None,
}
def _unknown(model_id):
return {
"model": model_id,
"known": False,
"scope": SCOPE_UNKNOWN,
"source": None,
"source_model": None,
"context_window": None,
"max_input_tokens": None,
"max_output_tokens": None,
"gateway_verified": False,
}
def for_model(model_id):
"""Metadata for one served model id. Unknown ids: explicit nulls, no guesses."""
if not isinstance(model_id, str) or not model_id:
return _unknown(model_id if isinstance(model_id, str) else None)
try:
_load()
with _LOCK:
entry = _CACHE["specs"].get(model_id)
source = _CACHE["source"]
scope = _CACHE["scope"]
if entry is None:
return _unknown(model_id)
meta = {
"model": model_id,
"known": True,
"scope": scope,
"source": source,
"source_model": entry["source_model"],
"context_window": entry["context_window"],
"max_input_tokens": None,
"max_output_tokens": entry["max_output_tokens"],
"gateway_verified": False,
}
if entry.get("top_provider_context_window") is not None:
meta["top_provider_context_window"] = entry["top_provider_context_window"]
return meta
except Exception:
return _unknown(model_id)
def for_models(model_ids):
"""Mapping id -> metadata for the given ids, in input order."""
result = {}
if not isinstance(model_ids, (list, tuple, set, frozenset)):
return result
for model_id in model_ids:
if isinstance(model_id, str) and model_id:
result[model_id] = for_model(model_id)
return result
def attach_rows(rows):
if not isinstance(rows, (list, tuple)):
return rows
try:
if not available():
return list(rows)
except Exception:
return list(rows)
out = []
for row in rows:
if not isinstance(row, dict) or not isinstance(row.get("id"), str):
out.append(row)
continue
copy = dict(row)
copy["model_metadata"] = for_model(row["id"])
out.append(copy)
return out
__all__ = ["attach_rows", "available", "candidate_paths", "describe", "for_model",
"for_models", "reload"]
+50
View File
@@ -0,0 +1,50 @@
{
"_comment": "Shape example for IISHKO_PROVIDERS_FILE, validated by ProviderRegistry in gateway/gateway_providers.py. Placeholders only: no credentials, no real endpoints, no upstream channel data. Pinning stays off until pinning_enabled is true AND the caller presents an administrative New API token (role >= 10, owner/admin).",
"pinning_enabled": false,
"providers": [
{
"id": "example-primary",
"name": "Example primary provider",
"channel_ids": [
101
],
"priority": 10,
"reserve": false,
"max_inflight": 32,
"models": {
"example-model": {
"effort_levels": [
"low",
"medium",
"high"
],
"verification": {
"status": "unverified",
"method": "none"
}
}
}
},
{
"id": "example-reserve",
"name": "Example reserve provider",
"channel_ids": [
202
],
"priority": 0,
"reserve": true,
"max_inflight": 8,
"models": {
"example-model": {
"effort_levels": null,
"verification": {
"status": "identity_checked",
"method": "response_model",
"checked_at": 1792950000,
"reference": "operator route check, see deploy notes"
}
}
}
}
]
}
+153
View File
@@ -0,0 +1,153 @@
"""Public desired catalogue, deliberately separate from routable API discovery."""
import ast
from contextlib import closing
from html import escape
import logging
from pathlib import Path
import sqlite3
import threading
import time
try:
from model_advisories import for_model as provider_moderation_for_model
except ImportError: # Keep the base catalogue available during a partial deployment.
def provider_moderation_for_model(_model_id):
return None
LOG = logging.getLogger("public_catalogue")
BOT_SOURCE = Path("/opt/grok-bot/iishko_bot.py")
GATEWAY_DB = Path("/opt/grok-gateway/new-api/one-api.db")
# [REMOVE-AGENTS-A1 20261027] owner request: model retired from the public catalogue.
EXCLUDED = frozenset(("SenseNova-6.8-Flash-Lite", "Atria-Dawn-Preview", "Agents-A1"))
# Exact IDs observed in the operator's gateway; no invented aliases or routes.
FALLBACK = {
"claude-sonnet-5-5": 2,
"claude-opus-5-5": 4,
"claude-fable-5-1": 4,
"claude-haiku-5-5": 4,
"gpt-6.1-sol": 4,
"gpt-6-luna": 2,
"gpt-6-astra": 4,
"kimi/kimi-k3.1-pro": 3,
"deepseek-v4.1-flash-1017": 1,
"glm-5.3": 1,
"qwen-plus": 1,
"qwen-max": 1,
"qwen3.8-max": 1,
"qwen3.7-max": 1,
"qwen3-vl-plus": 1,
"qwen3.8-flash": 1,
"glm-5.3-flash": 1,
"gpt-5.6-luna": 2,
"gpt-5.6-terra": 2,
"grok-4.6": 2,
"grok-4.7": 2,
"qwen3.8-max-0902": 2,
"qwen3.8-27b": 2,
"kimi-k2.7-code": 2,
"deepseek-v4-pro": 3,
"kimi-k3.1-pro-highspeed": 3,
"Qwen3.8-Flash-Next": 3,
}
_LOCK = threading.Lock()
_CACHE = {}
def desired_models(source):
"""Parse only literal catalogue assignments: never import or execute the bot."""
source = Path(source)
if source.stat().st_size > 2 * 1024 * 1024:
raise ValueError("Catalogue source too large")
tree = ast.parse(source.read_bytes(), filename=str(source))
values = {}
for node in tree.body:
if (isinstance(node, ast.Assign) and len(node.targets) == 1
and isinstance(node.targets[0], ast.Name)
and node.targets[0].id in ("TIER_MODELS", "MODEL_DESCS")):
values[node.targets[0].id] = ast.literal_eval(node.value)
tiers = values.get("TIER_MODELS")
if (not isinstance(tiers, dict) or set(tiers) != {1, 2, 3, 4}
or any(type(rank) is not int or not isinstance(names, (list, tuple))
for rank, names in tiers.items())):
raise ValueError("Invalid ranked catalogue")
ranks = {}
for rank, names in tiers.items():
for name in names:
if (not isinstance(name, str) or not 0 < len(name) <= 128
or any(ord(char) < 32 for char in name)):
raise ValueError("Invalid catalogue ID")
if name not in EXCLUDED and not name.lower().startswith("codai"):
ranks[name] = min(rank, ranks.get(name, 4))
descriptions = values.get("MODEL_DESCS")
descriptions = descriptions if isinstance(descriptions, dict) else {}
return ranks, {name: value for name, value in descriptions.items()
if name in ranks and isinstance(value, str) and len(value) <= 1000}
def catalogue_snapshot(source=BOT_SOURCE, database=GATEWAY_DB, *, now=None):
source, database = Path(source), Path(database)
stamp = time.monotonic() if now is None else now
key = (str(source), str(database))
with _LOCK:
cached = _CACHE.get(key)
if cached and 0 <= stamp - cached[0] < 20:
return cached[1]
origin = "bot"
try:
ranks, descriptions = desired_models(source)
except (OSError, ValueError, SyntaxError, RecursionError, UnicodeError):
LOG.warning("desired_catalogue_unavailable")
if cached:
ranks = {item["id"]: item["min_rank"] for item in cached[1]["models"]}
descriptions = {item["id"]: item["description"] for item in cached[1]["models"]}
origin = "last_known"
else:
ranks, descriptions, origin = dict(FALLBACK), {}, "fallback"
configured = None
try:
with closing(sqlite3.connect(database.resolve().as_uri() + "?mode=ro", uri=True,
timeout=0.5)) as db:
configured = {row[0] for row in db.execute(
"SELECT DISTINCT a.model FROM abilities a JOIN channels c ON c.id=a.channel_id "
"WHERE a.enabled=1 AND c.status=1")}
except sqlite3.Error:
LOG.warning("catalogue_route_status_unavailable")
rows = [{"id": name, "description": descriptions.get(name, ""),
"min_rank": rank, "configured": None if configured is None else name in configured,
"status": "unknown" if configured is None else (
"configured" if name in configured else "awaiting_provider")}
for name, rank in sorted(ranks.items(), key=lambda item: (item[1], item[0]))]
for row in rows:
row["provider_moderation"] = provider_moderation_for_model(row["id"])
result = {"models": rows, "source": origin,
"note": "Конфигурация маршрута не подтверждает успешную генерацию. Ранги и лимиты проверяются отдельно."}
_CACHE.clear() # One production source; bounded even with arbitrary test paths.
_CACHE[key] = (stamp, result)
return result
def render_catalogue(snapshot):
cards = []
for model in snapshot["models"]:
label = {"configured": "Маршрут настроен · проверь свежую пробу в Mini App",
"awaiting_provider": "Ожидает провайдера · модель сохранена в каталоге",
"unknown": "Наличие маршрута не проверено"}[model["status"]]
advisory = model.get("provider_moderation")
advisory_html = ('<p class="small"><strong>' + escape(advisory["label"])
+ '</strong><br>' + escape(advisory["notice"]) + '</p>'
if advisory else '')
cards.append('<article class="card"><h2><code>' + escape(model["id"])
+ '</code></h2><p>' + escape(model["description"])
+ '</p><p class="small">Ранг: ' + str(model["min_rank"])
+ ' и выше</p><p class="muted">' + escape(label) + '</p>'
+ advisory_html + '</article>')
degraded = ('<div class="note" role="status">Основной источник каталога временно недоступен. '
'Показан сохранённый список; наличие маршрута проверяется отдельно.</div>'
if snapshot.get("source") in ("fallback", "last_known") else "")
return ('<p class="eyebrow">Бот · Mini App · API</p><h1>Каталог моделей.</h1>'
'<p class="lead">Современные модели остаются здесь, даже если подходящий провайдер '
'временно отсутствует. Выбирается точный ID: другая модель не подставляется незаметно.</p>'
'<div class="note">«Маршрут настроен» — не обещание работоспособности. '
'Результат и время реальной пробы смотри в Mini App. Наличие в каталоге '
'не снимает ограничения ранга, бюджета или ключа.</div>' + degraded
+ '<section class="grid" aria-label="Модели и наличие маршрута">'
+ ''.join(cards) + '</section>')
+248
View File
@@ -0,0 +1,248 @@
"""Own public pages; the dashed skin entry point injects its existing hooks."""
import json
from html import escape
from xml.etree.ElementTree import Element, SubElement, tostring
from aiohttp import web
PUBLIC_ORIGIN = "https://api.your-domain.com"
BOT_URL = "https://t.me/iishkogatewaybot"
SUPPORT_URL = "https://t.me/your-handle"
MINI_SUPPORT_URL = "/webapp/#support"
PAGE_TITLES = {
"/": "IISHKO Gateway — доступ к моделям через Telegram",
"/docs": "Документация — IISHKO Gateway",
"/about": "О сервисе — IISHKO Gateway",
"/privacy": "Конфиденциальность — IISHKO Gateway",
"/support": "Поддержка — IISHKO Gateway",
}
PAGE_DESCRIPTIONS = {
"/": "Начни с Telegram-бота IISHKO Gateway: Mini App, API-ключи, выбор точной модели и первый ответ без отдельной публичной регистрации.",
"/docs": "Подключение к IISHKO API: примеры Bash и PowerShell, точные ID моделей, доступ по рангу, API-кредит ключа и разбор ошибок.",
"/about": "Как устроен IISHKO Gateway: Telegram-бот, Mini App и совместимый API; возможности бета-сервиса и ограничения доступности моделей.",
"/privacy": "Как IISHKO Gateway обрабатывает Telegram-идентичность, API-ключи, расчётные записи, эфемерные диалоги и обращения в поддержку.",
"/support": "Поддержка IISHKO Gateway: связь с @your-handle, заявка с квитанцией в Mini App и безопасная диагностика без передачи ключей.",
}
SITEMAP_PATHS = ("/", "/docs", "/pricing", "/about", "/privacy", "/support")
STYLE = """
:root{color-scheme:dark;--bg:#0a0a0a;--card:#171717;--fg:#fafafa;--mut:#b4b4b4;--line:#303030;--public-link:#e5e5e5;--public-link-hover:#fafafa;--public-action-line:#737373;--public-focus:#fafafa;--public-on-primary:#0a0a0a;--public-touch:44px;--public-space:4px}
*{box-sizing:border-box}html{scroll-padding-top:24px}body{margin:0;background:var(--bg);color:var(--fg);font:16px/1.65 Geist,Inter,ui-sans-serif,system-ui,-apple-system,"Segoe UI",sans-serif;-webkit-font-smoothing:antialiased}
a{color:inherit;text-underline-offset:4px}a:hover{color:#fff}a:focus-visible,summary:focus-visible,[tabindex]:focus-visible{outline:3px solid #fafafa;outline-offset:5px;border-radius:3px}
.wrap{width:min(1080px,100%);margin:auto;padding:0 28px}header{border-bottom:1px solid var(--line)}.top{display:flex;gap:24px;align-items:center;justify-content:space-between;min-height:88px;padding-top:12px;padding-bottom:12px}
.brand{font-weight:700;letter-spacing:-.04em;text-decoration:none;white-space:nowrap;font-size:20px}.brand span{color:var(--mut);font-weight:400}nav{display:flex;flex-wrap:wrap;gap:4px 18px;align-items:center}nav a,footer a{display:inline-flex;align-items:center;min-height:44px;font-size:14px}nav a{text-decoration:none;color:var(--mut)}nav a[aria-current=page]{color:#fff;text-decoration:underline}
.skip{position:absolute;left:16px;top:-100px;padding:12px 20px;background:#fafafa;color:#0a0a0a;z-index:1000}.skip:focus{top:12px}main{padding-top:64px;padding-bottom:64px;min-height:65vh}h1,h2,h3{line-height:1.15;letter-spacing:-.035em}h1{font-size:clamp(2.3rem,5.5vw,4.4rem);max-width:900px;margin:12px 0 24px}h2{font-size:clamp(1.45rem,3vw,2rem);margin:0 0 18px}h3{font-size:1.15rem;margin:0 0 12px}p{margin:0 0 18px}.muted,.lead,.eyebrow{color:var(--mut)}.lead{font-size:1.15rem;max-width:760px}.eyebrow{font-size:12px;letter-spacing:.13em;text-transform:uppercase}.actions{display:flex;flex-wrap:wrap;gap:12px;margin:28px 0}
.button{display:inline-flex;align-items:center;justify-content:center;min-height:46px;max-width:100%;padding:10px 18px;border:1px solid var(--line);border-radius:9px;text-decoration:none;font-weight:600;background:var(--card);color:var(--fg)}.button.primary{background:#fafafa;color:#0a0a0a}.button:hover{border-color:#777}.section{margin-top:56px}.grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:18px}.card,.note{padding:24px;border:1px solid var(--line);border-radius:12px;background:var(--card);min-width:0}.card p:last-child,.note p:last-child{margin-bottom:0}.note{margin:24px 0;color:var(--mut)}.note strong{color:var(--fg)}
.steps{list-style:none;counter-reset:step;margin:0;padding:0;display:grid;gap:16px}.steps li{counter-increment:step;position:relative;padding:22px 22px 22px 70px;border:1px solid var(--line);border-radius:12px}.steps li::before{content:counter(step,decimal-leading-zero);position:absolute;left:22px;top:22px;color:var(--mut);font:14px/1.5 ui-monospace,monospace}.steps h3{margin-top:0}.steps p{margin-bottom:0}ul,ol{padding-left:24px}li+li{margin-top:10px}
code,pre{font-family:"Geist Mono",ui-monospace,SFMono-Regular,Consolas,monospace;font-size:.88em}code{overflow-wrap:anywhere}pre{padding:22px;background:#111;border:1px solid var(--line);border-radius:10px;overflow:auto;line-height:1.65;white-space:pre}pre code{overflow-wrap:normal}table{border-collapse:collapse;width:100%;min-width:560px;text-align:left}th,td{border-bottom:1px solid var(--line);vertical-align:top;padding:14px 16px 14px 0}th{font-weight:600}td:first-child{white-space:nowrap}.table-scroll{overflow-x:auto}.toc{display:flex;gap:8px 20px;flex-wrap:wrap;margin:24px 0}.toc a{display:inline-flex;align-items:center;min-height:44px}dl{margin:0}dt{color:var(--mut);font-size:14px}dd{margin:4px 0 16px;font-size:1.25rem;font-variant-numeric:tabular-nums}.wallet-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:24px}footer{border-top:1px solid var(--line);color:var(--mut);padding-top:24px;padding-bottom:32px}.footer-row{display:flex;gap:16px 28px;flex-wrap:wrap;justify-content:space-between}.footer-links{display:flex;flex-wrap:wrap;gap:6px 20px}.small{font-size:14px}.prose{max-width:820px}.prose section+section{margin-top:40px}
/* Beat only the skin's late generic link/border rules, not its shared theme. */
body.public-site{overflow-wrap:anywhere}
body.public-site a{color:var(--public-link)!important}
body.public-site a:hover,body.public-site a:focus-visible{color:var(--public-link-hover)!important;text-decoration:underline;text-decoration-thickness:2px}
body.public-site .brand,body.public-site nav a[aria-current=page]{color:var(--public-link-hover)!important}
body.public-site a.button.primary,body.public-site a.skip{color:var(--public-on-primary)!important}
body.public-site .button{border-color:var(--public-action-line)!important;min-width:var(--public-touch);white-space:normal;text-align:center}
body.public-site .button:hover,body.public-site .button:focus-visible{border-color:var(--public-link-hover)!important}
body.public-site a:focus-visible,body.public-site [tabindex]:focus-visible{outline:3px solid var(--public-focus);outline-offset:var(--public-space)}
body.public-site .brand{display:inline-flex;align-items:center;gap:var(--public-space);min-height:var(--public-touch)}
body.public-site nav a,body.public-site footer a{min-width:var(--public-touch);max-width:100%}
body.public-site main,body.public-site nav,body.public-site .top>*,body.public-site .grid>*,body.public-site .wallet-grid>*,body.public-site .footer-row>*{min-width:0;max-width:100%}
body.public-site pre,body.public-site .table-scroll{min-width:0;max-width:100%;overscroll-behavior-x:contain}
@media(max-width:760px){.top{align-items:flex-start;flex-direction:column;gap:10px}.grid{grid-template-columns:1fr}main{padding-top:40px;padding-bottom:40px}.section{margin-top:40px}.wrap{padding-left:20px;padding-right:20px}nav{gap:2px 16px}.wallet-grid{grid-template-columns:1fr;gap:8px}}
@media(max-width:420px){.wrap{padding-left:16px;padding-right:16px}.brand{font-size:18px}.card,.note{padding:20px}.actions .button{width:100%}.steps li{padding:20px 18px 20px 58px}.steps li::before{left:18px;top:20px}pre{padding:16px}}
"""
def _start_steps():
return f"""<ol class="steps">
<li><h3>Открой Telegram-бота</h3><p>Перейди в <a href="{BOT_URL}">@iishkogatewaybot</a> и нажми «Старт». Публичная регистрация по email и паролю отключена.</p></li>
<li><h3>Запусти Mini App из меню бота</h3><p>Нажми «Открыть Mini App». Telegram передаст данные для входа: обычная вкладка браузера сама по себе не авторизует тебя.</p></li>
<li><h3>Получи ключ в разделе «Ключи»</h3><p>Создай или открой основной ключ в Mini App. Бот не показывает ключи в переписке. Проверь API-кредит ключа и условия доступа своего ранга.</p></li>
<li><h3>Выбери точную модель и получи первый ответ</h3><p>В Mini App открой «Модели»: проверь доступ твоему рангу, точный ID и время последней пробы. Для первого ответа открой «Агент» или подключи ключ к OpenAI-совместимому клиенту по <a href="/docs#first-request">инструкции</a>.</p></li>
</ol>"""
def _home():
return f"""<p class="eyebrow">Telegram · Mini App · API</p>
<h1>Твой доступ к ИИ.<br>От Telegram до первого ответа.</h1>
<p class="lead">IISHKO Gateway соединяет модели в одном API. Ключи, доступ по рангу и наблюдаемые статусы — в Mini App. Начни с бота, без отдельной публичной регистрации.</p>
<div class="actions"><a class="button primary" href="{BOT_URL}">Открыть Telegram</a><a class="button" href="/docs">Как подключиться</a><a class="button" href="/pricing">Модели и цены</a></div>
<p class="small muted">Уже входил на сайт? <a href="/sign-in">Вход через Telegram</a> · <a href="/console">Консоль</a></p>
<section class="section" aria-labelledby="start"><h2 id="start">Четыре шага до результата</h2>{_start_steps()}</section>
<section class="section grid" aria-label="Что важно знать"><article class="card"><h2>Модель выбираешь ты</h2><p>Используй точный ID из актуального каталога. Другая модель не должна подставляться незаметно. Наличие в каталоге не гарантирует ответ прямо сейчас.</p><a href="/docs#models">Модели и доступ</a></article><article class="card"><h2>Кредит — на ключе</h2><p>API-кредит основного ключа и квота аккаунта сайта — разные показатели. Их нельзя складывать или считать автоматически синхронизированными.</p><a href="/docs#wallet">Как читать баланс</a></article></section>
<div class="note"><strong>Бета-сервис.</strong> Доступность отдельных моделей меняется. В Mini App показаны результаты реальных проб и их время; отсутствие свежей пробы — не обещание работоспособности. <a href="/support">Если что-то не работает</a>.</div>"""
def _docs():
models_example = '''curl --silent --show-error https://api.your-domain.com/v1/models \\
--header "Authorization: Bearer $IISHKO_API_KEY"'''
request_example = '''# Set IISHKO_API_KEY privately in your environment.
# Replace EXACT_MODEL_ID with an exact ID from the current catalogue.
curl --silent --show-error https://api.your-domain.com/v1/chat/completions \\
--header "Authorization: Bearer $IISHKO_API_KEY" \\
--header 'Content-Type: application/json' \\
--data '{"model":"EXACT_MODEL_ID","messages":[{"role":"user","content":"Reply with OK"}],"max_tokens":32}' '''.rstrip()
powershell_example = '''# Set IISHKO_API_KEY privately in your environment.
if ([string]::IsNullOrWhiteSpace($env:IISHKO_API_KEY)) {
throw 'Set IISHKO_API_KEY in your local environment first.'
}
$headers = @{
Authorization = "Bearer $env:IISHKO_API_KEY"
}
$payload = @{
model = 'deepseek-v4.1-flash-1017'
messages = @(
@{ role = 'user'; content = 'Reply with OK' }
)
max_tokens = 32
}
$json = $payload | ConvertTo-Json -Depth 6
$body = [System.Text.Encoding]::UTF8.GetBytes($json)
$request = @{
Uri = 'https://api.your-domain.com/v1/chat/completions'
Method = 'Post'
Headers = $headers
ContentType = 'application/json; charset=utf-8'
Body = $body
}
Invoke-RestMethod @request'''
return f"""<p class="eyebrow">Своя документация IISHKO</p><h1>От ключа до первого ответа.</h1>
<p class="lead">Ключ получают только в авторизованном Mini App. Этот сайт объясняет подключение, но не создаёт аккаунт по email и не выдаёт ключ анонимному посетителю.</p>
<nav class="toc" aria-label="Содержание документации"><a href="#onboarding">Начало</a><a href="#first-request">Подключение</a><a href="#powershell-request">Windows</a><a href="#models">Модели</a><a href="#wallet">Баланс</a><a href="#errors">Ошибки</a><a href="#chats">Диалоги</a></nav>
<section id="onboarding" class="section"><h2>Начни с Telegram</h2>{_start_steps()}</section>
<section id="first-request" class="section prose"><h2>Подключи OpenAI-совместимый клиент</h2><p>В настройках клиента выбери OpenAI-compatible / Custom. Базовый адрес: <code>https://api.your-domain.com/v1</code>. API key — твой ключ из Mini App. Model — точный ID из актуального каталога.</p><p>Если клиент сам добавляет <code>/chat/completions</code>, не указывай этот путь в Base URL. Полный endpoint для чата: <code>https://api.your-domain.com/v1/chat/completions</code>. Поддержка OpenAI-совместимого чата не означает поддержку любого протокола или всех возможностей каждой модели.</p>
<h3 id="bash-models">Bash (Linux / macOS): посмотри доступные ID</h3><p>Перед запуском задай переменную <code>IISHKO_API_KEY</code> локально. Не отправляй её в чат или поддержку и не публикуй вывод с заголовком авторизации. Эти примеры <code>curl</code> предназначены для Bash; для Windows используй <a href="#powershell-request">пример PowerShell</a>.</p><pre tabindex="0" aria-labelledby="bash-models" aria-label="Запрос каталога моделей"><code class="language-bash">{escape(models_example)}</code></pre>
<h3 id="bash-request">Bash: отправь короткий тест</h3><p>Замени <code>EXACT_MODEL_ID</code> на ID чат-модели, доступной твоему ключу. Не используй ID модели изображений или видео для чат-запроса.</p><pre tabindex="0" aria-labelledby="bash-request" aria-label="Первый запрос к чат-модели"><code class="language-bash">{escape(request_example)}</code></pre>
<h3 id="powershell-request">Windows PowerShell 5.1 / PowerShell 7</h3><p>В PowerShell используй нативный <code>Invoke-RestMethod</code> с переменной <code>$env:IISHKO_API_KEY</code>, а не Bash-команду выше. Пример отправляет объект через <code>ConvertTo-Json</code> и явно кодирует тело в UTF-8, в том числе для кириллицы. Проверь в каталоге доступ ключа к точной модели <code>deepseek-v4.1-flash-1017</code>: наличие примера не гарантирует доступность.</p><pre tabindex="0" aria-labelledby="powershell-request" aria-label="Первый запрос в Windows PowerShell 5.1 или PowerShell 7"><code class="language-powershell">{escape(powershell_example)}</code></pre><p>Это реальный API-запрос: он может расходовать API-кредит и учитывается в действующих лимитах. Успешный ответ содержит результат выбранной модели. Сверяй имя модели в ответе; при несовпадении не считай подмену нормой — передай безопасный код ошибки и request ID в <a href="/support">поддержку</a>.</p></section>
<section id="models" class="section prose"><h2>Точные модели, ранг и доступность</h2><p>Источник актуальных ID — <code>GET /v1/models</code> с твоим ключом и раздел «Модели» в Mini App. Используй имя целиком, включая регистр, точки, дефисы и префикс провайдера. Не придумывай сокращения и не считай похожие названия взаимозаменяемыми.</p><p>Право доступа по рангу и состояние провайдера — разные вещи. «Доступна тебе» означает право использования, а не гарантированный успешный запрос. Статус и история в Mini App основаны на наблюдаемых пробах с отметкой времени. «Не проверена», устаревшая проба и отсутствие измерений не равны «работает». Даже свежая успешная проба не гарантирует следующий ответ.</p><p>Условия рангов, дневные лимиты и ограничения ключей остаются действующими. Каталог и эта инструкция не снимают блокировки и не меняют выбранную модель. Цены смотри на <a href="/pricing">существующей странице цен</a>; фактический расход зависит от модели и запроса.</p></section>
<section id="wallet" class="section prose"><h2>API-кредит ключа ≠ квота аккаунта сайта</h2><p><strong>API-кредит основного ключа</strong> — остаток канонического кошелька, который использует бот и Mini App. Дополнительные ключи могут иметь собственные остатки: основной кошелёк не является суммой всех ключей.</p><p><strong>Квота аккаунта сайта</strong> — отдельная запись учётной системы. Это не второй перевод денег и не подтверждение API-кредита ключа. Для запроса могут действовать ограничения обоих уровней. Сайт только читает показатели: ничего не переносит и не синхронизирует.</p><p>Приостановленный ключ может сохранять кредит; наличие денег не снимает блокировку. Если прочитать БД или безопасно подтвердить привязку не удалось, показатель недоступен — это не нулевой баланс. Для безлимитного ключа числовой остаток не выдаётся за доступный кредит.</p></section>
<section id="errors" class="section"><h2>Разбор ошибок</h2><div class="table-scroll" tabindex="0" role="region" aria-label="Коды ошибок и действия"><table><thead><tr><th scope="col">HTTP</th><th scope="col">Что означает</th><th scope="col">Что делать</th></tr></thead><tbody>
<tr><th scope="row">402</th><td>Недостаточно квоты для предоплаты конкретного запроса. Это не доказательство нулевого баланса: запрос с длинным контекстом может требовать больше остатка. Иногда принадлежность квоты не подтверждена.</td><td>Проверь API-кредит ключа и квоту аккаунта отдельно, сократи контекст или лимит ответа. Не повторяй тот же запрос бесконечно; при несоответствии обратись в поддержку.</td></tr>
<tr><th scope="row">429</th><td>Временный лимит ключа, частоты или дневного использования. Это не сообщение о списании всего кредита.</td><td>Прочитай код и пояснение ошибки. Выжди указанный срок, если он есть; проверь дневные ограничения в Mini App. Не запускай параллельные повторы.</td></tr>
<tr><th scope="row">503</th><td>Выбранный upstream временно недоступен: перегрузка, маршрут, учётные данные или квота провайдера. Это не подтверждение неисправности твоего ключа или обнуления кошелька.</td><td>Повтори позже с паузой. Выбор другой модели — только твоё явное решение. Если часть ответа или действие инструмента уже получены, не воспроизводи запрос вслепую.</td></tr>
<tr><th scope="row">401 / 403</th><td>401 — ключ не принят. 403 — запрет; причина может быть в доступе к точной модели, действующих условиях или другом ограничении, не обязательно в ранге.</td><td>Проверь актуальный ключ в Mini App, точный ID модели и текст ошибки. Не отправляй ключ в поддержку.</td></tr>
<tr><th scope="row">400 / 413 / 504</th><td>Некорректные параметры или контекст, слишком большой запрос либо таймаут.</td><td>Сократи запрос и проверь возможности модели. При таймауте результат уже начатой операции может быть неизвестен.</td></tr>
</tbody></table></div><p class="small muted">Для диагностики сохрани HTTP-статус, безопасный код ошибки и request ID, если он выдан. Не прикладывай ключ, Cookie, Telegram initData, полный запрос или содержимое файлов.</p></section>
<section id="chats" class="section prose"><h2>Эфемерные диалоги и остановка</h2><p>Диалоги ИИ не являются постоянным архивом. Контекст может временно жить в памяти процесса или открытого экрана и исчезнуть после очистки, закрытия или перезапуска. Не рассчитывай восстановить чат; нужный результат сохрани самостоятельно. Сообщения в Telegram подчиняются отдельным правилам Telegram.</p><p>«Стоп» останавливает текущую генерацию по возможности, но не откатывает уже выполненный инструмент или принятый провайдером запрос. Если результат действия неизвестен, сначала проверь его, прежде чем повторять.</p><p>Явно отправленное обращение в поддержку — не диалог ИИ: текст обращения и добровольно приложенная безопасная диагностика хранятся до 30 дней. Подробнее — <a href="/privacy">конфиденциальность</a>.</p></section>
<div class="actions"><a class="button primary" href="{BOT_URL}">Открыть бота и Mini App</a><a class="button" href="/support">Нужна помощь</a></div>"""
def _about():
return f"""<p class="eyebrow">О сервисе</p><h1>IISHKO Gateway.</h1><div class="prose"><p class="lead">Доступ к моделям через Telegram-бота, Mini App и единый API для совместимых клиентов.</p><section><h2>Что здесь есть</h2><p>Mini App объединяет профиль, ключи, каталог моделей, наблюдаемые статусы и поддержку. На сайте доступны собственная <a href="/docs">инструкция</a>, <a href="/pricing">цены</a> и существующая <a href="/console">консоль</a>.</p></section><section><h2>Чего мы не обещаем</h2><p>Наличие модели в каталоге не гарантирует постоянную доступность провайдера. Ранги и лимиты действуют независимо от последней успешной пробы. Мы не выдаём другую модель за выбранную и не считаем квоту аккаунта автоматически равной кредиту ключа.</p><p>Это бета-сервис: ошибки возможны. Обращение «получено» означает сохранение заявки, а не ответ оператора или решение проблемы.</p></section><section><h2>Как начать</h2><p>Публичная регистрация отключена. Открой <a href="{BOT_URL}">@iishkogatewaybot</a>, запусти Mini App из меню и получи ключ в разделе «Ключи».</p><p>Оператор поддержки — <a href="{SUPPORT_URL}">@your-handle</a>. <a href="/privacy">Как обрабатываются данные</a>.</p></section></div>"""
def _privacy():
return f"""<p class="eyebrow">Конфиденциальность</p><h1>Что происходит с данными.</h1><div class="prose"><section><h2>Вход и кошелёк</h2><p>Для входа используется проверенная Telegram-идентичность. Сайт связывает с ней учётную запись, а Mini App проверяет данные запуска Telegram. Для работы ключей и учёта сохраняются необходимые идентификаторы, права, остатки и записи операций. Квота аккаунта и API-кредит ключа читаются отдельно; этот сайт не переносит между ними средства.</p><p>Не передавай API-ключи, Cookie и Telegram initData другим людям. Для помощи оператору не нужен твой полный ключ.</p></section><section><h2>Диалоги ИИ — не постоянный архив</h2><p>Диалоги эфемерные: интерфейс и процесс могут временно держать контекст в памяти, но восстановление после закрытия, очистки или перезапуска не обещается. Эта политика не означает, что учётные записи, расчётные журналы, явно созданные напоминания или обращения в поддержку удаляются вместе с диалогом.</p><p>Запрос и нужные вложения передаются выбранному провайдеру для получения ответа; инструменты могут получать данные, необходимые для действия. У провайдеров, внешних сервисов и Telegram свои правила хранения. Здесь нет обещания отсутствия логов у третьих сторон.</p></section><section><h2>Обращения в поддержку — отдельно</h2><p>После явной отправки через авторизованный Mini App текст обращения, его квитанция и добровольно приложенная безопасная диагностика сохраняются до 30 дней. Оператору передаются сведения, необходимые для разбора. Диагностика может содержать экран, ID модели, код ошибки, request ID и ID операции; ключи, Cookie, initData, диалоги и файлы не должны прикладываться по умолчанию.</p><p>Статус «получено» подтверждает сохранение обращения, а не его прочтение или решение. Публичный сайт не принимает анонимную заявку и не рисует квитанцию без сохранения. Если пишешь напрямую в Telegram, сообщения хранятся по правилам Telegram, а не по сроку хранения квитанций Mini App.</p></section><section><h2>Вопросы и удаление</h2><p>По вопросам своих данных и обращений напиши <a href="{SUPPORT_URL}">@your-handle</a>. Для идентификации используй свой аккаунт Telegram, но не пересылай ключи или секреты. <a href="/support">Открыть страницу поддержки</a>.</p></section></div>"""
def _support():
return f"""<p class="eyebrow">Поддержка</p><h1>Разберёмся без передачи ключей.</h1><p class="lead">Для личного обращения напиши @your-handle. Для сохранённой заявки с квитанцией открой поддержку в авторизованном Mini App через меню бота.</p>
<div class="actions"><a class="button primary" href="{SUPPORT_URL}">Написать @your-handle</a><a class="button" href="{BOT_URL}">Открыть бота</a><a class="button" href="{MINI_SUPPORT_URL}">Поддержка в Mini App</a></div>
<div class="note"><strong>Mini App требует входа через Telegram.</strong> Если открылась обычная вкладка, вернись в бота и нажми «Открыть Mini App», затем «Поддержка». Здесь нет анонимной формы и нажатие на ссылку не создаёт заявку.</div>
<section class="section grid"><article class="card"><h2>Что приложить</h2><ul><li>Какой экран или точную модель открывал.</li><li>Что ожидал и что произошло, без содержимого личного запроса.</li><li>Время сбоя, HTTP-статус и безопасный код ошибки.</li><li>Request ID или ID операции, если интерфейс их показал.</li></ul></article><article class="card"><h2>Что не присылать</h2><ul><li>API-ключи и заголовок Authorization.</li><li>Cookie, пароли и Telegram initData.</li><li>Полную ссылку с секретными параметрами.</li><li>Диалог или файлы без явной необходимости и своего согласия.</li></ul></article></section>
<section class="section prose"><h2>Что означает квитанция</h2><p>В Mini App квитанция появляется только после успешного сохранения обращения. «Получено» не значит «оператор прочитал» или «проблема решена». Доставка уведомления оператору может задержаться; не отправляй повторно тот же отчёт из-за отсутствия ответа.</p><p>Текст обращения и добровольная безопасная диагностика хранятся до 30 дней, отдельно от эфемерных диалогов ИИ. Подробнее — <a href="/privacy">конфиденциальность</a>.</p><p>Перед обращением можно проверить <a href="/docs#errors">значение кодов 402, 429 и 503</a>. Ошибка провайдера не доказывает, что твой баланс обнулился.</p></section>"""
PAGE_BODIES = {"/": _home, "/docs": _docs, "/about": _about,
"/privacy": _privacy, "/support": _support}
def _money(value):
if not isinstance(value, (int, float)) or isinstance(value, bool):
return "Недоступно"
return "$" + format(value, ".2f")
def _account_panel(account):
if not isinstance(account, dict):
return ""
wallet = account.get("wallet") or {}
quota = account.get("account_quota") or {}
credit = "Недоступен — это не нулевой баланс"
if wallet.get("status") == "unlimited":
credit = "Безлимитный ключ; числовой остаток не применяется"
elif wallet.get("status") == "available":
credit = _money(wallet.get("balance_usd"))
if wallet.get("token_status") == 2:
credit += " · ключ приостановлен"
account_credit = (_money(quota.get("quota_usd"))
if quota.get("status") == "available" else "Недоступна")
return f"""<section class="section card" aria-labelledby="wallet-summary"><h2 id="wallet-summary">Показатели твоего аккаунта</h2><dl class="wallet-grid"><div><dt>API-кредит основного ключа</dt><dd>{escape(credit)}</dd></div><div><dt>Квота аккаунта сайта — отдельно</dt><dd>{escape(account_credit)}</dd></div></dl><p class="small muted">Это разные показатели, не сумма и не синхронизация. Наличие кредита не снимает ограничения доступа. <a href="/docs#wallet">Как читать показатели</a>.</p></section>"""
def render_page(path, *, head_inject=b"", account=None):
links = (("/docs", "Документация"), ("/pricing", "Цены"),
("/about", "О сервисе"), ("/support", "Поддержка"))
navigation = "".join(
'<a href="' + href + '"' + (' aria-current="page"' if path == href else '')
+ '>' + label + '</a>' for href, label in links)
body = PAGE_BODIES[path]()
if path == "/":
body += _account_panel(account)
title = escape(PAGE_TITLES[path])
description = escape(PAGE_DESCRIPTIONS[path])
url = escape(PUBLIC_ORIGIN + path)
image_url = escape(PUBLIC_ORIGIN + "/logo.png")
injected = head_inject.decode("utf-8") if isinstance(head_inject, bytes) else head_inject
return f"""<!doctype html><html lang="ru"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>{title}</title>
<meta name="description" content="{description}"><link rel="canonical" href="{url}">
<meta property="og:type" content="website"><meta property="og:site_name" content="IISHKO Gateway"><meta property="og:locale" content="ru_RU">
<meta property="og:title" content="{title}"><meta property="og:url" content="{url}"><meta property="og:description" content="{description}"><meta property="og:image" content="{image_url}"><meta property="og:image:alt" content="Логотип IISHKO Gateway">
<meta name="twitter:card" content="summary"><meta name="twitter:title" content="{title}"><meta name="twitter:url" content="{url}"><meta name="twitter:description" content="{description}"><meta name="twitter:image" content="{image_url}"><meta name="twitter:image:alt" content="Логотип IISHKO Gateway">
<link rel="icon" href="/favicon.ico"><style>{STYLE}</style>{injected}</head><body class="public-site"><a class="skip" href="#main">К содержимому</a><header><div class="wrap top"><a class="brand" href="/" aria-label="IISHKO Gateway — главная">IISHKO <span>GATEWAY</span></a><nav aria-label="Основная навигация">{navigation}</nav></div></header><main id="main" class="wrap" tabindex="-1">{body}</main><footer><div class="wrap footer-row"><span>IISHKO Gateway · бета</span><div class="footer-links"><a href="/docs">Документация</a><a href="/privacy">Конфиденциальность</a><a href="/support">Поддержка</a><a href="/console">Консоль</a></div></div></footer></body></html>"""
def adapt_public_status(raw):
"""Rewrite only the successful public status representation, never options."""
try:
payload = json.loads(raw)
except (ValueError, UnicodeDecodeError):
return raw
if (not isinstance(payload, dict) or payload.get("success") is not True
or not isinstance(payload.get("data"), dict)):
return raw
payload["data"]["docs_link"] = "/docs"
return json.dumps(payload, ensure_ascii=False, separators=(",", ":")).encode("utf-8")
def register_public_routes(app, *, head_inject=b"", account_lookup=None):
"""Mount before the wildcard proxy. All unlisted routes stay with the skin."""
headers = {"Cache-Control": "no-store", "X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin"}
async def page(request):
account = None
if request.path == "/" and account_lookup and request.cookies.get("tg_sid"):
try:
account = await account_lookup(request)
except Exception:
account = {"wallet": {"status": "unavailable"},
"account_quota": {"status": "unavailable"}}
return web.Response(text=render_page(request.path, head_inject=head_inject,
account=account),
content_type="text/html", headers=headers)
async def canonical_page(request):
raise web.HTTPPermanentRedirect(request.path.rstrip("/"), headers=headers)
async def robots(request):
private_paths = ("/api/", "/v1/", "/console", "/webapp/", "/oauth/",
"/tg-callback", "/sign-in", "/sign-up", "/reset")
text = "User-agent: *\nAllow: /\n" + "".join(
"Disallow: " + path + "\n" for path in private_paths)
return web.Response(text=text + "Sitemap: " + PUBLIC_ORIGIN + "/sitemap.xml\n",
content_type="text/plain", headers=headers)
async def sitemap(request):
root = Element("urlset", xmlns="http://www.sitemaps.org/schemas/sitemap/0.9")
for path in SITEMAP_PATHS:
SubElement(SubElement(root, "url"), "loc").text = PUBLIC_ORIGIN + path
return web.Response(body=tostring(root, encoding="utf-8", xml_declaration=True),
content_type="application/xml", charset="utf-8", headers=headers)
for path in PAGE_TITLES:
app.router.add_get(path, page)
if path != "/":
app.router.add_get(path + "/", canonical_page)
app.router.add_get("/robots.txt", robots)
app.router.add_get("/sitemap.xml", sitemap)
+27
View File
@@ -0,0 +1,27 @@
"""Validate effort metadata without rewriting generation requests or claiming support."""
class InvalidEffort(ValueError):
"""Malformed effort fields, safe to report before dispatch."""
def read_effort(payload):
"""Return the explicit effort; capability checks remain provider-specific."""
if not isinstance(payload, dict):
return None
if payload.get("effort") is not None:
raise InvalidEffort("Use reasoning_effort for Chat Completions or reasoning.effort for Responses.")
values = []
if payload.get("reasoning_effort") is not None:
values.append(payload["reasoning_effort"])
for key in ("reasoning", "output_config"):
value = payload.get(key)
if isinstance(value, dict) and value.get("effort") is not None:
values.append(value["effort"])
if not values:
return None
if any(not isinstance(value, str) or not value.strip() or len(value) > 32 for value in values):
raise InvalidEffort("Specify one non-empty effort string in the request body.")
if len(set(values)) != 1:
raise InvalidEffort("Specify one consistent effort value in the request body.")
return values[0]
+587
View File
@@ -0,0 +1,587 @@
"""Transparent successful API replies; bounded, neutral errors, no fake completions."""
import asyncio
import json
import logging
import math
import secrets
import time
import zlib
from email.utils import parsedate_to_datetime
from weakref import WeakKeyDictionary
import aiohttp
from aiohttp import web
from multidict import CIMultiDict
from gateway_errors import HOP_HEADERS, key_from_headers, public_error, public_json_dumps
from model_identity import ModelIdentityError, check_response_model
LOG = logging.getLogger("gateway_proxy")
MAX_ERROR_BODY = 65536
MAX_JSON_BODY = 40 * 1024 * 1024
MAX_SSE_FRAME = 65536
API_REQUEST_DEADLINE = 860.0
# Provider prefill for a large POST can spend minutes before response headers.
# That wait is not a stalled body stream: allow a longer preheader read budget
# and re-apply the original socket idle budget only after headers arrive.
PREFILL_SOCK_READ = 180.0
PREFILL_MIN_BODY = 64 * 1024
BUSY_MAX_RETRIES = 2
BUSY_BACKOFF_BASE = 0.25
BUSY_MAX_RETRY_AFTER = 2.0
BUSY_MAX_BACKOFF = 4.0
BUSY_MAX_WAITERS = 32
BUSY_MAX_MODEL_WAITERS = 4
BUSY_MAX_REPLAY_BODY = 1024 * 1024
_BUSY_PATHS = frozenset(("/v1/chat/completions", "/v1/completions",
"/v1/responses", "/v1/messages"))
_BUSY_WAITERS = WeakKeyDictionary()
class _BusyWaiters:
"""Single-loop recovery work, not generation/connection leases or an auth queue."""
def __init__(self):
self.total = 0
self.models = {}
def enter(self, model):
count = self.models.get(model, 0)
if self.total >= BUSY_MAX_WAITERS or count >= BUSY_MAX_MODEL_WAITERS:
return False
self.total += 1
self.models[model] = count + 1
return True
def leave(self, model):
count = self.models[model] - 1
if count:
self.models[model] = count
else:
del self.models[model]
self.total -= 1
def _unique_error_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise ValueError("ambiguous error envelope")
result[key] = value
return result
def _explicit_busy_rejection(raw, headers):
"""A complete provider capacity envelope only; HTTP 429/text alone is not proof."""
if (not raw or "json" not in headers.get("Content-Type", "").lower()
or headers.get("Content-Encoding", "").lower() not in ("", "identity")):
return False
try:
obj = json.loads(raw, object_pairs_hook=_unique_error_object)
except (ValueError, UnicodeDecodeError, RecursionError):
return False
if (not isinstance(obj, dict)
or set(obj) - {"error", "request_id", "gateway_request_id", "status", "success"}):
return False # Never replay choices, usage, output, partials or unknown envelopes.
error = obj.get("error")
if (not isinstance(error, dict) or error.get("retryable", True) is not True
or set(error) - {"message", "type", "code", "param", "status", "retryable",
"request_id", "gateway_request_id"}
or not isinstance(error.get("message", ""), str)
or obj.get("success", False) is not False):
return False
if any(node.get("status", 429) != 429 for node in (obj, error)):
return False
code, kind = error.get("code"), error.get("type")
if not all(value is None or isinstance(value, str)
for value in (code, kind, error.get("param"))):
return False
# Explicit provider origin is required: new-api's own rate_limit_error and
# generic rate_limit_exceeded envelopes are not authenticated admission proof.
provider_code = code in ("upstream_busy", "upstream_rate_limited",
"upstream_rate_limit_exceeded")
provider_kind = kind in ("upstream_error", "overloaded_error", "server_overloaded")
capacity_code = code in (None, "", "rate_limit_exceeded", "too_many_requests",
"overloaded", "overloaded_error", "server_overloaded")
if not (provider_code or (provider_kind and capacity_code)):
return False
text = json.dumps(error, ensure_ascii=False).lower()
return not any(marker in text for marker in (
"quota", "billing", "balance", "credit", "auth", "api_key", "api key",
"permission", "forbidden", "access_denied", "rank", "daily", "per_day",
"user_rate", "key_rate", "token_rate", "rate_limit_user", "rate_limit_key",
"this key", "your key", "this user", "your account", "account_limit",
"额度", "余额", "权限", "认证", "封禁", "дневн", "баланс", "ранг", "заблок",
))
def _busy_delay(headers, attempt):
delay = BUSY_BACKOFF_BASE * (2 ** attempt) * (0.8 + secrets.randbelow(401) / 1000)
hints = headers.getall("Retry-After", []) if hasattr(headers, "getall") else (
[headers["Retry-After"]] if "Retry-After" in headers else [])
if len(hints) > 1:
return None
if hints:
hint = hints[0].strip()
if not hint or len(hint) > 128:
return None
try:
if hint.isascii() and hint.isdigit():
seconds = float(hint)
else:
date = parsedate_to_datetime(hint)
if date.tzinfo is None:
return None
seconds = max(0.0, date.timestamp() - time.time())
except (ValueError, TypeError, OverflowError, OSError):
return None
if not math.isfinite(seconds) or seconds > BUSY_MAX_RETRY_AFTER:
return None # Do not retry earlier than an upstream hint exceeding our cap.
delay = max(delay, seconds)
return min(delay, BUSY_MAX_RETRY_AFTER)
def _finite_positive(value):
return isinstance(value, (int, float)) and math.isfinite(value) and value > 0
def _extended_prefill(request, body):
"""Large text-generation POST: provider prefill may outlast socket idle."""
return (request.method == "POST"
and request.path.rstrip("/") in _BUSY_PATHS
and isinstance(body, (bytes, bytearray, memoryview))
and len(body) >= PREFILL_MIN_BODY)
def _prefill_timeout(timeout):
"""Longer preheader read budget; never inflate a caller's explicit total."""
sock_read = timeout.sock_read
if not _finite_positive(sock_read) or sock_read >= PREFILL_SOCK_READ:
return timeout
budget = PREFILL_SOCK_READ
if _finite_positive(timeout.total):
budget = min(budget, timeout.total)
if budget <= sock_read:
return timeout
return aiohttp.ClientTimeout(
total=timeout.total, connect=timeout.connect, sock_connect=timeout.sock_connect,
sock_read=budget, ceil_threshold=timeout.ceil_threshold)
async def relay_api_request(request, session, url, *, headers, body,
requested_model=None, json_to_sse=False,
sse_include_usage=False, balance_lookup=None):
"""Exact dispatch after existing gates; replay only a definitive pre-generation 429.
No pre-auth queue, route/model substitution, replay of ambiguous failures or
renewed timeout. Recovery work is bounded independently of upstream leases.
A large generation POST gets a longer preheader read budget, while its body
still has to produce a chunk within the inherited socket idle timeout.
"""
loop = asyncio.get_running_loop()
original_timeout = session.timeout
extended = _extended_prefill(request, body)
dispatch_timeout = _prefill_timeout(original_timeout) if extended else original_timeout
body_idle_timeout = None
if dispatch_timeout is not original_timeout and _finite_positive(original_timeout.sock_read):
body_idle_timeout = original_timeout.sock_read
budget = API_REQUEST_DEADLINE
for seconds in (dispatch_timeout.total, dispatch_timeout.sock_read):
if _finite_positive(seconds):
budget = min(budget, seconds)
deadline = loop.time() + budget
recoverable = (request.method == "POST" and request.path.rstrip("/") in _BUSY_PATHS
and isinstance(body, bytes) and 0 < len(body) <= BUSY_MAX_REPLAY_BODY
and isinstance(requested_model, str) and 0 < len(requested_model) <= 128
and not any(ord(char) < 32 for char in requested_model)
and bool(key_from_headers(headers)))
attempts, waited, pool = 0, 0.0, None
rejection = None
try:
while True:
remaining = deadline - loop.time()
if remaining <= 0:
if rejection is not None:
return rejection
raise asyncio.TimeoutError()
# Preserve the healthy first attempt's existing timeout exactly.
# Only replays get a total timeout shortened to the original deadline.
timeout = dispatch_timeout if attempts == 0 else aiohttp.ClientTimeout(
total=remaining, connect=original_timeout.connect,
sock_connect=original_timeout.sock_connect, sock_read=dispatch_timeout.sock_read,
ceil_threshold=math.inf)
async with session.request(
request.method, url, headers=headers, data=body, allow_redirects=False,
auto_decompress=False, skip_auto_headers={"Accept-Encoding"},
timeout=timeout) as upstream:
raw = None
if recoverable and upstream.status == 429:
raw = await _read_bounded(upstream, MAX_ERROR_BODY, idle=body_idle_timeout)
safe_busy = (raw is not None and _explicit_busy_rejection(raw, upstream.headers))
user_balance = None
if upstream.status >= 400 and not safe_busy and balance_lookup is not None:
auth = headers.get("Authorization", "")
key = auth[7:].strip() if auth[:7].lower() == "bearer " else ""
user_balance = await asyncio.to_thread(balance_lookup, key)
if not safe_busy:
if pool is not None:
pool.leave(requested_model)
pool = None
return await relay_api(
request, upstream, user_balance=user_balance,
requested_model=requested_model, json_to_sse=json_to_sse,
sse_include_usage=sse_include_usage, body_idle_timeout=body_idle_timeout,
error_body=raw if raw is not None else (
b"" if recoverable and upstream.status == 429 else None))
rejection = await relay_api(
request, upstream, requested_model=requested_model,
body_idle_timeout=body_idle_timeout, error_body=raw)
delay = _busy_delay(upstream.headers, attempts)
# The fully read rejection and its context/connection are released
# BEFORE reserving bounded recovery work or sleeping.
transport = request.transport
if (attempts >= BUSY_MAX_RETRIES or delay is None
or waited + delay > BUSY_MAX_BACKOFF
or loop.time() + delay + 0.05 >= deadline
or transport is None or transport.is_closing()):
return rejection
if pool is None:
candidate = _BUSY_WAITERS.get(loop)
if candidate is None:
candidate = _BusyWaiters()
_BUSY_WAITERS[loop] = candidate
if not candidate.enter(requested_model):
return rejection
pool = candidate
LOG.info("api_busy_retry attempt=%s delay=%.3f path=%s",
attempts + 1, delay, request.path)
await asyncio.sleep(delay)
waited += delay
# Handler cancellation always unwinds the finally below. A browser
# disconnect need not cancel aiohttp handlers, so check it as well.
if (request.transport is None or request.transport.is_closing()
or loop.time() + 0.05 >= deadline):
return rejection
attempts += 1
finally:
if pool is not None:
pool.leave(requested_model)
def _decode(raw, encoding):
if not encoding or encoding == "identity":
return raw
if encoding not in ("gzip", "deflate"):
return b""
try:
decoder = zlib.decompressobj(47 if encoding == "gzip" else zlib.MAX_WBITS)
body = decoder.decompress(raw, MAX_JSON_BODY + 1)
return body if (len(body) <= MAX_JSON_BODY and decoder.eof and not decoder.unconsumed_tail) else b""
except zlib.error:
return b""
async def _bounded_chunks(content, idle):
"""Yield upstream chunks; an idle stream aborts at the caller's body budget."""
if idle is None:
async for chunk in content.iter_chunked(8192):
yield chunk
return
iterator = content.iter_chunked(8192).__aiter__()
while True:
try:
chunk = await asyncio.wait_for(iterator.__anext__(), idle)
except StopAsyncIteration:
return
yield chunk
async def _read_bounded(upstream, limit, idle=None):
body = bytearray()
async for chunk in _bounded_chunks(upstream.content, idle):
if len(body) + len(chunk) > limit:
return None
body.extend(chunk)
return bytes(body)
def _identity_error():
return {"error": {"message": "Выбранная модель сейчас недоступна. Повтори позже.",
"type": "upstream_error", "code": "model_identity_mismatch", "retryable": False}}
def _failure(code, retryable=True):
return {"error": {"message": "Выбранная модель сейчас недоступна. Повтори позже.",
"type": "upstream_error", "code": code, "retryable": retryable}}
def _sse_error(payload):
return b"event: error\ndata: " + json.dumps(payload, ensure_ascii=False).encode(), True
def _incomplete_sse_frame(request_id):
payload = _failure("upstream_stream_incomplete", False)
payload["error"]["message"] = (
"Поток ответа оборвался. Полученный текст может быть неполным. "
"Автоматический повтор не выполнялся.")
payload["error"]["gateway_request_id"] = request_id
frame, _ = _sse_error(payload)
return frame + b"\n\n"
def safe_sse_frame(frame, path, requested_model=None, user_balance=None):
"""Inspect bounded JSON data frames; valid successful frames are byte-exact."""
if len(frame) > MAX_SSE_FRAME:
return _sse_error(_failure("upstream_frame_too_large", False))
data = [line[5:].strip() for line in frame.splitlines() if line.startswith((b"data:", b"data "))]
if not data:
return frame, False
if b"\n".join(data).strip() == b"[DONE]":
return frame, True
try:
obj = json.loads(b"\n".join(data))
except (ValueError, UnicodeDecodeError):
return _sse_error(_failure("upstream_unparseable_response", False))
if not isinstance(obj, dict):
return _sse_error(_failure("upstream_unparseable_response", False))
if obj.get("error"):
error = obj["error"]
status = error.get("status", 502) if isinstance(error, dict) else 502
try:
status = int(status)
except (ValueError, TypeError):
status = 502
_, payload = public_error(status if 400 <= status <= 599 else 502, json.dumps(obj).encode(),
path, from_upstream=True, user_balance=user_balance)
else:
try:
if requested_model:
check_response_model(requested_model, obj.get("message", obj))
except ModelIdentityError:
payload = _identity_error()
else:
return frame, False
return _sse_error(payload)
def _json_to_sse_chunks(obj, include_usage):
"""Map a validated non-stream completion to chat.completion.chunk frames.
Nothing is invented: id/created/model/fingerprint/usage and every message
field are copied verbatim from the upstream object; only the chunk framing
(object type, finish_reason staging, positional tool_call indexes) is
protocol-required shape. Returns None when choices are not complete
successful completions — the caller must fail HTTP instead of streaming.
"""
choices = obj.get("choices")
if not isinstance(choices, list) or not choices:
return None
base = {k: v for k, v in obj.items() if k not in ("choices", "usage")}
base["object"] = "chat.completion.chunk"
chunks = []
for position, choice in enumerate(choices):
if not isinstance(choice, dict):
return None
message = choice.get("message")
if not isinstance(message, dict) or not isinstance(choice.get("finish_reason"), str):
return None
index = choice.get("index")
if not isinstance(index, int) or isinstance(index, bool):
index = position
delta = dict(message)
if delta.get("tool_calls") is not None:
if not isinstance(delta["tool_calls"], list):
return None
indexed = []
for tool_position, tool_call in enumerate(delta["tool_calls"]):
if not isinstance(tool_call, dict):
return None
tool_call = dict(tool_call)
if not isinstance(tool_call.get("index"), int) or isinstance(tool_call.get("index"), bool):
tool_call["index"] = tool_position
indexed.append(tool_call)
delta["tool_calls"] = indexed
if delta:
chunks.append(dict(base, choices=[{"index": index, "delta": delta,
"finish_reason": None}]))
finish = dict(base, choices=[{"index": index, "delta": {},
"finish_reason": choice["finish_reason"]}])
if choice.get("logprobs") is not None:
finish["choices"][0]["logprobs"] = choice["logprobs"]
chunks.append(finish)
if include_usage and obj.get("usage") is not None:
chunks.append(dict(base, choices=[], usage=obj["usage"]))
return chunks
async def relay_api(request, upstream, *, user_balance=None, requested_model=None,
json_to_sse=False, sse_include_usage=False, body_idle_timeout=None,
error_body=None):
excluded = HOP_HEADERS | {name.strip().lower() for name in upstream.headers.get("Connection", "").split(",")}
headers = CIMultiDict((name, value) for name, value in upstream.headers.items() if name.lower() not in excluded)
request_id = secrets.token_hex(16)
headers["X-Request-ID"] = request_id
ctype = headers.get("Content-Type", "").lower()
encoding = headers.get("Content-Encoding", "").lower()
if upstream.status >= 400:
raw = await _read_bounded(upstream, MAX_ERROR_BODY, idle=body_idle_timeout) if error_body is None else error_body
raw = _decode(raw or b"", encoding)
if len(raw) > MAX_ERROR_BODY:
raw = b""
status, payload = public_error(upstream.status, raw, request.path,
user_balance=user_balance, from_upstream=True,
api_key=key_from_headers(request.headers))
payload["error"]["gateway_request_id"] = request_id
safe_headers = {"X-Request-ID": request_id, "Cache-Control": "no-store"}
retry_after = headers.get("Retry-After", "")
if retry_after.isdigit() and len(retry_after) <= 8:
safe_headers["Retry-After"] = retry_after
LOG.warning("api_error status=%s upstream_status=%s code=%s model=%s path=%s request_id=%s",
status, upstream.status, payload["error"]["code"], requested_model, request.path, request_id)
return web.json_response(payload, status=status, headers=safe_headers, dumps=public_json_dumps)
if json_to_sse:
# [OPUS-SSE 2026-10-23] owner-approved JSON->SSE adapter, exact model only.
# Identity is proven on the real non-stream JSON before any SSE byte
# leaves the gateway; every failure below is a plain HTTP JSON error.
if not 200 <= upstream.status < 300 or "json" not in ctype:
return web.json_response(_failure("upstream_unexpected_stream"), status=502,
headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
raw = await _read_bounded(upstream, MAX_JSON_BODY, idle=body_idle_timeout)
if raw is None:
return web.json_response(_failure("upstream_response_too_large", False), status=502,
headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
decoded = _decode(raw, encoding)
try:
obj = json.loads(decoded)
except (ValueError, UnicodeDecodeError):
obj = None
if not isinstance(obj, dict):
return web.json_response(_failure("upstream_unparseable_response"), status=502,
headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
if obj.get("error"):
error = obj["error"]
status = error.get("status", 502) if isinstance(error, dict) else 502
try:
status = int(status)
except (ValueError, TypeError):
status = 502
status, payload = public_error(status if 400 <= status <= 599 else 502, decoded, request.path,
user_balance=user_balance, from_upstream=True,
api_key=key_from_headers(request.headers))
return web.json_response(payload, status=status, headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
try:
if not isinstance(obj.get("model"), str):
raise ModelIdentityError()
check_response_model(requested_model, obj)
except ModelIdentityError:
return web.json_response(_identity_error(), status=503,
headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
chunks = _json_to_sse_chunks(obj, sse_include_usage)
if chunks is None:
LOG.warning("opus_sse_incomplete request_id=%s path=%s", request_id, request.path)
return web.json_response(_failure("upstream_incomplete_response"), status=502,
headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
stream_body = b"".join(b"data: " + json.dumps(chunk, ensure_ascii=False).encode("utf-8") + b"\n\n"
for chunk in chunks) + b"data: [DONE]\n\n"
sse_headers = CIMultiDict((name, value) for name, value in headers.items()
if name.lower() not in ("content-type", "content-encoding", "content-length"))
sse_headers["Content-Type"] = "text/event-stream"
sse_headers["X-Gateway-Stream-Mode"] = "buffered-json"
LOG.info("opus_json_to_sse request_id=%s status=%s choices=%d usage=%s",
request_id, upstream.status, len(obj.get("choices", [])), sse_include_usage)
return web.Response(status=upstream.status, body=stream_body, headers=sse_headers)
if "text/event-stream" in ctype and encoding not in ("", "identity"):
return web.json_response(_failure("upstream_encoding_unsupported"), status=502,
headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
if requested_model and "json" in ctype:
raw = await _read_bounded(upstream, MAX_JSON_BODY, idle=body_idle_timeout)
if raw is None:
return web.json_response(_failure("upstream_response_too_large", False), status=502,
headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
try:
obj = json.loads(_decode(raw, encoding))
check_response_model(requested_model, obj)
if isinstance(obj, dict) and obj.get("error"):
error = obj["error"]
status = error.get("status", 502) if isinstance(error, dict) else 502
try:
status = int(status)
except (ValueError, TypeError):
status = 502
status, payload = public_error(status if 400 <= status <= 599 else 502,
_decode(raw, encoding), request.path,
user_balance=user_balance, from_upstream=True,
api_key=key_from_headers(request.headers))
return web.json_response(payload, status=status, headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
except ModelIdentityError:
return web.json_response(_identity_error(), status=503, headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
except (ValueError, UnicodeDecodeError):
return web.json_response(_failure("upstream_unparseable_response"), status=502,
headers={"X-Request-ID": request_id}, dumps=public_json_dumps)
return web.Response(status=upstream.status, body=raw, headers=headers)
response = web.StreamResponse(status=upstream.status, reason=upstream.reason, headers=headers)
chat_sse = ("text/event-stream" in ctype
and request.path.rstrip("/") in ("/v1/chat/completions", "/v1/completions"))
stream_started = time.monotonic()
# Count accepted data bytes only; incomplete-stream error frames are excluded.
_forwarded = 0
try:
await response.prepare(request)
buffered = b""
async for chunk in _bounded_chunks(upstream.content, body_idle_timeout):
if "text/event-stream" not in ctype:
await response.write(chunk)
_forwarded += len(chunk)
continue
buffered += chunk
while b"\n\n" in buffered or b"\r\n\r\n" in buffered:
choices = [(buffered.find(sep), sep) for sep in (b"\n\n", b"\r\n\r\n") if sep in buffered]
index, sep = min(choices, key=lambda pair: pair[0])
frame, buffered = buffered[:index], buffered[index + len(sep):]
frame, terminal = safe_sse_frame(frame, request.path, requested_model, user_balance)
await response.write(frame + sep)
_forwarded += len(frame) + len(sep)
if terminal:
await response.write_eof()
return response
if len(buffered) > MAX_SSE_FRAME:
frame, _ = _sse_error(_failure("upstream_frame_too_large", False))
await response.write(frame + b"\n\n")
_forwarded += len(frame) + 2
await response.write_eof()
return response
if buffered:
frame, terminal = safe_sse_frame(buffered, request.path, requested_model, user_balance)
await response.write(frame)
_forwarded += len(frame)
if terminal:
await response.write_eof()
return response
if chat_sse:
await response.write(b"\n\n")
_forwarded += 2
if chat_sse:
LOG.warning("api_stream_incomplete request_id=%s duration_ms=%d reason=eof",
request_id, int((time.monotonic() - stream_started) * 1000))
await response.write(_incomplete_sse_frame(request_id))
await response.write_eof()
except (aiohttp.ClientError, asyncio.TimeoutError, ConnectionResetError) as exc:
# Class and counters only: never exception text, payload, model, auth or user.
LOG.warning("api_stream_aborted type=%s elapsed=%.3f prepared=%s forwarded=%d "
"status=%s request_id=%s", type(exc).__name__,
time.monotonic() - stream_started, response.prepared, _forwarded,
upstream.status, request_id)
transport = request.transport
if chat_sse and response.prepared and transport is not None and not transport.is_closing():
LOG.warning("api_stream_incomplete request_id=%s duration_ms=%d reason=%s",
request_id, int((time.monotonic() - stream_started) * 1000), type(exc).__name__)
try:
await response.write(_incomplete_sse_frame(request_id))
await response.write_eof()
return response
except (aiohttp.ClientError, asyncio.TimeoutError, ConnectionResetError):
pass # The downstream has also gone away; close rather than replay.
response.force_close()
if request.transport is not None:
request.transport.close()
return response