from __future__ import annotations import asyncio import shutil from typing import Any class StockfishEngine: def __init__(self, path: str | None = None) -> None: self.path = path or shutil.which("stockfish") or "stockfish" self._proc: asyncio.subprocess.Process | None = None self._lock = asyncio.Lock() async def start(self) -> None: if self._proc is not None: return self._proc = await asyncio.create_subprocess_exec( self.path, stdin=asyncio.subprocess.PIPE, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.DEVNULL, ) await self._send("uci") await self._wait_for("uciok", timeout=5.0) await self._send("isready") await self._wait_for("readyok", timeout=5.0) async def stop(self) -> None: if self._proc is None: return try: await self._send("quit") await asyncio.wait_for(self._proc.wait(), timeout=2.0) except Exception: try: self._proc.kill() except ProcessLookupError: pass self._proc = None async def _send(self, line: str) -> None: assert self._proc and self._proc.stdin self._proc.stdin.write((line + "\n").encode()) await self._proc.stdin.drain() async def _wait_for(self, marker: str, *, timeout: float) -> str: assert self._proc and self._proc.stdout async def read() -> str: buf = [] while True: line = (await self._proc.stdout.readline()).decode().rstrip("\n") buf.append(line) if line.startswith(marker): return "\n".join(buf) if not line and self._proc.stdout.at_eof(): return "\n".join(buf) return await asyncio.wait_for(read(), timeout=timeout) async def analyze(self, fen: str, *, depth: int = 15) -> dict[str, Any]: async with self._lock: await self._send(f"position fen {fen}") await self._send(f"go depth {depth}") best_uci: str | None = None cp: int | None = None mate: int | None = None pv: list[str] = [] assert self._proc and self._proc.stdout while True: line = (await self._proc.stdout.readline()).decode().rstrip("\n") if not line: break if line.startswith("info"): tokens = line.split() # parse score if "score" in tokens: i = tokens.index("score") kind = tokens[i + 1] val = int(tokens[i + 2]) if kind == "cp": cp = val mate = None elif kind == "mate": mate = val cp = None if "pv" in tokens: j = tokens.index("pv") pv = tokens[j + 1 :] elif line.startswith("bestmove"): parts = line.split() if len(parts) >= 2 and parts[1] != "(none)": best_uci = parts[1] break return {"cp": cp, "mate": mate, "best_uci": best_uci, "pv": pv}