diff --git a/src/ai_chess/app.py b/src/ai_chess/app.py index 2c9a851..003aa98 100644 --- a/src/ai_chess/app.py +++ b/src/ai_chess/app.py @@ -1,6 +1,8 @@ from __future__ import annotations +import asyncio import json +from contextlib import asynccontextmanager from typing import Any from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect @@ -8,10 +10,14 @@ from fastapi.responses import FileResponse, JSONResponse from fastapi.staticfiles import StaticFiles import ai_chess.state as state_mod +from ai_chess.coordinator import Coordinator, start_new_game from ai_chess.mcp_server import TOOL_SCHEMAS, build_tools_for_side from ai_chess.persistence import list_games, load_game from ai_chess.settings import save_settings from ai_chess.sides import Side +from ai_chess.stockfish_engine import StockfishEngine +from ai_chess.tmux import TmuxSession +from ai_chess.tmux_tailer import TmuxTailer PROTOCOL_VERSION = "2025-06-18" @@ -19,7 +25,55 @@ SERVER_NAME = "ai-chess" def build_app(state: state_mod.AppState) -> FastAPI: - app = FastAPI(title="ai-chess") + @asynccontextmanager + async def lifespan(app: FastAPI): + session = TmuxSession("chess") + coord = Coordinator(state, tmux=session, pane_for={"white": 0, "black": 1}) + tailer = TmuxTailer(state, session, pane_for={"white": 0, "black": 1}) + eng = StockfishEngine() + state.runtime = {"session": session, "coord": coord, "tailer": tailer, "engine": eng} # type: ignore[attr-defined] + + try: + await eng.start() + except Exception: + pass + try: + await coord.start() + except Exception: + pass + try: + if await session.exists(): + tailer.start() + except Exception: + pass + + async def eval_bridge(): + q = state.events.subscribe() + try: + while True: + ev = await q.get() + if ev.get("type") == "move" and ev.get("fen"): + try: + res = await eng.analyze(ev["fen"], depth=state.settings.stockfish_depth) + await state.events.publish({"type": "eval", **res, "fen": ev["fen"]}) + except Exception: + pass + finally: + state.events.unsubscribe(q) + bridge_task = asyncio.create_task(eval_bridge()) + + yield + + bridge_task.cancel() + try: + await bridge_task + except (asyncio.CancelledError, Exception): + pass + await coord.stop() + await tailer.stop() + await eng.stop() + + app = FastAPI(title="ai-chess", lifespan=lifespan) # --------- REST --------- @@ -65,10 +119,10 @@ def build_app(state: state_mod.AppState) -> FastAPI: @app.post("/api/new-game") async def new_game_post() -> dict[str, Any]: - # Coordinator wiring happens in Task 16's lifespan. Deferred import to avoid - # ImportError at module load time (coordinator doesn't exist until Task 15). - from ai_chess.coordinator import start_new_game # noqa: PLC0415 await start_new_game(state) + runtime = getattr(state, "runtime", None) + if runtime and runtime.get("coord"): + await runtime["coord"].dispatch_first_prompt() return state.game.get_state() # type: ignore[union-attr] @app.get("/api/agent-binding/{side}")