Files
ai-chess/src/ai_chess/coordinator.py
T
ai-chess 33d6af764a fix: ulid API + tolerate missing tmux + dispatch-first endpoint
- coordinator: use `ulid.new().str` (ulid-py 1.x API), not `ULID()`
- coordinator._submit: swallow tmux errors so game logic continues
- app: split first-prompt dispatch into POST /api/dispatch-first
- start.sh: POST /api/dispatch-first ~12s after tmux create
- test_coordinator: isolate GAMES_DIR via tmp_path
2026-05-14 23:34:03 +03:00

211 lines
7.8 KiB
Python

from __future__ import annotations
import asyncio
import random
from typing import Any
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 = ulid.new().str
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:
# Tmux failures (missing session, dead pane) should not break the game
# state machine. Log and continue.
try:
await self.tmux.submit(pane=self._pane(side), text=text)
except Exception as e:
print(f"[coordinator] tmux submit to {side.value} failed: {e}", flush=True)
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()