from __future__ import annotations import asyncio import json from contextlib import asynccontextmanager from typing import Any from fastapi import FastAPI, HTTPException, Request, Response, WebSocket, WebSocketDisconnect 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" SERVER_NAME = "ai-chess" def build_app(state: state_mod.AppState) -> FastAPI: @asynccontextmanager async def lifespan(app: FastAPI): session = TmuxSession("chess") # Tear down any leftover tmux session from a prior run. Agents that # outlive the backend will desync with state.game (which lives only # in-process) and end up calling MCP move on a game the server no # longer knows about. Cleanest fix: kill them at startup so start.sh # spawns fresh ones aligned with the empty server state. try: if await session.exists(): print("[lifespan] killing stale tmux session 'chess'", flush=True) await session.kill() except Exception as e: print(f"[lifespan] startup session.kill failed: {e}", flush=True) 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() print("[lifespan] stockfish started", flush=True) except Exception as e: print(f"[lifespan] stockfish.start failed: {e}", flush=True) try: await coord.start() print("[lifespan] coordinator started", flush=True) except Exception as e: print(f"[lifespan] coordinator.start failed: {e}", flush=True) # TmuxTailer is intentionally NOT started — the browser UI no longer # mirrors the agent panes, so the polling would be wasted work and # also flood every subscriber queue with large term_chunk events. async def _analyze_and_publish(fen: str) -> bool: """Run stockfish analyze; revive a dead engine once if needed.""" for attempt in (1, 2): try: if not eng.is_alive(): await eng.start() res = await eng.analyze( fen, depth=state.settings.stockfish_depth, ) state.eval_cache[fen] = {**res, "fen": fen} await state.events.publish({"type": "eval", **res, "fen": fen}) return True except Exception as e: print(f"[eval_bridge] analyze attempt {attempt} failed: {e}", flush=True) # Drop the dead handle so the next start() spawns fresh. eng._proc = None # type: ignore[attr-defined] return False async def _backfill_missing_evals() -> None: """After (re)start, fill evals for any history positions that still don't have one. Replays history via python-chess to derive each FEN deterministically (same producer the move events use).""" import chess as _chess game = state.game if game is None: return b = _chess.Board() for h in game.history: if not h.uci or h.uci in ("resign", "agreement"): continue try: b.push(_chess.Move.from_uci(h.uci)) except Exception: continue fen = b.fen() if fen in state.eval_cache: continue ok = await _analyze_and_publish(fen) if not ok: return # engine refuses to come up; bail async def eval_bridge(): q = state.events.subscribe() # If something was missed before we subscribed (e.g. after a # silent stockfish crash), fill the gap once on startup. asyncio.create_task(_backfill_missing_evals()) try: while True: ev = await q.get() if ev.get("type") == "new_game": state.eval_cache.clear() continue if ev.get("type") != "move" or not ev.get("fen"): continue await _analyze_and_publish(ev["fen"]) 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() # Tear down the tmux session so claude/codex die with us. Without # this they keep running with stale conversation context that no # longer matches the next backend's state. try: await session.kill() print("[lifespan] tmux session 'chess' killed on shutdown", flush=True) except Exception as e: print(f"[lifespan] shutdown session.kill failed: {e}", flush=True) app = FastAPI(title="ai-chess", lifespan=lifespan) # --------- REST --------- @app.get("/api/state") async def get_state() -> dict[str, Any]: evals = list(state.eval_cache.values()) if state.game is None: return {"game": None, "settings": state.settings.model_dump(), "bindings": {s.value: b.to_dict() for s, b in state.bindings.items()}, "evals": evals} return { "game": state.game.get_state(), "settings": state.settings.model_dump(), "bindings": {s.value: b.to_dict() for s, b in state.bindings.items()}, "evals": evals, } def _require_no_active_game() -> None: if state.game is not None and not state.game.is_game_over(): raise HTTPException(409, "current game is in progress; abort it first") @app.get("/api/games") async def games_list() -> list[dict[str, Any]]: _require_no_active_game() return list_games(state_mod.GAMES_DIR) @app.get("/api/games/{game_id}") async def game_get(game_id: str) -> dict[str, Any]: _require_no_active_game() try: return load_game(state_mod.GAMES_DIR, game_id) except FileNotFoundError: raise HTTPException(404, "game not found") @app.get("/api/games/{game_id}/pgn") async def game_pgn(game_id: str) -> Any: _require_no_active_game() try: data = load_game(state_mod.GAMES_DIR, game_id) except FileNotFoundError: raise HTTPException(404, "game not found") return JSONResponse({"pgn": data["pgn"]}) @app.get("/api/settings") async def settings_get() -> dict[str, Any]: return state.settings.model_dump() @app.post("/api/settings") async def settings_post(patch: dict[str, Any]) -> dict[str, Any]: state.settings = save_settings(state_mod.CONFIG_DIR / "settings.json", state.settings, patch) await state.events.publish({"type": "settings", "settings": state.settings.model_dump()}) return state.settings.model_dump() @app.post("/api/new-game") async def new_game_post(body: dict[str, Any] | None = None) -> dict[str, Any]: # One game at a time — refuse if the current game hasn't finished. if state.game is not None and not state.game.is_game_over(): raise HTTPException( status_code=409, detail="current game is in progress; abort it first", ) overrides = (body or {}).get("overrides") if isinstance(body, dict) else None await start_new_game(state, overrides=overrides) return state.game.get_state() # type: ignore[union-attr] @app.post("/api/human-move") async def human_move(body: dict[str, Any]) -> dict[str, Any]: """The human side submits a move from the browser. Accepts UCI/SAN plus an optional comment. Only succeeds if the side-to-move is bound to agent='human'.""" if state.game is None or state.game.is_game_over(): return {"ok": False, "reason": "no_active_game"} side_to_move = state.game.side_to_move binding = state.bindings.get(side_to_move) if not binding or binding.agent != "human": return {"ok": False, "reason": "not_your_turn_or_not_human"} move_str = str(body.get("move") or "").strip() if not move_str: return {"ok": False, "reason": "missing_move"} comment = body.get("comment") if comment is not None: comment = str(comment) from ai_chess.mcp_server import build_tools_for_side tools = build_tools_for_side(side_to_move, state) return await tools["move"]({"move": move_str, "comment": comment}) @app.post("/api/abort-game") async def abort_game() -> dict[str, Any]: if state.game is None: return {"ok": False, "reason": "no_active_game"} if state.game.is_game_over(): return {"ok": False, "reason": "already_over", "result": state.game.result, "termination": state.game.termination} out = state.game.abort() if out.get("ok"): await state.events.publish({ "type": "game_over", "result": state.game.result, "termination": state.game.termination, }) return out @app.get("/api/options") async def options() -> dict[str, Any]: from ai_chess.coordinator import AGENTS, MODEL_OPTIONS from ai_chess.prompts import list_prompt_presets, DEFAULT_PROMPT return { "agents": AGENTS, # only AI agent ids — used for AI-vs-AI screen "all_agents": AGENTS + ["human"], "models": MODEL_OPTIONS, "prompts": list_prompt_presets(), "defaults": {"prompt": DEFAULT_PROMPT}, } @app.get("/api/stats") async def stats() -> dict[str, Any]: from collections import defaultdict games = list_games(state_mod.GAMES_DIR) # Aggregate per (agent, model) and per (agent, model, prompt) per_player: dict[tuple, dict[str, int]] = defaultdict( lambda: {"games": 0, "wins": 0, "losses": 0, "draws": 0, "as_white": 0, "as_black": 0} ) per_prompt: dict[str, dict[str, int]] = defaultdict( lambda: {"games": 0, "wins": 0, "losses": 0, "draws": 0} ) for g in games: result = g.get("result") ag = g.get("agents") or {} w = ag.get("white") or {} b = ag.get("black") or {} wkey = (w.get("agent", "?"), w.get("model", "?")) bkey = (b.get("agent", "?"), b.get("model", "?")) per_player[wkey]["games"] += 1 per_player[wkey]["as_white"] += 1 per_player[bkey]["games"] += 1 per_player[bkey]["as_black"] += 1 wprompt = w.get("prompt") bprompt = b.get("prompt") if result == "1-0": per_player[wkey]["wins"] += 1 per_player[bkey]["losses"] += 1 if wprompt: per_prompt[wprompt]["wins"] += 1 if bprompt: per_prompt[bprompt]["losses"] += 1 elif result == "0-1": per_player[wkey]["losses"] += 1 per_player[bkey]["wins"] += 1 if wprompt: per_prompt[wprompt]["losses"] += 1 if bprompt: per_prompt[bprompt]["wins"] += 1 elif result == "1/2-1/2": per_player[wkey]["draws"] += 1 per_player[bkey]["draws"] += 1 if wprompt: per_prompt[wprompt]["draws"] += 1 if bprompt: per_prompt[bprompt]["draws"] += 1 if wprompt: per_prompt[wprompt]["games"] += 1 if bprompt: per_prompt[bprompt]["games"] += 1 def _row(key, stats_): agent, model = key score = stats_["wins"] + 0.5 * stats_["draws"] return {"agent": agent, "model": model, **stats_, "score": score} players = sorted( (_row(k, v) for k, v in per_player.items()), key=lambda r: (-r["score"], -r["wins"], r["losses"]), ) prompts_rows = sorted( ({"prompt": k, **v, "score": v["wins"] + 0.5 * v["draws"]} for k, v in per_prompt.items()), key=lambda r: (-r["score"], -r["wins"]), ) return { "total_games": len(games), "players": players, "prompts": prompts_rows, } @app.post("/api/dispatch-first") async def dispatch_first() -> dict[str, Any]: runtime = getattr(state, "runtime", None) if not runtime or not runtime.get("coord"): return {"ok": False, "reason": "coordinator_not_running"} try: await runtime["coord"].dispatch_first_prompt() return {"ok": True} except Exception as e: return {"ok": False, "reason": "dispatch_failed", "detail": str(e)} @app.get("/api/agent-binding/{side}") async def agent_binding(side: str) -> dict[str, Any]: s = Side.from_str(side) b = state.bindings.get(s) if not b: raise HTTPException(404, "not bound yet") return b.to_dict() # --------- WebSocket --------- @app.websocket("/ws") async def ws_endpoint(ws: WebSocket) -> None: await ws.accept() q = state.events.subscribe() snapshot = await get_state() await ws.send_text(json.dumps({"type": "snapshot", **snapshot}, default=str)) try: while True: ev = await q.get() await ws.send_text(json.dumps(ev, default=str)) except WebSocketDisconnect: pass finally: state.events.unsubscribe(q) # --------- MCP JSON-RPC --------- async def handle_mcp(side: Side, body: dict[str, Any]) -> dict[str, Any]: rid = body.get("id") method = body.get("method") params = body.get("params") or {} def ok(result: Any) -> dict[str, Any]: return {"jsonrpc": "2.0", "id": rid, "result": result} def err(code: int, message: str) -> dict[str, Any]: return {"jsonrpc": "2.0", "id": rid, "error": {"code": code, "message": message}} if method == "initialize": return ok({ "protocolVersion": PROTOCOL_VERSION, "capabilities": {"tools": {"listChanged": False}}, "serverInfo": {"name": f"{SERVER_NAME}:{side.value}", "version": "0.1.0"}, }) if method == "notifications/initialized": return {} # no response for notifications if method == "tools/list": tools = [] for name, schema in TOOL_SCHEMAS.items(): tools.append({ "name": name, "description": schema["description"], "inputSchema": schema["inputSchema"], }) return ok({"tools": tools}) if method == "tools/call": name = params.get("name") arguments = params.get("arguments") or {} tools = build_tools_for_side(side, state) if name not in tools: return err(-32601, f"unknown tool: {name}") try: result = await tools[name](arguments) except Exception as e: # tool errors -> isError result return ok({ "content": [{"type": "text", "text": json.dumps( {"ok": False, "reason": "exception", "detail": str(e)}, ensure_ascii=False)}], "isError": True, }) return ok({ "content": [{"type": "text", "text": json.dumps(result, ensure_ascii=False)}], "isError": not result.get("ok", True), }) return err(-32601, f"method not found: {method}") @app.post("/mcp/{side}") async def mcp_post(side: str, request: Request) -> Any: try: s = Side.from_str(side) except ValueError: raise HTTPException(404, "unknown side") body = await request.json() # JSON-RPC notification (no "id" field) → MUST get HTTP 202 with no body # per streamable-HTTP MCP transport spec; otherwise rmcp (codex's client) # treats the 200+body as an unexpected response and closes the channel. if isinstance(body, list): responses = [] for item in body: if not isinstance(item, dict): continue if "id" not in item: await handle_mcp(s, item) continue responses.append(await handle_mcp(s, item)) if not responses: return Response(status_code=202) return responses if "id" not in body: await handle_mcp(s, body) return Response(status_code=202) return await handle_mcp(s, body) # --------- static UI --------- if state_mod.PUBLIC_DIR.exists(): app.mount("/static", StaticFiles(directory=state_mod.PUBLIC_DIR), name="static") @app.get("/") async def menu_page() -> FileResponse: return FileResponse(state_mod.PUBLIC_DIR / "menu.html") @app.get("/ai-vs-ai") async def ai_vs_ai_page() -> FileResponse: return FileResponse(state_mod.PUBLIC_DIR / "index.html") @app.get("/play") async def play_page() -> FileResponse: # Same UI as /ai-vs-ai — app.js detects the human binding and # enables board interactivity for that side. return FileResponse(state_mod.PUBLIC_DIR / "index.html") @app.get("/games") async def games_page() -> FileResponse: return FileResponse(state_mod.PUBLIC_DIR / "games.html") return app