Games
- ← back to live -| id | white | black | result | termination | moves | pgn |
|---|
-
-
-
-
-
- ${p.agent} / ${p.model}
+ ${p.games}
+ ${p.wins}
+ ${p.draws}
+ ${p.losses}
+ ${p.score.toFixed(1)}
+ ${wr}% `;
+ tb.appendChild(tr);
+ }
+ const tp = document.querySelector("#leaderboard-prompts tbody");
+ tp.innerHTML = "";
+ for (const p of stats.prompts) {
+ const tr = document.createElement("tr");
+ tr.innerHTML = `
+ ${p.prompt}
+ ${p.games}
+ ${p.wins}
+ ${p.draws}
+ ${p.losses}
+ ${p.score.toFixed(1)} `;
+ tp.appendChild(tr);
+ }
+}
+
+// ---------- games list ----------
+function renderGames(games) {
+ const tb = document.querySelector("#games-table tbody");
+ tb.innerHTML = "";
+ for (const g of games) {
+ const w = g.agents?.white || {};
+ const b = g.agents?.black || {};
+ const tr = document.createElement("tr");
+ const result = g.result || "*";
+ tr.innerHTML = `
+ ${(g.id || "?").slice(0, 10)}…
+ ${w.agent || "?"}/${w.model || "?"}
${w.prompt || ""}
+ ${b.agent || "?"}/${b.model || "?"}
${b.prompt || ""}
+ ${result}
+ ${g.termination || ""}
+ ${g.moves_count ?? 0}
+ pgn `;
+ tr.querySelector("a[data-id]").addEventListener("click", (e) => {
+ e.preventDefault();
+ openReplay(g.id);
+ });
+ tb.appendChild(tr);
+ }
+}
+
+// ---------- replay ----------
async function openReplay(id) {
const data = await (await fetch(`/api/games/${id}`)).json();
const meta = data.meta;
const w = meta.agents?.white || {};
const b = meta.agents?.black || {};
$("replay-title").textContent =
- `${id} — ${w.agent || "?"}/${w.model || "?"} vs ${b.agent || "?"}/${b.model || "?"} → ${meta.result || "*"}`;
- chess = new Chess();
- chess.load_pgn(data.pgn);
- // chess.js 0.13.4: history({verbose:true}) returns [{san, ...}, ...]
- history = chess.history({ verbose: true }).map(m => ({ san: m.san, comment: null }));
- ply = 0;
- if (!cg) cg = Chessground($("replay-board"), { viewOnly: true, fen: "start" });
- $("replay-wrap").style.display = "block";
+ `${id.slice(0,10)}… — ${w.agent||"?"}/${w.model||"?"} (${w.prompt||"?"}) vs ${b.agent||"?"}/${b.model||"?"} (${b.prompt||"?"}) → ${meta.result || "*"}`;
+ // Prefer saved history (with comments) if present in meta
+ let history = [];
+ if (Array.isArray(meta.history) && meta.history.length) {
+ history = meta.history.filter(h => h.san);
+ } else {
+ // fallback to PGN parse
+ const c = new Chess();
+ c.load_pgn(data.pgn);
+ history = c.history({ verbose: true }).map(m => ({
+ san: m.san, uci: m.from + m.to + (m.promotion || ""), comment: null, side: m.color === "w" ? "white" : "black",
+ }));
+ }
+ replay.history = history;
+ replay.evals.clear();
+ for (const e of (meta.evals || [])) {
+ const sideToMove = (e.fen || "").split(" ")[1] || "w";
+ const flip = sideToMove === "b";
+ replay.evals.set(fenKey(e.fen), {
+ cp: e.cp == null ? null : (flip ? -e.cp : e.cp),
+ mate: e.mate == null ? null : (flip ? -e.mate : e.mate),
+ best_uci: e.best_uci,
+ pv: e.pv,
+ });
+ }
+ replay.ply = 0;
+ if (!cg) {
+ cg = Chessground($("replay-board"), { viewOnly: true, fen: "start" });
+ }
+ $("replay-wrap").hidden = false;
renderReplay();
+ $("replay-wrap").scrollIntoView({ behavior: "smooth", block: "nearest" });
}
+function renderReplay() {
+ const c = new Chess();
+ for (let i = 0; i < replay.ply; i++) c.move(replay.history[i].san);
+ const fen = c.fen();
+ const e = replay.evals.get(fenKey(fen));
+ const shapes = (e?.best_uci && e.best_uci.length >= 4)
+ ? [{ orig: e.best_uci.slice(0,2), dest: e.best_uci.slice(2,4), brush: "green" }] : [];
+ cg.set({ fen, drawable: { autoShapes: shapes } });
+ $("replay-ply").textContent = `ply ${replay.ply}/${replay.history.length}`;
+ $("replay-eval").textContent = e
+ ? (e.mate != null ? `#${e.mate}` : (e.cp != null ? ((e.cp/100).toFixed(2)) : "—"))
+ : "—";
+ const ol = $("replay-history");
+ ol.innerHTML = "";
+ replay.history.forEach((h, i) => {
+ const li = document.createElement("li");
+ li.className = `replay-row bubble bubble-${h.side}`;
+ if (i === replay.ply - 1) li.classList.add("active");
+ const meta = document.createElement("div");
+ meta.className = "bubble-meta";
+ meta.innerHTML = `${h.side}${Math.floor(i/2)+1}${h.side==="white"?".":"..."} ${h.san}`;
+ const body = document.createElement("div");
+ body.className = "bubble-body" + (h.comment ? "" : " bubble-empty");
+ body.textContent = h.comment || "—";
+ li.append(meta, body);
+ li.addEventListener("click", () => { replay.ply = i + 1; renderReplay(); });
+ ol.appendChild(li);
+ });
+ const activeRow = ol.querySelector(".replay-row.active");
+ if (activeRow) activeRow.scrollIntoView({ behavior: "smooth", block: "nearest" });
+}
+
+$("replay-first").addEventListener("click", () => { replay.ply = 0; renderReplay(); });
+$("replay-prev").addEventListener("click", () => { if (replay.ply > 0) { replay.ply--; renderReplay(); } });
+$("replay-next").addEventListener("click", () => { if (replay.ply < replay.history.length) { replay.ply++; renderReplay(); } });
+$("replay-last").addEventListener("click", () => { replay.ply = replay.history.length; renderReplay(); });
+$("replay-close").addEventListener("click", () => { $("replay-wrap").hidden = true; });
+window.addEventListener("keydown", (e) => {
+ if ($("replay-wrap").hidden) return;
+ if (e.key === "ArrowLeft" && replay.ply > 0) { replay.ply--; renderReplay(); }
+ else if (e.key === "ArrowRight" && replay.ply < replay.history.length) { replay.ply++; renderReplay(); }
+});
+
+// ---------- bootstrap ----------
async function main() {
- const games = await (await fetch("/api/games")).json();
- for (const g of games) {
- const w = g.agents?.white || {};
- const b = g.agents?.black || {};
- const tr = document.createElement("tr");
- tr.innerHTML = `
- ${(g.id || "?").slice(0, 10)}…
- ${w.agent || "?"}/${w.model || "?"}
- ${b.agent || "?"}/${b.model || "?"}
- ${g.result || "*"}
- ${g.termination || ""}
- ${g.moves_count ?? 0}
- pgn
- `;
- tr.querySelector("a[data-id]").addEventListener("click", (e) => {
- e.preventDefault();
- openReplay(g.id);
- });
- tbody.appendChild(tr);
+ const blocked = await checkBlocked();
+ if (blocked) {
+ $("blocked-banner").hidden = false;
+ document.getElementById("page-grid").style.opacity = "0.4";
+ document.getElementById("page-grid").style.pointerEvents = "none";
+ // refresh every 5s — when game finishes, unblock
+ const intv = setInterval(async () => {
+ if (!(await checkBlocked())) {
+ clearInterval(intv);
+ location.reload();
+ }
+ }, 5000);
+ return;
}
+ const [games, stats] = await Promise.all([
+ fetch("/api/games").then(r => r.json()),
+ fetch("/api/stats").then(r => r.json()),
+ ]);
+ renderGames(games);
+ renderLeaderboard(stats);
}
main();
-
-$("prev").addEventListener("click", () => { if (ply > 0) { ply--; renderReplay(); } });
-$("next").addEventListener("click", () => { if (ply < history.length) { ply++; renderReplay(); } });
diff --git a/public/index.html b/public/index.html
index 3955cc5..9e1c0a9 100644
--- a/public/index.html
+++ b/public/index.html
@@ -22,6 +22,7 @@
…
+ games & stats
@@ -53,6 +54,59 @@
+
+
diff --git a/public/style.css b/public/style.css
index cac260e..8de4b9f 100644
--- a/public/style.css
+++ b/public/style.css
@@ -165,7 +165,100 @@ button:hover { background: #2e2e36; }
dialog {
background: #15151a; color: #e7e5e4; border: 1px solid #2a2a30;
- padding: 16px; border-radius: 6px;
+ padding: 16px; border-radius: 8px;
+ box-shadow: 0 10px 30px rgba(0,0,0,0.6);
}
-dialog form { display: flex; flex-direction: column; gap: 10px; min-width: 320px; }
+dialog::backdrop { background: rgba(0,0,0,0.55); }
+dialog form { display: flex; flex-direction: column; gap: 12px; min-width: 320px; }
dialog menu { display: flex; gap: 8px; justify-content: flex-end; padding: 0; margin: 0; }
+dialog h3 { margin: 0; font-size: 14px; letter-spacing: 0.06em; text-transform: uppercase; opacity: 0.85; }
+dialog select, dialog input[type="number"], dialog input[type="text"] {
+ background: #1f1f25; color: #e7e5e4; border: 1px solid #34343a;
+ border-radius: 4px; padding: 4px 6px; font-size: 12px;
+}
+
+/* setup dialog */
+#setup-dialog { min-width: 580px; }
+.setup-header { display: flex; justify-content: space-between; align-items: center; }
+.setup-actions { display: flex; gap: 8px; }
+.setup-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
+.setup-side {
+ border: 1px solid #34343a; border-radius: 6px; padding: 10px 12px;
+ display: flex; flex-direction: column; gap: 8px;
+ background: #1a1a20;
+}
+.setup-side legend { padding: 0 6px; font-size: 11px; letter-spacing: 0.1em; opacity: 0.8; }
+.setup-white legend { color: #e7e5e4; }
+.setup-black legend { color: #c0a060; }
+.setup-side label {
+ display: flex; flex-direction: column; gap: 3px;
+ font-size: 10px; opacity: 0.55; text-transform: uppercase; letter-spacing: 0.08em;
+}
+.setup-side select { font-size: 13px; opacity: 1; text-transform: none; letter-spacing: 0; }
+.setup-promptdesc {
+ margin: 4px 0 0; font-size: 11px; opacity: 0.55; line-height: 1.4;
+ min-height: 2.4em;
+}
+#setup-warning { background: #3a2a1a; border: 1px solid #5a4020; color: #f0c080; padding: 8px 10px; border-radius: 4px; font-size: 12px; margin: 0; }
+#setup-start { background: #3d342a; color: #f0d090; }
+#games-link { font-size: 12px; color: #c0a060; text-decoration: none; margin-right: 4px; }
+#games-link:hover { text-decoration: underline; }
+#games-link.disabled { color: #555; cursor: not-allowed; }
+#games-link.disabled:hover { text-decoration: none; }
+
+/* ============ /games page ============ */
+#games-page {
+ max-width: 1500px; margin: 0 auto; padding: 24px;
+ display: flex; flex-direction: column; gap: 18px;
+}
+#games-page-header {
+ display: flex; align-items: baseline; gap: 16px;
+ border-bottom: 1px solid #2a2a30; padding-bottom: 12px;
+}
+#games-page-header h1 { margin: 0; font-size: 18px; letter-spacing: 0.05em; }
+#games-count { opacity: 0.55; font-size: 12px; }
+#back-link { color: #c0a060; text-decoration: none; }
+#back-link:hover { text-decoration: underline; }
+
+#blocked-banner {
+ background: #3a2a1a; border: 1px solid #5a4020; color: #f0c080;
+ padding: 12px 14px; border-radius: 6px;
+}
+#blocked-banner a { color: #f0d090; }
+
+#page-grid {
+ display: grid; grid-template-columns: 420px 1fr; gap: 18px;
+}
+#stats-pane, #games-pane {
+ background: #15151a; border: 1px solid #2a2a30; border-radius: 8px;
+ overflow: hidden;
+}
+#stats-pane table, #games-pane table {
+ width: 100%; border-collapse: collapse; font-size: 12.5px;
+}
+#stats-pane th, #stats-pane td, #games-pane th, #games-pane td {
+ padding: 6px 10px; text-align: left; border-bottom: 1px solid #1f1f24;
+}
+#stats-pane th, #games-pane th {
+ font-size: 10px; text-transform: uppercase; letter-spacing: 0.08em;
+ opacity: 0.55; font-weight: 600;
+}
+#stats-pane td:nth-child(n+2), #games-pane td:nth-child(n+4) { font-variant-numeric: tabular-nums; }
+.persona { font-size: 10px; opacity: 0.5; }
+.result-1-0 { color: #f0eee6; font-weight: 700; }
+.result-0-1 { color: #c0a060; font-weight: 700; }
+.result-1_2-1_2 { color: #88c0a0; font-weight: 700; }
+.result-_ { opacity: 0.4; }
+
+/* replay */
+#replay-wrap { border-top: 1px solid #2a2a30; padding: 14px; }
+#replay-layout { display: grid; grid-template-columns: 360px 1fr; gap: 16px; }
+#replay-board { width: 360px; aspect-ratio: 1/1; }
+#replay-side { display: flex; flex-direction: column; gap: 10px; min-height: 0; }
+#replay-controls { display: flex; gap: 6px; align-items: center; font-size: 12px; }
+#replay-controls button { padding: 2px 8px; }
+#replay-ply { opacity: 0.6; margin-left: 8px; }
+#replay-eval { margin-left: auto; font-weight: 700; color: #f0d090; }
+#replay-history { list-style: none; padding: 0; margin: 0; display: flex; flex-direction: column; gap: 6px; max-height: 540px; overflow-y: auto; }
+.replay-row { font-size: 12px; }
+#replay-close { background: #25252b; }
diff --git a/src/ai_chess/app.py b/src/ai_chess/app.py
index 3c1eb59..61a47d9 100644
--- a/src/ai_chess/app.py
+++ b/src/ai_chess/app.py
@@ -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)
diff --git a/src/ai_chess/chess_game.py b/src/ai_chess/chess_game.py
index e8d0819..8658d0f 100644
--- a/src/ai_chess/chess_game.py
+++ b/src/ai_chess/chess_game.py
@@ -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]:
diff --git a/src/ai_chess/coordinator.py b/src/ai_chess/coordinator.py
index 1c5b4b9..03c4a60 100644
--- a/src/ai_chess/coordinator.py
+++ b/src/ai_chess/coordinator.py
@@ -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')}. "
diff --git a/src/ai_chess/persistence.py b/src/ai_chess/persistence.py
index 1f1f99e..76d6aac 100644
--- a/src/ai_chess/persistence.py
+++ b/src/ai_chess/persistence.py
@@ -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]]:
diff --git a/src/ai_chess/prompts.py b/src/ai_chess/prompts.py
index fb6a561..6530053 100644
--- a/src/ai_chess/prompts.py
+++ b/src/ai_chess/prompts.py
@@ -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(
diff --git a/src/ai_chess/state.py b/src/ai_chess/state.py
index e51d2f4..37da072 100644
--- a/src/ai_chess/state.py
+++ b/src/ai_chess/state.py
@@ -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
diff --git a/tests/test_app.py b/tests/test_app.py
index 815a2c2..9efe1dc 100644
--- a/tests/test_app.py
+++ b/tests/test_app.py
@@ -98,3 +98,66 @@ def test_mcp_batch_with_notification(client):
assert isinstance(body, list)
assert len(body) == 1
assert body[0]["id"] == 5
+
+
+def test_options_lists_models_and_prompts(client):
+ r = client.get("/api/options")
+ assert r.status_code == 200
+ b = r.json()
+ assert "claude" in b["agents"] and "codex" in b["agents"]
+ assert "opus" in b["models"]["claude"]
+ assert "gpt-5.5" in b["models"]["codex"]
+ prompt_ids = [p["id"] for p in b["prompts"]]
+ assert "уличный_гопник" in prompt_ids
+ assert "профессор" in prompt_ids
+
+
+def test_new_game_accepts_overrides(client):
+ # Abort the fixture's t1 game first — one game at a time.
+ client.post("/api/abort-game")
+ r = client.post("/api/new-game", json={"overrides": {
+ "white": {"agent": "claude", "model": "sonnet", "prompt": "профессор"},
+ "black": {"agent": "codex", "model": "gpt-5.4", "prompt": "шут"},
+ }})
+ assert r.status_code == 200
+ g = r.json()
+ a = g["agents"]
+ assert a["white"]["agent"] == "claude"
+ assert a["white"]["model"] == "sonnet"
+ assert a["white"]["prompt"] == "профессор"
+ assert a["black"]["agent"] == "codex"
+ assert a["black"]["model"] == "gpt-5.4"
+ assert a["black"]["prompt"] == "шут"
+
+
+def test_new_game_409_when_current_in_progress(client):
+ # First call: t1 game is active (no result), need to finish it first.
+ r = client.post("/api/new-game")
+ assert r.status_code == 409
+
+
+def test_abort_game_then_new(client):
+ r = client.post("/api/abort-game")
+ assert r.status_code == 200
+ assert r.json()["ok"] is True
+ r2 = client.post("/api/new-game")
+ assert r2.status_code == 200
+
+
+def test_games_endpoints_blocked_when_in_progress(client):
+ # t1 is in progress per fixture
+ assert client.get("/api/games").status_code == 409
+ assert client.get("/api/games/anything").status_code == 409
+ assert client.get("/api/games/anything/pgn").status_code == 409
+ # Abort and they become accessible
+ client.post("/api/abort-game")
+ assert client.get("/api/games").status_code == 200
+
+
+def test_stats_empty_when_no_games(client):
+ r = client.get("/api/stats")
+ assert r.status_code == 200
+ b = r.json()
+ assert b["total_games"] == 0
+ assert b["players"] == []
+ assert b["prompts"] == []
-
-
- ply 0
+
+
+ ← back to live
+
+
+
diff --git a/public/games.js b/public/games.js
index c376b5c..7170377 100644
--- a/public/games.js
+++ b/public/games.js
@@ -2,65 +2,184 @@ import { Chess } from "/static/vendor/chess.min.js";
import { Chessground } from "/static/vendor/chessground.min.js";
const $ = (id) => document.getElementById(id);
-const tbody = document.querySelector("#games-table tbody");
-let cg = null, chess = null, history = [], ply = 0;
+let cg = null;
+let replay = { history: [], evals: new Map(), ply: 0 };
-function renderReplay() {
- chess = new Chess();
- for (let i = 0; i < ply; i++) chess.move(history[i].san);
- cg.set({ fen: chess.fen() });
- $("ply").textContent = `ply ${ply}/${history.length}`;
- const ol = $("replay-history");
- ol.innerHTML = "";
- history.forEach((h, i) => {
- const li = document.createElement("li");
- li.textContent = h.san + (h.comment ? " «" + h.comment + "»" : "");
- if (i === ply - 1) li.style.background = "#444";
- ol.appendChild(li);
- });
+function fenKey(fen) { return fen.split(" ").slice(0, 3).join(" "); }
+
+// ---------- gating ----------
+async function checkBlocked() {
+ try {
+ const r = await fetch("/api/state");
+ const s = await r.json();
+ return !!(s.game && !s.game.status?.result);
+ } catch (e) { return false; }
}
+// ---------- leaderboard ----------
+function renderLeaderboard(stats) {
+ $("games-count").textContent = `${stats.total_games} games`;
+ const tb = document.querySelector("#leaderboard tbody");
+ tb.innerHTML = "";
+ for (const p of stats.players) {
+ const wr = p.games ? Math.round(100 * (p.wins + 0.5 * p.draws) / p.games) : 0;
+ const tr = document.createElement("tr");
+ tr.innerHTML = `
+ games & stats
+ +
+ Game in progress. Finish or abort it on the
+ main page before browsing past games.
+
+
+
+
+ leaderboard (player × model)
+
+
+
+
+ by persona
+
+
+
+
+
+
+ games
+
+
+
+
+
+
| agent / model | +games | +wins | +draws | +losses | +score | +winrate | +
|---|
| persona | games | wins | draws | losses | score |
|---|
| id | +white | +black | +result | +termination | +moves | +pgn | +
|---|
+ replay
+
+
+
-
+
+
- ${w.prompt || ""}
${b.prompt || ""}