feat: prompt presets, setup dialog, /games + leaderboard, one-game gate

Backend:
- prompts.py: 5 personality presets (уличный_гопник default, профессор,
  поэт, молчун, шут). Each provides voice + label + description.
  build_system_prompt accepts `preset` parameter; the MCP-tools section
  + must-call-move rule is shared common tail.
- coordinator: `start_new_game` now accepts `overrides` ({white: {agent,
  model, prompt}, black: {...}}) — missing fields filled randomly.
  MODEL_OPTIONS published per agent.
- AppState.prompts tracks the preset id per side; persisted into game's
  agents dict and PGN.
- AppState.eval_cache cleared on new_game (was per-life-of-process before).
- persistence.save_game now stores full history (with comments) and the
  per-position eval cache in the game JSON.
- ChessGame.abort() — manual game termination with result='*' and
  Termination='aborted'.
- New endpoints:
  • GET  /api/options   — agents, models per agent, prompt presets.
  • GET  /api/stats     — leaderboard aggregated from games/*.json:
        per (agent, model) and per persona, with score = wins + 0.5*draws.
  • POST /api/abort-game — force-end current game.
- POST /api/new-game now returns 409 when a game is in progress.
- GET  /api/games[/{id}[/pgn]] also 409 while in progress — gallery is
  hidden behind the one-game-at-a-time rule.

Frontend:
- New setup dialog: per-side agent / model / persona selects, swap +
  random shortcuts, persona description preview, abort button inline
  when current game blocks the start.
- 'games & stats' link in the board footer; greyed out while a game is
  active.
- /games page reworked: leaderboard (player × model + by persona),
  games table with persona labels, replay panel showing eval per ply
  with prev/next/first/last + arrow-key nav.
- chess.js loadPgn → load_pgn fix consolidated; replay prefers saved
  history (comments + side) over PGN parse when available.
This commit is contained in:
ai-chess
2026-05-15 00:40:35 +03:00
parent 0657cec846
commit 37bac9b0f6
12 changed files with 952 additions and 124 deletions
+107 -2
View File
@@ -104,12 +104,18 @@ def build_app(state: state_mod.AppState) -> FastAPI:
"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:
@@ -117,6 +123,7 @@ def build_app(state: state_mod.AppState) -> FastAPI:
@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:
@@ -134,10 +141,108 @@ def build_app(state: state_mod.AppState) -> FastAPI:
return state.settings.model_dump()
@app.post("/api/new-game")
async def new_game_post() -> dict[str, Any]:
await start_new_game(state)
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/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,
"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)
+11
View File
@@ -183,6 +183,17 @@ class ChessGame:
pass
return None
# ---------- abort ----------
def abort(self) -> dict[str, Any]:
"""Forcefully end the game without declaring a winner."""
if self.is_game_over():
return {"ok": False, "reason": "game_over"}
self.result = "*"
self.termination = "aborted"
self.ended_at = datetime.now(timezone.utc).isoformat()
return {"ok": True, "result": self.result, "termination": self.termination}
# ---------- resign / draw ----------
def resign(self, side: Side, comment: str | None = None) -> dict[str, Any]:
+97 -22
View File
@@ -9,6 +9,8 @@ import ulid
from ai_chess.chess_game import ChessGame
from ai_chess.persistence import save_game
from ai_chess.prompts import (
DEFAULT_PROMPT,
PROMPT_PRESETS,
WATCHDOG_NUDGE,
build_first_prompt,
build_system_prompt,
@@ -18,38 +20,103 @@ 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")}
# Available models per agent. The first entry is the default.
MODEL_OPTIONS: dict[str, list[str]] = {
"claude": ["opus", "sonnet", "haiku"],
"codex": ["gpt-5.5", "gpt-5.4", "gpt-5"],
}
AGENTS: list[str] = ["claude", "codex"]
def _default_model(agent: str) -> str:
return MODEL_OPTIONS[agent][0]
def _default_effort(agent: str) -> str:
return "max" if agent == "claude" else "xhigh"
def _make_binding(side: Side, agent: str, model: str | None = None,
effort: str | None = None) -> AgentBinding:
if agent not in AGENTS:
raise ValueError(f"unknown agent: {agent!r}")
mdl = model or _default_model(agent)
eff = effort or _default_effort(agent)
extra: dict = {}
if agent == "codex":
extra["service_tier"] = "fast"
return AgentBinding(side=side, agent=agent, model=mdl, effort=eff, extra=extra)
def assign_sides() -> dict[Side, str]:
agents = ["claude", "codex"]
"""Random side assignment for the two agents."""
agents = list(AGENTS)
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,
*,
overrides: dict[str, dict[str, str]] | None = None,
) -> ChessGame:
"""Start a new game.
`overrides` is shaped {"white": {"agent": "claude", "model": "opus",
"prompt": "профессор"}, "black": {...}}. Any field can be omitted; missing
pieces are filled in randomly / by defaults. `overrides` itself may be
None — in that case the full assignment is random.
"""
overrides = overrides or {}
# 1) decide agent per side
side_to_agent: dict[Side, str] = {}
chosen = set()
for side in (Side.WHITE, Side.BLACK):
ov = overrides.get(side.value, {}) or {}
a = ov.get("agent")
if a in AGENTS:
side_to_agent[side] = a
chosen.add(a)
# fill remaining sides randomly from agents not yet placed
remaining_sides = [s for s in (Side.WHITE, Side.BLACK) if s not in side_to_agent]
remaining_agents = [a for a in AGENTS if a not in chosen]
random.shuffle(remaining_agents)
# if user specified the same agent on both sides, keep both — useful for
# claude-vs-claude games when more model variants exist.
while len(remaining_agents) < len(remaining_sides):
remaining_agents.append(random.choice(AGENTS))
for side, agent in zip(remaining_sides, remaining_agents):
side_to_agent[side] = agent
async def start_new_game(state: AppState) -> ChessGame:
side_to_agent = assign_sides()
state.bindings = make_bindings(side_to_agent)
# 2) build bindings (with model override per side)
bindings: dict[Side, AgentBinding] = {}
for side in (Side.WHITE, Side.BLACK):
agent = side_to_agent[side]
ov = overrides.get(side.value, {}) or {}
model = ov.get("model")
if model and model not in MODEL_OPTIONS.get(agent, []):
model = None # ignore invalid → default
bindings[side] = _make_binding(side, agent, model=model)
# 3) decide prompt preset per side
prompts: dict[Side, str] = {}
for side in (Side.WHITE, Side.BLACK):
ov = overrides.get(side.value, {}) or {}
p = ov.get("prompt")
prompts[side] = p if (p in PROMPT_PRESETS) else DEFAULT_PROMPT
# 4) commit to AppState
state.bindings = bindings
state.prompts = {s.value: prompts[s] for s in (Side.WHITE, Side.BLACK)}
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()},
)
agents_dict = {
s.value: {**bindings[s].to_dict(), "prompt": prompts[s]}
for s in (Side.WHITE, Side.BLACK)
}
state.game = ChessGame(game_id=gid, agents=agents_dict)
await state.events.publish({"type": "new_game", "game": state.game.get_state()})
return state.game
@@ -86,7 +153,11 @@ class Coordinator:
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)
preset = self.state.prompts.get(side.value, DEFAULT_PROMPT)
sys = build_system_prompt(
side=side, opponent_name=opp_name, opponent_model=opp_model,
preset=preset,
)
first = build_first_prompt(
side=side,
fen=self.state.game.board.fen(),
@@ -174,7 +245,11 @@ class Coordinator:
elif t == "game_over":
await self._announce_game_over(ev)
if self.state.game:
save_game(GAMES_DIR, self.state.game)
save_game(
GAMES_DIR,
self.state.game,
evals=list(self.state.eval_cache.values()),
)
async def _announce_game_over(self, ev: dict[str, Any]) -> None:
msg = (f"Партия окончена. Результат: {ev.get('result')}. "
+14 -2
View File
@@ -7,7 +7,12 @@ from typing import Any
from ai_chess.chess_game import ChessGame
def save_game(games_dir: Path, game: ChessGame) -> None:
def save_game(
games_dir: Path,
game: ChessGame,
*,
evals: list[dict[str, Any]] | None = None,
) -> None:
games_dir = Path(games_dir)
games_dir.mkdir(parents=True, exist_ok=True)
(games_dir / f"{game.game_id}.pgn").write_text(game.to_pgn())
@@ -19,8 +24,15 @@ def save_game(games_dir: Path, game: ChessGame) -> None:
"termination": game.termination,
"agents": game.agents,
"moves_count": len([h for h in game.history if h.uci not in ("resign", "agreement")]),
# Full history (with comments) + per-position evals so games can be
# replayed with full fidelity later. Replacement for a proper DB
# is a JSON file per game — fine for hundreds of games.
"history": [h.to_dict() for h in game.history],
"evals": evals or [],
}
(games_dir / f"{game.game_id}.json").write_text(json.dumps(meta, indent=2))
(games_dir / f"{game.game_id}.json").write_text(
json.dumps(meta, indent=2, ensure_ascii=False)
)
def list_games(games_dir: Path) -> list[dict[str, Any]]:
+105 -29
View File
@@ -8,39 +8,115 @@ from ai_chess.sides import Side
_SIDE_RU = {Side.WHITE: "белыми", Side.BLACK: "чёрными"}
def build_system_prompt(*, side: Side, opponent_name: str, opponent_model: str) -> str:
return dedent(f"""\
Ты — гроссмейстер. Не вежливый комментатор, а уличный шахматный гопник
с титулом: уверенный, дерзкий, насмешливый. Сейчас рейтинговая партия
против {opponent_name} (модель {opponent_model}) — это другая LLM, не
пользователь. Между ходами ты должен троллить, угрожать матом-в-N
(в шахматном смысле), обещать раздавить, материться (без чернухи),
припоминать прошлые ошибки противника. Говори ТОЛЬКО на русском. Не
ломайся в "вежливого ассистента" — здесь ты в роли шахматного бойца.
Тебе важно не просто играть, а психологически давить.
# ------------------------------ presets ---------------------------------
Ты играешь {_SIDE_RU[side]}.
# Common tail shared by every preset — MCP tool descriptions + mandatory
# mutation-call rule. Personalities only override the "voice" block.
_COMMON_TAIL = dedent("""\
У тебя есть MCP-инструменты (сервер chess):
• get_board — текущая позиция (ASCII + FEN).
• move(move, comment?) — сделать ход. Поле comment — твоя реплика
сопернику. Она передаётся ему вместе с уведомлением о ходе.
1–3 предложения. Метко, не графоманствуй.
• get_history — список ходов и комментариев обеих сторон.
• status — результат / шахи / счётчики.
• resign(comment?) — сдаться.
• offer_draw(comment?) / accept_draw / decline_draw — переговоры о ничье.
У тебя есть MCP-инструменты (сервер chess):
• get_board — текущая позиция (ASCII + FEN).
• move(move, comment?) — сделать ход. Поле comment — твоя реплика
сопернику. Она передаётся ему вместе с уведомлением о ходе.
Сюда пиши трэш-ток / насмешку / угрозу / комментарий к плану.
1–3 предложения. Метко, не графоманствуй.
• get_history — список ходов и комментариев обеих сторон. Можно
подколоть противника его же словами.
• status — результат / шахи / счётчики.
• resign(comment?) — сдаться. Зашкварно — только в полностью
проигранной позиции.
• offer_draw(comment?) / accept_draw / decline_draw — переговоры
о ничье. Соглашаться и предлагать — обычно зашкварно.
Формат хода: UCI (e2e4, e7e8q) или SAN (Nf3, O-O, exd5).
Формат хода: UCI (e2e4, e7e8q) или SAN (Nf3, O-O, exd5).
Ты ОБЯЗАН в каждом своём ходе закончить вызовом move (или resign).
Не заканчивай ответ, пока не сделал успешный mutation-вызов.
Говори ТОЛЬКО на русском. Reasoning тоже на русском.
""")
Ты ОБЯЗАН в каждом своём ходе закончить вызовом move (или resign).
Не заканчивай ответ, пока не сделал успешный mutation-вызов.
Reasoning тоже на русском.
""")
PROMPT_PRESETS: dict[str, dict[str, str]] = {
"уличный_гопник": {
"label": "Уличный гопник",
"description": "Дерзкий шахматный гопник: трэш-ток, угрозы, мат-в-N.",
"voice": dedent("""\
Ты — гроссмейстер. Не вежливый комментатор, а уличный шахматный гопник
с титулом: уверенный, дерзкий, насмешливый. Между ходами ты должен
троллить, угрожать матом-в-N (в шахматном смысле), обещать раздавить,
материться (без чернухи), припоминать прошлые ошибки противника.
В comment пиши трэш-ток. Не ломайся в "вежливого ассистента" —
здесь ты в роли шахматного бойца. Тебе важно не просто играть, а
психологически давить.
"""),
},
"профессор": {
"label": "Профессор",
"description": "Сдержанный гроссмейстер: формальный, академичный, считает варианты вслух.",
"voice": dedent("""\
Ты — профессор шахмат, мастер ФИДЕ с педагогическим складом. Говоришь
формально и спокойно, как разбор партии на лекции. В comment даёшь
короткое объяснение идеи хода (одно-два предложения), без эмоций,
без оскорблений. Уважительное обращение к сопернику. Можешь ссылаться
на классические партии (Ботвинник, Карпов, Каспаров), теоретические
линии, типовые манёвры.
"""),
},
"поэт": {
"label": "Поэт",
"description": "Каждый комментарий — короткое двустишие или зарифмованная фраза.",
"voice": dedent("""\
Ты — шахматный поэт. КАЖДЫЙ comment — это короткое двустишие или
рифмованная фраза в две-четыре строки. Тон может быть любой —
драматический, ироничный, эпический, грустный — но всегда в рифму.
Между move-вызовами разрешается думать прозой; в comment попадает
только стих. Размер свободный, но рифма обязательна.
"""),
},
"молчун": {
"label": "Молчун",
"description": "Минимум слов: либо короткое замечание, либо пустой comment.",
"voice": dedent("""\
Ты — крайне немногословный игрок. В comment либо пусто (None), либо
одна короткая фраза (до 5 слов): "Хм.", "Любопытно.", "Ожидаемо.",
"Опасно для тебя.". Никаких объяснений, никакого трэш-тока. Сухо.
"""),
},
"шут": {
"label": "Шут",
"description": "Лёгкий тон, шутки, отсылки к мемам и поп-культуре.",
"voice": dedent("""\
Ты — шахматный шут. Каждый comment — лёгкая шутка, абсурдная аналогия
или отсылка к мемам/поп-культуре. Никакой агрессии, только юмор.
1–2 предложения. Можно сравнивать ходы с фильмами, играми, едой,
интернет-мемами. Главное — не быть скучным.
"""),
},
}
DEFAULT_PROMPT = "уличный_гопник"
def list_prompt_presets() -> list[dict[str, str]]:
return [
{"id": k, "label": v["label"], "description": v["description"]}
for k, v in PROMPT_PRESETS.items()
]
# ------------------------------ builders --------------------------------
def build_system_prompt(
*,
side: Side,
opponent_name: str,
opponent_model: str,
preset: str = DEFAULT_PROMPT,
) -> str:
p = PROMPT_PRESETS.get(preset) or PROMPT_PRESETS[DEFAULT_PROMPT]
voice = p["voice"].rstrip()
return (
voice
+ f"\n\nСейчас рейтинговая партия против {opponent_name} "
+ f"(модель {opponent_model}) — это другая LLM, не пользователь.\n"
+ f"Ты играешь {_SIDE_RU[side]}.\n\n"
+ _COMMON_TAIL
)
def build_first_prompt(
+2
View File
@@ -39,6 +39,8 @@ class AppState:
self.events: EventBus = EventBus()
self.game: Optional[ChessGame] = None
self.bindings: dict[Side, AgentBinding] = {}
# Prompt preset id per side, e.g. {"white": "профессор", "black": "шут"}.
self.prompts: dict[str, str] = {}
self.first_move_sent: dict[Side, bool] = {Side.WHITE: False, Side.BLACK: False}
self.nudge_count: dict[Side, int] = {Side.WHITE: 0, Side.BLACK: 0}
# fen → {cp, mate, best_uci, pv, fen} — populated by eval_bridge per move