A.Tuin commited on
Commit ·
a5c876b
1
Parent(s): 61898fa
SPEC_2026_04_09
Browse filesFiles changed (3)
- app2.py+5-182
- doctor_ws_module.py+87-22
- server_crash_log.txt+51-51
10 unmodified lines111213141516171819202122154 unmodified lines177178179180181182444 unmodified lines62762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481510 unmodified linesimport asyncioimport loggingimport jsonfrom dotenv import load_dotenvfrom core.app_state import get_current_projectfrom core.lab_composition import get_lab_compositionfrom core.prompt_registry import PromptRegistryfrom core.model_management import ModelManagerfrom core.role_binding_manager import RoleBindingManager# ============================================================================# DIAGNOSTIC LOGGING — SPEC_2026_04_02-1154 unmodified linesdef ensure_project_model_pool():from core.shared_state import get_shared_statestate = get_shared_state()project_path = state.get("current_project_path")444 unmodified lines# ============================================================================# DOCTOR CONTROL PLANE: /ws/doctor (SPEC_2026_04_06)# ============================================================================import json, logging, asynciofrom pathlib import Pathfrom datetime import datetime# Импорты get_role_manager и get_model_manager удалены, так как они теперь локальны и асинхронныlogger = logging.getLogger(__name__)class DoctorEngine:def __init__(self, role_manager: RoleBindingManager, model_manager: ModelManager):self.role_manager = role_managerself.model_manager = model_manager@staticmethodasync def create():role_manager = await get_role_manager()model_manager = await get_model_manager()return DoctorEngine(role_manager, model_manager)async def system_status(self):pool = self.role_manager._get_available_models()return {"type": "tool_result","tool": "system_status","data": {"endpoints": ["/api/secretary", "/api/ceo/consult", "/ws/doctor"],"active_models": len(pool),"timestamp": datetime.now().isoformat()}}async def test_secretary(self, role="flick"):try:model_id = await self.role_manager.get_model_for_role(role, task_id=None)return {"type": "tool_result","tool": "test_secretary","data": {"role": role,"model_selected": model_id,"pool_size": len(self.role_manager._get_available_models()),"status": "OK"}}except Exception as e:return {"type": "tool_result","tool": "test_secretary","data": {"role": role,"error": f"{type(e).__name__}: {e}","status": "FAIL"}}async def models_pool_check(self):pool = self.role_manager._get_available_models()return {"type": "tool_result","tool": "models_pool_check","data": {"pool_size": len(pool),"pool_sample": pool[:5],"is_sufficient": len(pool) >= 2}}async def process(self, message: str):msg = (message or "").strip().lower()if not msg:return {"error": "Empty message"}if msg == "ping":return {"response": "pong"}if msg == "status":return await self.system_status()if msg.startswith("test secretary"):parts = msg.split()role = parts[2] if len(parts) > 2 else "flick"return await self.test_secretary(role)if msg in ["pool check", "models_pool_check"]:return await self.models_pool_check()# --- безопасный доступ к call_gemini ---call_gemini_fn = globals().get("call_gemini")if not call_gemini_fn:return {"error": "call_gemini not available"}try:if asyncio.iscoroutinefunction(call_gemini_fn):result = await call_gemini_fn(message)else:loop = asyncio.get_event_loop()result = await loop.run_in_executor(None, call_gemini_fn, message)return {"type": "gemini_response", "response": result}except Exception as e:logger.error(f"[DOCTOR] Gemini call failed: {e}", exc_info=True)return {"error": f"Gemini error: {e}"}@app.websocket("/ws/doctor")async def doctor_ws(websocket):logger.info("[DOCTOR_WS] Connection attempt...")await websocket.accept()logger.info("[DOCTOR_WS] Connection accepted.")# REM [2026-04-08] Temporarily disabled to diagnose 500 error# try:# logger.info("[DOCTOR_WS] Attempting to send greetings...")# await send_role_greetings_to_client(websocket)# logger.info("[DOCTOR_WS] Greetings sent.")# except Exception as e:# logger.error(f"[DOCTOR_WS] Greetings failed: {e}", exc_info=True)# # raise e # Don't kill WS because of greetingssession_id = f"session_{datetime.now().strftime('%Y%m%d_%H%M%S')}"chat_file = Path("AIColab/chats/doctor") / f"{session_id}.json"chat_data = {"session_id": session_id, "messages": []}# REM [2026-04-08] Lazy engine creation to isolate 500 errorengine = Nonetry:engine = await DoctorEngine.create()logger.info("[DOCTOR_WS] DoctorEngine created.")except Exception as e:logger.error(f"[DOCTOR_WS] DoctorEngine creation failed: {e}", exc_info=True)try:while True:try:data = await websocket.receive_json()except Exception:await websocket.send_json({"error": "Invalid JSON"})continueuser_message = data.get("message", "")if not user_message:await websocket.send_json({"error": "Empty message"})continuelogger.info(f"[DOCTOR_WS] received: {user_message[:100]}")try:response = await engine.process(user_message)except Exception as e:logger.error(f"[DOCTOR_WS] Processing error: {e}", exc_info=True)response = {"error": str(e)}logger.info(f"[DOCTOR_WS] response: {str(response)[:200]}")await websocket.send_json(response)chat_data["messages"].append({"role": "user","text": user_message,"timestamp": datetime.now().isoformat()})chat_data["messages"].append({"role": "doctor","text": json.dumps(response, ensure_ascii=False),"timestamp": datetime.now().isoformat()})with open(chat_file, 'w', encoding='utf-8') as f:json.dump(chat_data, f, indent=2, ensure_ascii=False)except Exception as e:logger.error(f"[DOCTOR_WS] Connection error: {e}", exc_info=True)finally:try:await websocket.close()except Exception:pass# ============================================================================if __name__ == '__main__':10 unmodified lines1112131415161718192021222324154 unmodified lines179180181182183184185444 unmodified lines63063163263363463563663763810 unmodified linesimport asyncioimport loggingimport jsonfrom pathlib import Pathfrom dotenv import load_dotenvfrom core.app_state import get_current_projectfrom core.lab_composition import get_lab_compositionfrom core.prompt_registry import PromptRegistryfrom core.model_management import ModelManagerfrom core.role_binding_manager import RoleBindingManagerfrom doctor_ws_module import register_doctor_ws# ============================================================================# DIAGNOSTIC LOGGING — SPEC_2026_04_02-1154 unmodified linesdef ensure_project_model_pool():from pathlib import Pathfrom core.shared_state import get_shared_statestate = get_shared_state()project_path = state.get("current_project_path")444 unmodified lines# ============================================================================# DOCTOR CONTROL PLANE (SPEC_2026_04_09)# ============================================================================register_doctor_ws(app)# ============================================================================if __name__ == '__main__':
12345678910111213141516171819202122232425262728293031323334353637383940414243444546from quart import websocketfrom pathlib import Pathfrom datetime import datetimeimport jsonimport loggingimport asynciofrom core.role_binding_manager import RoleBindingManager, get_role_managerfrom core.model_management import ModelManager, get_model_managerlogger = logging.getLogger(__name__)class DoctorEngine:def __init__(self, role_manager: RoleBindingManager, model_manager: ModelManager):self.role_manager = role_managerself.model_manager = model_manager@staticmethodasync def create():role_manager = await get_role_manager()model_manager = await get_model_manager()return DoctorEngine(role_manager, model_manager)async def process(self, message: str):# Реализация процессаif message == "ping": return {"response": "pong"}return {"error": "Command not recognized"}async def register_doctor_ws(app):@app.websocket("/ws/doctor")async def doctor_ws(websocket):logger.info("[DOCTOR_WS] Connection attempt...")await websocket.accept()session_id = f"session_{datetime.now().strftime('%Y%m%d_%H%M%S')}"chat_file = Path("AIColab/chats/doctor") / f"{session_id}.json"engine = await DoctorEngine.create()try:while True:data = await websocket.receive_json()response = await engine.process(data.get("message", ""))await websocket.send_json(response)except Exception as e:logger.error(f"[DOCTOR_WS] Error: {e}")finally:await websocket.close()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111from pathlib import Pathfrom datetime import datetimeimport jsonimport loggingimport asyncioimport time# ZERO EXECUTION: импорты core перенесены внутрь обработчика или методов# чтобы избежать гонки при старте.logger = logging.getLogger(__name__)START_TIME = time.time()INIT_TIMEOUT = 10def _is_system_ready(app):"""Проверяет готовность менеджеров в объекте app."""if time.time() - START_TIME > INIT_TIMEOUT:return "FAILED"# Проверяем наличие проинициализированных менеджеров в appif not (hasattr(app, "role_binding_manager") and app.role_binding_manager is not Noneand hasattr(app, "model_manager") and app.model_manager is not None):return Falsereturn Trueclass DoctorEngine:_instance = Nonedef __init__(self, role_manager, model_manager):self.role_manager = role_managerself.model_manager = model_manager@classmethodasync def get_instance(cls, app):"""Lazy singleton creation with dependency injection from app."""if cls._instance is None:# В этот момент мы уверены, что менеджеры в app есть (проверено в _is_system_ready)cls._instance = cls(app.role_binding_manager, app.model_manager)return cls._instanceasync def process(self, message: str):# Реализация процесса (заглушка для совместимости со SPEC)msg = (message or "").strip().lower()if msg == "ping": return {"response": "pong"}return {"error": f"Command '{msg}' not recognized by DoctorEngine"}def register_doctor_ws(app):"""Synchronous registration of the Doctor WebSocket endpoint.Includes duplicate registration guard."""if getattr(app, "_doctor_ws_registered", False):return@app.websocket("/ws/doctor")async def doctor_ws():# Важно: Quart WebSocket хендлер не принимает аргумент websocket,# он использует глобальный объект websocket из quart.from quart import websocket as wslogger.info("[DOCTOR_WS] Connection attempt...")# Guard: System Readystatus = _is_system_ready(app)if status is False:await ws.accept()await ws.send_json({"type": "system","text": "⚠️ Система ещё инициализируется. Повторите через 2-3 секунды."})await ws.close(code=1013)returnif status == "FAILED":await ws.accept()await ws.send_json({"type": "error","text": "❌ System failed to initialize"})await ws.close(code=1013)returnawait ws.accept()logger.info("[DOCTOR_WS] Connection accepted.")session_id = f"session_{datetime.now().strftime('%Y%m%d_%H%M%S')}"# chat_file = Path("AIColab/chats/doctor") / f"{session_id}.json" # Пока не используем для минимизацииengine = await DoctorEngine.get_instance(app)try:while True:data = await ws.receive_json()user_message = data.get("message", "")response = await engine.process(user_message)await ws.send_json(response)except Exception as e:logger.error(f"[DOCTOR_WS] Connection error: {e}")finally:try:await ws.close()except:passapp._doctor_ws_registered = Truelogger.info("[WS] /ws/doctor registered")
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556INFO: Started server process [1704]INFO: Waiting for application startup.INFO: Application startup complete.INFO: Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)=== CRITICAL APP2.PY STARTUP TRY BLOCK ===DEBUG_CONFIG_PATH: D:\Gemini\AIColab\config\models_config.jsonINFO: 127.0.0.1:51048 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51048 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51048 - "GET / HTTP/1.1" 200 OKINFO: 127.0.0.1:51048 - "GET /A.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:51049 - "GET /B.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:51049 - "GET /C.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:51048 - "GET /D.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:51048 - "GET /api/project/current HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:51049 - "GET /api/model_mapping HTTP/1.1" 200 OKINFO: 127.0.0.1:51049 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51049 - "GET /favicon.ico HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:51049 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51049 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51049 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51052 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51052 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51055 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51055 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51049 - "POST /api/secretary HTTP/1.1" 200 OKINFO: 127.0.0.1:51049 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51057 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51057 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51059 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51059 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51059 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51059 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51061 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51052 - "POST /api/secretary HTTP/1.1" 200 OKD:\Gemini\AIColab\venv_cuda\Lib\site-packages\torch\cuda\__init__.py:65: FutureWarning: The pynvml package is deprecated. Please install nvidia-ml-py instead. If you did not install pynvml directly, please report this to the maintainers of the package that installed pynvml for you.import pynvml # type: ignore[import]llama_context: n_ctx_per_seq (2048) < n_ctx_train (4096) -- the full capacity of the model will not be utilizedINFO: 127.0.0.1:51061 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51061 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51062 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51062 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51062 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51062 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51063 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51063 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51063 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51064 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51064 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51065 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51065 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51066 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51067 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51067 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:51067 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: Shutting downINFO: Waiting for connections to close. (CTRL+C to force quit)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556INFO: Started server process [6892]INFO: Waiting for application startup.[2026-04-09 09:38:22,839] INFO in app2: ���������� ������� �������: d:\gemini\aicolab\projects\Bestihi.ru[2026-04-09 09:38:22,839] INFO in app2: Project pool already has 8 models, no sync needed[2026-04-09 09:38:22,839] INFO in prompt_registry: PromptRegistry initialized. Project path: D:\gemini\AIColab\projects\Bestihi.ru. Repo root: D:\Gemini[2026-04-09 09:38:22,839] INFO in app2: ������ ����� � ������� �������������INFO: Application startup complete.INFO: Uvicorn running on http://127.0.0.1:5000 (Press CTRL+C to quit)=== CRITICAL APP2.PY STARTUP TRY BLOCK ===INFO: 127.0.0.1:50054 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50054 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50049 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50049 - "GET / HTTP/1.1" 200 OKINFO: 127.0.0.1:50049 - "GET /A.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50057 - "GET /B.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50058 - "GET /C.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50049 - "GET /chat.js HTTP/1.1" 200 OKINFO: 127.0.0.1:50059 - "GET /D.png HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50059 - "GET /api/project/current HTTP/1.1" 404 Not Found[2026-04-09 09:38:35,702] INFO in model_management: ModelManager ������. ������� ������: D:\Gemini\AIColab\config\models_config.json[2026-04-09 09:38:35,704] INFO in model_management: �������� ������ � 10 �������� �� D:\Gemini\AIColab\config\models_config.json[2026-04-09 09:38:35,705] INFO in model_management: ModelManager ���������������[2026-04-09 09:38:35,706] INFO in prompt_registry: PromptRegistry initialized. Project path: D:\gemini\AIColab\projects\Bestihi.ru. Repo root: D:\Gemini[2026-04-09 09:38:35,706] INFO in role_binding_manager: RoleBindingManager initialized. Project: D:\gemini\AIColab\projects\Bestihi.ruINFO: 127.0.0.1:50049 - "GET /api/model_mapping HTTP/1.1" 200 OKINFO: 127.0.0.1:50059 - "GET /favicon.ico HTTP/1.1" 404 Not FoundINFO: 127.0.0.1:50058 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50060 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50060 - "GET /api/gcb/queue HTTP/1.1" 200 OK[2026-04-09 09:38:46,401] INFO in model_management: �������� ������ � 10 �������� �� D:\Gemini\AIColab\config\models_config.json[2026-04-09 09:38:46,401] INFO in role_binding_manager: [BINDING] Memory MISS: flick -> arcee-ai/trinity-large-preview:free[2026-04-09 09:38:46,401] INFO in app2: [POOL_EFFECTIVE] role=flick first=arcee-ai/trinity-large-preview:free second=arcee-ai/trinity-large-preview:free[2026-04-09 09:38:46,684] INFO in prompt_registry: PromptRegistry initialized. Project path: D:\gemini\AIColab\projects\Bestihi.ru. Repo root: D:\Gemini[2026-04-09 09:38:46,684] INFO in role_binding_manager: RoleBindingManager initialized. Project: D:\gemini\AIColab\projects\Bestihi.ruINFO: 127.0.0.1:50067 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50067 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50067 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50067 - "GET /api/gcb/queue HTTP/1.1" 200 OK[2026-04-09 09:39:08,640] INFO in model_management: �������� ������ � 10 �������� �� D:\Gemini\AIColab\config\models_config.jsonINFO: 127.0.0.1:50068 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50068 - "GET /api/gcb/queue HTTP/1.1" 200 OK[2026-04-09 09:39:18,275] INFO in openrouter_adapter: \u2705 ����� �� ��������������� ������ arcee-ai/trinity-large-preview:free ��� arcee-ai/trinity-large-preview:free �������.INFO: 127.0.0.1:50060 - "POST /api/secretary HTTP/1.1" 200 OK[2026-04-09 09:39:18,284] INFO in role_binding_manager: [BINDING] Memory MISS: doctor -> liquid/lfm-2.5-1.2b-instruct:free[2026-04-09 09:39:18,285] INFO in app2: [POOL_EFFECTIVE] role=doctor first=liquid/lfm-2.5-1.2b-instruct:free second=liquid/lfm-2.5-1.2b-instruct:free[2026-04-09 09:39:18,288] INFO in prompt_registry: PromptRegistry initialized. Project path: D:\gemini\AIColab\projects\Bestihi.ru. Repo root: D:\Gemini[2026-04-09 09:39:18,288] INFO in role_binding_manager: RoleBindingManager initialized. Project: D:\gemini\AIColab\projects\Bestihi.ru[2026-04-09 09:39:19,214] INFO in openrouter_adapter: \u2705 ����� �� ��������������� ������ liquid/lfm-2.5-1.2b-instruct:free ��� liquid/lfm-2.5-1.2b-instruct:free �������.INFO: 127.0.0.1:50067 - "POST /api/secretary HTTP/1.1" 200 OKINFO: 127.0.0.1:50067 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50067 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: 127.0.0.1:50070 - "GET /api/gcb/queue HTTP/1.1" 200 OKINFO: Shutting downINFO: Waiting for application shutdown.INFO: Application shutdown complete.INFO: Finished server process [6892]
app2.py+5-182
doctor_ws_module.py+87-22
server_crash_log.txt+51-51