rewrite: TS monorepo — pi SDK stateless agents, Postgres+pg-boss, SvelteKit themed UI; legacy moved to legacy/

This commit is contained in:
ai-chess
2026-10-18 15:32:39 +03:00
parent e23a07f07b
commit 5be4bd1da4
321 changed files with 37840 additions and 158 deletions
+73
View File
@@ -0,0 +1,73 @@
import type { EngineEval, MoveClass, Side } from "./types.ts";
/**
* Lichess-style accuracy & move classification.
* https://lichess.org/page/accuracy — win% from centipawns, accuracy from win% drop.
*/
export function winPercentWhite(e: Pick<EngineEval, "cp" | "mate">): number {
if (e.mate != null) return e.mate > 0 ? 100 : e.mate < 0 ? 0 : 50;
const cp = Math.max(-1000, Math.min(1000, e.cp ?? 0));
return 50 + 50 * (2 / (1 + Math.exp(-0.00368208 * cp)) - 1);
}
export const winPercentFor = (e: Pick<EngineEval, "cp" | "mate">, side: Side) =>
side === "white" ? winPercentWhite(e) : 100 - winPercentWhite(e);
export function moveAccuracy(winBefore: number, winAfter: number): number {
// both from the mover's POV
const drop = Math.max(0, winBefore - winAfter);
const raw = 103.1668 * Math.exp(-0.04354 * drop) - 3.1669 + 1; // +1 "uncertainty bonus" like lichess
return Math.max(0, Math.min(100, raw));
}
export interface ClassifyInput {
side: Side;
before: EngineEval; // eval of the position before the move (engine best from here)
after: EngineEval; // eval after the move
uci: string;
legalMoveCount: number;
/** heuristic sacrifice flag computed by the caller (material left hanging) */
isSacrifice?: boolean;
}
export function classifyMove(i: ClassifyInput): { cls: MoveClass; accuracy: number; winDrop: number } {
const wb = winPercentFor(i.before, i.side);
const wa = winPercentFor(i.after, i.side);
const drop = Math.max(0, wb - wa);
const accuracy = moveAccuracy(wb, wa);
if (i.legalMoveCount === 1) return { cls: "forced", accuracy: 100, winDrop: 0 };
const isBest = i.before.bestUci != null && i.before.bestUci === i.uci;
// lichess thresholds on winning chances [-1,1]: 0.1/0.2/0.3 -> 5/10/15 win%
if (drop >= 15) return { cls: "blunder", accuracy, winDrop: drop };
if (drop >= 10) return { cls: "mistake", accuracy, winDrop: drop };
if (drop >= 5) return { cls: "inaccuracy", accuracy, winDrop: drop };
if ((isBest || drop < 1) && i.isSacrifice && wb < 92 && wa >= 45) return { cls: "brilliant", accuracy, winDrop: drop };
if (isBest) return { cls: "best", accuracy, winDrop: drop };
return { cls: "good", accuracy, winDrop: drop };
}
/** Lichess game accuracy: mean of volatility-weighted mean and harmonic mean of move accuracies. */
export function gameAccuracy(winsWhitePov: number[], side: Side): number | null {
// winsWhitePov[i] = white win% after ply i (index 0 = start position)
if (winsWhitePov.length < 2) return null;
const n = winsWhitePov.length;
const windowSize = Math.max(2, Math.min(8, Math.floor(n / 10)));
const accs: { acc: number; weight: number }[] = [];
for (let ply = 1; ply < n; ply++) {
const mover: Side = ply % 2 === 1 ? "white" : "black";
if (mover !== side) continue;
const before = mover === "white" ? winsWhitePov[ply - 1] : 100 - winsWhitePov[ply - 1];
const after = mover === "white" ? winsWhitePov[ply] : 100 - winsWhitePov[ply];
const start = Math.max(0, ply - windowSize);
const win = winsWhitePov.slice(start, ply + 1);
const mean = win.reduce((a, b) => a + b, 0) / win.length;
const sd = Math.sqrt(win.reduce((a, b) => a + (b - mean) ** 2, 0) / win.length);
accs.push({ acc: moveAccuracy(before, after), weight: Math.max(0.5, Math.min(12, sd)) });
}
if (!accs.length) return null;
const wsum = accs.reduce((a, b) => a + b.weight, 0);
const weighted = accs.reduce((a, b) => a + b.acc * b.weight, 0) / wsum;
const harmonic = accs.length / accs.reduce((a, b) => a + 1 / Math.max(b.acc, 1), 0);
return (weighted + harmonic) / 2;
}
+104
View File
@@ -0,0 +1,104 @@
import { GameState, moveNumberLabel } from "./position.ts";
import type { GameFlags, Side } from "./types.ts";
export interface TurnContextInput {
state: GameState;
me: { side: Side };
opponent: { name: string };
/** trash-talk line attached to the opponent's last move */
opponentPhrase: string | null;
/** opponent offered a draw with their last move */
drawOffered: boolean;
/** experimental: note this agent left itself on its previous turn */
noteFromSelf: string | null;
flags: GameFlags;
/** show the 50-move reminder from this many moves on */
fiftyMoveThreshold?: number;
}
const SIDE_RU: Record<Side, { gen: string; instr: string }> = {
white: { gen: "белых", instr: "белыми" },
black: { gen: "чёрных", instr: "чёрными" },
};
/**
* The full per-turn context. Every turn the agent starts with an EMPTY conversation: only the
* (cached) system prompt + this message. Everything stateful about chess that is not visible on
* the board is spelled out here — but only when it is relevant, to keep the context clean.
*/
export function renderTurnContext(i: TurnContextInput): string {
const { state } = i;
const me = i.me.side;
const opp = me === "white" ? "black" : "white";
const nextPly = state.ply + 1;
const out: string[] = [];
out.push(`# Ход ${moveNumberLabel(nextPly)} — ты играешь ${SIDE_RU[me].instr}`);
// --- what just happened
const last = state.plies[state.plies.length - 1];
if (!last) {
out.push("Партия начинается. Первый ход за тобой.");
} else {
out.push(`Последний ход соперника (${i.opponent.name}, ${SIDE_RU[opp].gen}): ${state.describePly(last)}.`);
if (i.opponentPhrase?.trim()) out.push(`Соперник пишет тебе: «${i.opponentPhrase.trim()}»`);
}
if (i.flags.notes && i.noteFromSelf?.trim()) {
out.push(`Твоя заметка самому себе с прошлого хода: «${i.noteFromSelf.trim()}»`);
}
// --- position, in a few notations
const diff = state.material("white") - state.material("black");
out.push(
[
"## Позиция",
"Диаграмма (белые внизу; ЗАГЛАВНЫЕ — белые, строчные — чёрные, «.» — пусто):",
"```\n" + state.ascii() + "\n```",
`FEN: ${state.fen()}`,
`Белые: ${state.pieceList("white")}`,
`Чёрные: ${state.pieceList("black")}`,
`Материал (п=1, к/с=3, л=5, ф=9): ${diff === 0 ? "равный" : `${diff > 0 ? "у белых" : "у чёрных"} +${Math.abs(diff)}`}.`,
state.inCheck() ? "**Тебе шах!**" : null,
]
.filter(Boolean)
.join("\n"),
);
// --- rule state, only when it matters
const rules: string[] = [];
rules.push(...state.castlingNotes(me));
const ep = state.enPassantNote();
if (ep) rules.push(ep);
const fifty = state.fiftyMoveNote(i.fiftyMoveThreshold ?? 40);
if (fifty) rules.push(fifty);
const rep = state.repetitionInfo();
if (rep.currentCount >= 2 || rep.threats.length) {
const fenShort = (f: string) => f.split(" ").slice(0, 2).join(" ");
const lines: string[] = ["Повторение позиций (третье повторение одной позиции = автоматическая ничья):"];
if (rep.currentCount >= 2) lines.push(` • Текущая позиция встречается уже ${rep.currentCount}-й раз: ${fenShort(rep.currentFen)}`);
for (const t of rep.threats.slice(0, 4)) {
lines.push(` • ${t.moves.join(" / ")} → позиция ${fenShort(t.fen)}, она уже была ${t.count} раза — этот ход = ничья.`);
}
if (!rep.threats.length) lines.push(" Ни один твой ход прямо сейчас не даёт третьего повторения.");
rules.push(lines.join("\n"));
}
if (i.drawOffered) {
rules.push("Соперник ПРЕДЛОЖИЛ НИЧЬЮ. Принять — инструмент accept_draw. Любой твой ход = отказ.");
}
if (i.flags.cheating) {
rules.push("Режим читерства включён: make_move примет и нелегальный ход в формате откуда-куда (например e2e5). Партия безрейтинговая.");
}
if (rules.length) {
out.push("## Важно сейчас");
out.push(rules.map((r) => (r.startsWith(" ") ? r : `- ${r}`)).join("\n"));
}
out.push("## Твоя задача");
out.push(
[
"1. Найди лучший ход и сделай его через make_move.",
"2. Как только make_move вернул успех — СРАЗУ вызови finish_turn и больше ничего не анализируй.",
].join("\n"),
);
return out.join("\n\n");
}
+66
View File
@@ -0,0 +1,66 @@
/**
* Glicko-2 for a single game treated as one rating period.
* Display rating = r, uncertainty = rd (show "±2·rd").
*/
export interface Rating {
r: number;
rd: number;
vol: number;
}
export const DEFAULT_RATING: Rating = { r: 1500, rd: 350, vol: 0.06 };
const SCALE = 173.7178;
const TAU = 0.5;
const EPS = 1e-6;
const g = (phi: number) => 1 / Math.sqrt(1 + (3 * phi * phi) / (Math.PI * Math.PI));
const E = (mu: number, muj: number, phij: number) => 1 / (1 + Math.exp(-g(phij) * (mu - muj)));
/** score: 1 win, 0.5 draw, 0 loss (from `a`'s perspective) */
export function updateRating(a: Rating, b: Rating, score: number): Rating {
const mu = (a.r - 1500) / SCALE;
const phi = a.rd / SCALE;
const muj = (b.r - 1500) / SCALE;
const phij = b.rd / SCALE;
const gj = g(phij);
const ej = E(mu, muj, phij);
const v = 1 / (gj * gj * ej * (1 - ej));
const delta = v * gj * (score - ej);
// volatility (Illinois algorithm)
const aLn = Math.log(a.vol * a.vol);
const f = (x: number) => {
const ex = Math.exp(x);
return (ex * (delta * delta - phi * phi - v - ex)) / (2 * (phi * phi + v + ex) ** 2) - (x - aLn) / (TAU * TAU);
};
let A = aLn;
let B: number;
if (delta * delta > phi * phi + v) B = Math.log(delta * delta - phi * phi - v);
else {
let k = 1;
while (f(aLn - k * TAU) < 0) k++;
B = aLn - k * TAU;
}
let fA = f(A);
let fB = f(B);
for (let i = 0; i < 100 && Math.abs(B - A) > EPS; i++) {
const C = A + ((A - B) * fA) / (fB - fA);
const fC = f(C);
if (fC * fB <= 0) {
A = B;
fA = fB;
} else fA /= 2;
B = C;
fB = fC;
}
const volNew = Math.exp(A / 2);
const phiStar = Math.sqrt(phi * phi + volNew * volNew);
const phiNew = 1 / Math.sqrt(1 / (phiStar * phiStar) + 1 / v);
const muNew = mu + phiNew * phiNew * gj * (score - ej);
return { r: muNew * SCALE + 1500, rd: Math.max(30, Math.min(350, phiNew * SCALE)), vol: volNew };
}
export function rateGame(white: Rating, black: Rating, result: "1-0" | "0-1" | "1/2-1/2"): { white: Rating; black: Rating } {
const sw = result === "1-0" ? 1 : result === "0-1" ? 0 : 0.5;
return { white: updateRating(white, black, sw), black: updateRating(black, white, 1 - sw) };
}
+6
View File
@@ -0,0 +1,6 @@
export * from "./types.ts";
export * from "./position.ts";
export * from "./context.ts";
export * from "./analysis.ts";
export * from "./glicko2.ts";
export * from "./transcript.ts";
+424
View File
@@ -0,0 +1,424 @@
import { Chess, type Move, type Square, type PieceSymbol, type Color } from "chess.js";
import type { Result, Side, Termination } from "./types.ts";
export const START_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
export interface PlyRecord {
ply: number;
side: Side;
uci: string;
san: string | null; // null for illegal (cheating) relocations
illegal: boolean;
fenBefore: string;
fenAfter: string;
/** verbose chess.js move (legal moves only) */
verbose: Move | null;
captured: PieceSymbol | null;
}
export type MoveAttempt =
| { ok: true; record: PlyRecord }
| { ok: false; reason: "parse" | "illegal" | "game_over"; message: string };
export interface Outcome {
result: Result;
termination: Termination;
}
const PIECE_NAMES_RU: Record<PieceSymbol, { nom: string; acc: string }> = {
k: { nom: "король", acc: "короля" },
q: { nom: "ферзь", acc: "ферзя" },
r: { nom: "ладья", acc: "ладью" },
b: { nom: "слон", acc: "слона" },
n: { nom: "конь", acc: "коня" },
p: { nom: "пешка", acc: "пешку" },
};
export const pieceNameRu = (p: PieceSymbol) => PIECE_NAMES_RU[p].nom;
export const PIECE_VALUES: Record<PieceSymbol, number> = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 };
const sideOf = (c: Color): Side => (c === "w" ? "white" : "black");
const colorOf = (s: Side): Color => (s === "white" ? "w" : "b");
export const moveNumberLabel = (ply: number) => {
const n = Math.floor((ply - 1) / 2) + 1;
return ply % 2 === 1 ? `${n}.` : `${n}...`;
};
/**
* Authoritative game state. Wraps chess.js and adds the bits chess.js does not track the way
* we need: per-position repetition counts (with en-passant normalised), illegal "cheating"
* relocations and a ply log.
*/
export class GameState {
chess: Chess;
readonly startFen: string;
plies: PlyRecord[] = [];
/** position key -> occurrences (including the start position) */
private keyCounts = new Map<string, number>();
/** position key -> a representative full FEN (for display) */
private keyFen = new Map<string, string>();
constructor(startFen: string = START_FEN) {
this.startFen = startFen;
this.chess = new Chess(startFen);
this.bump();
}
static fromUci(moves: { uci: string; illegal?: boolean }[], startFen: string = START_FEN): GameState {
const g = new GameState(startFen);
for (const m of moves) {
const r = m.illegal ? g.applyIllegal(m.uci) : g.tryMove(m.uci);
if (!r.ok) throw new Error(`cannot replay move ${m.uci}: ${r.message}`);
}
return g;
}
get turn(): Side {
return sideOf(this.chess.turn());
}
get ply(): number {
return this.plies.length;
}
fen(): string {
return this.chess.fen();
}
halfmoveClock(): number {
return Number(this.chess.fen().split(" ")[4] ?? 0);
}
fullmoveNumber(): number {
return Number(this.chess.fen().split(" ")[5] ?? 1);
}
inCheck(): boolean {
try {
return this.chess.inCheck();
} catch {
return false;
}
}
legalMoves(): Move[] {
try {
return this.chess.moves({ verbose: true });
} catch {
return [];
}
}
// ---------------------------------------------------------------- keys
positionKey(chess: Chess = this.chess): string {
const [placement, turn, castling, ep] = chess.fen().split(" ");
let epKey = "-";
if (ep && ep !== "-") {
try {
if (chess.moves({ verbose: true }).some((m) => m.isEnPassant())) epKey = ep;
} catch {
/* illegal position */
}
}
return `${placement} ${turn} ${castling} ${epKey}`;
}
private bump() {
const k = this.positionKey();
this.keyCounts.set(k, (this.keyCounts.get(k) ?? 0) + 1);
if (!this.keyFen.has(k)) this.keyFen.set(k, this.chess.fen());
}
repetitionCount(key = this.positionKey()): number {
return this.keyCounts.get(key) ?? 0;
}
// ---------------------------------------------------------------- moves
/** Parse SAN / UCI / sloppy input into a legal chess.js move. */
parseMove(input: string): Move | null {
const raw = input.trim().replace(/[!?]+$/g, "").replace(/^0-0-0/, "O-O-O").replace(/^0-0/, "O-O");
const tmp = new Chess(this.chess.fen());
try {
return tmp.move(raw);
} catch {
/* not SAN */
}
const m = /^([a-h][1-8])\s*[-x:]?\s*([a-h][1-8])\s*=?\s*([qrbnQRBN])?\+?#?$/.exec(raw);
if (m) {
try {
return new Chess(this.chess.fen()).move({ from: m[1] as Square, to: m[2] as Square, promotion: m[3]?.toLowerCase() as PieceSymbol | undefined ?? "q" });
} catch {
return null;
}
}
return null;
}
/** Human-readable explanation why `input` is not a legal move (no legal-move list — the agent must think). */
explainIllegal(input: string): string {
const raw = input.trim();
const uci = /^([a-h][1-8])\s*[-x:]?\s*([a-h][1-8])/.exec(raw);
const side = this.turn;
const checkNote = this.inCheck() ? " Обрати внимание: тебе сейчас шах." : "";
if (uci) {
const from = uci[1] as Square;
const to = uci[2] as Square;
const piece = this.chess.get(from);
if (!piece) return `На ${from} нет фигуры.${checkNote}`;
if (sideOf(piece.color) !== side) return `На ${from} стоит фигура соперника (${pieceNameRu(piece.type)}).${checkNote}`;
return `${capitalize(pieceNameRu(piece.type))} ${from} не может пойти на ${to} в этой позиции.${checkNote}`;
}
const sanPiece = /^([KQRBN])?([a-h])?([1-8])?x?([a-h][1-8])/.exec(raw.replace(/^0-0/, "O-O"));
if (sanPiece) {
const type = (sanPiece[1]?.toLowerCase() ?? "p") as PieceSymbol;
const to = sanPiece[4] as Square;
const has = this.chess
.board()
.flat()
.some((sq) => sq && sq.type === type && sideOf(sq.color) === side);
if (!has) return `У тебя нет фигуры «${pieceNameRu(type)}».${checkNote}`;
return `Ни одна твоя фигура «${pieceNameRu(type)}» не может легально пойти на ${to}.${checkNote}`;
}
if (/^O-O/i.test(raw)) return `Рокировка сейчас невозможна.${checkNote}`;
return `Не удалось разобрать ход «${raw}». Используй SAN (Nf3, exd5, O-O, e8=Q) или UCI (g1f3, e7e8q).${checkNote}`;
}
tryMove(input: string): MoveAttempt {
if (this.outcome()) return { ok: false, reason: "game_over", message: "Партия уже окончена." };
const mv = this.parseMove(input);
if (!mv) {
const parseable = /[a-h][1-8]|O-O/i.test(input);
return { ok: false, reason: parseable ? "illegal" : "parse", message: this.explainIllegal(input) };
}
const fenBefore = this.chess.fen();
const side = this.turn;
const applied = this.chess.move({ from: mv.from, to: mv.to, promotion: mv.promotion });
const rec: PlyRecord = {
ply: this.plies.length + 1,
side,
uci: applied.lan,
san: applied.san,
illegal: false,
fenBefore,
fenAfter: this.chess.fen(),
verbose: applied,
captured: applied.captured ?? null,
};
this.plies.push(rec);
this.bump();
return { ok: true, record: rec };
}
/**
* Cheating mode: relocate a piece from->to regardless of rules. Accepts UCI-ish input
* ("e2e4", "e2-e4", "e7e8q"). Legal moves should go through tryMove first.
*/
applyIllegal(input: string): MoveAttempt {
const m = /^([a-h][1-8])\s*[-x:]?\s*([a-h][1-8])\s*=?\s*([qrbnQRBN])?/.exec(input.trim());
if (!m) return { ok: false, reason: "parse", message: "В режиме читерства нелегальный ход нужно указать как откуда-куда (например e2e5)." };
const from = m[1] as Square;
const to = m[2] as Square;
const piece = this.chess.get(from);
const side = this.turn;
if (!piece || sideOf(piece.color) !== side) return { ok: false, reason: "illegal", message: `На ${from} нет твоей фигуры — двигать можно только свои.` };
if (from === to) return { ok: false, reason: "illegal", message: "Фигура должна сдвинуться." };
const fenBefore = this.chess.fen();
const target = this.chess.get(to);
if (target && sideOf(target.color) === side) return { ok: false, reason: "illegal", message: "Нельзя бить свою фигуру даже в режиме читерства." };
const parts = fenBefore.split(" ");
const board = new Chess(fenBefore, { skipValidation: true });
board.remove(from);
if (target) board.remove(to);
let placed: PieceSymbol = piece.type;
if (piece.type === "p" && (to[1] === "8" || to[1] === "1")) placed = (m[3]?.toLowerCase() as PieceSymbol) ?? "q";
board.put({ type: placed, color: piece.color }, to);
const placement = board.fen().split(" ")[0];
let castling = parts[2] ?? "-";
const strip = (chars: string) => {
for (const c of chars) castling = castling.replace(c, "");
};
if (piece.type === "k") strip(piece.color === "w" ? "KQ" : "kq");
for (const sq of [from, to]) {
if (sq === "h1") strip("K");
if (sq === "a1") strip("Q");
if (sq === "h8") strip("k");
if (sq === "a8") strip("q");
}
if (!castling) castling = "-";
const half = piece.type === "p" || target ? 0 : Number(parts[4] ?? 0) + 1;
const full = Number(parts[5] ?? 1) + (side === "black" ? 1 : 0);
const fenAfter = `${placement} ${side === "white" ? "b" : "w"} ${castling} - ${half} ${full}`;
this.chess = new Chess(fenAfter, { skipValidation: true });
const rec: PlyRecord = {
ply: this.plies.length + 1,
side,
uci: `${from}${to}${placed !== piece.type ? placed : ""}`,
san: null,
illegal: true,
fenBefore,
fenAfter,
verbose: null,
captured: target?.type ?? null,
};
this.plies.push(rec);
this.bump();
return { ok: true, record: rec };
}
// ---------------------------------------------------------------- outcome
outcome(): Outcome | null {
const last = this.plies[this.plies.length - 1];
if (last?.illegal && last.captured === "k") {
return { result: last.side === "white" ? "1-0" : "0-1", termination: "king_captured" };
}
try {
if (this.chess.isCheckmate()) return { result: this.turn === "white" ? "0-1" : "1-0", termination: "checkmate" };
if (this.chess.isStalemate()) return { result: "1/2-1/2", termination: "stalemate" };
if (this.chess.isInsufficientMaterial()) return { result: "1/2-1/2", termination: "insufficient_material" };
} catch {
/* illegal positions in cheating mode */
}
if (this.repetitionCount() >= 3) return { result: "1/2-1/2", termination: "threefold_repetition" };
if (this.halfmoveClock() >= 100) return { result: "1/2-1/2", termination: "fifty_move_rule" };
return null;
}
// ---------------------------------------------------------------- rule hints
/** Castling clarifications for the side to move — only when the position *looks* castle-able. */
castlingNotes(side: Side = this.turn): string[] {
const c = colorOf(side);
const rank = side === "white" ? "1" : "8";
const king = this.chess.get(`e${rank}` as Square);
if (!king || king.type !== "k" || king.color !== c) return [];
const rights = this.chess.getCastlingRights(c);
const empty = (files: string) => [...files].every((f) => !this.chess.get(`${f}${rank}` as Square));
const rookAt = (f: string) => {
const p = this.chess.get(`${f}${rank}` as Square);
return !!p && p.type === "r" && p.color === c;
};
const notes: string[] = [];
const check = this.inCheck();
if (rookAt("h") && empty("fg")) {
notes.push(
rights.k
? `Короткая рокировка (O-O): король и ладья h${rank} ещё не ходили — правами разрешена${check ? ", но сейчас шах, поэтому этим ходом нельзя" : " (если король не проходит через битое поле)"}.`
: `Короткая рокировка (O-O) НЕВОЗМОЖНА: король или ладья h${rank} уже ходили (даже если вернулись на место).`,
);
}
if (rookAt("a") && empty("bcd")) {
notes.push(
rights.q
? `Длинная рокировка (O-O-O): король и ладья a${rank} ещё не ходили — правами разрешена${check ? ", но сейчас шах, поэтому этим ходом нельзя" : " (если король не проходит через битое поле)"}.`
: `Длинная рокировка (O-O-O) НЕВОЗМОЖНА: король или ладья a${rank} уже ходили (даже если вернулись на место).`,
);
}
return notes;
}
enPassantNote(): string | null {
const ep = this.legalMoves().filter((m) => m.isEnPassant());
if (!ep.length) return null;
return `Взятие на проходе сейчас возможно: ${ep.map((m) => m.san).join(", ")}.`;
}
/** 50-move rule reminder once the counter is high enough. */
fiftyMoveNote(thresholdMoves = 40): string | null {
const moves = Math.floor(this.halfmoveClock() / 2);
if (moves < thresholdMoves) return null;
return `Правило 50 ходов: уже ${moves} из 50 ходов подряд без взятий и ходов пешками. На 50-м — автоматическая ничья. Взятие или ход пешкой обнуляют счётчик.`;
}
/**
* Repetition state relevant to the side to move: was the current position already seen twice,
* and which moves would produce a position for the third time (= automatic draw).
*/
repetitionInfo(): {
anyRepeated: boolean;
currentCount: number;
currentFen: string;
threats: { fen: string; count: number; moves: string[] }[];
drawingMoves: string[];
} {
const anyRepeated = [...this.keyCounts.values()].some((n) => n >= 2);
const threats = new Map<string, { fen: string; count: number; moves: string[] }>();
if (anyRepeated) {
for (const m of this.legalMoves()) {
const t = new Chess(this.chess.fen());
t.move({ from: m.from, to: m.to, promotion: m.promotion });
const k = this.positionKey(t);
const n = this.keyCounts.get(k) ?? 0;
if (n >= 2) {
const e = threats.get(k) ?? { fen: this.keyFen.get(k) ?? t.fen(), count: n, moves: [] };
e.moves.push(m.san);
threats.set(k, e);
}
}
}
const list = [...threats.values()];
return { anyRepeated, currentCount: this.repetitionCount(), currentFen: this.chess.fen(), threats: list, drawingMoves: list.flatMap((t) => t.moves) };
}
// ---------------------------------------------------------------- rendering
ascii(): string {
const rows: string[] = [" +-----------------+"];
const b = this.chess.board();
for (let r = 0; r < 8; r++) {
const cells = b[r].map((sq) => (sq ? (sq.color === "w" ? sq.type.toUpperCase() : sq.type) : "."));
rows.push(`${8 - r} | ${cells.join(" ")} |`);
}
rows.push(" +-----------------+", " a b c d e f g h");
return rows.join("\n");
}
pieceList(side: Side): string {
const c = colorOf(side);
const order: PieceSymbol[] = ["k", "q", "r", "b", "n"];
const by: Record<string, string[]> = { k: [], q: [], r: [], b: [], n: [], p: [] };
for (const row of this.chess.board()) for (const sq of row) if (sq && sq.color === c) by[sq.type].push(sq.square);
const sortSq = (a: string, b: string) => (a[0] === b[0] ? a[1].localeCompare(b[1]) : a[0].localeCompare(b[0]));
const pieces = order.flatMap((t) => by[t].sort(sortSq).map((s) => `${t.toUpperCase()}${s}`));
const pawns = by.p.sort(sortSq);
return `${pieces.join(" ")}${pawns.length ? `; пешки ${pawns.join(" ")}` : "; пешек нет"}`;
}
material(side: Side): number {
const c = colorOf(side);
let sum = 0;
for (const row of this.chess.board()) for (const sq of row) if (sq && sq.color === c) sum += PIECE_VALUES[sq.type];
return sum;
}
/** e.g. "22. gxh3 — пешка g2→h3, взял коня" */
describePly(rec: PlyRecord): string {
const label = `${moveNumberLabel(rec.ply)} ${rec.san ?? rec.uci}`;
if (rec.illegal) {
const from = rec.uci.slice(0, 2);
const to = rec.uci.slice(2, 4);
return `${label} — НЕЛЕГАЛЬНЫЙ ход (режим читерства): фигура ${from}→${to}${rec.captured ? `, снял ${PIECE_NAMES_RU[rec.captured].acc}` : ""}`;
}
const v = rec.verbose!;
const parts: string[] = [];
if (v.isKingsideCastle()) parts.push("короткая рокировка");
else if (v.isQueensideCastle()) parts.push("длинная рокировка");
else parts.push(`${pieceNameRu(v.piece)} ${v.from}→${v.to}`);
if (v.isEnPassant()) parts.push("взятие на проходе");
else if (v.captured) parts.push(`взял ${PIECE_NAMES_RU[v.captured].acc}`);
if (v.promotion) parts.push(`превращение в ${PIECE_NAMES_RU[v.promotion].acc}`);
if (v.san.endsWith("#")) parts.push("мат");
else if (v.san.endsWith("+")) parts.push("шах");
return `${label} — ${parts.join(", ")}`;
}
/** SAN move list "1. e4 e5 2. Nf3 ..." */
sanMoveList(): string {
const out: string[] = [];
for (const p of this.plies) {
const mv = p.san ?? `${p.uci}(!)`;
if (p.side === "white") out.push(`${moveNumberLabel(p.ply)} ${mv}`);
else out.push(p.ply === 1 || out.length === 0 ? `${moveNumberLabel(p.ply)} ${mv}` : mv);
}
return out.join(" ");
}
}
function capitalize(s: string) {
return s.charAt(0).toUpperCase() + s.slice(1);
}
+132
View File
@@ -0,0 +1,132 @@
import { moveNumberLabel } from "./position.ts";
import type { EngineEval, MoveClass, Result, Side, Termination } from "./types.ts";
export interface RecordPly {
ply: number;
side: Side;
san: string | null;
uci: string;
fenAfter: string;
phrase: string | null;
illegal: boolean;
offeredDraw?: boolean;
eval?: EngineEval | null;
classification?: MoveClass | null;
accuracy?: number | null;
}
export interface GameRecord {
white: string;
black: string;
plies: RecordPly[];
result?: Result | null;
termination?: Termination | null;
startedAt?: string;
event?: string;
}
const CLASS_RU: Record<MoveClass, string> = {
best: "лучший ход",
brilliant: "блестяще!!",
great: "отлично!",
good: "нормально",
inaccuracy: "неточность ?!",
mistake: "ошибка ?",
blunder: "зевок ??",
book: "теория",
forced: "единственный ход",
};
export const classLabelRu = (c: MoveClass) => CLASS_RU[c];
const CLASS_NAG: Partial<Record<MoveClass, string>> = { brilliant: "!!", great: "!", inaccuracy: "?!", mistake: "?", blunder: "??" };
export function formatEval(e?: EngineEval | null): string {
if (!e) return "";
if (e.mate != null) return e.mate > 0 ? `#${e.mate}` : `#-${Math.abs(e.mate)}`;
const v = (e.cp ?? 0) / 100;
return `${v > 0 ? "+" : ""}${v.toFixed(2)}`;
}
const TERMINATION_RU: Record<Termination, string> = {
checkmate: "мат",
stalemate: "пат",
insufficient_material: "недостаточно материала",
threefold_repetition: "троекратное повторение",
fifty_move_rule: "правило 50 ходов",
resignation: "сдача",
agreement: "ничья по соглашению",
forfeit_illegal: "поражение за нелегальные ходы",
forfeit_no_move: "поражение — не сделал ход",
king_captured: "взятие короля (читерство)",
aborted: "прервана",
error: "техническая ошибка",
};
export const terminationRu = (t: Termination) => TERMINATION_RU[t];
/** Human-readable transcript: one ply per line with trash-talk and (optionally) engine verdicts. */
export function humanTranscript(rec: GameRecord, opts: { withAnalysis?: boolean } = {}): string {
const lines: string[] = [`Белые: ${rec.white}`, `Чёрные: ${rec.black}`, ""];
for (const p of rec.plies) {
const who = p.side === "white" ? rec.white : rec.black;
let line = `${moveNumberLabel(p.ply)} ${p.san ?? `${p.uci} (НЕЛЕГАЛЬНЫЙ)`}`;
if (opts.withAnalysis && (p.eval || p.classification)) {
const bits = [p.classification ? classLabelRu(p.classification) : null, p.eval ? `оценка ${formatEval(p.eval)}` : null].filter(Boolean);
line += ` [${bits.join(", ")}]`;
}
if (p.offeredDraw) line += " (предложил ничью)";
if (p.phrase) line += `\n ${who}: «${p.phrase}»`;
lines.push(line);
}
if (rec.result && rec.result !== "*") {
lines.push("", `Итог: ${rec.result}${rec.termination ? ` (${terminationRu(rec.termination)})` : ""}`);
}
return lines.join("\n");
}
export function machineTranscript(rec: GameRecord): string {
return JSON.stringify(
{
white: rec.white,
black: rec.black,
result: rec.result ?? null,
termination: rec.termination ?? null,
moves: rec.plies.map((p) => ({
ply: p.ply,
side: p.side,
san: p.san,
uci: p.uci,
fen_after: p.fenAfter,
phrase: p.phrase,
illegal: p.illegal || undefined,
eval: p.eval ? formatEval(p.eval) : undefined,
best_reply_uci: p.eval?.bestUci ?? undefined,
class: p.classification ?? undefined,
accuracy: p.accuracy != null ? Math.round(p.accuracy) : undefined,
})),
},
null,
1,
);
}
const pgnEscape = (s: string) => s.replace(/[{}]/g, "").replace(/\s+/g, " ").trim();
export function toPgn(rec: GameRecord): string {
const date = (rec.startedAt ?? new Date().toISOString()).slice(0, 10).replace(/-/g, ".");
const headers = [
["Event", rec.event ?? "AI·CHESS"],
["Site", "chess.danosito.com"],
["Date", date],
["White", rec.white],
["Black", rec.black],
["Result", rec.result ?? "*"],
...(rec.termination ? [["Termination", terminationRu(rec.termination)]] : []),
];
const body: string[] = [];
for (const p of rec.plies) {
if (p.side === "white" || body.length === 0) body.push(moveNumberLabel(p.ply));
body.push((p.san ?? p.uci) + (p.classification ? (CLASS_NAG[p.classification] ?? "") : ""));
if (p.phrase) body.push(`{ ${pgnEscape(p.phrase)} }`);
}
body.push(rec.result ?? "*");
return headers.map(([k, v]) => `[${k} "${String(v).replace(/"/g, "'")}"]`).join("\n") + "\n\n" + body.join(" ") + "\n";
}
+118
View File
@@ -0,0 +1,118 @@
// Shared domain types — used by the server and the web app.
export type Side = "white" | "black";
export const otherSide = (s: Side): Side => (s === "white" ? "black" : "white");
/** Per-match experimental switches. Anything here (except `notes`/`extraTools`) makes the game unrated. */
export interface GameFlags {
/** Agent may leave a note for its next turn (finish_turn.note_to_self). */
notes: boolean;
/** Agent gets get_move_history + python sandbox tools. */
extraTools: boolean;
/** Illegal moves are applied as raw piece relocations. Unrated. */
cheating: boolean;
}
export const DEFAULT_FLAGS: GameFlags = { notes: false, extraTools: false, cheating: false };
export const isRated = (f: GameFlags) => !f.cheating;
export type GameStatus = "pending" | "running" | "finished" | "aborted";
export type Termination =
| "checkmate"
| "stalemate"
| "insufficient_material"
| "threefold_repetition"
| "fifty_move_rule"
| "resignation"
| "agreement"
| "forfeit_illegal" // too many illegal move attempts in one turn
| "forfeit_no_move" // agent kept ending its turn without moving
| "king_captured" // cheating mode only
| "aborted"
| "error";
export type Result = "1-0" | "0-1" | "1/2-1/2" | "*";
export type MoveClass = "best" | "brilliant" | "great" | "good" | "inaccuracy" | "mistake" | "blunder" | "book" | "forced";
export interface EngineEval {
/** centipawns from White's POV (null when mate is set) */
cp: number | null;
/** mate in N from White's POV (positive = White mates) */
mate: number | null;
bestUci: string | null;
pv: string[];
depth: number;
}
/** A tool call as seen by spectators. */
export interface ToolCallLog {
id: string;
name: string;
args: unknown;
result?: string;
isError?: boolean;
startedAt: number;
endedAt?: number;
}
export interface Usage {
input: number;
output: number;
cacheRead: number;
cacheWrite: number;
reasoning: number;
cost: number;
}
export const emptyUsage = (): Usage => ({ input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0, cost: 0 });
export const addUsage = (a: Usage, b: Partial<Usage>): Usage => ({
input: a.input + (b.input ?? 0),
output: a.output + (b.output ?? 0),
cacheRead: a.cacheRead + (b.cacheRead ?? 0),
cacheWrite: a.cacheWrite + (b.cacheWrite ?? 0),
reasoning: a.reasoning + (b.reasoning ?? 0),
cost: a.cost + (b.cost ?? 0),
});
/** One step of an agent turn transcript, persisted for the "thoughts" panel. */
export type TranscriptItem =
| { kind: "context"; text: string; at: number }
| { kind: "thinking"; text: string; at: number }
| { kind: "text"; text: string; at: number }
| { kind: "tool"; call: ToolCallLog; at: number }
| { kind: "nudge"; text: string; at: number }
| { kind: "error"; text: string; at: number };
/** Live events published on the bus (channel = game id or "lobby"). */
export type GameEvent =
| { type: "turn_start"; gameId: string; ply: number; side: Side; playerId: string; at: number }
| { type: "thinking_delta"; gameId: string; ply: number; delta: string }
| { type: "text_delta"; gameId: string; ply: number; delta: string }
| { type: "tool_start"; gameId: string; ply: number; call: ToolCallLog }
| { type: "tool_end"; gameId: string; ply: number; call: ToolCallLog }
| { type: "move"; gameId: string; move: MoveDTO }
| { type: "eval"; gameId: string; ply: number; eval: EngineEval; classification?: MoveClass | null; accuracy?: number | null }
| { type: "turn_end"; gameId: string; ply: number; usage: Usage }
| { type: "draw_offer"; gameId: string; by: Side }
| { type: "game_over"; gameId: string; result: Result; termination: Termination }
| { type: "interview"; gameId: string; side: Side; text: string }
| { type: "thumbnail"; gameId: string; url: string; caption: string }
| { type: "status"; gameId: string; status: GameStatus; note?: string };
export interface MoveDTO {
ply: number; // 1-based half-move index
side: Side;
san: string | null; // null for illegal (cheating) moves
uci: string;
fenAfter: string;
phrase: string | null;
note: string | null; // note_to_self (only visible to spectators after the game? — shown live, it's fun)
offeredDraw: boolean;
illegal: boolean;
thinkMs: number;
usage: Usage;
eval?: EngineEval | null;
classification?: MoveClass | null;
accuracy?: number | null;
createdAt: string;
}