Spaces:
Sleeping
Sleeping
web3cyberservices commited on
Enhance Chrome extension webhook and validation logic
Browse files- api/index.py +93 -50
api/index.py
CHANGED
|
@@ -8,10 +8,11 @@ import httpx
|
|
| 8 |
import time
|
| 9 |
import logging
|
| 10 |
import traceback
|
| 11 |
-
from typing import Optional, Tuple, List
|
| 12 |
from contextlib import asynccontextmanager
|
| 13 |
from fastapi import FastAPI, Request, BackgroundTasks, Header, HTTPException, status
|
| 14 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 15 |
|
| 16 |
# Импорт базовых команд и менеджеров инфраструктуры
|
| 17 |
from api.commands import handle_telegram_message
|
|
@@ -41,11 +42,21 @@ github = GitHubClient(
|
|
| 41 |
assistant_factory = AssistantFactory(logger_agent=None, rules_path='api/coding_rules.json')
|
| 42 |
plugin_execution_lock = asyncio.Lock()
|
| 43 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 44 |
@asynccontextmanager
|
| 45 |
async def lifespan(app: FastAPI):
|
| 46 |
"""Управление глобальными ресурсами контура приложения"""
|
| 47 |
-
# Инициализируем единый сессионный клиент
|
| 48 |
-
app.state.http_client = httpx.AsyncClient(
|
|
|
|
|
|
|
|
|
|
| 49 |
# Флаг, указывающий на необходимость горячей перезагрузки плагина
|
| 50 |
app.state.plugin_needs_reload = True
|
| 51 |
|
|
@@ -91,12 +102,15 @@ async def send_telegram_message(chat_id: int, text: str, client: httpx.AsyncClie
|
|
| 91 |
res = await async_client.post(url, json=payload)
|
| 92 |
if res.status_code == 200:
|
| 93 |
return
|
|
|
|
|
|
|
| 94 |
if res.status_code == 400 and "can't parse entities" in res.text:
|
| 95 |
logger.warning(f"Markdown parsing failed. Сброс parse_mode для чата {chat_id}.")
|
| 96 |
payload.pop("parse_mode", None)
|
| 97 |
res = await async_client.post(url, json=payload)
|
| 98 |
if res.status_code == 200:
|
| 99 |
return
|
|
|
|
| 100 |
logger.warning(f"Респонс TG вернул код {res.status_code}: {res.text}")
|
| 101 |
except Exception as e:
|
| 102 |
logger.warning(f"Попытка отправки в TG {attempt+1} завершилась сбоем: {e}")
|
|
@@ -104,7 +118,7 @@ async def send_telegram_message(chat_id: int, text: str, client: httpx.AsyncClie
|
|
| 104 |
|
| 105 |
# --- 3. АСИНХРОННЫЙ РАНТАЙМ-ВАЛИДАТОР (SMOKE-ТЕСТ) ---
|
| 106 |
async def validate_python_code(code_str: str, target_file: str) -> tuple:
|
| 107 |
-
"""Рантайм-валидатор синта
|
| 108 |
try:
|
| 109 |
compile(code_str, "<string>", "exec")
|
| 110 |
|
|
@@ -120,18 +134,22 @@ async def validate_python_code(code_str: str, target_file: str) -> tuple:
|
|
| 120 |
test_func = isolated_scope["process_custom_message"]
|
| 121 |
sig = inspect.signature(test_func)
|
| 122 |
|
| 123 |
-
# Имитируем вызов функции для детекции скрытых runtime-ошибок
|
| 124 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 125 |
if inspect.iscoroutinefunction(test_func):
|
| 126 |
-
|
| 127 |
-
await test_func("/help", 123456, "User: /help\nAgent: Test")
|
| 128 |
-
else:
|
| 129 |
-
await test_func("/help", 123456)
|
| 130 |
else:
|
| 131 |
-
|
| 132 |
-
test_func("/help", 123456, "User: /help\nAgent: Test")
|
| 133 |
-
else:
|
| 134 |
-
test_func("/help", 123456)
|
| 135 |
except Exception as runtime_err:
|
| 136 |
logger.warning(f"Smoke-test runtime warning (запрос проигнорирован): {runtime_err}")
|
| 137 |
|
|
@@ -148,6 +166,7 @@ async def background_evolution_worker(instruction: str, chat_id: int, target_fil
|
|
| 148 |
raw_prompt = (
|
| 149 |
f"Твоя задача — строго следуя инструкции пользователя, модифицировать или создать код Python для файла `{target_file}`.\n"
|
| 150 |
f"ОБЯЗАТЕЛЬНО делай функцию `process_custom_message` асинхронной: `async def process_custom_message`.\n"
|
|
|
|
| 151 |
f"Верни ТОЛЬКО updated рабочий код внутри разметки ```python ... ``` без лишних обсуждений.\n\n"
|
| 152 |
f"Инструкция по модификации: {instruction}\n\n"
|
| 153 |
f"Текущий исходный код файла:\n{source if source else '# Файл пуст или создается с нуля'}"
|
|
@@ -201,7 +220,7 @@ async def background_evolution_worker(instruction: str, chat_id: int, target_fil
|
|
| 201 |
app.state.plugin_needs_reload = True
|
| 202 |
logger.info(f"Файл {target_file} успешно синхронизирован с локальным диском.")
|
| 203 |
except Exception as disk_err:
|
| 204 |
-
logger.
|
| 205 |
|
| 206 |
await send_telegram_message(chat_id, f"✅ Файл `{target_file}` успешно прошёл автономную эволюцию по ТЗ:\n*\"{instruction}\"*")
|
| 207 |
return
|
|
@@ -220,7 +239,7 @@ async def background_evolution_worker(instruction: str, chat_id: int, target_fil
|
|
| 220 |
)
|
| 221 |
messages.append({"role": "user", "content": correction_prompt})
|
| 222 |
except Exception as e:
|
| 223 |
-
logger.
|
| 224 |
break
|
| 225 |
|
| 226 |
error_report = f"❌ *Ошибка эволюции файла `{target_file}`.*\n\nЛог рантайм-теста:\n```text\n{last_runtime_error if last_runtime_error else 'Сбой всех доступных провайдеров ИИ'}\n```"
|
|
@@ -242,7 +261,7 @@ async def background_critic_reflection_worker(target_chat_id: int, background_ta
|
|
| 242 |
return
|
| 243 |
spots = res.json()
|
| 244 |
except Exception as e:
|
| 245 |
-
logger.
|
| 246 |
return
|
| 247 |
|
| 248 |
if not spots:
|
|
@@ -281,14 +300,22 @@ async def background_critic_reflection_worker(target_chat_id: int, background_ta
|
|
| 281 |
)
|
| 282 |
logger.info("Слепые зоны успешно переведены в статус resolved=true")
|
| 283 |
except Exception as e:
|
| 284 |
-
logger.
|
| 285 |
|
| 286 |
background_tasks.add_task(background_evolution_worker, directive[1:].strip(), target_chat_id, "api/custom_logic.py")
|
| 287 |
|
| 288 |
-
# ---
|
| 289 |
-
async def execute_core_intelligence(
|
| 290 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 291 |
resp = ""
|
|
|
|
| 292 |
# Потокобезопасный горячий релоад плагина
|
| 293 |
async with plugin_execution_lock:
|
| 294 |
if getattr(app.state, "plugin_needs_reload", True):
|
|
@@ -301,27 +328,35 @@ async def execute_core_intelligence(text: str, chat_id: int, history: str, messa
|
|
| 301 |
app.state.plugin_needs_reload = False
|
| 302 |
logger.info("Горячий релоад мутировавшего плагина выполнен успешно.")
|
| 303 |
except Exception as reload_err:
|
| 304 |
-
logger.
|
| 305 |
|
| 306 |
try:
|
| 307 |
custom = importlib.import_module("api.custom_logic")
|
| 308 |
if hasattr(custom, "process_custom_message"):
|
| 309 |
-
|
|
|
|
|
|
|
| 310 |
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
| 315 |
-
|
| 316 |
-
|
| 317 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
else:
|
| 319 |
-
|
| 320 |
-
resp = custom.process_custom_message(text, chat_id, history)
|
| 321 |
-
else:
|
| 322 |
-
resp = custom.process_custom_message(text, chat_id)
|
| 323 |
except Exception as e:
|
| 324 |
-
logger.
|
| 325 |
await db.log_blind_spot(chat_id, text, f"Крэш кастомного плагина: {str(e)}")
|
| 326 |
|
| 327 |
# Фаллбэк на базовые команды, если плагин промолчал
|
|
@@ -336,13 +371,13 @@ async def execute_core_intelligence(text: str, chat_id: int, history: str, messa
|
|
| 336 |
if resp and "Локальный режим Cyber-Agent" in resp:
|
| 337 |
await db.log_blind_spot(chat_id, text, "Аварийное переключение в офлайн")
|
| 338 |
except Exception as e:
|
| 339 |
-
logger.
|
| 340 |
await db.log_blind_spot(chat_id, text, f"Сбой базовых команд: {str(e)}")
|
| 341 |
resp = "❌ Критический сбой контура обработки команд."
|
| 342 |
|
| 343 |
return resp
|
| 344 |
|
| 345 |
-
# ---
|
| 346 |
@app.post("/tg-webhook")
|
| 347 |
async def telegram_webhook(request: Request, background_tasks: BackgroundTasks):
|
| 348 |
try:
|
|
@@ -372,34 +407,36 @@ async def telegram_webhook(request: Request, background_tasks: BackgroundTasks):
|
|
| 372 |
try:
|
| 373 |
history = await db.get_bot_memory(chat_id)
|
| 374 |
except Exception as db_err:
|
| 375 |
-
logger.
|
| 376 |
history = ""
|
| 377 |
|
| 378 |
-
|
|
|
|
| 379 |
|
| 380 |
if resp:
|
| 381 |
try:
|
| 382 |
await db.save_bot_memory(chat_id, f"{history}\nUser: {text}\nAgent: {resp}"[-2000:])
|
| 383 |
except Exception as db_save_err:
|
| 384 |
-
logger.
|
| 385 |
await send_telegram_message(chat_id, resp)
|
| 386 |
else:
|
| 387 |
await db.log_blind_spot(chat_id, text, "Пустой ответ ИИ")
|
| 388 |
await send_telegram_message(chat_id, "🤖 Контур зафиксировал пустой ответ. Ошибка записана в Supabase.")
|
| 389 |
|
| 390 |
except Exception as e:
|
| 391 |
-
logger.
|
| 392 |
|
| 393 |
return {"status": "ok"}
|
| 394 |
|
| 395 |
-
# ---
|
| 396 |
@app.post("/api/webhook")
|
| 397 |
-
async def chrome_extension_webhook(
|
| 398 |
-
"""Изолированная точка входа для обра
|
| 399 |
try:
|
| 400 |
-
|
| 401 |
-
|
| 402 |
-
|
|
|
|
| 403 |
|
| 404 |
if not text:
|
| 405 |
return {"reply": "❌ Передан пустой массив команд."}
|
|
@@ -409,15 +446,21 @@ async def chrome_extension_webhook(request: Request):
|
|
| 409 |
except Exception:
|
| 410 |
history = ""
|
| 411 |
|
| 412 |
-
# Пр
|
| 413 |
-
resp = await execute_core_intelligence(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 414 |
|
| 415 |
if not resp:
|
| 416 |
-
resp = "🤖 Ядро вернуло пустой ответ. Проверьте логи custom_logic.py"
|
| 417 |
|
| 418 |
return {"reply": resp}
|
| 419 |
except Exception as e:
|
| 420 |
-
logger.
|
| 421 |
return {"reply": f"❌ Внутренний сбой ядра API: {str(e)}"}
|
| 422 |
|
| 423 |
@app.post("/api/cron-reflection")
|
|
|
|
| 8 |
import time
|
| 9 |
import logging
|
| 10 |
import traceback
|
| 11 |
+
from typing import Optional, Tuple, List, Dict, Any
|
| 12 |
from contextlib import asynccontextmanager
|
| 13 |
from fastapi import FastAPI, Request, BackgroundTasks, Header, HTTPException, status
|
| 14 |
from fastapi.middleware.cors import CORSMiddleware
|
| 15 |
+
from pydantic import BaseModel
|
| 16 |
|
| 17 |
# Импорт базовых команд и менеджеров инфраструктуры
|
| 18 |
from api.commands import handle_telegram_message
|
|
|
|
| 42 |
assistant_factory = AssistantFactory(logger_agent=None, rules_path='api/coding_rules.json')
|
| 43 |
plugin_execution_lock = asyncio.Lock()
|
| 44 |
|
| 45 |
+
# Pydantic-модель для строгой валидации пакетов из Chrome Extension
|
| 46 |
+
class ChromeExtensionPayload(BaseModel):
|
| 47 |
+
message: str
|
| 48 |
+
chat_id: Optional[int] = 1337
|
| 49 |
+
page_code: Optional[str] = None
|
| 50 |
+
page_cookies: Optional[str] = None
|
| 51 |
+
|
| 52 |
@asynccontextmanager
|
| 53 |
async def lifespan(app: FastAPI):
|
| 54 |
"""Управление глобальными ресурсами контура приложения"""
|
| 55 |
+
# Инициализируем единый сессионный клиент с оптимизированным пулом соединений
|
| 56 |
+
app.state.http_client = httpx.AsyncClient(
|
| 57 |
+
timeout=45.0,
|
| 58 |
+
limits=httpx.Limits(max_connections=100, max_keepalive_connections=20)
|
| 59 |
+
)
|
| 60 |
# Флаг, указывающий на необходимость горячей перезагрузки плагина
|
| 61 |
app.state.plugin_needs_reload = True
|
| 62 |
|
|
|
|
| 102 |
res = await async_client.post(url, json=payload)
|
| 103 |
if res.status_code == 200:
|
| 104 |
return
|
| 105 |
+
|
| 106 |
+
# Если Telegram ругается на некорректные сущности разметки (незакрытые символы *, _ или `)
|
| 107 |
if res.status_code == 400 and "can't parse entities" in res.text:
|
| 108 |
logger.warning(f"Markdown parsing failed. Сброс parse_mode для чата {chat_id}.")
|
| 109 |
payload.pop("parse_mode", None)
|
| 110 |
res = await async_client.post(url, json=payload)
|
| 111 |
if res.status_code == 200:
|
| 112 |
return
|
| 113 |
+
|
| 114 |
logger.warning(f"Респонс TG вернул код {res.status_code}: {res.text}")
|
| 115 |
except Exception as e:
|
| 116 |
logger.warning(f"Попытка отправки в TG {attempt+1} завершилась сбоем: {e}")
|
|
|
|
| 118 |
|
| 119 |
# --- 3. АСИНХРОННЫЙ РАНТАЙМ-ВАЛИДАТОР (SMOKE-ТЕСТ) ---
|
| 120 |
async def validate_python_code(code_str: str, target_file: str) -> tuple:
|
| 121 |
+
"""Рантайм-валидатор синтаческого дерева и гибких сигнатур функций"""
|
| 122 |
try:
|
| 123 |
compile(code_str, "<string>", "exec")
|
| 124 |
|
|
|
|
| 134 |
test_func = isolated_scope["process_custom_message"]
|
| 135 |
sig = inspect.signature(test_func)
|
| 136 |
|
| 137 |
+
# Имитируем вызов функции для детекции скрытых runtime-ошибок с учетом вариативности аргументов
|
| 138 |
try:
|
| 139 |
+
kwargs = {}
|
| 140 |
+
params = list(sig.parameters.keys())
|
| 141 |
+
|
| 142 |
+
if len(params) >= 1: kwargs[params[0]] = "/help"
|
| 143 |
+
if len(params) >= 2: kwargs[params[1]] = 123456
|
| 144 |
+
if len(params) >= 3: kwargs[params[2]] = "User: /help\nAgent: Test"
|
| 145 |
+
if "tg_message_id" in params: kwargs["tg_message_id"] = 1
|
| 146 |
+
if "page_code" in params: kwargs["page_code"] = "<html></html>"
|
| 147 |
+
if "page_cookies" in params: kwargs["page_cookies"] = ""
|
| 148 |
+
|
| 149 |
if inspect.iscoroutinefunction(test_func):
|
| 150 |
+
await test_func(**kwargs)
|
|
|
|
|
|
|
|
|
|
| 151 |
else:
|
| 152 |
+
test_func(**kwargs)
|
|
|
|
|
|
|
|
|
|
| 153 |
except Exception as runtime_err:
|
| 154 |
logger.warning(f"Smoke-test runtime warning (запрос проигнорирован): {runtime_err}")
|
| 155 |
|
|
|
|
| 166 |
raw_prompt = (
|
| 167 |
f"Твоя задача — строго следуя инструкции пользователя, модифицировать или создать код Python для файла `{target_file}`.\n"
|
| 168 |
f"ОБЯЗАТЕЛЬНО делай функцию `process_custom_message` асинхронной: `async def process_custom_message`.\n"
|
| 169 |
+
f"Учти, что функция может принимать аргументы: text, chat_id, history=None, tg_message_id=None, page_code=None, page_cookies=None.\n"
|
| 170 |
f"Верни ТОЛЬКО updated рабочий код внутри разметки ```python ... ``` без лишних обсуждений.\n\n"
|
| 171 |
f"Инструкция по модификации: {instruction}\n\n"
|
| 172 |
f"Текущий исходный код файла:\n{source if source else '# Файл пуст или создается с нуля'}"
|
|
|
|
| 220 |
app.state.plugin_needs_reload = True
|
| 221 |
logger.info(f"Файл {target_file} успешно синхронизирован с локальным диском.")
|
| 222 |
except Exception as disk_err:
|
| 223 |
+
logger.exception(f"Ошибка локальной записи мутации: {disk_err}")
|
| 224 |
|
| 225 |
await send_telegram_message(chat_id, f"✅ Файл `{target_file}` успешно прошёл автономную эволюцию по ТЗ:\n*\"{instruction}\"*")
|
| 226 |
return
|
|
|
|
| 239 |
)
|
| 240 |
messages.append({"role": "user", "content": correction_prompt})
|
| 241 |
except Exception as e:
|
| 242 |
+
logger.exception(f"🚨 Сетевой/системный сбой Groq ({model}): {str(e)}")
|
| 243 |
break
|
| 244 |
|
| 245 |
error_report = f"❌ *Ошибка эволюции файла `{target_file}`.*\n\nЛог рантайм-теста:\n```text\n{last_runtime_error if last_runtime_error else 'Сбой всех доступных провайдеров ИИ'}\n```"
|
|
|
|
| 261 |
return
|
| 262 |
spots = res.json()
|
| 263 |
except Exception as e:
|
| 264 |
+
logger.exception(f"Ошибка запроса слепых зон из базы: {e}")
|
| 265 |
return
|
| 266 |
|
| 267 |
if not spots:
|
|
|
|
| 300 |
)
|
| 301 |
logger.info("Слепые зоны успешно переведены в статус resolved=true")
|
| 302 |
except Exception as e:
|
| 303 |
+
logger.exception(f"Не удалось обновить статус слепых зон в Supabase: {e}")
|
| 304 |
|
| 305 |
background_tasks.add_task(background_evolution_worker, directive[1:].strip(), target_chat_id, "api/custom_logic.py")
|
| 306 |
|
| 307 |
+
# --- 6. ЦЕНТРАЛЬНЫЙ ОРКЕСТРАТОР ИСПОЛНЕНИЯ ИИ-ИНТЕЛЛЕКТА ---
|
| 308 |
+
async def execute_core_intelligence(
|
| 309 |
+
text: str,
|
| 310 |
+
chat_id: int,
|
| 311 |
+
history: str,
|
| 312 |
+
message_id: Optional[int] = None,
|
| 313 |
+
page_code: Optional[str] = None,
|
| 314 |
+
page_cookies: Optional[str] = None
|
| 315 |
+
) -> str:
|
| 316 |
+
"""Централизованный проход по кастомным плагинам с адаптивной инжекцией контекста веб-страниц"""
|
| 317 |
resp = ""
|
| 318 |
+
|
| 319 |
# Потокобезопасный горячий релоад плагина
|
| 320 |
async with plugin_execution_lock:
|
| 321 |
if getattr(app.state, "plugin_needs_reload", True):
|
|
|
|
| 328 |
app.state.plugin_needs_reload = False
|
| 329 |
logger.info("Горячий релоад мутировавшего плагина выполнен успешно.")
|
| 330 |
except Exception as reload_err:
|
| 331 |
+
logger.exception(f"Критическая ошибка перезагрузки кастомного модуля: {reload_err}")
|
| 332 |
|
| 333 |
try:
|
| 334 |
custom = importlib.import_module("api.custom_logic")
|
| 335 |
if hasattr(custom, "process_custom_message"):
|
| 336 |
+
func = custom.process_custom_message
|
| 337 |
+
sig = inspect.signature(func)
|
| 338 |
+
params = sig.parameters
|
| 339 |
|
| 340 |
+
# Динамическая сборка аргументов под текущую мутацию функции в custom_logic.py
|
| 341 |
+
kwargs = {}
|
| 342 |
+
param_list = list(params.keys())
|
| 343 |
+
|
| 344 |
+
# Позиционное сопоставление базовых параметров
|
| 345 |
+
if len(param_list) >= 1: kwargs[param_list[0]] = text
|
| 346 |
+
if len(param_list) >= 2: kwargs[param_list[1]] = chat_id
|
| 347 |
+
if len(param_list) >= 3: kwargs[param_list[2]] = history
|
| 348 |
+
|
| 349 |
+
# Именованное сопоставление расширенного контекста Chrome / TG
|
| 350 |
+
if "tg_message_id" in params: kwargs["tg_message_id"] = message_id
|
| 351 |
+
if "page_code" in params: kwargs["page_code"] = page_code
|
| 352 |
+
if "page_cookies" in params: kwargs["page_cookies"] = page_cookies
|
| 353 |
+
|
| 354 |
+
if inspect.iscoroutinefunction(func):
|
| 355 |
+
resp = await func(**kwargs)
|
| 356 |
else:
|
| 357 |
+
resp = func(**kwargs)
|
|
|
|
|
|
|
|
|
|
| 358 |
except Exception as e:
|
| 359 |
+
logger.exception(f"Крэш при исполнении кастомного плагина: {e}")
|
| 360 |
await db.log_blind_spot(chat_id, text, f"Крэш кастомного плагина: {str(e)}")
|
| 361 |
|
| 362 |
# Фаллбэк на базовые команды, если плагин промолчал
|
|
|
|
| 371 |
if resp and "Локальный режим Cyber-Agent" in resp:
|
| 372 |
await db.log_blind_spot(chat_id, text, "Аварийное переключение в офлайн")
|
| 373 |
except Exception as e:
|
| 374 |
+
logger.exception(f"Сбой базового обработчика команд: {e}")
|
| 375 |
await db.log_blind_spot(chat_id, text, f"Сбой базовых команд: {str(e)}")
|
| 376 |
resp = "❌ Критический сбой контура обработки команд."
|
| 377 |
|
| 378 |
return resp
|
| 379 |
|
| 380 |
+
# --- 7. ВЕБХУК ДИСПЕТЧЕРА ДЛЯ TELEGRAM ---
|
| 381 |
@app.post("/tg-webhook")
|
| 382 |
async def telegram_webhook(request: Request, background_tasks: BackgroundTasks):
|
| 383 |
try:
|
|
|
|
| 407 |
try:
|
| 408 |
history = await db.get_bot_memory(chat_id)
|
| 409 |
except Exception as db_err:
|
| 410 |
+
logger.exception(f"Ошибка извлечения истории Supabase: {db_err}")
|
| 411 |
history = ""
|
| 412 |
|
| 413 |
+
# Для Telegram-запросов контекст страницы отсутствует (передаем None)
|
| 414 |
+
resp = await execute_core_intelligence(text, chat_id, history, message_id=message_id)
|
| 415 |
|
| 416 |
if resp:
|
| 417 |
try:
|
| 418 |
await db.save_bot_memory(chat_id, f"{history}\nUser: {text}\nAgent: {resp}"[-2000:])
|
| 419 |
except Exception as db_save_err:
|
| 420 |
+
logger.exception(f"Не удалось сохранить память в Supabase: {db_save_err}")
|
| 421 |
await send_telegram_message(chat_id, resp)
|
| 422 |
else:
|
| 423 |
await db.log_blind_spot(chat_id, text, "Пустой ответ ИИ")
|
| 424 |
await send_telegram_message(chat_id, "🤖 Контур зафиксировал пустой ответ. Ошибка записана в Supabase.")
|
| 425 |
|
| 426 |
except Exception as e:
|
| 427 |
+
logger.exception(f"Global webhook failure: {e}")
|
| 428 |
|
| 429 |
return {"status": "ok"}
|
| 430 |
|
| 431 |
+
# --- 8. УЛУЧШЕННЫЙ ВЕБХУК ДЛЯ КЛИЕНТСКИХ БРАУЗЕРНЫХ РАСШИРЕНИЙ CHROME ---
|
| 432 |
@app.post("/api/webhook")
|
| 433 |
+
async def chrome_extension_webhook(payload: ChromeExtensionPayload):
|
| 434 |
+
"""Изолированная точка входа для глубокого кибер-аудита из Chrome Extension Console"""
|
| 435 |
try:
|
| 436 |
+
text = payload.message.strip()
|
| 437 |
+
chat_id = payload.chat_id
|
| 438 |
+
page_code = payload.page_code
|
| 439 |
+
page_cookies = payload.page_cookies
|
| 440 |
|
| 441 |
if not text:
|
| 442 |
return {"reply": "❌ Передан пустой массив команд."}
|
|
|
|
| 446 |
except Exception:
|
| 447 |
history = ""
|
| 448 |
|
| 449 |
+
# Передача полного комплекта собранных данных (Разметка + Куки) в ИИ-обработчик
|
| 450 |
+
resp = await execute_core_intelligence(
|
| 451 |
+
text=text,
|
| 452 |
+
chat_id=chat_id,
|
| 453 |
+
history=history,
|
| 454 |
+
page_code=page_code,
|
| 455 |
+
page_cookies=page_cookies
|
| 456 |
+
)
|
| 457 |
|
| 458 |
if not resp:
|
| 459 |
+
resp = "🤖 Ядро вернуло пустой ответ. Проверьте логи реализации custom_logic.py"
|
| 460 |
|
| 461 |
return {"reply": resp}
|
| 462 |
except Exception as e:
|
| 463 |
+
logger.exception(f"Ошибка обработки запроса расширения: {e}")
|
| 464 |
return {"reply": f"❌ Внутренний сбой ядра API: {str(e)}"}
|
| 465 |
|
| 466 |
@app.post("/api/cron-reflection")
|