feat(app): lifespan wires coordinator, tailer, stockfish + eval bridge

This commit is contained in:
ai-chess
2026-05-14 23:23:07 +03:00
parent 601fd64b16
commit 94de1cc1f9
+58 -4
View File
@@ -1,6 +1,8 @@
from __future__ import annotations from __future__ import annotations
import asyncio
import json import json
from contextlib import asynccontextmanager
from typing import Any from typing import Any
from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect from fastapi import FastAPI, HTTPException, Request, WebSocket, WebSocketDisconnect
@@ -8,10 +10,14 @@ from fastapi.responses import FileResponse, JSONResponse
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
import ai_chess.state as state_mod 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.mcp_server import TOOL_SCHEMAS, build_tools_for_side
from ai_chess.persistence import list_games, load_game from ai_chess.persistence import list_games, load_game
from ai_chess.settings import save_settings from ai_chess.settings import save_settings
from ai_chess.sides import Side 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" PROTOCOL_VERSION = "2025-06-18"
@@ -19,7 +25,55 @@ SERVER_NAME = "ai-chess"
def build_app(state: state_mod.AppState) -> FastAPI: 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 --------- # --------- REST ---------
@@ -65,10 +119,10 @@ def build_app(state: state_mod.AppState) -> FastAPI:
@app.post("/api/new-game") @app.post("/api/new-game")
async def new_game_post() -> dict[str, Any]: 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) 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] return state.game.get_state() # type: ignore[union-attr]
@app.get("/api/agent-binding/{side}") @app.get("/api/agent-binding/{side}")