ChessUp/src/server/stockfish.ts

783 lines
23 KiB
TypeScript

import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process';
import { createRequire } from 'node:module';
import fs from 'node:fs';
import path from 'node:path';
import readline from 'node:readline';
import { Chess } from '../shared/chess';
import type { Color, GameAnalysisReport, MultiPvLine, PlyAnalysis } from '../shared/types';
import {
classifyMove,
computeMoveAccuracy,
computePlayerSummary,
cpToWinPercent,
winPercentForSide
} from '../shared/winProb';
interface BotTuning {
skillLevel: number;
depth: number;
movetime: number;
multiPv: number;
weights?: number[];
}
const BOT_TUNING: Record<number, BotTuning> = {
1: { skillLevel: 0, depth: 1, movetime: 60, multiPv: 4, weights: [0.15, 0.25, 0.3, 0.3] },
2: { skillLevel: 2, depth: 2, movetime: 90, multiPv: 3, weights: [0.35, 0.4, 0.25] },
3: { skillLevel: 5, depth: 3, movetime: 120, multiPv: 1 },
4: { skillLevel: 8, depth: 5, movetime: 200, multiPv: 1 },
5: { skillLevel: 11, depth: 7, movetime: 300, multiPv: 1 },
6: { skillLevel: 14, depth: 10, movetime: 450, multiPv: 1 },
7: { skillLevel: 17, depth: 13, movetime: 700, multiPv: 1 },
8: { skillLevel: 20, depth: 16, movetime: 1100, multiPv: 1 }
};
export function resolveStockfishScriptPath(): string {
const req = createRequire(__filename);
const pkgJsonPath = req.resolve('stockfish/package.json');
const pkgDir = path.dirname(pkgJsonPath);
const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8')) as { buildVersion?: string };
const binDir = path.join(pkgDir, 'bin');
if (pkg.buildVersion) {
const preferred = [
`stockfish-${pkg.buildVersion}-lite-single.js`,
`stockfish-${pkg.buildVersion}-single.js`,
`stockfish-${pkg.buildVersion}-lite.js`,
`stockfish-${pkg.buildVersion}.js`
];
for (const file of preferred) {
const full = path.join(binDir, file);
if (fs.existsSync(full)) return full;
}
}
if (fs.existsSync(binDir)) {
const entries = fs.readdirSync(binDir);
const liteSingle = entries.find((e) => e.endsWith('-lite-single.js'));
if (liteSingle) return path.join(binDir, liteSingle);
const single = entries.find((e) => e.endsWith('-single.js'));
if (single) return path.join(binDir, single);
const anyJs = entries.find((e) => e.endsWith('.js'));
if (anyJs) return path.join(binDir, anyJs);
}
throw new Error('Could not locate a runnable Stockfish engine JS file inside node_modules/stockfish/bin');
}
interface ParsedInfoLine {
depth: number;
multipv: number;
scoreCp: number | null;
scoreMate: number | null;
isBound: boolean;
pvUci: string[];
}
function parseUciInfoLine(line: string): ParsedInfoLine | null {
if (!line.startsWith('info ')) return null;
const tokens = line.trim().split(/\s+/);
let depth = 0;
let multipv = 1;
let scoreCp: number | null = null;
let scoreMate: number | null = null;
let isBound = false;
let pvUci: string[] = [];
for (let i = 1; i < tokens.length; i++) {
const tok = tokens[i]!;
if (tok === 'depth' && i + 1 < tokens.length) {
depth = parseInt(tokens[++i]!, 10) || 0;
} else if (tok === 'multipv' && i + 1 < tokens.length) {
multipv = parseInt(tokens[++i]!, 10) || 1;
} else if (tok === 'score' && i + 2 < tokens.length) {
const kind = tokens[++i]!;
const val = parseInt(tokens[++i]!, 10);
if (!Number.isNaN(val)) {
if (kind === 'cp') {
scoreCp = val;
scoreMate = null;
} else if (kind === 'mate') {
scoreMate = val;
scoreCp = null;
}
}
if (tokens[i + 1] === 'lowerbound' || tokens[i + 1] === 'upperbound') {
isBound = true;
}
} else if (tok === 'pv') {
pvUci = tokens.slice(i + 1);
break;
}
}
if (depth <= 0 && pvUci.length === 0) return null;
if (scoreCp === null && scoreMate === null) return null;
return { depth, multipv, scoreCp, scoreMate, isBound, pvUci };
}
function pvUciToSan(fen: string, pvUci: ReadonlyArray<string>, maxPlies: number = 10): string[] {
try {
const chess = new Chess(fen);
const out: string[] = [];
const limit = Math.min(pvUci.length, maxPlies);
for (let i = 0; i < limit; i++) {
const mv = chess.moveUci(pvUci[i]!);
if (!mv) break;
out.push(mv.san);
}
return out;
} catch {
return [];
}
}
interface SearchRequest {
fen: string;
depth?: number;
movetime?: number;
skillLevel: number;
multiPv: number;
newGame?: boolean;
cancelSignal?: AbortSignal;
onUpdate?: (lines: MultiPvLine[], depth: number) => void;
}
interface SearchResult {
bestMove: string | null;
lines: MultiPvLine[];
}
class StockfishWorker {
private proc: ChildProcessWithoutNullStreams | null = null;
private rl: readline.Interface | null = null;
private readyPromise: Promise<void> | null = null;
private currentSkillLevel = 20;
private currentMultiPv = 1;
private closed = false;
private exited = false;
private busy = false;
private lineHandler: ((line: string) => void) | null = null;
private exitHandler: ((err: Error) => void) | null = null;
constructor(private readonly scriptPath: string) {}
async init(): Promise<void> {
if (this.readyPromise) return this.readyPromise;
this.readyPromise = new Promise<void>((resolve, reject) => {
const child = spawn(process.execPath, [this.scriptPath], {
stdio: ['pipe', 'pipe', 'pipe']
});
this.proc = child;
this.rl = readline.createInterface({ input: child.stdout });
let initialized = false;
let sawUciOk = false;
const onLine = (rawLine: string) => {
const line = rawLine.trim();
if (!line) return;
if (!initialized) {
if (line === 'uciok' && !sawUciOk) {
sawUciOk = true;
this.send('setoption name Hash value 32');
this.send('setoption name Skill Level value 20');
this.send('setoption name MultiPV value 1');
this.send('isready');
} else if (line === 'readyok' && sawUciOk) {
initialized = true;
resolve();
}
return;
}
if (this.lineHandler) {
this.lineHandler(line);
}
};
this.rl.on('line', onLine);
child.stderr.on('data', () => {
// Ignore non-fatal WASM info/warnings
});
child.on('error', (err) => {
if (!initialized) {
reject(err);
} else if (this.exitHandler) {
this.exitHandler(err);
}
});
child.on('exit', (code, signal) => {
this.exited = true;
const err = new Error(`Stockfish worker exited (code=${code}, signal=${signal})`);
if (!initialized) {
reject(err);
} else if (!this.closed && this.exitHandler) {
this.exitHandler(err);
}
this.cleanupHandles();
});
this.send('uci');
});
return this.readyPromise;
}
isBusy(): boolean {
return this.busy;
}
isAlive(): boolean {
if (this.closed || this.exited) return false;
if (this.proc && this.proc.exitCode !== null) return false;
return true;
}
private send(cmd: string): void {
if (this.proc && this.proc.stdin.writable) {
this.proc.stdin.write(cmd + '\n');
}
}
private cleanupHandles(): void {
try {
this.rl?.close();
} catch {
// Ignore
}
this.rl = null;
this.proc = null;
this.readyPromise = null;
}
async search(req: SearchRequest): Promise<SearchResult> {
if (this.closed) {
throw new Error('Stockfish worker is closed');
}
if (this.busy) {
throw new Error('Stockfish worker is already busy');
}
this.busy = true;
try {
await this.init();
} catch (err) {
this.busy = false;
throw err;
}
if (this.closed || !this.proc) {
this.busy = false;
throw new Error('Stockfish worker is closed');
}
const chessTurn: Color = req.fen.trim().split(/\s+/)[1] === 'b' ? 'b' : 'w';
const sign = chessTurn === 'w' ? 1 : -1;
return new Promise<SearchResult>((resolve, reject) => {
const pvMap = new Map<number, MultiPvLine>();
let highestDepth = 0;
let stopped = false;
let waitingReady = true;
const finish = (bestMove: string | null) => {
this.lineHandler = null;
this.exitHandler = null;
this.busy = false;
if (req.cancelSignal) {
req.cancelSignal.removeEventListener('abort', onAbort);
}
const sorted = Array.from(pvMap.values()).sort((a, b) => a.multipv - b.multipv);
resolve({ bestMove, lines: sorted });
};
const fail = (err: Error) => {
this.lineHandler = null;
this.exitHandler = null;
this.busy = false;
if (req.cancelSignal) {
req.cancelSignal.removeEventListener('abort', onAbort);
}
reject(err);
};
const onAbort = () => {
if (!stopped && !waitingReady) {
stopped = true;
this.send('stop');
}
};
if (req.cancelSignal) {
if (req.cancelSignal.aborted) {
this.busy = false;
resolve({ bestMove: null, lines: [] });
return;
}
req.cancelSignal.addEventListener('abort', onAbort, { once: true });
}
this.exitHandler = (err) => fail(err);
this.lineHandler = (line: string) => {
if (waitingReady) {
if (line === 'readyok') {
waitingReady = false;
if (req.cancelSignal?.aborted) {
finish(null);
return;
}
this.send(`position fen ${req.fen}`);
const goParts = ['go'];
if (req.depth !== undefined) goParts.push(`depth ${req.depth}`);
if (req.movetime !== undefined) goParts.push(`movetime ${req.movetime}`);
if (req.depth === undefined && req.movetime === undefined) goParts.push('depth 12');
this.send(goParts.join(' '));
}
return;
}
if (line.startsWith('info ')) {
const parsed = parseUciInfoLine(line);
if (!parsed) return;
if (parsed.multipv > req.multiPv) return;
const existing = pvMap.get(parsed.multipv);
// Avoid overwriting an exact score at the same depth with a bound
if (existing && existing.depth === parsed.depth && parsed.isBound) {
return;
}
const scoreCp = parsed.scoreCp !== null ? parsed.scoreCp * sign : null;
const scoreMate = parsed.scoreMate !== null ? parsed.scoreMate * sign : null;
const pvLine: MultiPvLine = {
multipv: parsed.multipv,
depth: parsed.depth,
scoreCp,
scoreMate,
pvUci: parsed.pvUci,
pvSan: pvUciToSan(req.fen, parsed.pvUci, 10)
};
pvMap.set(parsed.multipv, pvLine);
if (parsed.depth > highestDepth) highestDepth = parsed.depth;
if (req.onUpdate && !req.cancelSignal?.aborted) {
const snapshot = Array.from(pvMap.values()).sort((a, b) => a.multipv - b.multipv);
req.onUpdate(snapshot, highestDepth);
}
return;
}
if (line.startsWith('bestmove ')) {
const parts = line.split(/\s+/);
const rawMove = parts[1] || null;
const bestMove = rawMove && rawMove !== '(none)' ? rawMove : null;
finish(bestMove);
}
};
// Configure options cleanly before starting search
if (req.newGame) {
this.send('ucinewgame');
}
if (this.currentSkillLevel !== req.skillLevel) {
this.currentSkillLevel = req.skillLevel;
this.send(`setoption name Skill Level value ${req.skillLevel}`);
}
if (this.currentMultiPv !== req.multiPv) {
this.currentMultiPv = req.multiPv;
this.send(`setoption name MultiPV value ${req.multiPv}`);
}
this.send('isready');
});
}
close(): void {
this.closed = true;
if (this.exitHandler) {
this.exitHandler(new Error('Stockfish worker closed'));
}
if (this.proc) {
try {
this.proc.stdin.write('quit\n');
} catch {
// Ignore
}
const p = this.proc;
setTimeout(() => {
try {
if (p.exitCode === null) p.kill('SIGKILL');
} catch {
// Ignore
}
}, 200).unref();
}
this.cleanupHandles();
}
}
interface QueuedJob {
priority: number; // 1 = bot, 2 = live multipv, 3 = full game analysis
seq: number;
req: SearchRequest;
resolve: (res: SearchResult) => void;
reject: (err: unknown) => void;
}
interface PositionEval {
cp: number | null;
mate: number | null;
bestMoveUci: string | null;
bestMoveSan: string | null;
pvUci: string[];
pvSan: string[];
}
export class StockfishPool {
private readonly scriptPath: string;
private readonly workers: StockfishWorker[] = [];
private readonly queue: QueuedJob[] = [];
private seqCounter = 0;
private shuttingDown = false;
private readonly activeGameAnalyses = new Map<
string,
{ promise: Promise<GameAnalysisReport>; listeners: Set<(done: number, total: number) => void> }
>();
constructor(private readonly workerCount: number = 2) {
this.scriptPath = resolveStockfishScriptPath();
const count = Math.max(1, workerCount);
for (let i = 0; i < count; i++) {
this.workers.push(new StockfishWorker(this.scriptPath));
}
}
async warmup(): Promise<void> {
await Promise.all(this.workers.map((w) => w.init()));
}
private enqueue(priority: number, req: SearchRequest): Promise<SearchResult> {
if (this.shuttingDown) {
return Promise.reject(new Error('Stockfish pool is shutting down'));
}
if (req.cancelSignal?.aborted) {
return Promise.resolve({ bestMove: null, lines: [] });
}
return new Promise<SearchResult>((resolve, reject) => {
const job: QueuedJob = {
priority,
seq: ++this.seqCounter,
req,
resolve,
reject
};
if (req.cancelSignal) {
const onAbort = () => {
const idx = this.queue.indexOf(job);
if (idx >= 0) {
this.queue.splice(idx, 1);
resolve({ bestMove: null, lines: [] });
}
};
req.cancelSignal.addEventListener('abort', onAbort, { once: true });
}
this.queue.push(job);
this.queue.sort((a, b) => (a.priority !== b.priority ? a.priority - b.priority : a.seq - b.seq));
this.pump();
});
}
private pump(): void {
if (this.shuttingDown) return;
for (let i = 0; i < this.workers.length; i++) {
if (this.queue.length === 0) break;
let worker = this.workers[i]!;
if (!worker.isAlive()) {
worker = new StockfishWorker(this.scriptPath);
this.workers[i] = worker;
}
if (worker.isBusy()) continue;
const job = this.queue.shift();
if (!job) break;
if (job.req.cancelSignal?.aborted) {
job.resolve({ bestMove: null, lines: [] });
continue;
}
worker
.search(job.req)
.then((res) => job.resolve(res))
.catch((err) => job.reject(err))
.finally(() => {
this.pump();
});
}
}
async getBotMove(fen: string, level: number): Promise<string> {
const safeLevel = Math.min(8, Math.max(1, Math.round(level)));
const tuning = BOT_TUNING[safeLevel] ?? BOT_TUNING[4]!;
const chess = new Chess(fen);
const legal = chess.legalMoves();
if (legal.length === 0) {
throw new Error('No legal moves in position');
}
if (legal.length === 1) {
return legal[0]!.uci;
}
const res = await this.enqueue(1, {
fen,
depth: tuning.depth,
movetime: tuning.movetime,
skillLevel: tuning.skillLevel,
multiPv: tuning.multiPv
});
if (tuning.weights && res.lines.length > 1) {
const candidateLines = res.lines.filter((l) => l.pvUci.length > 0);
if (candidateLines.length > 0) {
// Avoid picking catastrophic blunders too wildly on Lv 2, but give Lv 1/2 realistic variety
const count = Math.min(candidateLines.length, tuning.weights.length);
const weights = tuning.weights.slice(0, count);
const total = weights.reduce((a, b) => a + b, 0);
let r = Math.random() * total;
for (let i = 0; i < count; i++) {
r -= weights[i]!;
if (r <= 0) {
const pickedUci = candidateLines[i]!.pvUci[0]!;
if (legal.some((m) => m.uci === pickedUci)) {
return pickedUci;
}
break;
}
}
}
}
if (res.bestMove && legal.some((m) => m.uci === res.bestMove)) {
return res.bestMove;
}
return legal[0]!.uci;
}
async analyzePositionMultiPv(
fen: string,
depth: number,
multiPv: number,
cancelSignal?: AbortSignal,
onUpdate?: (lines: MultiPvLine[], depth: number) => void
): Promise<MultiPvLine[]> {
const chess = new Chess(fen);
if (chess.isGameOver()) {
return [];
}
const res = await this.enqueue(2, {
fen,
depth: Math.min(20, Math.max(4, depth)),
multiPv: Math.min(5, Math.max(1, multiPv)),
skillLevel: 20,
cancelSignal,
onUpdate
});
return res.lines;
}
private async evaluatePositionExact(fen: string, depth: number): Promise<PositionEval> {
const chess = new Chess(fen);
if (!chess.legalMoves().length) {
if (chess.inCheck()) {
// Side to move is checkmated -> enemy delivered mate
const mateWinner = chess.turn() === 'w' ? -1 : 1;
return {
cp: null,
mate: mateWinner,
bestMoveUci: null,
bestMoveSan: null,
pvUci: [],
pvSan: []
};
}
// Stalemate
return {
cp: 0,
mate: null,
bestMoveUci: null,
bestMoveSan: null,
pvUci: [],
pvSan: []
};
}
if (chess.isInsufficientMaterial()) {
return {
cp: 0,
mate: null,
bestMoveUci: chess.legalMoves()[0]?.uci ?? null,
bestMoveSan: chess.legalMoves()[0]?.san ?? null,
pvUci: [],
pvSan: []
};
}
const res = await this.enqueue(3, {
fen,
depth,
skillLevel: 20,
multiPv: 1
});
const top = res.lines[0];
const bestMoveUci = top?.pvUci[0] ?? res.bestMove ?? null;
let bestMoveSan: string | null = null;
if (bestMoveUci) {
const clone = new Chess(fen);
bestMoveSan = clone.moveUci(bestMoveUci)?.san ?? null;
}
return {
cp: top ? top.scoreCp : 0,
mate: top ? top.scoreMate : null,
bestMoveUci,
bestMoveSan,
pvUci: top?.pvUci ?? (bestMoveUci ? [bestMoveUci] : []),
pvSan: top?.pvSan ?? (bestMoveSan ? [bestMoveSan] : [])
};
}
analyzeFullGame(
gameId: string,
initialFen: string,
movesUci: ReadonlyArray<string>,
movesSan: ReadonlyArray<string>,
depth: number,
onProgress?: (done: number, total: number) => void
): Promise<GameAnalysisReport> {
const existing = this.activeGameAnalyses.get(gameId);
if (existing) {
if (onProgress) existing.listeners.add(onProgress);
return existing.promise;
}
const listeners = new Set<(done: number, total: number) => void>();
if (onProgress) listeners.add(onProgress);
const run = async (): Promise<GameAnalysisReport> => {
const startedAt = Date.now();
const chess = new Chess(initialFen);
const positions: Array<{ fen: string; turn: Color }> = [{ fen: chess.fen(), turn: chess.turn() }];
for (let i = 0; i < movesUci.length; i++) {
const mv = chess.moveUci(movesUci[i]!);
if (!mv) {
throw new Error(`Invalid move ${movesUci[i]} at ply ${i + 1} during analysis`);
}
positions.push({ fen: chess.fen(), turn: chess.turn() });
}
const totalPositions = positions.length;
const evals: Array<PositionEval | undefined> = new Array(totalPositions);
let completed = 0;
// Evaluate all positions through the priority-3 pool (runs concurrently across workers)
await Promise.all(
positions.map(async (pos, idx) => {
const ev = await this.evaluatePositionExact(pos.fen, depth);
evals[idx] = ev;
completed++;
for (const cb of listeners) {
cb(Math.min(movesUci.length, completed), movesUci.length);
}
})
);
const initialEval = evals[0]!;
const initialWinPercent = cpToWinPercent(initialEval.cp, initialEval.mate);
const plies: PlyAnalysis[] = [];
for (let i = 0; i < movesUci.length; i++) {
const before = evals[i]!;
const after = evals[i + 1]!;
const moverColor = positions[i]!.turn;
const whiteWinBefore = cpToWinPercent(before.cp, before.mate);
const whiteWinAfter = cpToWinPercent(after.cp, after.mate);
const moverWinBefore = winPercentForSide(whiteWinBefore, moverColor);
const moverWinAfter = winPercentForSide(whiteWinAfter, moverColor);
const winDrop = Math.max(0, moverWinBefore - moverWinAfter);
const isBest = before.bestMoveUci !== null && before.bestMoveUci === movesUci[i];
const classification = classifyMove(moverWinBefore, moverWinAfter, isBest);
const accuracy = computeMoveAccuracy(winDrop);
plies.push({
ply: i + 1,
moveUci: movesUci[i]!,
moveSan: movesSan[i] || movesUci[i]!,
color: moverColor,
evalCpBefore: before.cp,
evalMateBefore: before.mate,
evalCpAfter: after.cp,
evalMateAfter: after.mate,
winPercentBefore: Math.round(whiteWinBefore * 10) / 10,
winPercentAfter: Math.round(whiteWinAfter * 10) / 10,
winDrop: Math.round(winDrop * 10) / 10,
accuracy: Math.round(accuracy * 10) / 10,
bestMoveUci: before.bestMoveUci,
bestMoveSan: before.bestMoveSan,
pvUci: before.pvUci,
pvSan: before.pvSan,
classification
});
}
const now = Date.now();
return {
gameId,
status: 'done',
depth,
progressPly: movesUci.length,
totalPlies: movesUci.length,
whiteSummary: computePlayerSummary(plies, 'w'),
blackSummary: computePlayerSummary(plies, 'b'),
initialEvalCp: initialEval.cp,
initialEvalMate: initialEval.mate,
initialWinPercent: Math.round(initialWinPercent * 10) / 10,
initialBestMoveUci: initialEval.bestMoveUci,
initialBestMoveSan: initialEval.bestMoveSan,
initialPvSan: initialEval.pvSan,
plies,
createdAt: startedAt,
updatedAt: now
};
};
const promise = run().finally(() => {
this.activeGameAnalyses.delete(gameId);
});
this.activeGameAnalyses.set(gameId, { promise, listeners });
return promise;
}
shutdown(): void {
this.shuttingDown = true;
while (this.queue.length > 0) {
const job = this.queue.shift()!;
job.reject(new Error('Stockfish pool shutdown'));
}
for (const w of this.workers) {
w.close();
}
}
}