premoves (server-side, survive closed tab), provider outages pause games instead of aborting, turn watchdog, lock race fix, overthinking experiment harness

This commit is contained in:
ai-chess
2026-10-18 17:23:15 +03:00
parent 141fb9022e
commit e4b5b8ada5
19 changed files with 1788 additions and 23 deletions
+2
View File
@@ -0,0 +1,2 @@
ALTER TABLE "games" ADD COLUMN "premove" jsonb;--> statement-breakpoint
ALTER TABLE "moves" ADD COLUMN "premoved" boolean DEFAULT false NOT NULL;
File diff suppressed because it is too large Load Diff
+7
View File
@@ -8,6 +8,13 @@
"when": 1792323366900,
"tag": "0000_init",
"breakpoints": true
},
{
"idx": 1,
"version": "7",
"when": 1792332661442,
"tag": "0001_premove",
"breakpoints": true
}
]
}
+136
View File
@@ -0,0 +1,136 @@
/**
* Overthinking experiment: replay real positions where Opus thought for minutes, with prompt variants.
* node --env-file=../../.env --import tsx scripts/think-exp.ts /tmp/exp-moves.json /tmp/think-exp
* Writes <out>/results.jsonl (+ one thinking dump per run).
*/
import { mkdirSync, readFileSync, writeFileSync, appendFileSync } from "node:fs";
import { GameState, type GameFlags, type Side } from "@aichess/core";
import { runAgentTurn, type AgentPlayer } from "../src/agents/turn.ts";
import { engine } from "../src/engine/stockfish.ts";
type Row = { game: string; ply: number; uci: string; san: string; phrase: string | null; note: string | null };
const [, , movesPath = "/tmp/exp-moves.json", outDir = "/tmp/think-exp"] = process.argv;
const rows: Row[] = JSON.parse(readFileSync(movesPath, "utf8"));
mkdirSync(outDir, { recursive: true });
const POSITIONS = [
{ id: "H8", game: "mvdvvxxmhlsqkmnbbvuq", ply: 8, persona: "professor", opp: "artsaf", oppHuman: true, flags: { notes: false, extraTools: false, cheating: false } },
{ id: "H10", game: "mvdvvxxmhlsqkmnbbvuq", ply: 10, persona: "professor", opp: "artsaf", oppHuman: true, flags: { notes: false, extraTools: false, cheating: false } },
{ id: "A29", game: "mvdtmab5ef49hb4wkb6n", ply: 29, persona: "gopnik", opp: "GPT-6.1 Sol MAX", oppHuman: false, flags: { notes: true, extraTools: false, cheating: false } },
];
const DISCIPLINE = [
"## Как думать над ходом",
"Ты играешь с контролем времени — рапид: на ход у тебя примерно 1–3 минуты, не больше.",
"- Играй позицию на доске. Не восстанавливай порядок ходов и не пытайся дословно вспомнить теорию — если позиция знакома, доверься общему пониманию.",
"- Сначала форсирующее: шахи, взятия, угрозы — свои и соперника. Убедись, что у тебя ничего не висит.",
"- Выбери 2–3 кандидата и доведи расчёт каждого до спокойной позиции. Не прыгай между кандидатами: сначала вывод по одному, потом следующий.",
"- Когда ход выбран и проверен на зевок — сразу делай его. Не перепроверяй уже проверенное; смутное «а вдруг» без конкретного ответа соперника — не повод думать дальше.",
].join("\n");
const opus = (variant: "max" | "high"): AgentPlayer => ({
id: `opus-${variant}`,
displayName: "Claude Opus 5.5",
variant,
provider: "anthropic",
modelId: "claude-opus-5-5",
thinking: variant,
options: {},
});
const VARIANTS = [
{ id: "base", me: opus("max"), hist: false, disc: false },
{ id: "hist", me: opus("max"), hist: true, disc: false },
{ id: "disc", me: opus("max"), hist: false, disc: true },
{ id: "hist+disc", me: opus("max"), hist: true, disc: true },
{ id: "high", me: opus("high"), hist: false, disc: false },
];
const REPS = Number(process.env.REPS ?? 2);
const CONC = Number(process.env.CONC ?? 5);
function movetext(plies: Row[]) {
const parts: string[] = [];
plies.forEach((r, k) => parts.push(k % 2 === 0 ? `${k / 2 + 1}. ${r.san}` : r.san));
return parts.join(" ");
}
const evalCache = new Map<string, Promise<number>>();
/** eval in centipawns from the POV of `pov` (mate = ±10000) */
function evalFor(fen: string, pov: Side): Promise<number> {
const k = `${fen}|${pov}`;
if (!evalCache.has(k))
evalCache.set(
k,
engine.analyze(fen, 20).then((e) => {
const white = e.mate != null ? Math.sign(e.mate) * 10000 : (e.cp ?? 0);
return pov === "white" ? white : -white;
}),
);
return evalCache.get(k)!;
}
type Job = { pos: (typeof POSITIONS)[number]; v: (typeof VARIANTS)[number]; rep: number };
const jobs: Job[] = [];
for (let rep = 1; rep <= REPS; rep++) for (const pos of POSITIONS) for (const v of VARIANTS) jobs.push({ pos, v, rep });
async function runJob({ pos, v, rep }: Job) {
const plies = rows.filter((r) => r.game === pos.game && r.ply < pos.ply).sort((a, b) => a.ply - b.ply);
const state = GameState.fromUci(plies.map((p) => ({ uci: p.uci })));
const side: Side = pos.ply % 2 === 1 ? "white" : "black";
const last = plies[plies.length - 1];
const myLast = [...plies].reverse().find((p) => (p.ply % 2 === 1 ? "white" : "black") === side);
const tag = `${pos.id}/${v.id}/r${rep}`;
const t0 = Date.now();
try {
const res = await runAgentTurn({
gameId: `exp-${tag}`,
side,
me: v.me,
opponentName: pos.opp,
opponentIsHuman: pos.oppHuman,
persona: pos.persona,
flags: pos.flags as GameFlags,
state,
history: [],
opponentPhrase: last?.phrase ?? null,
drawOffered: false,
noteFromSelf: pos.flags.notes ? (myLast?.note ?? null) : null,
onLive: () => {},
tweaks: {
system: v.disc ? DISCIPLINE : undefined,
context: v.hist ? `## Ходы партии\n${movetext(plies)}` : undefined,
},
});
const d = res.decision;
let san: string | null = null;
let loss: number | null = null;
if (d.kind === "move") {
san = d.san;
const before = await evalFor(state.fen(), side);
const after = GameState.fromUci([...plies.map((p) => ({ uci: p.uci })), { uci: d.uci }]);
const afterEval = await evalFor(after.fen(), side);
loss = Math.max(0, before - afterEval);
}
const thinking = res.transcript.filter((t) => t.kind === "thinking").map((t: any) => t.text).join("\n\n");
writeFileSync(`${outDir}/${tag.replaceAll("/", "_")}.txt`, `${res.context}\n\n=====THINKING=====\n${thinking}`);
const out = {
pos: pos.id, variant: v.id, rep, decision: d.kind, san, cpLoss: loss,
secs: Math.round((Date.now() - t0) / 1000), reasoning: res.usage.reasoning, output: res.usage.output,
cost: Number(res.usage.cost.toFixed(3)), thinkChars: thinking.length,
};
appendFileSync(`${outDir}/results.jsonl`, JSON.stringify(out) + "\n");
console.log(JSON.stringify(out));
} catch (e) {
console.log(JSON.stringify({ pos: pos.id, variant: v.id, rep, error: String(e).slice(0, 300) }));
}
}
let next = 0;
await Promise.all(
Array.from({ length: CONC }, async () => {
while (next < jobs.length) await runJob(jobs[next++]);
}),
);
engine.stop();
console.log("done");
process.exit(0);
+6 -2
View File
@@ -44,6 +44,8 @@ export interface TurnInput {
noteFromSelf: string | null;
signal?: AbortSignal;
onLive: (ev: LiveTurnEvent) => void;
/** experiments only (scripts/think-exp.ts): extra text appended to the system prompt / turn message */
tweaks?: { system?: string; context?: string };
}
export type LiveTurnEvent =
@@ -208,8 +210,9 @@ export async function runAgentTurn(i: TurnInput): Promise<TurnResult> {
}
const persona = personaById(i.persona);
const systemPrompt = buildSystemPrompt({ side: i.side, opponentName: i.opponentName, opponentIsHuman: i.opponentIsHuman, persona, flags: i.flags });
const context = renderTurnContext({
let systemPrompt = buildSystemPrompt({ side: i.side, opponentName: i.opponentName, opponentIsHuman: i.opponentIsHuman, persona, flags: i.flags });
if (i.tweaks?.system) systemPrompt += "\n\n" + i.tweaks.system;
let context = renderTurnContext({
state: i.state,
me: { side: i.side },
opponent: { name: i.opponentName },
@@ -219,6 +222,7 @@ export async function runAgentTurn(i: TurnInput): Promise<TurnResult> {
flags: i.flags,
fiftyMoveThreshold: config.game.fiftyMoveReminderFrom,
});
if (i.tweaks?.context) context = context.replace("\n\n## \u0422\u0432\u043e\u044f \u0437\u0430\u0434\u0430\u0447\u0430", `\n\n${i.tweaks.context}\n\n## \u0422\u0432\u043e\u044f \u0437\u0430\u0434\u0430\u0447\u0430`);
transcript.push({ kind: "context", text: context, at: Date.now() });
const { session } = await createChessSession({
+11
View File
@@ -58,6 +58,13 @@ export const players = pgTable("players", {
createdAt: now(),
});
export interface Premove {
side: Side;
uci: string;
ply: number;
phrase: string | null;
}
export const games = pgTable("games", {
id: text("id").primaryKey(),
status: text("status").$type<"pending" | "running" | "finished" | "aborted">().notNull().default("pending"),
@@ -72,6 +79,8 @@ export const games = pgTable("games", {
fen: text("fen").notNull(),
ply: integer("ply").notNull().default(0),
pendingDrawBy: text("pending_draw_by").$type<Side | null>(),
/** a human's queued move, played the instant the AI replies (`ply` = the ply it is meant for) */
premove: jsonb("premove").$type<Premove | null>(),
result: text("result").$type<Result | null>(),
termination: text("termination").$type<Termination | null>(),
startsAt: ts("starts_at"), // scheduled start (predictions lock at this time)
@@ -105,6 +114,8 @@ export const moves = pgTable("moves", {
note: text("note"),
offeredDraw: boolean("offered_draw").notNull().default(false),
illegal: boolean("illegal").notNull().default(false),
/** played automatically from a human's premove */
premoved: boolean("premoved").notNull().default(false),
thinkMs: integer("think_ms").notNull().default(0),
usage: jsonb("usage").$type<Usage>(),
eval: jsonb("eval").$type<EngineEval | null>(),
+45 -6
View File
@@ -10,7 +10,7 @@ import {
} from "@aichess/core";
import { db, schema, sqlClient } from "../db/client.ts";
import { bus, gameChannel } from "../bus.ts";
import { boss, Q, type EvalJob, type TurnJob } from "../jobs.ts";
import { boss, enqueueTurn, hasLiveTurnJob, Q, type EvalJob, type TurnJob } from "../jobs.ts";
import { config } from "../config.ts";
import { engine } from "../engine/stockfish.ts";
import { runAgentTurn, type AgentPlayer, type LiveTurnEvent } from "../agents/turn.ts";
@@ -70,8 +70,15 @@ async function handleTurn(data: TurnJob, retryCount: number) {
const conn = await sqlClient.reserve();
const key = `turn:${data.gameId}`;
try {
const [row] = await conn`select pg_try_advisory_lock(hashtext(${key})) as ok`;
if (!row?.ok) {
// The previous ply's handler enqueues this job from inside its own locked section and releases the
// lock a few ms later \u2014 so wait briefly before concluding that a genuine duplicate is running.
let ok = false;
for (let t = 0; t < 60 && !ok; t++) {
const [row] = await conn`select pg_try_advisory_lock(hashtext(${key})) as ok`;
ok = !!row?.ok;
if (!ok) await new Promise((r) => setTimeout(r, 250));
}
if (!ok) {
log("turn", `${data.gameId}#${data.ply}: another worker holds the game — skipping duplicate`);
return;
}
@@ -178,12 +185,14 @@ async function runTurnLocked(data: TurnJob, retryCount: number) {
const msg = err instanceof Error ? err.message : String(err);
await db.update(schema.turns).set({ status: "failed", error: msg.slice(0, 2000), endedAt: new Date() }).where(eq(schema.turns.id, turnId));
if (ac.signal.aborted) return;
logErr("turn", `${g.game.id}#${data.ply} attempt ${n + 1} failed: ${msg}`);
if (retryCount >= 4) {
const transient = isTransientProviderError(msg);
logErr("turn", `${g.game.id}#${data.ply} attempt ${n + 1} failed (${transient ? "transient" : "fatal?"}): ${msg}`);
// provider outages never kill a game — the job keeps retrying (backoff ≤ 5 min) until it comes back
if (!transient && retryCount >= 4) {
await abortGame(g.game.id, `agent turn failed repeatedly: ${msg}`);
return;
}
bus.publish(gameChannel(g.game.id), { type: "status", gameId: g.game.id, status: "running", note: "Ошибка провайдера — ход будет переигран" });
bus.publish(gameChannel(g.game.id), { type: "status", gameId: g.game.id, status: "running", note: providerNote(msg, me.provider) });
throw err;
} finally {
live.delete(g.game.id);
@@ -259,6 +268,36 @@ export async function startWorkers() {
}
/** Make sure every running game has its next turn queued (after restarts / lost jobs). */
const TRANSIENT_RE =
/provider error|\b5\d\d\b|\b429\b|\b401\b|overload|rate.?limit|auth_unavailable|revoked|unauthori|timed? ?out|ECONN|ETIMEDOUT|EAI_AGAIN|fetch failed|socket|network|stream ended|model fallback|terminated/i;
export const isTransientProviderError = (msg: string) => TRANSIENT_RE.test(msg);
const PROVIDER_RU: Record<string, string> = { anthropic: "Anthropic (Claude)", openai: "OpenAI" };
/** human-readable status line for spectators while a turn is being retried */
export function providerNote(msg: string, provider?: string | null) {
const who = (provider && PROVIDER_RU[provider]) || "Провайдер модели";
if (/auth_unavailable|revoked|unauthori|\b401\b/i.test(msg)) return `${who} временно недоступен (слетела авторизация) — партия на паузе, ход будет переигран автоматически`;
if (/\b429\b|rate.?limit|overload/i.test(msg)) return `${who} перегружен — ход будет переигран автоматически`;
return `${who}: ошибка — ход будет переигран автоматически`;
}
/**
* Watchdog (every scheduler tick): a running game whose side to move is an AI must have a live turn
* job. Jobs can disappear (retries exhausted, failed during a restart…) — re-enqueue them.
*/
export async function reviveStalledGames() {
const running = await db.select().from(schema.games).where(eq(schema.games.status, "running"));
for (const g of running) {
const ply = g.ply + 1;
const pid = sideOfPly(ply) === "white" ? g.whiteId : g.blackId;
const p = await db.query.players.findFirst({ where: eq(schema.players.id, pid) });
if (p?.kind !== "ai" || live.has(g.id)) continue;
if (await hasLiveTurnJob(g.id, ply)) continue;
log("watchdog", `no live turn job for ${g.id}#${ply} — re-enqueueing`);
await enqueueTurn({ gameId: g.id, ply });
}
}
export async function recoverRunningGames() {
const running = await db.select().from(schema.games).where(eq(schema.games.status, "running"));
const { kickTurn } = await import("./service.ts");
+2
View File
@@ -7,6 +7,7 @@ import { config } from "../config.ts";
import { PERSONAS } from "../agents/prompts.ts";
import { log, logErr, newId, pick, shuffle } from "../util.ts";
import { createGame, startPendingGame } from "./service.ts";
import { reviveStalledGames } from "./runner.ts";
/**
* Every minute:
@@ -66,6 +67,7 @@ async function announceScheduled(s: typeof schema.schedules.$inferSelect) {
export async function startScheduler() {
await boss.work(Q.scheduleTick, { batchSize: 1, pollingIntervalSeconds: 5 } as any, async () => {
await scheduleTick();
await reviveStalledGames().catch((e) => logErr("watchdog", e));
});
await boss.schedule(Q.scheduleTick, "* * * * *");
// default schedule on first boot
+53 -2
View File
@@ -13,6 +13,7 @@ import {
type Usage,
} from "@aichess/core";
import { db, schema } from "../db/client.ts";
import type { Premove } from "../db/schema.ts";
import { bus, gameChannel } from "../bus.ts";
import { enqueueEval, enqueueFinalize, enqueueTurn } from "../jobs.ts";
import { log, newId } from "../util.ts";
@@ -41,6 +42,7 @@ export function moveToDTO(m: MoveRow): MoveDTO {
note: m.note,
offeredDraw: m.offeredDraw,
illegal: m.illegal,
premoved: m.premoved,
thinkMs: m.thinkMs,
usage: (m.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0, cost: 0 }) as Usage,
eval: m.eval,
@@ -149,6 +151,7 @@ export interface MoveMeta {
thinkMs: number;
usage: Usage | null;
turnId: string | null;
premoved?: boolean;
}
/**
@@ -168,13 +171,18 @@ export async function applyMove(gameId: string, ply: number, input: { uci: strin
const moveId = newId();
const pendingDrawBy: Side | null = meta.offerDraw ? side : null;
let premove: Premove | null = null;
const updated = await db.transaction(async (tx) => {
// any move consumes the queued premove; grab it under the row lock so a concurrent PUT can't slip between
const [locked] = await tx.select({ premove: schema.games.premove }).from(schema.games).where(eq(schema.games.id, gameId)).for("update");
premove = locked?.premove ?? null;
const [row] = await tx
.update(schema.games)
.set({
ply,
fen: rec.fenAfter,
pendingDrawBy,
premove: null,
costTotal: sql`${schema.games.costTotal} + ${meta.usage?.cost ?? 0}`,
})
.where(and(eq(schema.games.id, gameId), eq(schema.games.ply, ply - 1), eq(schema.games.status, "running")))
@@ -193,6 +201,7 @@ export async function applyMove(gameId: string, ply: number, input: { uci: strin
note: meta.note,
offeredDraw: meta.offerDraw,
illegal: rec.illegal,
premoved: !!meta.premoved,
thinkMs: meta.thinkMs,
usage: meta.usage,
turnId: meta.turnId,
@@ -208,11 +217,53 @@ export async function applyMove(gameId: string, ply: number, input: { uci: strin
await enqueueEval({ gameId, ply });
const outcome = state.outcome();
if (outcome) await finishGame(gameId, outcome.result, outcome.termination);
else await kickTurn(updated);
if (outcome) {
await finishGame(gameId, outcome.result, outcome.termination);
return { ok: true, move: dto };
}
const pm = premove as Premove | null;
if (pm && pm.ply === ply + 1 && pm.side === sideOfPly(ply + 1)) {
const r = await applyMove(gameId, ply + 1, { uci: pm.uci }, { phrase: pm.phrase, note: null, offerDraw: false, thinkMs: 0, usage: null, turnId: null, premoved: true });
if (r.ok) return { ok: true, move: dto };
bus.publish(gameChannel(gameId), { type: "premove_dropped", gameId, side: pm.side, uci: pm.uci, reason: r.error });
}
await kickTurn(updated);
return { ok: true, move: dto };
}
// ------------------------------------------------------------------ premoves
/**
* Queue a premove for the human whose opponent (AI) is thinking. If the AI has already replied by the
* time this lands, the move is simply played. Returns whether it was queued or played.
*/
export async function setPremove(gameId: string, side: Side, uci: string, phrase: string | null): Promise<{ ok: true; played: boolean } | { ok: false; error: string }> {
const g = await loadGame(gameId);
if (!g || g.game.status !== "running") return { ok: false, error: "\u041f\u0430\u0440\u0442\u0438\u044f \u043d\u0435 \u0438\u0434\u0451\u0442" };
const nextSide = sideOfPly(g.game.ply + 1);
if (nextSide === side) {
const r = await applyMove(gameId, g.game.ply + 1, { uci }, { phrase, note: null, offerDraw: false, thinkMs: 0, usage: null, turnId: null });
return r.ok ? { ok: true, played: true } : { ok: false, error: r.error };
}
// must at least move one of my own pieces
const piece = stateOf(g).pieceAt(uci.slice(0, 2));
if (!piece || piece.side !== side) return { ok: false, error: "\u041d\u0430 \u044d\u0442\u043e\u0439 \u043a\u043b\u0435\u0442\u043a\u0435 \u043d\u0435\u0442 \u0442\u0432\u043e\u0435\u0439 \u0444\u0438\u0433\u0443\u0440\u044b" };
const [row] = await db
.update(schema.games)
.set({ premove: { side, uci, ply: g.game.ply + 2, phrase } })
.where(and(eq(schema.games.id, gameId), eq(schema.games.ply, g.game.ply), eq(schema.games.status, "running")))
.returning({ id: schema.games.id });
if (row) return { ok: true, played: false };
return setPremove(gameId, side, uci, phrase); // the AI moved in between \u2014 retry against the new state
}
export async function clearPremove(gameId: string, side: Side) {
await db
.update(schema.games)
.set({ premove: null })
.where(and(eq(schema.games.id, gameId), sql`${schema.games.premove}->>'side' = ${side}`));
}
// ------------------------------------------------------------------ finishing
export async function finishGame(gameId: string, result: Result, termination: Termination, opts: { error?: string } = {}) {
+49 -2
View File
@@ -10,8 +10,8 @@ import { config } from "../config.ts";
import { db, schema } from "../db/client.ts";
import { authMiddleware, createSession, destroySession, findUserByName, registerUser, requireAdmin, requireUser, USERNAME_RE, verifyPassword, type AppEnv } from "../auth.ts";
import { PERSONAS } from "../agents/prompts.ts";
import { abortGame, applyMove, applyTerminalDecision, createGame, loadGame, playerIdFor, recordOf, sideOfPly } from "../games/service.ts";
import { abortRunningTurn, getLiveTurn } from "../games/runner.ts";
import { abortGame, applyMove, applyTerminalDecision, clearPremove, createGame, loadGame, playerIdFor, recordOf, setPremove, sideOfPly } from "../games/service.ts";
import { abortRunningTurn, getLiveTurn, providerNote } from "../games/runner.ts";
import { enqueueFinalize } from "../jobs.ts";
import { newId } from "../util.ts";
import { gameSummaryDTO, movesDTO, playerDTO, userDTO } from "./dto.ts";
@@ -198,6 +198,20 @@ export function buildApp() {
const me = c.get("user");
const mine = me ? await db.query.predictions.findFirst({ where: and(eq(schema.predictions.gameId, g.game.id), eq(schema.predictions.userId, me.id)) }) : null;
const lt = getLiveTurn(g.game.id);
// a failed attempt with no retry running yet = the game is paused waiting for the provider
let stall: { note: string; at: string; attempts: number } | null = null;
if (g.game.status === "running" && !lt) {
const [t] = await db
.select()
.from(schema.turns)
.where(and(eq(schema.turns.gameId, g.game.id), eq(schema.turns.ply, g.game.ply + 1)))
.orderBy(desc(schema.turns.attempt))
.limit(1);
if (t?.status === "failed") {
const p = t.side === "white" ? g.white : g.black;
stall = { note: providerNote(t.error ?? "", p.provider), at: (t.endedAt ?? t.startedAt).toISOString(), attempts: t.attempt };
}
}
return c.json({
game: {
...gameSummaryDTO(g.game, pm, { withReview: true }),
@@ -206,10 +220,16 @@ export function buildApp() {
interviews: g.game.interviews,
lastWords: g.game.lastWords,
pendingDrawBy: g.game.pendingDrawBy,
// a premove is private to the human who queued it
premove:
me && g.game.premove && (g.game.premove.side === "white" ? g.white : g.black).userId === me.id
? { uci: g.game.premove.uci, phrase: g.game.premove.phrase }
: null,
createdBy: g.game.createdBy,
error: g.game.error,
},
moves: movesDTO(g.moves),
stall,
live: lt ? { ply: lt.ply, side: lt.side, startedAt: lt.startedAt, thinking: lt.thinking, text: lt.text, tools: Object.values(lt.tools) } : null,
predictions: { counts: Object.fromEntries(preds.map((p) => [p.pick, p.n])), mine: mine?.pick ?? null },
});
@@ -286,6 +306,33 @@ export function buildApp() {
return c.json({ ok: true, move: r.move });
});
/** the human participant's side (any turn), or an error response */
async function participant(c: any) {
const u = c.get("user")!;
const g = await loadGame(c.req.param("id"));
if (!g || g.game.status !== "running") return { error: c.json({ error: "\u041f\u0430\u0440\u0442\u0438\u044f \u043d\u0435 \u0438\u0434\u0451\u0442" }, 409) };
const side: Side | null = g.white.kind === "human" && g.white.userId === u.id ? "white" : g.black.kind === "human" && g.black.userId === u.id ? "black" : null;
if (!side) return { error: c.json({ error: "\u0422\u044b \u043d\u0435 \u0438\u0433\u0440\u0430\u0435\u0448\u044c \u0432 \u044d\u0442\u043e\u0439 \u043f\u0430\u0440\u0442\u0438\u0438" }, 403) };
return { g, side };
}
// premove: queued while the AI thinks, played server-side the instant it replies (tab may be closed)
app.put("/api/games/:id/premove", requireUser, async (c) => {
const t = await participant(c);
if ("error" in t) return t.error;
const b = await body(c, z.object({ move: z.string().regex(/^[a-h][1-8][a-h][1-8][qrbn]?$/), phrase: z.string().max(400).optional() }));
const r = await setPremove(t.g.game.id, t.side, b.move, b.phrase?.trim() || null);
if (!r.ok) return c.json({ error: r.error }, 400);
return c.json({ ok: true, played: r.played });
});
app.delete("/api/games/:id/premove", requireUser, async (c) => {
const t = await participant(c);
if ("error" in t) return t.error;
await clearPremove(t.g.game.id, t.side);
return c.json({ ok: true });
});
app.post("/api/games/:id/resign", requireUser, async (c) => {
const u = c.get("user")!;
const g = await loadGame(c.req.param("id"));
+14 -6
View File
@@ -1,5 +1,6 @@
import { PgBoss } from "pg-boss";
import { config } from "./config.ts";
import { sqlClient } from "./db/client.ts";
import { log, logErr } from "./util.ts";
export const Q = {
@@ -20,7 +21,9 @@ export async function startBoss() {
await boss.start();
// agent turns can take very long (MAX thinking) — generous expiry, a few retries
// heartbeat: a crashed/restarted worker's job is retried within ~a minute instead of waiting for expiry
await ensureQueue(Q.turn, { expireInSeconds: 3 * 3600, retryLimit: 4, retryDelay: 20, retryBackoff: true, heartbeatSeconds: 60 });
// Provider outages (revoked auth, 5xx) can last hours: keep retrying with backoff capped at 5 min;
// the runner itself decides when a non-transient error should abort the game.
await ensureQueue(Q.turn, { expireInSeconds: 3 * 3600, retryLimit: 500, retryDelay: 20, retryBackoff: true, retryDelayMax: 300, heartbeatSeconds: 60 });
await ensureQueue(Q.evalPly, { expireInSeconds: 600, retryLimit: 3, retryDelay: 5 });
await ensureQueue(Q.finalize, { expireInSeconds: 3600, retryLimit: 2, retryDelay: 30, heartbeatSeconds: 60 });
await ensureQueue(Q.scheduleTick, { expireInSeconds: 120, retryLimit: 0 });
@@ -28,11 +31,16 @@ export async function startBoss() {
}
async function ensureQueue(name: string, opts: Record<string, unknown>) {
try {
await boss.createQueue(name, opts as any);
} catch {
await boss.updateQueue(name, opts as any).catch(() => {});
}
// createQueue is a no-op for an existing queue — always push the current options too
await boss.createQueue(name, opts as any).catch(() => {});
const { heartbeatSeconds: _h, ...upd } = opts;
await boss.updateQueue(name, upd as any).catch((e: unknown) => logErr("pg-boss", `updateQueue ${name}`, e));
}
/** is there a live (queued / retrying / running) turn job for this game+ply? */
export async function hasLiveTurnJob(gameId: string, ply: number): Promise<boolean> {
const rows = await sqlClient`select 1 from pgboss.job where name = ${Q.turn} and singleton_key = ${`${gameId}:${ply}`} and state in ('created','retry','active') limit 1`;
return rows.length > 0;
}
export const enqueueTurn = (j: TurnJob) => boss.send(Q.turn, j, { singletonKey: `${j.gameId}:${j.ply}` });
+1
View File
@@ -24,5 +24,6 @@ export const api = {
get: <T>(p: string) => req<T>('GET', p),
post: <T>(p: string, b?: unknown) => req<T>('POST', p, b ?? {}),
patch: <T>(p: string, b?: unknown) => req<T>('PATCH', p, b ?? {}),
put: <T>(p: string, b?: unknown) => req<T>('PUT', p, b ?? {}),
del: <T>(p: string) => req<T>('DELETE', p)
};
+36 -2
View File
@@ -11,7 +11,10 @@
orientation = 'white',
arrow = null,
movable = null,
onmove
onmove,
premove = null,
onpremove,
onpremoveunset
}: {
fen: string;
lastMove?: [string, string];
@@ -21,10 +24,18 @@
/** when set, the given color may move: dests = legal destinations per square */
movable?: { color: 'white' | 'black'; dests: Map<string, string[]> } | null;
onmove?: (from: string, to: string) => void;
/** queued premove to display (owned by the page; null = none) */
premove?: [string, string] | null;
/** user dragged a piece while it was the opponent's turn (requires movable.color = my side) */
onpremove?: (from: string, to: string) => void;
onpremoveunset?: () => void;
} = $props();
let el: HTMLDivElement;
let api: Api | undefined;
let lastFen = '';
// chessground fires premove callbacks async (setTimeout) \u2014 count our own cancels to swallow them
let silentUnsets = 0;
onMount(() => {
api = Chessground(el, {
@@ -35,7 +46,18 @@
animation: { enabled: true, duration: 220 },
highlight: { lastMove: true, check: true },
movable: { free: false, color: undefined, showDests: true, events: { after: (o, d) => onmove?.(o, d) } },
premovable: { enabled: false },
premovable: {
enabled: true,
showDests: true,
castle: true,
events: {
set: (o, d) => onpremove?.(o, d),
unset: () => {
if (silentUnsets > 0) silentUnsets--;
else onpremoveunset?.();
}
}
},
draggable: { enabled: true, showGhost: true },
drawable: {
enabled: true,
@@ -65,6 +87,18 @@
: { color: undefined, dests: new Map() },
drawable: { autoShapes: arrow ? [{ orig: arrow[0] as Key, dest: arrow[1] as Key, brush: 'best' }] : [] }
});
const fenChanged = fen !== lastFen;
lastFen = fen;
const cur = api.state.premovable.current;
if (premove) {
if (!cur || cur[0] !== premove[0] || cur[1] !== premove[1]) {
api.state.premovable.current = premove as Key[] as [Key, Key];
api.state.dom.redraw();
}
} else if (cur && fenChanged) {
silentUnsets++;
api.cancelPremove();
}
});
</script>
+5 -1
View File
@@ -57,7 +57,7 @@
{#if m}
<div class="cell" class:cur={current === m.ply} class:open={expanded === m.ply}>
<button class="mv" onclick={() => onselect(m.ply)} title={m.classification ? CLS_LABEL[m.classification] : ''}>
<span class="san" class:illegal={m.illegal}>{m.san ?? m.uci}</span>{#if m.classification && NAG[m.classification]}<span class="nag {m.classification}">{NAG[m.classification]}</span>{/if}
<span class="san" class:illegal={m.illegal}>{m.san ?? m.uci}</span>{#if m.premoved}<span class="pm" title="Сыграно премувом — сразу после хода соперника">⚡</span>{/if}{#if m.classification && NAG[m.classification]}<span class="nag {m.classification}">{NAG[m.classification]}</span>{/if}
{#if m.offeredDraw}<span class="draw" title="Предложил ничью">½?</span>{/if}
</button>
<span class="ev mono">{evalLabel(m.eval)}</span>
@@ -148,6 +148,10 @@
font-weight: 600;
font-size: 14px;
}
.pm {
font-size: 0.8em;
margin-left: 2px;
}
.san.illegal {
text-decoration: line-through wavy var(--danger);
}
+9
View File
@@ -18,6 +18,9 @@ export class GameView {
turn = $state<LiveTurn | null>(null);
predictions = $state<GameResponse['predictions']>({ counts: {}, mine: null });
error = $state<string | null>(null);
/** server dropped my premove (illegal after the opponent's reply) */
stall = $state<GameResponse['stall']>(null);
premoveDropped = $state<{ side: Side; uci: string; reason: string; at: number } | null>(null);
private offs: (() => void)[] = [];
constructor(id: string) {
@@ -31,6 +34,7 @@ export class GameView {
this.moves = r.moves;
this.turn = r.live ? { ...r.live, tools: [...r.live.tools] } : null;
this.predictions = r.predictions;
this.stall = r.stall ?? null;
this.error = null;
} catch (e) {
this.error = (e as Error).message;
@@ -51,6 +55,7 @@ export class GameView {
const t = this.turn;
switch (ev.type) {
case 'turn_start':
this.stall = null;
this.turn = { ply: ev.ply, side: ev.side, startedAt: ev.at, thinking: '', text: '', tools: [] };
break;
case 'thinking_delta':
@@ -68,6 +73,7 @@ export class GameView {
break;
}
case 'move':
this.stall = null;
if (!this.moves.some((m) => m.ply === ev.move.ply)) this.moves.push(ev.move);
if (this.game) {
this.game.ply = ev.move.ply;
@@ -87,6 +93,9 @@ export class GameView {
}
case 'turn_end':
break;
case 'premove_dropped':
this.premoveDropped = { side: ev.side, uci: ev.uci, reason: ev.reason, at: Date.now() };
break;
case 'interview':
if (this.game) this.game.interviews = { ...this.game.interviews, [ev.side]: ev.text };
break;
+4
View File
@@ -60,6 +60,8 @@ export interface GameDetail extends GameSummary {
interviews: { white?: string | null; black?: string | null };
lastWords: { white?: string | null; black?: string | null };
pendingDrawBy: Side | null;
/** my own queued premove (only sent to the human who set it) */
premove?: { uci: string; phrase: string | null } | null;
createdBy: string | null;
error: string | null;
}
@@ -77,6 +79,8 @@ export interface GameResponse {
game: GameDetail;
moves: MoveDTO[];
live: LiveTurn | null;
/** last attempt failed (provider outage) — game paused, retried automatically */
stall?: { note: string; at: string; attempts: number } | null;
predictions: { counts: Partial<Record<'white' | 'draw' | 'black', number>>; mine: 'white' | 'draw' | 'black' | null };
}
+93 -2
View File
@@ -74,13 +74,72 @@
// ---- human move input
const myTurn = $derived(!!mySide && g?.status === 'running' && view.sideToMove === mySide && atLive);
// premoves: allowed while the AI opponent thinks (the server plays them the instant it replies)
const canPremove = $derived(!!mySide && g?.status === 'running' && atLive && !myTurn && view.player(otherSide(mySide)).kind === 'ai');
const dests = $derived.by(() => {
if (canPremove) return { color: mySide!, dests: new Map<string, string[]>() };
if (!myTurn) return null;
const c = new Chess(g!.fen);
const m = new Map<string, string[]>();
for (const mv of c.moves({ verbose: true })) m.set(mv.from, [...(m.get(mv.from) ?? []), mv.to]);
return { color: mySide!, dests: m };
});
/** my queued premove, pinned to the position (move count) it was made in */
let pm = $state<{ at: number; from: string; to: string; phrase: string | null } | null>(null);
$effect(() => {
// adopt a premove the server still holds (after a reload) — once per REST snapshot
const sp = g?.premove;
if (!g || !sp) return;
pm = { at: g.ply, from: sp.uci.slice(0, 2), to: sp.uci.slice(2, 4), phrase: sp.phrase };
g.premove = null;
});
const premoveShown = $derived<[string, string] | null>(pm && pm.at === view.moves.length && canPremove ? [pm.from, pm.to] : null);
async function setPremove(from: string, to: string) {
moveErr = null;
const piece = new Chess(g!.fen).get(from as any);
const promo = piece?.type === 'p' && (to[1] === '8' || to[1] === '1') ? 'q' : '';
const at = view.moves.length;
const ph = phrase.trim() || null;
pm = { at, from, to, phrase: ph };
try {
const r = await api.put<{ played: boolean }>(`/api/games/${view.id}/premove`, { move: from + to + promo, phrase: ph ?? undefined });
if (ph) phrase = '';
if (r.played) pm = null;
} catch (e) {
pm = null;
moveErr = (e as Error).message;
}
}
async function unsetPremove() {
if (!pm) return;
pm = null;
await api.del(`/api/games/${view.id}/premove`).catch(() => {});
}
// ping when the AI finally replies (title + a short beep) — the opponent may think for minutes
let wasMyTurn: boolean | null = null;
$effect(() => {
const now = myTurn;
if (wasMyTurn === false && now) beep();
wasMyTurn = now;
});
function beep() {
try {
const ctx = new AudioContext();
const o = ctx.createOscillator();
const gn = ctx.createGain();
o.frequency.value = 660;
gn.gain.setValueAtTime(0.0001, ctx.currentTime);
gn.gain.exponentialRampToValueAtTime(0.15, ctx.currentTime + 0.02);
gn.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.35);
o.connect(gn).connect(ctx.destination);
o.start();
o.stop(ctx.currentTime + 0.4);
o.onended = () => ctx.close();
} catch {
/* autoplay policy — ignore */
}
}
const dropped = $derived(view.premoveDropped && view.premoveDropped.side === mySide ? view.premoveDropped : null);
let phrase = $state('');
let offerDraw = $state(false);
let moveErr = $state<string | null>(null);
@@ -134,7 +193,7 @@
</script>
<svelte:window onkeydown={key} />
<svelte:head><title>{g ? `${g.status === 'running' ? 'LIVE · ' : ''}${playerTitle(g.white)} — ${playerTitle(g.black)} · AI·CHESS` : 'AI·CHESS'}</title></svelte:head>
<svelte:head><title>{g ? `${myTurn ? '● Твой ход · ' : g.status === 'running' ? 'LIVE · ' : ''}${playerTitle(g.white)} — ${playerTitle(g.black)} · AI·CHESS` : 'AI·CHESS'}</title></svelte:head>
{#if view.error}
<div class="error-box">{view.error}</div>
@@ -199,6 +258,9 @@
<!-- ───── center ───── -->
<section class="col-board">
{#if g.status === 'running' && view.stall}
<div class="notes mono hot stall">⏸ {view.stall.note} <span class="muted">· попыток: {view.stall.attempts}</span></div>
{/if}
{#if g.status === 'running' && atLive}
<div class="notes mono" class:hot={repetitionHot}><span class="label">агент видит:</span> {ruleNotes.join(' · ')}</div>
{:else if !atLive}
@@ -215,7 +277,7 @@
<div class="board-row">
<EvalBar ev={shownEval} {orientation} />
<Board fen={pos.fen} lastMove={pos.lastMove} check={pos.check} {orientation} {arrow} movable={dests} onmove={humanMove} />
<Board fen={pos.fen} lastMove={pos.lastMove} check={pos.check} {orientation} {arrow} movable={dests} onmove={humanMove} premove={premoveShown} onpremove={setPremove} onpremoveunset={unsetPremove} />
</div>
<div class="controls">
@@ -236,6 +298,15 @@
<div class="panel play">
<div class="panel-head">{myTurn ? 'Твой ход' : 'Ход соперника'} <span class="spacer"></span><small>ты играешь {mySide === 'white' ? 'белыми' : 'чёрными'}</small></div>
<div class="panel-body stack">
{#if premoveShown}
<div class="premove mono">
⚡ премув <b>{premoveShown[0]}–{premoveShown[1]}</b>{#if pm?.phrase} · с репликой{/if} — сыграется сразу после хода соперника, даже если закроешь вкладку
<button class="btn sm" onclick={() => unsetPremove()}>отменить</button>
</div>
{:else if canPremove}
<div class="hint muted">Пока соперник думает, можно сделать <b>премув</b>: перетащи фигуру — ход сыграется мгновенно после его ответа (если будет легален).</div>
{/if}
{#if dropped && myTurn}<div class="hint warn-text">Премув {dropped.uci.slice(0, 2)}–{dropped.uci.slice(2, 4)} не сработал: стал нелегальным после ответа соперника.</div>{/if}
<input class="input" placeholder="Реплика сопернику (уйдёт вместе со следующим ходом)" maxlength="400" bind:value={phrase} />
<div class="row wrap-row">
<label class="row"><input type="checkbox" bind:checked={offerDraw} /> предложить ничью с ходом</label>
@@ -458,6 +529,26 @@
.nav button:last-child {
border-right: 0;
}
.premove {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
font-size: 12px;
padding: 8px 10px;
border: 1px dashed var(--accent);
border-radius: var(--radius);
}
.premove .btn {
margin-left: auto;
}
.hint {
font-size: 12px;
line-height: 1.4;
}
.warn-text {
color: var(--accent-text, var(--accent));
}
.wrap-row {
flex-wrap: wrap;
font-size: 13px;
+7
View File
@@ -203,6 +203,13 @@ export class GameState {
return { ok: true, record: rec };
}
/** piece standing on a square of the current position (null if empty / bad square) */
pieceAt(square: string): { side: Side; type: PieceSymbol } | null {
if (!/^[a-h][1-8]$/.test(square)) return null;
const p = this.chess.get(square as Square);
return p ? { side: sideOf(p.color), type: p.type } : null;
}
/**
* 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.
+3
View File
@@ -94,6 +94,7 @@ export type GameEvent =
| { 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: "premove_dropped"; gameId: string; side: Side; uci: string; reason: string }
| { 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 }
@@ -109,6 +110,8 @@ export interface MoveDTO {
note: string | null; // note_to_self (only visible to spectators after the game? — shown live, it's fun)
offeredDraw: boolean;
illegal: boolean;
/** played automatically from the human's premove */
premoved?: boolean;
thinkMs: number;
usage: Usage;
eval?: EngineEval | null;