import { spawn, type ChildProcessWithoutNullStreams } from 'node:child_process'; import type { Logger } from './logger.js'; import type { AppConfig } from './types.js'; /** * Manages Stockfish evaluation. Spawns a Stockfish child process per evaluation * and communicates via UCI protocol over stdin/stdout. * * Worker threads would add complexity without benefit here -- the Stockfish process * itself runs in a separate OS process, so the Node.js event loop is never blocked. */ export class Engine { private log: Logger; private stockfishPath: string; private activeCount = 0; constructor(logger: Logger, stockfishConfig: AppConfig['stockfish']) { this.log = logger.child({ component: 'engine' }); this.stockfishPath = stockfishConfig.path; } async evaluatePosition(fen: string, depth: number, skillLevel?: number): Promise { this.activeCount++; try { return await this.runStockfish(fen, depth, skillLevel); } finally { this.activeCount--; } } private runStockfish(fen: string, depth: number, skillLevel?: number): Promise { return new Promise((resolve, reject) => { let proc: ChildProcessWithoutNullStreams; try { proc = spawn(this.stockfishPath); } catch (err) { reject(new Error(`Failed to spawn Stockfish: ${err}`)); return; } let output = ''; let resolved = false; const timeout = setTimeout(() => { if (!resolved) { resolved = true; proc.kill(); reject(new Error('Stockfish evaluation timed out')); } }, 30000); proc.stdout.on('data', (data: Buffer) => { output += data.toString(); const lines = output.split('\n'); for (const line of lines) { const match = line.match(/^bestmove\s+(\S+)/); if (match && !resolved) { resolved = true; clearTimeout(timeout); proc.kill(); resolve(match[1]); return; } } }); proc.stderr.on('data', (data: Buffer) => { this.log.warn({ stderr: data.toString() }, 'stockfish stderr'); }); proc.on('error', (err) => { if (!resolved) { resolved = true; clearTimeout(timeout); reject(err); } }); proc.on('close', (code) => { if (!resolved) { resolved = true; clearTimeout(timeout); reject(new Error(`Stockfish exited with code ${code}`)); } }); // UCI handshake then evaluate proc.stdin.write('uci\n'); if (skillLevel !== undefined) { proc.stdin.write(`setoption name Skill Level value ${skillLevel}\n`); } proc.stdin.write('isready\n'); proc.stdin.write(`position fen ${fen}\n`); proc.stdin.write(`go depth ${depth}\n`); }); } getActiveCount(): number { return this.activeCount; } async shutdown(): Promise { // Active evaluations will time out on their own this.log.info('engine shut down'); } }