Download app2.py from lhc-lab/AI-Colab: direct link, hf CLI and curl.
- Browser
- Download file 36.1 kB
-
https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/app2.py
- Command line
-
hf download hf://datasets/lhc-lab/AI-Colab/app2.py
-
curl -L -o app2.py https://huggingface.co/datasets/lhc-lab/AI-Colab/resolve/main/app2.py
36.1 kB
| import sys | |
| import os | |
| import traceback | |
| from datetime import datetime | |
| try: | |
| print("=== CRITICAL APP2.PY STARTUP TRY BLOCK ===") | |
| from quart import Quart, request, jsonify, websocket, render_template, send_from_directory | |
| from typing import Optional, Dict | |
| import asyncio | |
| import logging | |
| import json | |
| import pathlib | |
| from dotenv import load_dotenv | |
| from core.app_state import get_current_project | |
| from core.lab_composition import get_lab_composition | |
| from core.prompt_registry import PromptRegistry | |
| from core.model_management import ModelManager | |
| from core.role_binding_manager import RoleBindingManager | |
| from core.gemini_cli_executor import execute | |
| from core.project_context import ProjectContext | |
| from core.chat_storage import get_chat_storage | |
| from doctor_ws_module import register_doctor_ws | |
| # from core.agent_orchestrator import launch_agents, terminate_agents | |
| # ============================================================================ | |
| # DIAGNOSTIC LOGGING — SPEC_2026_04_02-1 | |
| # ============================================================================ | |
| logging.basicConfig( | |
| level=logging.DEBUG, | |
| format='[%(asctime)s] %(levelname)s in %(module)s: %(message)s', | |
| handlers=[ | |
| logging.FileHandler('server_debug.log', encoding='utf-8', mode='a'), | |
| logging.StreamHandler() | |
| ] | |
| ) | |
| logger = logging.getLogger(__name__) | |
| # ============================================================================ | |
| def extract_ui_model_name(model_id: str) -> str: | |
| """Преобразует технический model_id в человекочитаемое имя.""" | |
| if not model_id: | |
| return "unknown" | |
| name = model_id.split("/")[-1] | |
| name = name.split(":")[0] | |
| name = name.replace("-", " ").replace("_", " ") | |
| name = name.replace("(", "").replace(")", "") | |
| return name.title() | |
| load_dotenv() | |
| # Ленивая инициализация менеджеров (асинхронно) | |
| async def get_model_manager() -> ModelManager: | |
| if not hasattr(app, 'model_manager') or app.model_manager is None: | |
| app.model_manager = ModelManager() | |
| await app.model_manager._ensure_initialized() | |
| return app.model_manager | |
| async def get_role_manager() -> RoleBindingManager: | |
| if not hasattr(app, 'role_binding_manager') or app.role_binding_manager is None: | |
| model_mgr = await get_model_manager() | |
| app.role_binding_manager = RoleBindingManager(model_manager=model_mgr) | |
| return app.role_binding_manager | |
| # === CONFIG FOR ROLE GREETINGS (SPEC_2026_04_07-2) === | |
| ROLE_GREETINGS = { | |
| "left": [ | |
| "chief", | |
| "secretary_chief", | |
| "secretary_ceo", | |
| "consultant_strategic", | |
| "audit_orchestrator" | |
| ], | |
| "right": [ | |
| "ceo", | |
| "flick", | |
| "flock", | |
| "click", | |
| "clack", | |
| "check", | |
| "chock", | |
| "link", | |
| "sync" | |
| ] | |
| } | |
| ROLE_DISPLAY_NAMES = { | |
| "ceo": "CEO", | |
| "chief": "Шеф", | |
| "secretary_ceo": "Секретарь CEO", | |
| "secretary_chief": "Секретарь Шефа", | |
| "consultant_strategic": "Стратегический советник", | |
| "audit_orchestrator": "Доктор (Аудитор)" | |
| } | |
| async def send_role_greetings_to_client(ws): | |
| """ | |
| Отправляет пакет приветствий ролей при подключении (SPEC_2026_04_07-2). | |
| """ | |
| greetings = [] | |
| try: | |
| rm = await get_role_manager() | |
| for chat_side, roles in ROLE_GREETINGS.items(): | |
| for role_key in roles: | |
| try: | |
| # Heavy operation (async) | |
| model_id = await rm.get_model_for_role( | |
| role_key, | |
| None | |
| ) | |
| display_name = ROLE_DISPLAY_NAMES.get( | |
| role_key, | |
| role_key.replace("_", " ").title() | |
| ) | |
| model_short = ( | |
| model_id.split("/")[-1].split(":")[0] | |
| if model_id else "unknown" | |
| ) | |
| greetings.append({ | |
| "chat": chat_side, | |
| "text": f"👋 [{display_name}] онлайн. Модель: {model_short}. Статус: готов." | |
| }) | |
| except Exception as e: | |
| logger.warning(f"[GREETING] {role_key} failed: {e}") | |
| if greetings: | |
| await ws.send_json({ | |
| "type": "system_batch", | |
| "session": "init", | |
| "messages": greetings | |
| }) | |
| except Exception as e: | |
| logger.error(f"[GREETING_CRITICAL] {e}", exc_info=True) | |
| async def call_gemini(prompt: str, role_key: str = "gemini_console") -> str: | |
| """ | |
| Вызов внешнего мозга через эфемерный CLI (Gemini CLI). | |
| """ | |
| project_path = ProjectContext.get_instance().get_current_project_path() | |
| return await execute( | |
| mode="console", | |
| message=prompt, | |
| for_role=role_key, | |
| project_path=str(project_path) if project_path else None | |
| ) | |
| app = Quart(__name__, static_folder='static', template_folder='templates') | |
| app.config['SECRET_KEY'] = os.urandom(24) | |
| # ---------------------------------------------------------------------- | |
| # Вспомогательные функции и инициализация | |
| # ---------------------------------------------------------------------- | |
| async def ensure_project_dirs(): | |
| from core.project_context import ProjectContext | |
| from core.app_state import get_current_project | |
| project_path_str = get_current_project() | |
| if not project_path_str: | |
| app.logger.info("Проект не выбран в SharedState, пропуск создания директорий.") | |
| return | |
| ctx = ProjectContext.get_instance() | |
| await ctx.ensure_initialized() | |
| project_path = ctx.get_current_project_path() | |
| required_dirs = ["logs", "logs/sessions", "info/ceo", "info/chief", "info/doctor"] | |
| for dir_name in required_dirs: | |
| dir_path = project_path / dir_name | |
| dir_path.mkdir(parents=True, exist_ok=True) | |
| app.logger.info(f"Директории проекта созданы: {project_path}") | |
| def ensure_project_model_pool(): | |
| from core.shared_state import get_shared_state | |
| from pathlib import Path | |
| state = get_shared_state() | |
| project_path = state.get("current_project_path") | |
| if not project_path: | |
| return | |
| # Используем локально импортированный Path | |
| global_config_path = Path(__file__).parent.resolve() / "config" / "models_config.json" | |
| project_config_path = Path(project_path) / "config" / "models_config.json" | |
| if not global_config_path.exists(): | |
| app.logger.warning("Global config missing, cannot sync project pool") | |
| return | |
| try: | |
| with open(global_config_path, 'r', encoding='utf-8') as f: | |
| global_config = json.load(f) | |
| global_pool = global_config.get("available_openrouter_models", []) | |
| if not global_pool: | |
| app.logger.warning("Global pool is empty, nothing to sync") | |
| return | |
| if not project_config_path.exists(): | |
| project_config = { | |
| "available_openrouter_models": global_pool, | |
| "last_synced": datetime.now().isoformat(), | |
| "sync_source": "global" | |
| } | |
| project_config_path.parent.mkdir(parents=True, exist_ok=True) | |
| with open(project_config_path, 'w', encoding='utf-8') as f: | |
| json.dump(project_config, f, indent=2, ensure_ascii=False) | |
| app.logger.info(f"Created project config with {len(global_pool)} models") | |
| return | |
| with open(project_config_path, 'r', encoding='utf-8') as f: | |
| project_config = json.load(f) | |
| current_pool = project_config.get("available_openrouter_models", []) | |
| if len(current_pool) >= 2: | |
| app.logger.info(f"Project pool already has {len(current_pool)} models, no sync needed") | |
| return | |
| project_config["available_openrouter_models"] = global_pool | |
| project_config["last_synced"] = datetime.now().isoformat() | |
| project_config["sync_note"] = "Updated from global config (project pool was too small)" | |
| with open(project_config_path, 'w', encoding='utf-8') as f: | |
| json.dump(project_config, f, indent=2, ensure_ascii=False) | |
| app.logger.info(f"Synced project pool: now {len(global_pool)} models (was {len(current_pool)})") | |
| except Exception as e: | |
| app.logger.error(f"Error syncing project model pool: {e}") | |
| async def startup(): | |
| await ensure_project_dirs() | |
| ensure_project_model_pool() | |
| # Diagnostic | |
| app.logger.info(f"STARTUP DIAG: role_mgr={hasattr(app, 'role_binding_manager')}, model_mgr={hasattr(app, 'model_manager')}") | |
| # app.add_background_task(update_models) | |
| # app.logger.info("🚀 Updater моделей (интегрированный) запущен в фоне") | |
| app.project_context = None | |
| app.orchestrator = None | |
| app.gcb = None | |
| app.prompt_registry = PromptRegistry() | |
| app.logger.info("Сервер готов к ленивой инициализации") | |
| async def get_gcb(): | |
| if not hasattr(app, 'gcb') or app.gcb is None: | |
| from core.llm_integrations.gcb_engine import GCBEngine | |
| app.gcb = GCBEngine() | |
| return app.gcb | |
| async def get_orchestrator(): | |
| if not hasattr(app, 'orchestrator') or app.orchestrator is None: | |
| from core.llm_integrations.chief_orchestrator import ChiefOrchestrator | |
| model_manager_instance = await get_model_manager() | |
| app.orchestrator = ChiefOrchestrator(model_manager=model_manager_instance) | |
| return app.orchestrator | |
| # ---------------------------------------------------------------------- | |
| # Роуты | |
| # ---------------------------------------------------------------------- | |
| async def index(): | |
| return await render_template('index.html') | |
| async def send_static(path): | |
| return await send_from_directory('static', path) | |
| async def admin_switch_binding(): | |
| role_manager = await get_role_manager() | |
| data = await request.get_json() | |
| role = data.get('role') | |
| model = data.get('model') | |
| reason = data.get('reason', 'admin_request') | |
| if not role or not model: | |
| return jsonify({'success': False, 'error': 'Missing role or model'}), 400 | |
| success = await role_manager.switch_binding(role, model, reason) | |
| return jsonify({'success': success}) | |
| async def ceo_consult(): | |
| data = await request.get_json() | |
| message = data.get('message', '') | |
| session_id = data.get('session_id', 'default') | |
| role_manager = await get_role_manager() | |
| result = await role_manager.run_department("D", {"message": message, "session_id": session_id}, caller="ceo") | |
| if result: | |
| proposal = result.get('proposal', 'Нет предложения') | |
| weak_points = "\n- ".join(result.get('weak_points', [])) | |
| alternatives = "\n- ".join(result.get('alternatives', [])) | |
| reply = f"🧠 Внешний Консилиум (Отдел D):\n\n**Предложение:**\n{proposal}\n\n**Слабые стороны:**\n- {weak_points}\n\n**Альтернативы:**\n- {alternatives}" | |
| return jsonify({'reply': reply, 'model': 'ceo_council', 'session_id': session_id}) | |
| else: | |
| return jsonify({'error': 'Не удалось получить ответ от консилиума'}), 500 | |
| from core.mode_handler import apply_mode_logic | |
| from core import gateway | |
| import re | |
| def log_redirect(entry: dict): | |
| try: | |
| from core.project_context import ProjectContext | |
| ctx = ProjectContext.get_instance() | |
| project_path = ctx.get_current_project_path() | |
| redirects_log = project_path / "logs" / "redirects.jsonl" | |
| redirects_log.parent.mkdir(parents=True, exist_ok=True) | |
| with open(redirects_log, "a", encoding="utf-8") as f: | |
| f.write(json.dumps(entry, ensure_ascii=False) + "\n") | |
| except Exception as e: | |
| app.logger.error(f"Failed to log redirect: {e}") | |
| async def call_secretary(user_message: str, reason_code: str, source_role: str) -> str: | |
| role_manager = await get_role_manager() | |
| system_prompt = await role_manager.get_prompt('secretary') | |
| user_prompt = ( | |
| f"ИНСТРУКЦИЯ ДЛЯ СЕКРЕТАРЯ:\n" | |
| f"1. Ты получил отказ от роли: {source_role}\n" | |
| f"2. Код причины отказа: {reason_code}\n" | |
| f"3. Сообщение пользователя: {user_message}\n\n" | |
| f"ЗАДАНИЕ: Объясни пользователю причину отказа простыми словами на русском языке. " | |
| f"СТРОГО ЗАПРЕЩЕНО ИСПОЛЬЗОВАТЬ JSON ИЛИ ЛЮБЫЕ ТЕХНИЧЕСКИЕ СИМВОЛЫ. " | |
| f"ОТВЕЧАЙ ТОЛЬКО ТЕКСТОМ ДЛЯ ЧЕЛОВЕКА." | |
| ) | |
| try: | |
| # Используем secretary_chief как default-Секретаря для перенаправлений | |
| response = await call_gemini(user_prompt, role_key="secretary_chief") | |
| stripped = response.strip() | |
| if stripped.startswith('{') and stripped.endswith('}'): | |
| try: | |
| data = json.loads(stripped) | |
| for key in ['content', 'response', 'message', 'text', 'reply']: | |
| if key in data: | |
| return str(data[key]) | |
| if 'redirect' in data or 'reason_code' in data: | |
| return f"Роль {source_role} отклонила запрос (код: {reason_code}). Пожалуйста, уточните ваш вопрос." | |
| except: | |
| pass | |
| return response | |
| except Exception as e: | |
| app.logger.error(f"Gemini call failed: {e}") | |
| return f"Ошибка связи с Секретарём (Gemini CLI): {e}" | |
| async def secretary_internal_endpoint(): | |
| data = await request.get_json() | |
| user_message = data.get('user_message', '') | |
| reason_code = data.get('reason_code', 'unspecified') | |
| source_role = data.get('source_role', 'unknown') | |
| response = await call_secretary(user_message, reason_code, source_role) | |
| return jsonify({"response": response}) | |
| async def chat(): | |
| resp = jsonify({'error': 'This endpoint is deprecated. Use /api/secretary instead.', 'new_endpoint': '/api/secretary'}) | |
| resp.headers['Location'] = '/api/secretary' | |
| return resp, 410 | |
| async def secretary(): | |
| try: | |
| data = await request.get_json() | |
| model_key = data.get('model') | |
| user_message = data.get('message', data.get('user_message', '')) | |
| session_id = data.get('session_id', 'default') | |
| if not model_key: | |
| return jsonify({"error": "Missing model parameter"}), 400 | |
| model_manager = await get_model_manager() | |
| await model_manager._ensure_initialized() | |
| source_role = model_key | |
| ROLE_NAMES = { | |
| "chief": "Шеф", "ceo": "СЕО", "secretary": "Секретарь", | |
| "flick": "Флик", "flock": "Флок", "click": "Клик", "clack": "Клак", | |
| "check": "Чек", "chock": "Чок", "link": "Линк", "sync": "Синх" | |
| } | |
| try: | |
| async with model_manager._generate_lock: | |
| if model_key == 'ceo': | |
| role_manager = await get_role_manager() | |
| ceo_model = await model_manager.get_model('ceo') | |
| system_prompt_ceo = await role_manager.get_prompt('ceo') | |
| raw_response = await ceo_model.generate(user_message, system_prompt=system_prompt_ceo) | |
| elif model_key == 'chief': | |
| role_manager = await get_role_manager() | |
| chief_model = await model_manager.get_model('chief') | |
| system_prompt_chief = await role_manager.get_prompt('chief') | |
| raw_response = await chief_model.generate(user_message, system_prompt=system_prompt_chief) | |
| elif model_key in ('gemini_direct', 'gemini', 'secretary'): | |
| return jsonify({"redirect": "secretary", "reason_code": "gemini_direct_call", "user_message": user_message}), 200 | |
| else: | |
| # Staff-модели (Direct interaction) | |
| role_manager = await get_role_manager() | |
| system_prompt = app.prompt_registry.get_prompt(model_key) | |
| # 1. Первая попытка | |
| model_id = await role_manager.get_model_for_role(model_key, task_id=session_id) | |
| # === TEMP DIAG: Effective pool audit (SPEC_2026_04_05-R) === | |
| first_model = model_id | |
| second_model = None | |
| try: | |
| second_model = await role_manager.get_model_for_role( | |
| model_key, | |
| task_id=session_id, | |
| exclude=[first_model] | |
| ) | |
| except Exception as e: | |
| second_model = f"ERROR: {type(e).__name__}" | |
| app.logger.info( | |
| f"[POOL_EFFECTIVE] role={model_key} " | |
| f"first={first_model} " | |
| f"second={second_model}" | |
| ) | |
| # === END TEMP DIAG === | |
| try: | |
| model_inst = await model_manager.get_model(model_id) | |
| staff_response = await model_inst.generate( | |
| prompt=user_message, | |
| system_prompt=system_prompt, | |
| max_tokens=2048 | |
| ) | |
| except Exception as e: | |
| # 2. Если ошибка (например, 429) — пробуем Failover один раз | |
| app.logger.warning(f"Failover trigger for {model_key} (failed model: {model_id}): {e}") | |
| # Пытаемся выбрать другую модель | |
| model_id = await role_manager.get_model_for_role(model_key, task_id=session_id, exclude=[model_id]) | |
| try: | |
| model_inst = await model_manager.get_model(model_id) | |
| staff_response = await model_inst.generate( | |
| prompt=user_message, | |
| system_prompt=system_prompt, | |
| max_tokens=2048 | |
| ) | |
| except Exception as e2: | |
| # Если и вторая упала — выходим с ошибкой, но сохраняем modelId для UI | |
| display_name = ROLE_NAMES.get(model_key, model_key.capitalize()) | |
| return jsonify({ | |
| "response": f"Ошибка {model_key}: {e2}", | |
| "modelInfo": { | |
| "key": model_key, | |
| "roleName": display_name, | |
| "modelId": extract_ui_model_name(model_id), | |
| "error": str(e2) | |
| } | |
| }), 500 | |
| # Если и вторая упала — выходим с ошибкой, но сохраняем modelId для UI | |
| display_name = ROLE_NAMES.get(model_key, model_key.capitalize()) | |
| return jsonify({ | |
| "response": f"Ошибка {model_key}: {e2}", | |
| "modelInfo": { | |
| "key": model_key, | |
| "roleName": display_name, | |
| "modelId": extract_ui_model_name(model_id), | |
| "error": str(e2) | |
| } | |
| }), 500 | |
| # Запись лога диалога | |
| project_path = get_current_project() | |
| if project_path: | |
| log_dir = pathlib.Path(project_path) / "logs" / "subjects" | |
| log_dir.mkdir(parents=True, exist_ok=True) | |
| with open(log_dir / f"{model_key}.log", "a", encoding="utf-8") as f: | |
| f.write(f"User: {user_message}\nAI: {staff_response}\n\n") | |
| display_name = ROLE_NAMES.get(model_key, model_key.capitalize()) | |
| return jsonify({ | |
| "response": str(staff_response), | |
| "modelInfo": { | |
| "key": model_key, | |
| "roleName": display_name, | |
| "modelId": extract_ui_model_name(model_id) | |
| } | |
| }) | |
| except asyncio.TimeoutError: | |
| app.logger.error(f"Timeout calling {model_key}") | |
| # Пытаемся достать model_id если он был определен | |
| try: | |
| role_manager = await get_role_manager() | |
| model_id = await role_manager.get_model_for_role(model_key, task_id=session_id) | |
| except: | |
| model_id = "unknown" | |
| return jsonify({"response": f"Модель {ROLE_NAMES.get(model_key, model_key.capitalize())} не ответила вовремя.", "modelInfo": {"key": model_key, "roleName": ROLE_NAMES.get(model_key, model_key.capitalize()), "modelId": extract_ui_model_name(model_id), "error": "timeout"}}), 504 | |
| except Exception as e: | |
| # ============================================================================ | |
| # EXTENDED ERROR LOGGING — SPEC_2026_04_02-1 | |
| # ============================================================================ | |
| logger.error( | |
| f"[SECRETARY_500] Error: {type(e).__name__}: {e}\n" | |
| f"Traceback:\n{{''.join(traceback.format_exc())}}", | |
| exc_info=True | |
| ) | |
| # ============================================================================ | |
| app.logger.error(f"Critical error calling Staff model {model_key}: {e}", exc_info=True) | |
| # Пытаемся достать хоть какой-то model_id для UI | |
| try: | |
| role_manager = await get_role_manager() | |
| model_id = await role_manager.get_model_for_role(model_key, task_id=session_id) | |
| m_name = extract_ui_model_name(model_id) | |
| except: | |
| m_name = "unknown" | |
| return jsonify({ | |
| "response": f"Критическая ошибка {ROLE_NAMES.get(model_key, model_key.capitalize())}: {e}", | |
| "modelInfo": { | |
| "key": model_key, | |
| "roleName": ROLE_NAMES.get(model_key, model_key.capitalize()), | |
| "modelId": m_name, | |
| "error": str(e) | |
| } | |
| }), 500 | |
| if not raw_response: | |
| secretary_reply = await call_secretary(user_message, "unspecified", source_role) | |
| return jsonify({"response": secretary_reply, "modelInfo": {"key": "secretary", "roleName": "Секретарь"}}) | |
| intercepted = gateway.intercept_response(str(raw_response), source_role) | |
| if intercepted['type'] == 'redirect': | |
| reason_code = intercepted.get('reason_code', 'unspecified') | |
| log_redirect({ | |
| "timestamp": datetime.now().isoformat(), | |
| "role": source_role, | |
| "reason_code": reason_code, | |
| "user_message": user_message | |
| }) | |
| return jsonify({"response": f"[REDIRECT] Модель {ROLE_NAMES.get(source_role, source_role)} запросила перенаправление. Код: {reason_code}.", "modelInfo": {"key": source_role, "roleName": ROLE_NAMES.get(source_role, source_role)}}), 200 | |
| elif intercepted['type'] == 'gemini': | |
| reason_code = intercepted.get('reason_code', 'unspecified') | |
| return jsonify({"response": f"[GEMINI] Модель {ROLE_NAMES.get(source_role, source_role)} запросила внешний разум. Код: {reason_code}.", "modelInfo": {"key": source_role, "roleName": ROLE_NAMES.get(source_role, source_role)}}), 200 | |
| elif intercepted['type'] == 'directive': | |
| app.logger.info(f"Directive received from {source_role}: {intercepted['directive']}") | |
| return jsonify({"response": "Директива принята.", "modelInfo": {"key": source_role, "roleName": ROLE_NAMES.get(source_role, source_role)}}) | |
| display_name = ROLE_NAMES.get(source_role, source_role.capitalize()) | |
| return jsonify({"response": intercepted['content'], "modelInfo": {"key": source_role, "roleName": display_name}}) | |
| except Exception as e: | |
| app.logger.error( | |
| f"[SECRETARY_FAIL] role={model_key} error={type(e).__name__}: {e}", | |
| exc_info=True | |
| ) | |
| return jsonify({"error": "Internal server error"}), 500 | |
| async def get_model_mapping(): | |
| try: | |
| role_manager = await get_role_manager() | |
| state = await role_manager.get_state() | |
| roles = state.get('roles', {}) | |
| mapping = {} | |
| for key, info in roles.items(): | |
| mapping[key] = {"key": key, "model_id": info.get('model_id', 'unknown'), "provider": info.get('provider', 'unknown')} | |
| return jsonify({"model_mapping": mapping}) | |
| except Exception as e: | |
| app.logger.error(f"Ошибка в get_model_mapping: {e}") | |
| return jsonify({"model_mapping": {}}) | |
| async def list_work_files(): | |
| try: | |
| files = [f.name for f in pathlib.Path('data').glob('*') if f.is_file()] | |
| return jsonify(files) | |
| except Exception: | |
| return jsonify([]) | |
| async def list_result_files(): | |
| try: | |
| files = [f.name for f in pathlib.Path('logs').glob('*') if f.is_file()] | |
| return jsonify(files) | |
| except Exception: | |
| return jsonify([]) | |
| async def gcb_get_queue(): | |
| gcb = await get_gcb() | |
| queue = await gcb.get_queue() | |
| return jsonify(queue) | |
| async def gcb_execute_command(cmd_id: str): | |
| gcb = await get_gcb() | |
| result = await gcb.execute_local(cmd_id) | |
| return jsonify(result) | |
| async def run_briefing(): | |
| data = await request.get_json() | |
| topic = data.get('topic', 'Текущий статус проекта') | |
| session_id = data.get('session_id') | |
| try: | |
| orchestrator = await get_orchestrator() | |
| summary = await orchestrator.run_briefing(topic, session_id=session_id) | |
| return jsonify({"reply": summary}) | |
| except Exception as e: | |
| app.logger.error(f"Ошибка в /api/briefing: {e}") | |
| return jsonify({"error": str(e)}), 500 | |
| async def doctor_health_check(): | |
| return jsonify({"reply": "doctor: Система в норме. Процедурный движок на техобслуживании.", "status": "online"}) | |
| async def list_doctor_sessions(): | |
| try: | |
| limit = int(request.args.get('limit', 10)) | |
| storage = get_chat_storage() | |
| sessions = storage.list_sessions("doctor", limit=limit) | |
| return jsonify({ | |
| "sessions": sessions, | |
| "total": len(sessions), | |
| "role": "doctor" | |
| }) | |
| except Exception as e: | |
| app.logger.error(f"[API] Failed to list doctor sessions: {e}", exc_info=True) | |
| return jsonify({"error": "Failed to list sessions"}), 500 | |
| async def get_doctor_session(session_id: str): | |
| try: | |
| storage = get_chat_storage() | |
| session = storage.get_session(session_id, "doctor") | |
| if not session: | |
| return jsonify({"error": "Session not found"}), 404 | |
| return jsonify(session) | |
| except Exception as e: | |
| app.logger.error(f"[API] Failed to get doctor session {session_id}: {e}", exc_info=True) | |
| return jsonify({"error": "Failed to get session"}), 500 | |
| async def get_info_content(info_type): | |
| project_path = get_current_project() | |
| if info_type == 'default': | |
| return await render_template('index.html') | |
| elif info_type == 'operativka': | |
| if project_path: | |
| log_path = os.path.join(project_path, 'logs', 'chief.log') | |
| if os.path.exists(log_path): | |
| with open(log_path, 'r', encoding='utf-8') as f: | |
| content = f.read() | |
| return f'<div style="padding: 15px;"><h3>📋 Оперативка Шефа</h3><pre style="font-size: 11px;">{content}</pre></div>' | |
| return '<div style="padding: 15px;">Лог оперативки не найден</div>' | |
| elif info_type == 'project_file': | |
| filename = request.args.get('file', '') | |
| if project_path and filename: | |
| file_path = os.path.join(project_path, filename) | |
| if os.path.exists(file_path) and os.path.isfile(file_path): | |
| try: | |
| with open(file_path, 'r', encoding='utf-8') as f: | |
| content = f.read() | |
| escaped = content.replace('<', '<').replace('>', '>') | |
| return f'<div style="padding: 15px;"><h3>📄 {filename}</h3><pre style="font-size: 11px; max-height: 400px; overflow: auto;">{escaped}</pre></div>' | |
| except: | |
| return f'<div style="padding: 15px;">Ошибка чтения файла {filename}</div>' | |
| return '<div style="padding: 15px;">Файл не указан или не найден</div>' | |
| elif info_type == 'doctor': | |
| composition_text = get_lab_composition() | |
| return f'<div style="padding: 15px;"><pre style="font-size: 12px; white-space: pre-wrap; font-family: inherit;">{composition_text}</pre></div>' | |
| return jsonify({'error': 'Unknown info type'}), 404 | |
| # ============================================================================ | |
| # DOCTOR CONTROL PLANE (SPEC_2026_04_09) | |
| # ============================================================================ | |
| register_doctor_ws(app) | |
| # ============================================================================ | |
| # ============================================================================ | |
| # GRACEFUL SHUTDOWN FIX — Windows + Uvicorn compatibility (SPEC_2026-04-11 №22) | |
| # ============================================================================ | |
| if __name__ == "__main__": | |
| import sys | |
| import logging | |
| from core.config_loader import load_gemini_sockets | |
| logger = logging.getLogger(__name__) | |
| # 1. Загрузка конфигурации и запуск агентов | |
| config = load_gemini_sockets() | |
| main_cfg = config.get("main_server", {}) | |
| host = main_cfg.get("host", "127.0.0.1") | |
| port = main_cfg.get("port", 5005) | |
| # from core.agent_orchestrator import launch_agents, terminate_agents | |
| # agents_ok = launch_agents() | |
| # if not agents_ok: | |
| # logger.warning("⚠️ Some agents failed to start — system may be partially functional") | |
| # 2. Запуск сервера | |
| try: | |
| import uvicorn | |
| uvicorn.run( | |
| "app2:app", | |
| host=host, | |
| port=port, | |
| log_level="info" | |
| ) | |
| except KeyboardInterrupt: | |
| logger.info("⌨️ Keyboard interrupt received — shutting down...") | |
| except Exception as e: | |
| logger.error(f"❌ Server error: {e}", exc_info=True) | |
| finally: | |
| # 3. ГАРАНТИРОВАННАЯ очистка | |
| # logger.info("🧹 Cleaning up agents...") | |
| # terminate_agents() | |
| # logger.info("✅ Cleanup complete") | |
| sys.exit(0) | |
| # ============================================================================ | |
| except Exception as critical_e: | |
| with open("app2_critical_error.log", "w", encoding="utf-8") as f: | |
| f.write(f"=== CRITICAL UNHANDLED ERROR IN APP2.PY ===\n") | |
| f.write(f"Timestamp: {datetime.now().isoformat()}\n") | |
| f.write(f"Error Type: {type(critical_e).__name__}\n") | |
| f.write(f"Message: {critical_e}\n") | |
| f.write(f"Traceback:\n{''.join(traceback.format_exc())}\n") | |
| print(f"CRITICAL ERROR WRITTEN TO app2_critical_error.log: {critical_e}") | |