import logging import re import json from datetime import datetime from core.project_context import ProjectContext # from core.gemini.connector import call_gemini # Добавлен импорт call_gemini logger = logging.getLogger(__name__) # Промпты для Gemini FIXED_GEMINI_PROMPT = "Translate the following protocol response to a simple, user-friendly message. Protocol: {response}" def _strip_markdown(text: str) -> str: """Удаляет Markdown-обрамление JSON (```json ... ```).""" if not text: return "" # Если текст содержит блоки кода, извлекаем содержимое первого блока pattern = r'```(?:json)?\s*(.*?)\s*```' match = re.search(pattern, text, re.DOTALL | re.IGNORECASE) if match: return match.group(1).strip() return text.strip() # async def call_gemini(prompt: str) -> str: # """ # Вызов Секретаря для интерпретации (использует локальную 'вторую модель' СЕО для экономии). # """ # try: # from core.model_management import ModelManager # mm = ModelManager() # # Шогун: "вторая модель. этот проект слишком быстро сжигает лимиты" # # Переключаем Секретаря на локальную модель 'ceo' (Gemma-2) # model_inst = await mm.get_model('ceo') # response = await model_inst.generate(prompt) # return response # except Exception as e: # logger.error(f"Error calling Secretary (local): {e}") # return "Секретарь: В данный момент я не могу обработать ваш запрос." def intercept_response(response_text: str, source: str) -> dict: """ Интерпретирует ответ от модели согласно протоколу. Returns: dict: { 'type': 'text' | 'redirect' | 'directive' | 'gemini', 'content': str, 'reason_code': str (optional), 'directive': str (optional) } """ # 1. Если ответ от Secretary – сразу возвращаем как текст (инвариант Дефекта №4) if source == 'secretary': return {'type': 'text', 'content': response_text} # 2. Очистка от Markdown cleaned = _strip_markdown(response_text) # 3. Попытка парсинга JSON try: # Ищем JSON структуру, если в ответе есть лишний текст start = cleaned.find('{') end = cleaned.rfind('}') if start != -1 and end != -1: json_str = cleaned[start:end+1] data = json.loads(json_str) # 4. Проверка на redirect if 'redirect' in data: return { 'type': 'redirect', 'target': data['redirect'], 'reason_code': data.get('reason_code', 'unspecified'), 'content': response_text } # 5. Проверка на directive if 'directive' in data: return { 'type': 'directive', 'directive': data['directive'], 'content': response_text } # Если это просто JSON без спец. полей return { 'type': 'gemini', 'reason_code': data.get('status', 'status'), 'content': response_text } # Если есть открывающая скобка, но нет закрывающей - это malformed JSON if cleaned.startswith('{'): raise json.JSONDecodeError("Missing closing brace", cleaned, len(cleaned)) except (json.JSONDecodeError, Exception) as e: # Если ответ начинается с '{', но не распарсился - это malformed JSON if cleaned.startswith('{'): logger.warning(f"Malformed JSON from {source}: {cleaned[:100]}...") return { 'type': 'gemini', 'reason_code': 'malformed_json', 'content': response_text } # 6. Если это обычный текст return {'type': 'text', 'content': response_text} def log_hil_decision(user_message: str, gemini_decision: str, forwarded_to: str, final_response: str): """Логирует интерфейсные решения (HIL decisions) для аудита.""" try: entry = { "timestamp": datetime.now().isoformat(), "user_message": user_message, "gemini_decision": gemini_decision, "forwarded_to": forwarded_to, "final_response": final_response } ctx = ProjectContext.get_instance() project_path = ctx.get_current_project_path() logs_dir = project_path / "logs" logs_dir.mkdir(parents=True, exist_ok=True) with open(logs_dir / "hil_decisions.jsonl", "a", encoding="utf-8") as f: f.write(json.dumps(entry, ensure_ascii=False) + "\n") except Exception as e: logger.error(f"CRITICAL: Failed to write HIL log: {e}")