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}` });