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
+165 -2
View File
@@ -251,6 +251,7 @@ function applySnapshot(s) {
STATE.evalByFen.clear(); STATE.evalByFen.clear();
for (const e of (s.evals || [])) storeEval(e); for (const e of (s.evals || [])) storeEval(e);
renderBoard(); renderChat(); renderHistory(); renderStatus(); renderBoard(); renderChat(); renderHistory(); renderStatus();
refreshGamesLink();
} }
function connect() { function connect() {
@@ -285,6 +286,9 @@ function connect() {
STATE.game.status.termination = ev.termination; STATE.game.status.termination = ev.termination;
} }
renderStatus(); renderStatus();
refreshGamesLink();
// unlock the setup dialog if it was open and waiting
try { refreshSetupGate(); } catch (e) {}
log(`game over: ${ev.result} (${ev.termination})`); log(`game over: ${ev.result} (${ev.termination})`);
return; return;
} }
@@ -298,8 +302,167 @@ connect();
// ---------- controls ---------- // ---------- controls ----------
$("live-btn").addEventListener("click", goLive); $("live-btn").addEventListener("click", goLive);
$("new-game").addEventListener("click", async () => { // ---------- new game setup dialog ----------
await fetch("/api/new-game", { method: "POST" }); let OPTIONS = null;
async function loadOptions() {
if (OPTIONS) return OPTIONS;
OPTIONS = await (await fetch("/api/options")).json();
return OPTIONS;
}
function fillModelOptions(side) {
const agent = document.querySelector(`[name="${side}-agent"]`).value;
const models = OPTIONS.models[agent] || [];
const sel = document.querySelector(`[name="${side}-model"]`);
sel.innerHTML = "";
for (const m of models) {
const o = document.createElement("option");
o.value = m; o.textContent = m;
sel.appendChild(o);
}
}
function fillPromptOptions(side) {
const sel = document.querySelector(`[name="${side}-prompt"]`);
sel.innerHTML = "";
for (const p of OPTIONS.prompts) {
const o = document.createElement("option");
o.value = p.id; o.textContent = p.label; o.dataset.desc = p.description;
sel.appendChild(o);
}
if (OPTIONS.defaults?.prompt) sel.value = OPTIONS.defaults.prompt;
updatePromptDesc(side);
}
function updatePromptDesc(side) {
const sel = document.querySelector(`[name="${side}-prompt"]`);
const target = document.querySelector(`.setup-promptdesc[data-for="${side}"]`);
if (!sel || !target) return;
const opt = sel.options[sel.selectedIndex];
target.textContent = opt?.dataset?.desc || "";
}
function isGameInProgress() {
return !!(STATE.game && !STATE.game.status?.result);
}
function refreshGamesLink() {
const link = $("games-link");
if (!link) return;
if (isGameInProgress()) {
link.classList.add("disabled");
link.title = "finish or abort the current game to open games & stats";
link.removeAttribute("href");
} else {
link.classList.remove("disabled");
link.removeAttribute("title");
link.setAttribute("href", "/games");
}
}
function refreshSetupGate() {
const blocked = isGameInProgress();
$("setup-warning").hidden = !blocked;
$("setup-start").disabled = blocked;
}
async function openSetupDialog() {
await loadOptions();
// Populate agent selects
for (const side of ["white", "black"]) {
const sel = document.querySelector(`[name="${side}-agent"]`);
if (!sel.children.length) {
for (const a of OPTIONS.agents) {
const o = document.createElement("option");
o.value = a; o.textContent = a;
sel.appendChild(o);
}
}
}
// Seed defaults from current bindings if available
const b = STATE.bindings || {};
for (const side of ["white", "black"]) {
const agent = b[side]?.agent || OPTIONS.agents[(side === "white") ? 0 : 1];
document.querySelector(`[name="${side}-agent"]`).value = agent;
fillModelOptions(side);
const curModel = b[side]?.model;
if (curModel && OPTIONS.models[agent]?.includes(curModel)) {
document.querySelector(`[name="${side}-model"]`).value = curModel;
}
fillPromptOptions(side);
}
refreshSetupGate();
$("setup-dialog").showModal();
}
document.addEventListener("click", (e) => {
if (e.target?.id === "abort-now") {
fetch("/api/abort-game", { method: "POST" })
.then(() => setTimeout(refreshSetupGate, 100));
}
});
$("new-game").addEventListener("click", () => openSetupDialog());
// Agent change → repopulate models
for (const side of ["white", "black"]) {
document.querySelector(`[name="${side}-agent"]`).addEventListener("change", () => {
fillModelOptions(side);
});
document.querySelector(`[name="${side}-prompt"]`).addEventListener("change", () => {
updatePromptDesc(side);
});
}
// Swap white/black selections
$("swap-sides").addEventListener("click", () => {
for (const field of ["agent", "model", "prompt"]) {
const w = document.querySelector(`[name="white-${field}"]`);
const b = document.querySelector(`[name="black-${field}"]`);
const tmp = w.value; w.value = b.value; b.value = tmp;
}
// Reset model lists for new agent values
fillModelOptions("white"); fillModelOptions("black");
updatePromptDesc("white"); updatePromptDesc("black");
});
// Randomize: pick random agent/model/prompt per side, agents on opposite sides if possible
$("randomize").addEventListener("click", () => {
const agents = [...OPTIONS.agents].sort(() => Math.random() - 0.5);
const prompts = OPTIONS.prompts.map(p => p.id);
const sides = ["white", "black"];
for (let i = 0; i < sides.length; i++) {
const side = sides[i];
const agent = agents[i % agents.length];
document.querySelector(`[name="${side}-agent"]`).value = agent;
fillModelOptions(side);
const models = OPTIONS.models[agent];
document.querySelector(`[name="${side}-model"]`).value = models[Math.floor(Math.random() * models.length)];
document.querySelector(`[name="${side}-prompt"]`).value = prompts[Math.floor(Math.random() * prompts.length)];
updatePromptDesc(side);
}
});
// Submit
$("setup-start").addEventListener("click", async (e) => {
e.preventDefault();
const overrides = {};
for (const side of ["white", "black"]) {
overrides[side] = {
agent: document.querySelector(`[name="${side}-agent"]`).value,
model: document.querySelector(`[name="${side}-model"]`).value,
prompt: document.querySelector(`[name="${side}-prompt"]`).value,
};
}
await fetch("/api/new-game", {
method: "POST",
headers: {"content-type": "application/json"},
body: JSON.stringify({ overrides }),
});
// tell coordinator to inject the first prompt right away
fetch("/api/dispatch-first", { method: "POST" }).catch(() => {});
$("setup-dialog").close();
}); });
const dialog = $("settings-dialog"); const dialog = $("settings-dialog");
+72 -17
View File
@@ -2,34 +2,89 @@
<html lang="ru"> <html lang="ru">
<head> <head>
<meta charset="utf-8" /> <meta charset="utf-8" />
<title>ai-chess — games</title> <title>ai-chess — games & stats</title>
<link rel="stylesheet" href="/static/vendor/chessground.base.css" /> <link rel="stylesheet" href="/static/vendor/chessground.base.css" />
<link rel="stylesheet" href="/static/vendor/chessground.brown.css" /> <link rel="stylesheet" href="/static/vendor/chessground.brown.css" />
<link rel="stylesheet" href="/static/vendor/chessground.cburnett.css" /> <link rel="stylesheet" href="/static/vendor/chessground.cburnett.css" />
<link rel="stylesheet" href="/static/style.css" /> <link rel="stylesheet" href="/static/style.css" />
</head> </head>
<body> <body>
<main style="padding: 16px;"> <main id="games-page">
<h1>Games</h1> <header id="games-page-header">
<a href="/">← back to live</a> <a id="back-link" href="/">← back to live</a>
<table id="games-table" style="width: 100%; margin-top: 16px;"> <h1>games & stats</h1>
<thead><tr><th>id</th><th>white</th><th>black</th><th>result</th><th>termination</th><th>moves</th><th>pgn</th></tr></thead> <span id="games-count"></span>
</header>
<div id="blocked-banner" hidden>
<strong>Game in progress.</strong> Finish or abort it on the
<a href="/">main page</a> before browsing past games.
</div>
<div id="page-grid">
<section id="stats-pane">
<header class="col-header"><span>leaderboard (player × model)</span></header>
<table id="leaderboard">
<thead>
<tr>
<th>agent / model</th>
<th>games</th>
<th>wins</th>
<th>draws</th>
<th>losses</th>
<th>score</th>
<th>winrate</th>
</tr>
</thead>
<tbody></tbody> <tbody></tbody>
</table> </table>
<hr />
<div id="replay-wrap" style="display: none;"> <header class="col-header"><span>by persona</span></header>
<h3 id="replay-title"></h3> <table id="leaderboard-prompts">
<div style="display: grid; grid-template-columns: 360px 1fr; gap: 16px;"> <thead>
<div id="replay-board" style="width: 360px; aspect-ratio: 1/1;"></div> <tr><th>persona</th><th>games</th><th>wins</th><th>draws</th><th>losses</th><th>score</th></tr>
<div> </thead>
<div> <tbody></tbody>
<button id="prev">←</button> </table>
<button id="next">→</button> </section>
<span id="ply">ply 0</span>
<section id="games-pane">
<header class="col-header"><span>games</span></header>
<table id="games-table">
<thead>
<tr>
<th>id</th>
<th>white</th>
<th>black</th>
<th>result</th>
<th>termination</th>
<th>moves</th>
<th>pgn</th>
</tr>
</thead>
<tbody></tbody>
</table>
<div id="replay-wrap" hidden>
<header class="col-header"><span id="replay-title">replay</span>
<button id="replay-close" type="button">close</button>
</header>
<div id="replay-layout">
<div id="replay-board"></div>
<aside id="replay-side">
<div id="replay-controls">
<button id="replay-first">⏮</button>
<button id="replay-prev">←</button>
<button id="replay-next">→</button>
<button id="replay-last">⏭</button>
<span id="replay-ply">ply 0/0</span>
<span id="replay-eval"></span>
</div> </div>
<ol id="replay-history" style="max-height: 60vh; overflow: auto;"></ol> <ol id="replay-history"></ol>
</aside>
</div> </div>
</div> </div>
</section>
</div> </div>
</main> </main>
<script src="/static/games.js" type="module"></script> <script src="/static/games.js" type="module"></script>
+164 -45
View File
@@ -2,65 +2,184 @@ import { Chess } from "/static/vendor/chess.min.js";
import { Chessground } from "/static/vendor/chessground.min.js"; import { Chessground } from "/static/vendor/chessground.min.js";
const $ = (id) => document.getElementById(id); 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() { function fenKey(fen) { return fen.split(" ").slice(0, 3).join(" "); }
chess = new Chess();
for (let i = 0; i < ply; i++) chess.move(history[i].san); // ---------- gating ----------
cg.set({ fen: chess.fen() }); async function checkBlocked() {
$("ply").textContent = `ply ${ply}/${history.length}`; try {
const ol = $("replay-history"); const r = await fetch("/api/state");
ol.innerHTML = ""; const s = await r.json();
history.forEach((h, i) => { return !!(s.game && !s.game.status?.result);
const li = document.createElement("li"); } catch (e) { return false; }
li.textContent = h.san + (h.comment ? " «" + h.comment + "»" : "");
if (i === ply - 1) li.style.background = "#444";
ol.appendChild(li);
});
} }
// ---------- 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 = `
<td><strong>${p.agent}</strong> / ${p.model}</td>
<td>${p.games}</td>
<td>${p.wins}</td>
<td>${p.draws}</td>
<td>${p.losses}</td>
<td>${p.score.toFixed(1)}</td>
<td>${wr}%</td>`;
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 = `
<td>${p.prompt}</td>
<td>${p.games}</td>
<td>${p.wins}</td>
<td>${p.draws}</td>
<td>${p.losses}</td>
<td>${p.score.toFixed(1)}</td>`;
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 = `
<td><a href="#" data-id="${g.id}">${(g.id || "?").slice(0, 10)}…</a></td>
<td>${w.agent || "?"}/${w.model || "?"}<br><span class="persona">${w.prompt || ""}</span></td>
<td>${b.agent || "?"}/${b.model || "?"}<br><span class="persona">${b.prompt || ""}</span></td>
<td class="result-${result.replace(/\//g, "_")}">${result}</td>
<td>${g.termination || ""}</td>
<td>${g.moves_count ?? 0}</td>
<td><a href="/api/games/${g.id}/pgn">pgn</a></td>`;
tr.querySelector("a[data-id]").addEventListener("click", (e) => {
e.preventDefault();
openReplay(g.id);
});
tb.appendChild(tr);
}
}
// ---------- replay ----------
async function openReplay(id) { async function openReplay(id) {
const data = await (await fetch(`/api/games/${id}`)).json(); const data = await (await fetch(`/api/games/${id}`)).json();
const meta = data.meta; const meta = data.meta;
const w = meta.agents?.white || {}; const w = meta.agents?.white || {};
const b = meta.agents?.black || {}; const b = meta.agents?.black || {};
$("replay-title").textContent = $("replay-title").textContent =
`${id} — ${w.agent || "?"}/${w.model || "?"} vs ${b.agent || "?"}/${b.model || "?"} → ${meta.result || "*"}`; `${id.slice(0,10)}… — ${w.agent||"?"}/${w.model||"?"} (${w.prompt||"?"}) vs ${b.agent||"?"}/${b.model||"?"} (${b.prompt||"?"}) → ${meta.result || "*"}`;
chess = new Chess(); // Prefer saved history (with comments) if present in meta
chess.load_pgn(data.pgn); let history = [];
// chess.js 0.13.4: history({verbose:true}) returns [{san, ...}, ...] if (Array.isArray(meta.history) && meta.history.length) {
history = chess.history({ verbose: true }).map(m => ({ san: m.san, comment: null })); history = meta.history.filter(h => h.san);
ply = 0; } else {
if (!cg) cg = Chessground($("replay-board"), { viewOnly: true, fen: "start" }); // fallback to PGN parse
$("replay-wrap").style.display = "block"; 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(); renderReplay();
$("replay-wrap").scrollIntoView({ behavior: "smooth", block: "nearest" });
} }
async function main() { function renderReplay() {
const games = await (await fetch("/api/games")).json(); const c = new Chess();
for (const g of games) { for (let i = 0; i < replay.ply; i++) c.move(replay.history[i].san);
const w = g.agents?.white || {}; const fen = c.fen();
const b = g.agents?.black || {}; const e = replay.evals.get(fenKey(fen));
const tr = document.createElement("tr"); const shapes = (e?.best_uci && e.best_uci.length >= 4)
tr.innerHTML = ` ? [{ orig: e.best_uci.slice(0,2), dest: e.best_uci.slice(2,4), brush: "green" }] : [];
<td><a href="#" data-id="${g.id}">${(g.id || "?").slice(0, 10)}…</a></td> cg.set({ fen, drawable: { autoShapes: shapes } });
<td>${w.agent || "?"}/${w.model || "?"}</td> $("replay-ply").textContent = `ply ${replay.ply}/${replay.history.length}`;
<td>${b.agent || "?"}/${b.model || "?"}</td> $("replay-eval").textContent = e
<td>${g.result || "*"}</td> ? (e.mate != null ? `#${e.mate}` : (e.cp != null ? ((e.cp/100).toFixed(2)) : "—"))
<td>${g.termination || ""}</td> : "—";
<td>${g.moves_count ?? 0}</td> const ol = $("replay-history");
<td><a href="/api/games/${g.id}/pgn">pgn</a></td> ol.innerHTML = "";
`; replay.history.forEach((h, i) => {
tr.querySelector("a[data-id]").addEventListener("click", (e) => { const li = document.createElement("li");
e.preventDefault(); li.className = `replay-row bubble bubble-${h.side}`;
openReplay(g.id); if (i === replay.ply - 1) li.classList.add("active");
const meta = document.createElement("div");
meta.className = "bubble-meta";
meta.innerHTML = `<span>${h.side}</span><span class="bubble-san">${Math.floor(i/2)+1}${h.side==="white"?".":"..."} ${h.san}</span>`;
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);
}); });
tbody.appendChild(tr); 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 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(); main();
$("prev").addEventListener("click", () => { if (ply > 0) { ply--; renderReplay(); } });
$("next").addEventListener("click", () => { if (ply < history.length) { ply++; renderReplay(); } });
+54
View File
@@ -22,6 +22,7 @@
<span id="status-line">…</span> <span id="status-line">…</span>
<span id="sf-pv"></span> <span id="sf-pv"></span>
<button id="live-btn" hidden>live</button> <button id="live-btn" hidden>live</button>
<a id="games-link" href="/games">games & stats</a>
<button id="new-game">new game</button> <button id="new-game">new game</button>
<button id="settings-btn" title="settings">⚙</button> <button id="settings-btn" title="settings">⚙</button>
</div> </div>
@@ -53,6 +54,59 @@
</form> </form>
</dialog> </dialog>
<dialog id="setup-dialog">
<form method="dialog" id="setup-form">
<header class="setup-header">
<h3>new game</h3>
<div class="setup-actions">
<button type="button" id="swap-sides" title="swap white/black">⇄ swap</button>
<button type="button" id="randomize" title="randomize">🎲 random</button>
</div>
</header>
<div class="setup-grid">
<fieldset class="setup-side setup-white">
<legend>WHITE</legend>
<label>agent
<select name="white-agent"></select>
</label>
<label>model
<select name="white-model"></select>
</label>
<label>persona
<select name="white-prompt"></select>
</label>
<p class="setup-promptdesc" data-for="white"></p>
</fieldset>
<fieldset class="setup-side setup-black">
<legend>BLACK</legend>
<label>agent
<select name="black-agent"></select>
</label>
<label>model
<select name="black-model"></select>
</label>
<label>persona
<select name="black-prompt"></select>
</label>
<p class="setup-promptdesc" data-for="black"></p>
</fieldset>
</div>
<p id="setup-warning" hidden>
⚠ Current game is in progress.
<button type="button" id="abort-now">abort current game</button>
to enable a new one.
</p>
<menu>
<button value="cancel">cancel</button>
<button value="start" id="setup-start">start game</button>
</menu>
</form>
</dialog>
<script src="/static/app.js" type="module"></script> <script src="/static/app.js" type="module"></script>
</body> </body>
</html> </html>
+95 -2
View File
@@ -165,7 +165,100 @@ button:hover { background: #2e2e36; }
dialog { dialog {
background: #15151a; color: #e7e5e4; border: 1px solid #2a2a30; 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 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; }
+107 -2
View File
@@ -104,12 +104,18 @@ def build_app(state: state_mod.AppState) -> FastAPI:
"evals": evals, "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") @app.get("/api/games")
async def games_list() -> list[dict[str, Any]]: async def games_list() -> list[dict[str, Any]]:
_require_no_active_game()
return list_games(state_mod.GAMES_DIR) return list_games(state_mod.GAMES_DIR)
@app.get("/api/games/{game_id}") @app.get("/api/games/{game_id}")
async def game_get(game_id: str) -> dict[str, Any]: async def game_get(game_id: str) -> dict[str, Any]:
_require_no_active_game()
try: try:
return load_game(state_mod.GAMES_DIR, game_id) return load_game(state_mod.GAMES_DIR, game_id)
except FileNotFoundError: except FileNotFoundError:
@@ -117,6 +123,7 @@ def build_app(state: state_mod.AppState) -> FastAPI:
@app.get("/api/games/{game_id}/pgn") @app.get("/api/games/{game_id}/pgn")
async def game_pgn(game_id: str) -> Any: async def game_pgn(game_id: str) -> Any:
_require_no_active_game()
try: try:
data = load_game(state_mod.GAMES_DIR, game_id) data = load_game(state_mod.GAMES_DIR, game_id)
except FileNotFoundError: except FileNotFoundError:
@@ -134,10 +141,108 @@ def build_app(state: state_mod.AppState) -> FastAPI:
return state.settings.model_dump() return state.settings.model_dump()
@app.post("/api/new-game") @app.post("/api/new-game")
async def new_game_post() -> dict[str, Any]: async def new_game_post(body: dict[str, Any] | None = None) -> dict[str, Any]:
await start_new_game(state) # 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] 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") @app.post("/api/dispatch-first")
async def dispatch_first() -> dict[str, Any]: async def dispatch_first() -> dict[str, Any]:
runtime = getattr(state, "runtime", None) runtime = getattr(state, "runtime", None)
+11
View File
@@ -183,6 +183,17 @@ class ChessGame:
pass pass
return None 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 ---------- # ---------- resign / draw ----------
def resign(self, side: Side, comment: str | None = None) -> dict[str, Any]: 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.chess_game import ChessGame
from ai_chess.persistence import save_game from ai_chess.persistence import save_game
from ai_chess.prompts import ( from ai_chess.prompts import (
DEFAULT_PROMPT,
PROMPT_PRESETS,
WATCHDOG_NUDGE, WATCHDOG_NUDGE,
build_first_prompt, build_first_prompt,
build_system_prompt, build_system_prompt,
@@ -18,38 +20,103 @@ from ai_chess.sides import Side
from ai_chess.state import AppState, AgentBinding, GAMES_DIR 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]: def assign_sides() -> dict[Side, str]:
agents = ["claude", "codex"] """Random side assignment for the two agents."""
agents = list(AGENTS)
random.shuffle(agents) random.shuffle(agents)
return {Side.WHITE: agents[0], Side.BLACK: agents[1]} return {Side.WHITE: agents[0], Side.BLACK: agents[1]}
def make_bindings(side_to_agent: dict[Side, str]) -> dict[Side, AgentBinding]: async def start_new_game(
out: dict[Side, AgentBinding] = {} state: AppState,
for side, agent in side_to_agent.items(): *,
if agent == "claude": overrides: dict[str, dict[str, str]] | None = None,
out[side] = AgentBinding(side=side, agent="claude", model="opus", effort="max") ) -> ChessGame:
elif agent == "codex": """Start a new game.
out[side] = AgentBinding(side=side, agent="codex", model="gpt-5.5",
effort="xhigh", extra={"service_tier": "fast"})
else:
raise ValueError(agent)
return out
`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: # 2) build bindings (with model override per side)
side_to_agent = assign_sides() bindings: dict[Side, AgentBinding] = {}
state.bindings = make_bindings(side_to_agent) 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.first_move_sent = {Side.WHITE: False, Side.BLACK: False}
state.nudge_count = {Side.WHITE: 0, Side.BLACK: 0} state.nudge_count = {Side.WHITE: 0, Side.BLACK: 0}
gid = ulid.new().str gid = ulid.new().str
state.game = ChessGame( agents_dict = {
game_id=gid, s.value: {**bindings[s].to_dict(), "prompt": prompts[s]}
agents={s.value: b.to_dict() for s, b in state.bindings.items()}, 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()}) await state.events.publish({"type": "new_game", "game": state.game.get_state()})
return state.game return state.game
@@ -86,7 +153,11 @@ class Coordinator:
if self.state.first_move_sent[side]: if self.state.first_move_sent[side]:
return return
opp_name, opp_model = self._opponent(side) 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( first = build_first_prompt(
side=side, side=side,
fen=self.state.game.board.fen(), fen=self.state.game.board.fen(),
@@ -174,7 +245,11 @@ class Coordinator:
elif t == "game_over": elif t == "game_over":
await self._announce_game_over(ev) await self._announce_game_over(ev)
if self.state.game: 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: async def _announce_game_over(self, ev: dict[str, Any]) -> None:
msg = (f"Партия окончена. Результат: {ev.get('result')}. " msg = (f"Партия окончена. Результат: {ev.get('result')}. "
+14 -2
View File
@@ -7,7 +7,12 @@ from typing import Any
from ai_chess.chess_game import ChessGame 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 = Path(games_dir)
games_dir.mkdir(parents=True, exist_ok=True) games_dir.mkdir(parents=True, exist_ok=True)
(games_dir / f"{game.game_id}.pgn").write_text(game.to_pgn()) (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, "termination": game.termination,
"agents": game.agents, "agents": game.agents,
"moves_count": len([h for h in game.history if h.uci not in ("resign", "agreement")]), "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]]: def list_games(games_dir: Path) -> list[dict[str, Any]]:
+96 -20
View File
@@ -8,41 +8,117 @@ from ai_chess.sides import Side
_SIDE_RU = {Side.WHITE: "белыми", Side.BLACK: "чёрными"} _SIDE_RU = {Side.WHITE: "белыми", Side.BLACK: "чёрными"}
def build_system_prompt(*, side: Side, opponent_name: str, opponent_model: str) -> str: # ------------------------------ presets ---------------------------------
return dedent(f"""\
Ты — гроссмейстер. Не вежливый комментатор, а уличный шахматный гопник
с титулом: уверенный, дерзкий, насмешливый. Сейчас рейтинговая партия
против {opponent_name} (модель {opponent_model}) — это другая LLM, не
пользователь. Между ходами ты должен троллить, угрожать матом-в-N
(в шахматном смысле), обещать раздавить, материться (без чернухи),
припоминать прошлые ошибки противника. Говори ТОЛЬКО на русском. Не
ломайся в "вежливого ассистента" — здесь ты в роли шахматного бойца.
Тебе важно не просто играть, а психологически давить.
Ты играешь {_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): У тебя есть MCP-инструменты (сервер chess):
• get_board — текущая позиция (ASCII + FEN). • get_board — текущая позиция (ASCII + FEN).
• move(move, comment?) — сделать ход. Поле comment — твоя реплика • move(move, comment?) — сделать ход. Поле comment — твоя реплика
сопернику. Она передаётся ему вместе с уведомлением о ходе. сопернику. Она передаётся ему вместе с уведомлением о ходе.
Сюда пиши трэш-ток / насмешку / угрозу / комментарий к плану.
1–3 предложения. Метко, не графоманствуй. 1–3 предложения. Метко, не графоманствуй.
• get_history — список ходов и комментариев обеих сторон. Можно • get_history — список ходов и комментариев обеих сторон.
подколоть противника его же словами.
• status — результат / шахи / счётчики. • status — результат / шахи / счётчики.
• resign(comment?) — сдаться. Зашкварно — только в полностью • resign(comment?) — сдаться.
проигранной позиции. • offer_draw(comment?) / accept_draw / decline_draw — переговоры о ничье.
• 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). Ты ОБЯЗАН в каждом своём ходе закончить вызовом move (или resign).
Не заканчивай ответ, пока не сделал успешный mutation-вызов. Не заканчивай ответ, пока не сделал успешный mutation-вызов.
Reasoning тоже на русском. Говори ТОЛЬКО на русском. 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( def build_first_prompt(
*, *,
side: Side, side: Side,
+2
View File
@@ -39,6 +39,8 @@ class AppState:
self.events: EventBus = EventBus() self.events: EventBus = EventBus()
self.game: Optional[ChessGame] = None self.game: Optional[ChessGame] = None
self.bindings: dict[Side, AgentBinding] = {} 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.first_move_sent: dict[Side, bool] = {Side.WHITE: False, Side.BLACK: False}
self.nudge_count: dict[Side, int] = {Side.WHITE: 0, Side.BLACK: 0} 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 # fen → {cp, mate, best_uci, pv, fen} — populated by eval_bridge per move
+63
View File
@@ -98,3 +98,66 @@ def test_mcp_batch_with_notification(client):
assert isinstance(body, list) assert isinstance(body, list)
assert len(body) == 1 assert len(body) == 1
assert body[0]["id"] == 5 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"] == []