feat(coordinator): start game, dispatch prompts, watchdog

This commit is contained in:
ai-chess
2026-05-14 23:21:20 +03:00
parent e20c26a055
commit 601fd64b16
2 changed files with 281 additions and 0 deletions
+205
View File
@@ -0,0 +1,205 @@
from __future__ import annotations
import asyncio
import random
from typing import Any
from ulid import ULID
from ai_chess.chess_game import ChessGame
from ai_chess.persistence import save_game
from ai_chess.prompts import (
WATCHDOG_NUDGE,
build_first_prompt,
build_system_prompt,
build_turn_prompt,
)
from ai_chess.sides import Side
from ai_chess.state import AppState, AgentBinding, GAMES_DIR
OPPONENT_LABEL = {"claude": ("claude", "opus-4.7"), "codex": ("codex", "gpt-5.5")}
def assign_sides() -> dict[Side, str]:
agents = ["claude", "codex"]
random.shuffle(agents)
return {Side.WHITE: agents[0], Side.BLACK: agents[1]}
def make_bindings(side_to_agent: dict[Side, str]) -> dict[Side, AgentBinding]:
out: dict[Side, AgentBinding] = {}
for side, agent in side_to_agent.items():
if agent == "claude":
out[side] = AgentBinding(side=side, agent="claude", model="opus", effort="max")
elif agent == "codex":
out[side] = AgentBinding(side=side, agent="codex", model="gpt-5.5",
effort="xhigh", extra={"service_tier": "fast"})
else:
raise ValueError(agent)
return out
async def start_new_game(state: AppState) -> ChessGame:
side_to_agent = assign_sides()
state.bindings = make_bindings(side_to_agent)
state.first_move_sent = {Side.WHITE: False, Side.BLACK: False}
state.nudge_count = {Side.WHITE: 0, Side.BLACK: 0}
gid = str(ULID())
state.game = ChessGame(
game_id=gid,
agents={s.value: b.to_dict() for s, b in state.bindings.items()},
)
await state.events.publish({"type": "new_game", "game": state.game.get_state()})
return state.game
class Coordinator:
def __init__(self, state: AppState, tmux: Any, pane_for: dict[str, int]) -> None:
self.state = state
self.tmux = tmux
self.pane_for = pane_for # {"white": 0, "black": 1}
self._sub_task: asyncio.Task | None = None
self._watchdog_task: asyncio.Task | None = None
self._waiting_side: Side | None = None
self._waiting_started_at: float = 0.0
# ---------- prompt helpers ----------
def _opponent(self, side: Side) -> tuple[str, str]:
opp_binding = self.state.bindings[side.opposite()]
return opp_binding.agent, opp_binding.model
def _pane(self, side: Side) -> int:
return self.pane_for[side.value]
async def _submit(self, side: Side, text: str) -> None:
await self.tmux.submit(pane=self._pane(side), text=text)
async def _send_first(self, side: Side, *, opponent_san: str | None,
opponent_comment: str | None) -> None:
if self.state.first_move_sent[side]:
return
opp_name, opp_model = self._opponent(side)
sys = build_system_prompt(side=side, opponent_name=opp_name, opponent_model=opp_model)
first = build_first_prompt(
side=side,
fen=self.state.game.board.fen(),
ascii_board=str(self.state.game.board),
opponent_san=opponent_san,
opponent_comment=opponent_comment,
)
await self._submit(side, sys + "\n\n" + first)
self.state.first_move_sent[side] = True
self._mark_waiting(side)
async def _send_turn(self, side: Side, *, opponent_san: str,
opponent_comment: str | None, pending_draw: bool) -> None:
if not self.state.first_move_sent[side]:
await self._send_first(side, opponent_san=opponent_san, opponent_comment=opponent_comment)
return
msg = build_turn_prompt(
opponent_san=opponent_san,
opponent_comment=opponent_comment,
fen=self.state.game.board.fen(),
ascii_board=str(self.state.game.board),
pending_draw_from_opponent=pending_draw,
)
await self._submit(side, msg)
self._mark_waiting(side)
def _mark_waiting(self, side: Side) -> None:
self._waiting_side = side
self._waiting_started_at = asyncio.get_event_loop().time()
self.state.nudge_count[side] = 0
def _clear_waiting(self) -> None:
self._waiting_side = None
# ---------- public ----------
async def dispatch_first_prompt(self) -> None:
if self.state.game is None:
return
await self._send_first(Side.WHITE, opponent_san=None, opponent_comment=None)
async def start(self) -> None:
self._sub_task = asyncio.create_task(self._subscribe_loop())
self._watchdog_task = asyncio.create_task(self._watchdog_loop())
async def stop(self) -> None:
for t in (self._sub_task, self._watchdog_task):
if t:
t.cancel()
try:
await t
except asyncio.CancelledError:
pass
async def _subscribe_loop(self) -> None:
q = self.state.events.subscribe()
try:
while True:
ev = await q.get()
await self.run_subscriber_step_once(ev)
finally:
self.state.events.unsubscribe(q)
async def run_subscriber_step_once(self, ev: dict[str, Any]) -> None:
t = ev.get("type")
if t == "move":
self._clear_waiting()
mover = Side.from_str(ev["side"])
opp = mover.opposite()
await self._send_turn(
opp,
opponent_san=ev.get("san") or ev.get("uci") or "?",
opponent_comment=ev.get("comment"),
pending_draw=False,
)
elif t == "draw_offered":
offerer = Side.from_str(ev["side"])
opp = offerer.opposite()
await self._send_turn(
opp,
opponent_san="(draw offered)",
opponent_comment=ev.get("comment"),
pending_draw=True,
)
elif t == "game_over":
await self._announce_game_over(ev)
if self.state.game:
save_game(GAMES_DIR, self.state.game)
async def _announce_game_over(self, ev: dict[str, Any]) -> None:
msg = (f"Партия окончена. Результат: {ev.get('result')}. "
f"Termination: {ev.get('termination')}.")
for side in (Side.WHITE, Side.BLACK):
await self._submit(side, msg)
self._clear_waiting()
async def _watchdog_loop(self) -> None:
while True:
await asyncio.sleep(5.0)
if self._waiting_side is None:
continue
elapsed = asyncio.get_event_loop().time() - self._waiting_started_at
if elapsed < self.state.settings.watchdog_seconds:
continue
side = self._waiting_side
if self.state.nudge_count[side] >= self.state.settings.watchdog_max_nudges:
# Abandon
if self.state.game and not self.state.game.is_game_over():
self.state.game.result = "0-1" if side is Side.WHITE else "1-0"
self.state.game.termination = "abandoned"
self.state.game.ended_at = self.state.game.started_at
await self.state.events.publish({
"type": "game_over",
"result": self.state.game.result,
"termination": "abandoned",
})
self._clear_waiting()
else:
self.state.nudge_count[side] += 1
await self._submit(side, WATCHDOG_NUDGE)
self._waiting_started_at = asyncio.get_event_loop().time()
+76
View File
@@ -0,0 +1,76 @@
import asyncio
import pytest
from ai_chess.chess_game import ChessGame
from ai_chess.coordinator import Coordinator
from ai_chess.sides import Side
from ai_chess.state import AppState, AgentBinding
class FakeTmux:
def __init__(self):
self.calls: list[tuple] = []
async def submit(self, pane: int, text: str):
self.calls.append(("submit", pane, text))
async def send_keys(self, pane: int, keys):
self.calls.append(("send_keys", pane, list(keys)))
@pytest.mark.asyncio
async def test_first_prompt_white_on_start():
state = AppState()
state.game = ChessGame(game_id="t1")
state.bindings[Side.WHITE] = AgentBinding(Side.WHITE, "claude", "opus", "max")
state.bindings[Side.BLACK] = AgentBinding(Side.BLACK, "codex", "gpt-5.5", "xhigh")
fake = FakeTmux()
coord = Coordinator(state, tmux=fake, pane_for={"white": 0, "black": 1})
await coord.dispatch_first_prompt()
assert any(call[0] == "submit" and call[1] == 0 for call in fake.calls)
text = next(c[2] for c in fake.calls if c[0] == "submit" and c[1] == 0)
assert "белыми" in text
@pytest.mark.asyncio
async def test_on_move_sends_to_opponent():
state = AppState()
state.game = ChessGame(game_id="t1")
state.bindings[Side.WHITE] = AgentBinding(Side.WHITE, "claude", "opus", "max")
state.bindings[Side.BLACK] = AgentBinding(Side.BLACK, "codex", "gpt-5.5", "xhigh")
fake = FakeTmux()
coord = Coordinator(state, tmux=fake, pane_for={"white": 0, "black": 1})
await coord.run_subscriber_step_once({
"type": "move",
"side": "white",
"san": "e4",
"comment": "готовься",
"fen": state.game.board.fen(),
"ascii": str(state.game.board),
})
assert any(c[0] == "submit" and c[1] == 1 for c in fake.calls)
text = next(c[2] for c in fake.calls if c[0] == "submit" and c[1] == 1)
assert "e4" in text
assert "готовься" in text
@pytest.mark.asyncio
async def test_game_over_sends_summary_to_both():
state = AppState()
state.game = ChessGame(game_id="t1")
state.bindings[Side.WHITE] = AgentBinding(Side.WHITE, "claude", "opus", "max")
state.bindings[Side.BLACK] = AgentBinding(Side.BLACK, "codex", "gpt-5.5", "xhigh")
fake = FakeTmux()
coord = Coordinator(state, tmux=fake, pane_for={"white": 0, "black": 1})
state.game.try_move(Side.WHITE, "f3")
state.game.try_move(Side.BLACK, "e5")
state.game.try_move(Side.WHITE, "g4")
state.game.try_move(Side.BLACK, "Qh4")
await coord.run_subscriber_step_once({
"type": "game_over",
"result": "0-1",
"termination": "checkmate",
})
panes = sorted({c[1] for c in fake.calls if c[0] == "submit"})
assert panes == [0, 1]