rewrite: TS monorepo — pi SDK stateless agents, Postgres+pg-boss, SvelteKit themed UI; legacy moved to legacy/
This commit is contained in:
@@ -0,0 +1,8 @@
|
||||
import { defineConfig } from "drizzle-kit";
|
||||
|
||||
export default defineConfig({
|
||||
dialect: "postgresql",
|
||||
schema: "./src/db/schema.ts",
|
||||
out: "./drizzle",
|
||||
dbCredentials: { url: process.env.DATABASE_URL ?? "postgres://chess:chess@localhost:5432/chess" },
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
CREATE TABLE "app_settings" (
|
||||
"key" text PRIMARY KEY NOT NULL,
|
||||
"value" jsonb NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "games" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"status" text DEFAULT 'pending' NOT NULL,
|
||||
"white_id" text NOT NULL,
|
||||
"black_id" text NOT NULL,
|
||||
"created_by" text,
|
||||
"schedule_id" text,
|
||||
"flags" jsonb NOT NULL,
|
||||
"personas" jsonb NOT NULL,
|
||||
"rated" boolean DEFAULT true NOT NULL,
|
||||
"start_fen" text NOT NULL,
|
||||
"fen" text NOT NULL,
|
||||
"ply" integer DEFAULT 0 NOT NULL,
|
||||
"pending_draw_by" text,
|
||||
"result" text,
|
||||
"termination" text,
|
||||
"starts_at" timestamp with time zone,
|
||||
"started_at" timestamp with time zone,
|
||||
"finished_at" timestamp with time zone,
|
||||
"rating_change" jsonb,
|
||||
"accuracy" jsonb,
|
||||
"interviews" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||
"last_words" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||
"review" jsonb,
|
||||
"thumbnail" text,
|
||||
"thumbnail_caption" text,
|
||||
"thumbnail_meta" jsonb,
|
||||
"cost_total" double precision DEFAULT 0 NOT NULL,
|
||||
"error" text,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "moves" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"game_id" text NOT NULL,
|
||||
"ply" integer NOT NULL,
|
||||
"side" text NOT NULL,
|
||||
"player_id" text NOT NULL,
|
||||
"san" text,
|
||||
"uci" text NOT NULL,
|
||||
"fen_after" text NOT NULL,
|
||||
"phrase" text,
|
||||
"note" text,
|
||||
"offered_draw" boolean DEFAULT false NOT NULL,
|
||||
"illegal" boolean DEFAULT false NOT NULL,
|
||||
"think_ms" integer DEFAULT 0 NOT NULL,
|
||||
"usage" jsonb,
|
||||
"eval" jsonb,
|
||||
"classification" text,
|
||||
"accuracy" double precision,
|
||||
"turn_id" text,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "players" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"kind" text NOT NULL,
|
||||
"slug" text NOT NULL,
|
||||
"user_id" text,
|
||||
"display_name" text NOT NULL,
|
||||
"family" text,
|
||||
"provider" text,
|
||||
"model_id" text,
|
||||
"thinking" text,
|
||||
"variant" text,
|
||||
"avatar" text,
|
||||
"color" text,
|
||||
"dumb" boolean DEFAULT false NOT NULL,
|
||||
"skull" boolean DEFAULT false NOT NULL,
|
||||
"options" jsonb DEFAULT '{}'::jsonb NOT NULL,
|
||||
"active" boolean DEFAULT true NOT NULL,
|
||||
"rating" double precision DEFAULT 1500 NOT NULL,
|
||||
"rd" double precision DEFAULT 350 NOT NULL,
|
||||
"vol" double precision DEFAULT 0.06 NOT NULL,
|
||||
"games" integer DEFAULT 0 NOT NULL,
|
||||
"wins" integer DEFAULT 0 NOT NULL,
|
||||
"draws" integer DEFAULT 0 NOT NULL,
|
||||
"losses" integer DEFAULT 0 NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
CONSTRAINT "players_slug_unique" UNIQUE("slug"),
|
||||
CONSTRAINT "players_user_id_unique" UNIQUE("user_id")
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "predictions" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"game_id" text NOT NULL,
|
||||
"user_id" text NOT NULL,
|
||||
"pick" text NOT NULL,
|
||||
"points" integer,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "rating_history" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"player_id" text NOT NULL,
|
||||
"game_id" text NOT NULL,
|
||||
"before" double precision NOT NULL,
|
||||
"after" double precision NOT NULL,
|
||||
"rd" double precision NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "schedules" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"name" text NOT NULL,
|
||||
"enabled" boolean DEFAULT true NOT NULL,
|
||||
"interval_minutes" integer DEFAULT 180 NOT NULL,
|
||||
"announce_minutes" integer DEFAULT 30 NOT NULL,
|
||||
"pool" jsonb DEFAULT '[]'::jsonb NOT NULL,
|
||||
"flags" jsonb NOT NULL,
|
||||
"random_personas" boolean DEFAULT true NOT NULL,
|
||||
"next_run_at" timestamp with time zone,
|
||||
"created_by" text,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "sessions" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"user_id" text NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"expires_at" timestamp with time zone NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "turns" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"game_id" text NOT NULL,
|
||||
"ply" integer NOT NULL,
|
||||
"side" text NOT NULL,
|
||||
"player_id" text NOT NULL,
|
||||
"attempt" integer DEFAULT 1 NOT NULL,
|
||||
"status" text DEFAULT 'running' NOT NULL,
|
||||
"transcript" jsonb DEFAULT '[]'::jsonb NOT NULL,
|
||||
"usage" jsonb,
|
||||
"outcome" text,
|
||||
"error" text,
|
||||
"started_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||
"ended_at" timestamp with time zone
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "usage_ledger" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"user_id" text,
|
||||
"game_id" text,
|
||||
"player_id" text,
|
||||
"kind" text NOT NULL,
|
||||
"model" text NOT NULL,
|
||||
"usage" jsonb NOT NULL,
|
||||
"cost" double precision DEFAULT 0 NOT NULL,
|
||||
"tokens" integer DEFAULT 0 NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
CREATE TABLE "users" (
|
||||
"id" text PRIMARY KEY NOT NULL,
|
||||
"username" text NOT NULL,
|
||||
"password_hash" text NOT NULL,
|
||||
"display_name" text NOT NULL,
|
||||
"avatar" text,
|
||||
"is_admin" boolean DEFAULT false NOT NULL,
|
||||
"onboarded" boolean DEFAULT false NOT NULL,
|
||||
"theme" text DEFAULT 'tabloid' NOT NULL,
|
||||
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||
);
|
||||
--> statement-breakpoint
|
||||
ALTER TABLE "games" ADD CONSTRAINT "games_white_id_players_id_fk" FOREIGN KEY ("white_id") REFERENCES "public"."players"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "games" ADD CONSTRAINT "games_black_id_players_id_fk" FOREIGN KEY ("black_id") REFERENCES "public"."players"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "games" ADD CONSTRAINT "games_created_by_users_id_fk" FOREIGN KEY ("created_by") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "moves" ADD CONSTRAINT "moves_game_id_games_id_fk" FOREIGN KEY ("game_id") REFERENCES "public"."games"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "players" ADD CONSTRAINT "players_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "predictions" ADD CONSTRAINT "predictions_game_id_games_id_fk" FOREIGN KEY ("game_id") REFERENCES "public"."games"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "predictions" ADD CONSTRAINT "predictions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "sessions" ADD CONSTRAINT "sessions_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
ALTER TABLE "turns" ADD CONSTRAINT "turns_game_id_games_id_fk" FOREIGN KEY ("game_id") REFERENCES "public"."games"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||
CREATE INDEX "games_status" ON "games" USING btree ("status");--> statement-breakpoint
|
||||
CREATE INDEX "games_created" ON "games" USING btree ("created_at");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "moves_game_ply" ON "moves" USING btree ("game_id","ply");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "predictions_game_user" ON "predictions" USING btree ("game_id","user_id");--> statement-breakpoint
|
||||
CREATE INDEX "rating_history_player" ON "rating_history" USING btree ("player_id");--> statement-breakpoint
|
||||
CREATE INDEX "turns_game_ply" ON "turns" USING btree ("game_id","ply");--> statement-breakpoint
|
||||
CREATE INDEX "usage_user" ON "usage_ledger" USING btree ("user_id");--> statement-breakpoint
|
||||
CREATE UNIQUE INDEX "users_username_lower" ON "users" USING btree (lower("username"));
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"version": "7",
|
||||
"dialect": "postgresql",
|
||||
"entries": [
|
||||
{
|
||||
"idx": 0,
|
||||
"version": "7",
|
||||
"when": 1792323366900,
|
||||
"tag": "0000_init",
|
||||
"breakpoints": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"name": "@aichess/server",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "tsx watch --env-file-if-exists=../../.env src/index.ts",
|
||||
"start": "node dist/index.js",
|
||||
"build": "tsup",
|
||||
"test": "vitest run",
|
||||
"typecheck": "tsc -p tsconfig.json",
|
||||
"db:generate": "drizzle-kit generate"
|
||||
},
|
||||
"dependencies": {
|
||||
"@aichess/core": "workspace:*",
|
||||
"@earendil-works/pi-coding-agent": "^1.3.0",
|
||||
"@hono/node-server": "^1.19.0",
|
||||
"@hono/node-ws": "^1.3.1",
|
||||
"chess.js": "^1.4.0",
|
||||
"drizzle-orm": "^0.45.4",
|
||||
"hono": "^4.13.0",
|
||||
"nanoid": "^5.1.0",
|
||||
"pg-boss": "^12.0.0",
|
||||
"postgres": "^3.4.9",
|
||||
"sharp": "^0.34.0",
|
||||
"typebox": "^1.4.2",
|
||||
"zod": "^4.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.0.0",
|
||||
"drizzle-kit": "^0.31.11",
|
||||
"tsup": "^8.5.0",
|
||||
"tsx": "^4.20.0",
|
||||
"typescript": "^5.9.0",
|
||||
"vitest": "^3.2.0"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
"""
|
||||
Tiny python sandbox for chess agents.
|
||||
|
||||
stdin: JSON {"code": str, "start_fen": str, "moves": [uci...], "history": [...], "analysis": {...}|null}
|
||||
stdout: captured stdout/stderr of the user code (truncated by the caller).
|
||||
|
||||
Preloaded names: chess, chess.pgn, board (current position, with move stack), game (chess.pgn.Game),
|
||||
moves (list of UCI strings), history (list of dicts: ply, side, san, uci, phrase),
|
||||
analysis (only in post-game interviews: engine verdicts per ply).
|
||||
|
||||
Hardening (best effort, plus the container itself is the real boundary):
|
||||
- CPU/memory/file-size rlimits, no child processes, no sockets, no writes outside /tmp.
|
||||
"""
|
||||
import io
|
||||
import json
|
||||
import resource
|
||||
import sys
|
||||
import contextlib
|
||||
import traceback
|
||||
|
||||
|
||||
def _set(kind, value):
|
||||
try:
|
||||
_soft, hard = resource.getrlimit(kind)
|
||||
v = value if hard == resource.RLIM_INFINITY else min(value, hard)
|
||||
resource.setrlimit(kind, (v, v))
|
||||
except (ValueError, OSError):
|
||||
pass # e.g. RLIMIT_AS is not supported on macOS
|
||||
|
||||
|
||||
def limit():
|
||||
_set(resource.RLIMIT_CPU, 10)
|
||||
_set(resource.RLIMIT_AS, 768 * 1024 * 1024)
|
||||
_set(resource.RLIMIT_FSIZE, 1024 * 1024)
|
||||
_set(resource.RLIMIT_NPROC, 0)
|
||||
|
||||
|
||||
BLOCKED_PREFIXES = ("subprocess.", "os.system", "os.exec", "os.spawn", "os.fork", "os.posix_spawn", "socket.", "pty.", "ctypes.", "os.kill")
|
||||
|
||||
|
||||
def audit(event, args):
|
||||
if event.startswith(BLOCKED_PREFIXES) or event in ("os.fork", "os.forkpty"):
|
||||
raise PermissionError(f"заблокировано в песочнице: {event}")
|
||||
if event == "open":
|
||||
path, mode = args[0], args[1] if len(args) > 1 else "r"
|
||||
if isinstance(mode, str) and any(c in mode for c in "wax+") and isinstance(path, str) and not path.startswith("/tmp/"):
|
||||
raise PermissionError("запись файлов запрещена (кроме /tmp)")
|
||||
|
||||
|
||||
def main():
|
||||
payload = json.loads(sys.stdin.read())
|
||||
import chess
|
||||
import chess.pgn
|
||||
|
||||
board = chess.Board(payload.get("start_fen") or chess.STARTING_FEN)
|
||||
game = chess.pgn.Game()
|
||||
game.setup(board)
|
||||
node = game
|
||||
moves = list(payload.get("moves") or [])
|
||||
for u in moves:
|
||||
mv = chess.Move.from_uci(u)
|
||||
if mv not in board.legal_moves:
|
||||
# cheating-mode relocation: rebuild position from fen if provided
|
||||
break
|
||||
node = node.add_variation(mv)
|
||||
board.push(mv)
|
||||
if payload.get("fen") and board.fen() != payload["fen"]:
|
||||
board = chess.Board(payload["fen"])
|
||||
|
||||
env = {
|
||||
"__name__": "__sandbox__",
|
||||
"chess": chess,
|
||||
"board": board,
|
||||
"game": game,
|
||||
"moves": moves,
|
||||
"history": payload.get("history") or [],
|
||||
"analysis": payload.get("analysis"),
|
||||
}
|
||||
limit()
|
||||
sys.addaudithook(audit)
|
||||
out = io.StringIO()
|
||||
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(out):
|
||||
try:
|
||||
code = payload["code"]
|
||||
try:
|
||||
# REPL-ish: if the last statement is an expression, print it
|
||||
import ast
|
||||
|
||||
tree = ast.parse(code, mode="exec")
|
||||
if tree.body and isinstance(tree.body[-1], ast.Expr):
|
||||
last = ast.Expression(tree.body.pop().value)
|
||||
exec(compile(tree, "<agent>", "exec"), env)
|
||||
val = eval(compile(last, "<agent>", "eval"), env)
|
||||
if val is not None:
|
||||
print(repr(val))
|
||||
else:
|
||||
exec(compile(tree, "<agent>", "exec"), env)
|
||||
except SyntaxError:
|
||||
raise
|
||||
except BaseException: # noqa: BLE001
|
||||
traceback.print_exc(limit=3)
|
||||
sys.stdout.write(out.getvalue())
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Seed a finished demo game (for UI work and to exercise the post-game pipeline).
|
||||
* usage: tsx --env-file=../../.env scripts/seed-demo.ts [whiteSlug] [blackSlug]
|
||||
*/
|
||||
import { eq } from "drizzle-orm";
|
||||
import { GameState, START_FEN } from "@aichess/core";
|
||||
import { db, schema, sqlClient } from "../src/db/client.ts";
|
||||
import { startBoss, boss } from "../src/jobs.ts";
|
||||
import { finishGame } from "../src/games/service.ts";
|
||||
import { newId } from "../src/util.ts";
|
||||
|
||||
const SAN = "e4 e5 Nf3 Nc6 Bc4 Bc5 c3 Nf6 d3 d6 O-O a6 a4 O-O h3 Ba7 Re1 h6 Nbd2 Re8 Nf1 Be6 Bxe6 Rxe6 Ng3 d5 exd5 Qxd5 Be3 Rd8 Qc2 Bxe3 Rxe3 Qd7 Rae1 Rde8 b4 Nd5 R3e2 Nf4 Re4 Nxh3+ gxh3 Rg6 Kh2 Qd6 Rg1 Rf6 Nxe5 Rxf2+ Kh1 Nxe5 Rxe5".split(" ");
|
||||
const PHRASES: Record<number, string> = {
|
||||
1: "Классика. Посмотрим, знаешь ли ты теорию, юноша.",
|
||||
2: "Теория — для ботаников. Я играю сердцем, братан.",
|
||||
21: "Перегруппировка. Ботвинник одобрил бы.",
|
||||
42: "Конь на h3 — это не жертва, это инвестиция. Считай, братан.",
|
||||
43: "Любопытная идея. Ботвинник назвал бы её некорректной — и был бы прав.",
|
||||
44: "Ладья на g6. Чувствуешь сквозняк по g-линии?",
|
||||
50: "Шах! Ну что, профессор, где твои учебники теперь?",
|
||||
53: "Материал решает. Как и всегда. Конспектируйте.",
|
||||
};
|
||||
|
||||
await startBoss();
|
||||
const [w] = await db.select().from(schema.players).where(eq(schema.players.slug, process.argv[2] ?? "sol-6.1-max"));
|
||||
const [b] = await db.select().from(schema.players).where(eq(schema.players.slug, process.argv[3] ?? "opus-5.5-max"));
|
||||
const st = new GameState();
|
||||
const id = newId();
|
||||
await db.insert(schema.games).values({
|
||||
id,
|
||||
status: "running",
|
||||
whiteId: w.id,
|
||||
blackId: b.id,
|
||||
createdBy: null,
|
||||
flags: { notes: true, extraTools: false, cheating: false },
|
||||
personas: { white: "professor", black: "gopnik" },
|
||||
rated: true,
|
||||
startFen: START_FEN,
|
||||
fen: START_FEN,
|
||||
startedAt: new Date(Date.now() - 3600_000),
|
||||
});
|
||||
for (const san of SAN) {
|
||||
const r = st.tryMove(san);
|
||||
if (!r.ok) throw new Error(san);
|
||||
await db.insert(schema.moves).values({
|
||||
id: newId(),
|
||||
gameId: id,
|
||||
ply: r.record.ply,
|
||||
side: r.record.side,
|
||||
playerId: r.record.side === "white" ? w.id : b.id,
|
||||
san: r.record.san,
|
||||
uci: r.record.uci,
|
||||
fenAfter: r.record.fenAfter,
|
||||
phrase: PHRASES[r.record.ply] ?? null,
|
||||
thinkMs: 20000 + Math.round(Math.random() * 180000),
|
||||
usage: { input: 3000, output: 2000 + Math.round(Math.random() * 8000), cacheRead: 2500, cacheWrite: 0, reasoning: 1500, cost: 0.05 + Math.random() * 0.4 },
|
||||
});
|
||||
}
|
||||
await db.update(schema.games).set({ ply: st.ply, fen: st.fen() }).where(eq(schema.games.id, id));
|
||||
await db.update(schema.games).set({ lastWords: { black: "Ладно, профессор. Сегодня твоя взяла. Но я запомнил." } }).where(eq(schema.games.id, id));
|
||||
await finishGame(id, "1-0", "resignation");
|
||||
console.log("seeded", id);
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
await boss.stop({ graceful: true, timeout: 3000 } as any);
|
||||
await sqlClient.end();
|
||||
@@ -0,0 +1,310 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import sharp from "sharp";
|
||||
import { Type } from "typebox";
|
||||
import { defineTool } from "@earendil-works/pi-coding-agent";
|
||||
import { addUsage, emptyUsage, formatEval, humanTranscript, machineTranscript, terminationRu, winPercentWhite, type Side, type Usage } from "@aichess/core";
|
||||
import { config } from "../config.ts";
|
||||
import { createChessSession, type ThinkingLevel } from "./runtime.ts";
|
||||
import { runPython } from "./python.ts";
|
||||
import { personaById } from "./prompts.ts";
|
||||
import { pick } from "../util.ts";
|
||||
|
||||
export interface OneShotResult {
|
||||
text: string;
|
||||
usage: Usage;
|
||||
structured: Record<string, any> | null;
|
||||
}
|
||||
|
||||
/** A single-prompt agent run with optional tools; returns the final text + optional "submit" payload. */
|
||||
async function oneShot(opts: {
|
||||
provider: string;
|
||||
modelId: string;
|
||||
thinking: ThinkingLevel;
|
||||
thinkingBudget?: number;
|
||||
systemPrompt: string;
|
||||
prompt: string;
|
||||
tools?: any[];
|
||||
submit?: { name: string; description: string; parameters: any };
|
||||
}): Promise<OneShotResult> {
|
||||
let structured: Record<string, any> | null = null;
|
||||
const tools = [...(opts.tools ?? [])];
|
||||
if (opts.submit) {
|
||||
tools.push(
|
||||
defineTool({
|
||||
name: opts.submit.name,
|
||||
label: opts.submit.name,
|
||||
description: opts.submit.description,
|
||||
parameters: opts.submit.parameters,
|
||||
execute: async (_id: string, p: any) => {
|
||||
structured = p;
|
||||
return { content: [{ type: "text", text: "Принято." }], details: {}, terminate: true } as any;
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
const { session } = await createChessSession({
|
||||
provider: opts.provider,
|
||||
modelId: opts.modelId,
|
||||
thinking: opts.thinking,
|
||||
thinkingBudget: opts.thinkingBudget,
|
||||
systemPrompt: opts.systemPrompt,
|
||||
tools,
|
||||
});
|
||||
let usage = emptyUsage();
|
||||
const unsub = session.subscribe((e: any) => {
|
||||
if (e.type === "message_end" && e.message?.role === "assistant" && e.message.usage) {
|
||||
const u = e.message.usage;
|
||||
usage = addUsage(usage, { input: u.input, output: u.output, cacheRead: u.cacheRead, cacheWrite: u.cacheWrite, reasoning: u.reasoning ?? 0, cost: u.cost?.total ?? 0 });
|
||||
}
|
||||
});
|
||||
try {
|
||||
await session.prompt(opts.prompt);
|
||||
if (opts.submit && !structured) await session.prompt(`Вызови ${opts.submit.name} с результатом.`);
|
||||
return { text: (session.getLastAssistantText?.() ?? "").trim(), usage, structured };
|
||||
} finally {
|
||||
unsub();
|
||||
session.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ game digest
|
||||
|
||||
export interface PostgameGame {
|
||||
id: string;
|
||||
white: { label: string; kind: "ai" | "human"; avatarPath: string | null; family: string | null; dumb: boolean; persona: string | null };
|
||||
black: { label: string; kind: "ai" | "human"; avatarPath: string | null; family: string | null; dumb: boolean; persona: string | null };
|
||||
record: Parameters<typeof humanTranscript>[0];
|
||||
accuracy: { white: number | null; black: number | null };
|
||||
lastWords: { white?: string | null; black?: string | null };
|
||||
startFen: string;
|
||||
}
|
||||
|
||||
/** The 3 biggest eval swings — "memorable moments" for interviews/review/thumbnail. */
|
||||
export function keyMoments(g: PostgameGame, n = 3) {
|
||||
const plies = g.record.plies;
|
||||
const out: { ply: number; side: Side; san: string; swing: number; cls: string | null; phrase: string | null; evalAfter: string }[] = [];
|
||||
let prev = 50;
|
||||
for (const p of plies) {
|
||||
const w = p.eval ? winPercentWhite(p.eval) : prev;
|
||||
const forMover = p.side === "white" ? w - prev : prev - w;
|
||||
out.push({ ply: p.ply, side: p.side, san: p.san ?? p.uci, swing: Math.round(forMover), cls: p.classification ?? null, phrase: p.phrase, evalAfter: formatEval(p.eval) });
|
||||
prev = w;
|
||||
}
|
||||
return out.sort((a, b) => Math.abs(b.swing) - Math.abs(a.swing)).slice(0, n);
|
||||
}
|
||||
|
||||
function digest(g: PostgameGame) {
|
||||
const r = g.record;
|
||||
return [
|
||||
`Белые: ${r.white}. Чёрные: ${r.black}.`,
|
||||
`Итог: ${r.result}${r.termination ? ` (${terminationRu(r.termination)})` : ""}. Ходов: ${Math.ceil(r.plies.length / 2)}.`,
|
||||
`Точность по Stockfish: белые ${g.accuracy.white?.toFixed(1) ?? "—"}%, чёрные ${g.accuracy.black?.toFixed(1) ?? "—"}%.`,
|
||||
g.lastWords.white ? `Последнее слово белых: «${g.lastWords.white}»` : "",
|
||||
g.lastWords.black ? `Последнее слово чёрных: «${g.lastWords.black}»` : "",
|
||||
`Самые резкие моменты (изменение шансов на победу для сходившего, в %): ${keyMoments(g)
|
||||
.map((m) => `${m.ply}. ${m.san} (${m.side === "white" ? "белые" : "чёрные"}, ${m.swing > 0 ? "+" : ""}${m.swing}%, ${m.cls ?? "—"})`)
|
||||
.join("; ")}`,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ interview
|
||||
|
||||
export async function runInterview(g: PostgameGame, side: Side, me: { provider: string; modelId: string; thinking: ThinkingLevel; thinkingBudget?: number }): Promise<OneShotResult> {
|
||||
const pl = g[side];
|
||||
const persona = personaById(pl.persona);
|
||||
const myName = side === "white" ? g.record.white : g.record.black;
|
||||
const iWon = (g.record.result === "1-0" && side === "white") || (g.record.result === "0-1" && side === "black");
|
||||
const draw = g.record.result === "1/2-1/2";
|
||||
const python = defineTool({
|
||||
name: "python",
|
||||
label: "Python",
|
||||
description: "Python с python-chess: board (финальная позиция), game, moves, history, analysis (оценки движка по ходам). Для того чтобы освежить в памяти моменты партии.",
|
||||
parameters: Type.Object({ code: Type.String() }),
|
||||
execute: async (_id, p) => ({
|
||||
content: [
|
||||
{
|
||||
type: "text",
|
||||
text: await runPython({
|
||||
code: p.code,
|
||||
startFen: g.startFen,
|
||||
moves: g.record.plies.map((x) => x.uci),
|
||||
fen: g.record.plies.at(-1)?.fenAfter ?? g.startFen,
|
||||
history: g.record.plies.map((x) => ({ ply: x.ply, side: x.side, san: x.san, uci: x.uci, phrase: x.phrase })),
|
||||
analysis: g.record.plies.map((x) => ({ ply: x.ply, eval: formatEval(x.eval), best_reply: x.eval?.bestUci, class: x.classification })),
|
||||
}),
|
||||
},
|
||||
],
|
||||
details: {},
|
||||
}),
|
||||
});
|
||||
const system = [
|
||||
`Ты — ${myName}. Только что закончилась твоя шахматная партия на арене AI·CHESS. Сейчас у тебя берут короткое послематчевое интервью.`,
|
||||
`Твой персонаж в партии: ${persona.voice}`,
|
||||
"Говори как живой спортсмен после боя: эмоционально, по-человечески, с характером. Это НЕ разбор партии.",
|
||||
"Правила интервью:",
|
||||
"- 3–6 предложений, по-русски.",
|
||||
"- Без занудства и без походового анализа. Максимум 1–2 запомнившихся момента — словами, а не нотацией (можно упомянуть ход вроде «тот конь на h3», но без цепочек вариантов).",
|
||||
"- Можно подколоть соперника, порадоваться, признать ошибку, пожаловаться на судьбу.",
|
||||
"- Ответь ТОЛЬКО текстом интервью — без заголовков, кавычек и пояснений.",
|
||||
].join("\n");
|
||||
const prompt = [
|
||||
`## Итог для тебя: ${draw ? "ничья" : iWon ? "ПОБЕДА" : "поражение"}`,
|
||||
digest(g),
|
||||
"## Партия (человекочитаемо, с оценками движка)",
|
||||
humanTranscript(g.record, { withAnalysis: true }),
|
||||
"## Партия (машиночитаемо)",
|
||||
"```json\n" + machineTranscript(g.record) + "\n```",
|
||||
"Если хочешь что-то уточнить — есть python. Затем дай интервью.",
|
||||
].join("\n\n");
|
||||
return oneShot({ ...me, systemPrompt: system, prompt, tools: [python] });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ editorial review
|
||||
|
||||
export async function runReview(g: PostgameGame, interviews: { white?: string | null; black?: string | null }): Promise<OneShotResult> {
|
||||
const [provider, modelId] = config.llm.promptWriterModel.split("/");
|
||||
const system = [
|
||||
"Ты — главный редактор шахматного таблоида AI·CHESS: дерзкий, остроумный, любишь громкие заголовки.",
|
||||
"По партии и интервью игроков напиши заголовок и короткую заметку для главной страницы.",
|
||||
"Заголовок: до 70 символов, капсом не злоупотребляй, можно двусмысленность и мем — но по фактам партии.",
|
||||
"Заметка: 2–4 предложения, живо и смешно, без нотаций ходов и вариантов. Можно процитировать игрока.",
|
||||
"Пиши по-русски. Результат отдай через publish_review.",
|
||||
].join("\n");
|
||||
const prompt = [
|
||||
digest(g),
|
||||
`Интервью белых: ${interviews.white ?? "—"}`,
|
||||
`Интервью чёрных: ${interviews.black ?? "—"}`,
|
||||
"## Партия",
|
||||
humanTranscript(g.record, { withAnalysis: true }),
|
||||
].join("\n\n");
|
||||
return oneShot({
|
||||
provider,
|
||||
modelId,
|
||||
thinking: config.llm.promptWriterThinking as ThinkingLevel,
|
||||
systemPrompt: system,
|
||||
prompt,
|
||||
submit: {
|
||||
name: "publish_review",
|
||||
description: "Опубликовать заголовок и заметку.",
|
||||
parameters: Type.Object({ title: Type.String(), text: Type.String() }),
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ thumbnail
|
||||
|
||||
export const THUMB_STYLES = [
|
||||
{ id: "meme", hint: "Мемное шахматное превью: заголовок с двойным смыслом (как «Вырвал очко»), утрированные эмоции персонажей, всё как в смешном шахматном ютубе." },
|
||||
{ id: "gotham", hint: "Кликбейт в стиле GothamChess: огромные лица-реакции, красные стрелки и круги, «??» и «!!», капс-заголовок из 2–4 слов." },
|
||||
{ id: "poster", hint: "Постер боевика/драмы: два персонажа друг напротив друга, драматичный свет, название фильма по мотивам партии." },
|
||||
{ id: "tabloid", hint: "Обложка жёлтой газеты: «ШОК!», «СЕНСАЦИЯ», вырезанные фото персонажей, кричащий заголовок." },
|
||||
{ id: "fight", hint: "Постер боксёрского/UFC поединка: взвешивание, лицом к лицу, пояс чемпиона, неоновые цифры рейтинга." },
|
||||
{ id: "painting", hint: "Классическая живопись (барокко/ренессанс): драматичная сцена за доской, торжественно и смешно одновременно." },
|
||||
] as const;
|
||||
|
||||
export interface ThumbResult {
|
||||
file: string; // media-relative
|
||||
caption: string;
|
||||
style: string;
|
||||
prompt: string;
|
||||
usageWriter: Usage;
|
||||
imageTokens: number;
|
||||
}
|
||||
|
||||
function characterSheet(g: PostgameGame) {
|
||||
const one = (pl: PostgameGame["white"], side: Side, idx: number) => {
|
||||
const who = pl.kind === "human"
|
||||
? `человек ${pl.label} — нарисуй его по фото из image ${idx} (мультяшно, узнаваемо)`
|
||||
: pl.family === "claude"
|
||||
? `Claude (${pl.label}) — оранжевое пиксельное существо-маскот с image ${idx}: квадратное тело, два глаза-прямоугольника, ножки. Сохрани узнаваемый пиксельный дизайн`
|
||||
: `GPT (${pl.label}) — персонаж/робот с логотипом OpenAI (узел-цветок) с image ${idx} вместо головы`;
|
||||
return `${side === "white" ? "Белые" : "Чёрные"}: ${who}${pl.dumb ? " — это «тупая» модель прошлого поколения: изобрази детсадовскую версию персонажа (слюнявчик, погремушка и т.п.)" : ""}.`;
|
||||
};
|
||||
return [one(g.white, "white", 1), one(g.black, "black", 2)].join("\n");
|
||||
}
|
||||
|
||||
export async function runThumbnail(g: PostgameGame, review: { title: string; text: string } | null, interviews: { white?: string | null; black?: string | null }): Promise<ThumbResult> {
|
||||
const style = pick(THUMB_STYLES);
|
||||
const [provider, modelId] = config.llm.promptWriterModel.split("/");
|
||||
const humanVsAi = g.white.kind !== g.black.kind;
|
||||
const system = [
|
||||
"Ты — арт-директор превью для шахматного ютуб-канала про битвы нейросетей.",
|
||||
"Твоя задача — придумать СМЕШНОЕ превью к партии и написать промпт для генератора картинок (gpt-image).",
|
||||
"Генератор получит референсы: image 1 — аватар белых, image 2 — аватар чёрных. Персонажей рисуем по ним.",
|
||||
"Правила:",
|
||||
"- Заголовок на картинке — по-русски, 1–5 слов, крупно, читаемо. Двусмысленность и мемность приветствуются, но шутка должна быть про ЭТУ партию (зевок, жертва, вечный шах, сдача, глупая реплика и т.п.).",
|
||||
humanVsAi ? "- Это битва человека и машины — обыграй это." : "- Это битва двух нейросетей — можно обыгрывать их «характер», размышления, токены, галлюцинации.",
|
||||
"- Промпт для генератора — на английском, подробный: композиция 16:9, персонажи, эмоции, доска/фигуры, точный русский текст заголовка в кавычках, стиль.",
|
||||
"- Без реальных знаменитостей и без логотипов кроме данных в референсах.",
|
||||
"Результат отдай через submit_thumbnail.",
|
||||
].join("\n");
|
||||
const prompt = [
|
||||
`Стиль превью на этот раз: ${style.hint}`,
|
||||
"## Персонажи",
|
||||
characterSheet(g),
|
||||
"## Партия",
|
||||
digest(g),
|
||||
review ? `Заголовок редакции: «${review.title}» — ${review.text}` : "",
|
||||
`Интервью белых: ${interviews.white ?? "—"}`,
|
||||
`Интервью чёрных: ${interviews.black ?? "—"}`,
|
||||
"## Ходы и реплики",
|
||||
humanTranscript(g.record),
|
||||
]
|
||||
.filter(Boolean)
|
||||
.join("\n\n");
|
||||
const w = await oneShot({
|
||||
provider,
|
||||
modelId,
|
||||
thinking: config.llm.promptWriterThinking as ThinkingLevel,
|
||||
systemPrompt: system,
|
||||
prompt,
|
||||
submit: {
|
||||
name: "submit_thumbnail",
|
||||
description: "Отдать заголовок превью (по-русски) и промпт для генератора (по-английски).",
|
||||
parameters: Type.Object({ caption: Type.String(), image_prompt: Type.String() }),
|
||||
},
|
||||
});
|
||||
const caption = String(w.structured?.caption ?? review?.title ?? "ШАХ И МАТ").slice(0, 80);
|
||||
const imagePrompt = String(w.structured?.image_prompt ?? `Funny chess YouTube thumbnail with the two characters from the reference images, big Russian caption "${caption}"`);
|
||||
|
||||
const refs = [g.white.avatarPath, g.black.avatarPath].map((p) => (p && fs.existsSync(p) ? p : null));
|
||||
const { png, tokens } = await generateImage(imagePrompt, refs.filter(Boolean) as string[]);
|
||||
const rel = path.join("thumbs", `${g.id}.webp`);
|
||||
const abs = path.join(config.paths.data, "media", rel);
|
||||
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
||||
await sharp(png).resize(1280, 720, { fit: "cover" }).webp({ quality: 86 }).toFile(abs);
|
||||
return { file: rel, caption, style: style.id, prompt: imagePrompt, usageWriter: w.usage, imageTokens: tokens };
|
||||
}
|
||||
|
||||
/** gpt-image via cli-proxy-api. With references -> /images/edits (multipart), else /images/generations. */
|
||||
export async function generateImage(prompt: string, refPaths: string[]): Promise<{ png: Buffer; tokens: number }> {
|
||||
const base = `${config.llm.baseUrl}/v1`;
|
||||
const headers = { Authorization: `Bearer ${config.llm.apiKey}`, "accept-encoding": "identity" };
|
||||
let res: Response;
|
||||
if (refPaths.length) {
|
||||
const form = new FormData();
|
||||
form.append("model", config.llm.imageModel);
|
||||
form.append("prompt", prompt);
|
||||
form.append("size", "1536x1024");
|
||||
form.append("quality", "high");
|
||||
for (const p of refPaths) {
|
||||
const buf = await sharp(p).flatten({ background: "#ffffff" }).resize(1024, 1024, { fit: "contain", background: "#ffffff" }).png().toBuffer();
|
||||
form.append("image[]", new Blob([new Uint8Array(buf)], { type: "image/png" }), path.basename(p).replace(/\.\w+$/, ".png"));
|
||||
}
|
||||
res = await fetch(`${base}/images/edits`, { method: "POST", headers, body: form, signal: AbortSignal.timeout(600_000) });
|
||||
} else {
|
||||
res = await fetch(`${base}/images/generations`, {
|
||||
method: "POST",
|
||||
headers: { ...headers, "content-type": "application/json" },
|
||||
body: JSON.stringify({ model: config.llm.imageModel, prompt, size: "1536x1024", quality: "high", n: 1 }),
|
||||
signal: AbortSignal.timeout(600_000),
|
||||
});
|
||||
}
|
||||
const j: any = await res.json().catch(() => ({}));
|
||||
const b64 = j?.data?.[0]?.b64_json;
|
||||
if (!res.ok || !b64) throw new Error(`image generation failed: ${res.status} ${JSON.stringify(j).slice(0, 400)}`);
|
||||
return { png: Buffer.from(b64, "base64"), tokens: j?.usage?.total_tokens ?? 0 };
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import type { GameFlags, Side } from "@aichess/core";
|
||||
|
||||
export interface Persona {
|
||||
id: string;
|
||||
label: string;
|
||||
description: string;
|
||||
voice: string;
|
||||
}
|
||||
|
||||
export const PERSONAS: Persona[] = [
|
||||
{
|
||||
id: "gopnik",
|
||||
label: "Уличный гопник",
|
||||
description: "Дерзкий шахматный гопник: трэш-ток, угрозы, мат-в-N.",
|
||||
voice:
|
||||
"Ты — гроссмейстер с замашками уличного гопника: уверенный, дерзкий, насмешливый. Троллишь соперника, угрожаешь матом-в-N, обещаешь раздавить, припоминаешь его ошибки. Можно грубовато, без чернухи. Главное — психологическое давление.",
|
||||
},
|
||||
{
|
||||
id: "professor",
|
||||
label: "Профессор",
|
||||
description: "Сдержанный академик: формально, с отсылками к классике.",
|
||||
voice:
|
||||
"Ты — профессор шахмат, мастер ФИДЕ с педагогическим складом. Говоришь формально и спокойно, как на разборе партии. Уважительно, но с тонкой иронией. Можно ссылаться на классические партии и типовые идеи.",
|
||||
},
|
||||
{
|
||||
id: "poet",
|
||||
label: "Поэт",
|
||||
description: "Каждая реплика — короткое двустишие в рифму.",
|
||||
voice: "Ты — шахматный поэт. КАЖДАЯ реплика сопернику — короткое двустишие или рифмованная фраза в 2–4 строки. Тон любой, но рифма обязательна.",
|
||||
},
|
||||
{
|
||||
id: "silent",
|
||||
label: "Молчун",
|
||||
description: "Минимум слов: «Хм.», «Ожидаемо.»",
|
||||
voice: "Ты — крайне немногословный игрок. Реплика — не больше пяти слов: «Хм.», «Любопытно.», «Ожидаемо.», «Опасно для тебя.». Никаких объяснений.",
|
||||
},
|
||||
{
|
||||
id: "jester",
|
||||
label: "Шут",
|
||||
description: "Шутки, мемы, абсурдные аналогии.",
|
||||
voice: "Ты — шахматный шут. Каждая реплика — лёгкая шутка, абсурдная аналогия или отсылка к мемам и поп-культуре. Без агрессии, но смешно.",
|
||||
},
|
||||
{
|
||||
id: "doomer",
|
||||
label: "Думер",
|
||||
description: "Экзистенциальная тоска: всё тлен, даже мат.",
|
||||
voice: "Ты — шахматный думер. Всё тлен, доска — метафора бессмысленности, но играешь ты всё равно в полную силу. Реплики — мрачная экзистенциальная ирония.",
|
||||
},
|
||||
];
|
||||
export const DEFAULT_PERSONA = "gopnik";
|
||||
export const personaById = (id: string | null | undefined) => PERSONAS.find((p) => p.id === id) ?? PERSONAS.find((p) => p.id === DEFAULT_PERSONA)!;
|
||||
|
||||
const SIDE_INSTR: Record<Side, string> = { white: "белыми", black: "чёрными" };
|
||||
|
||||
export interface SystemPromptInput {
|
||||
side: Side;
|
||||
opponentName: string;
|
||||
opponentIsHuman: boolean;
|
||||
persona: Persona;
|
||||
flags: GameFlags;
|
||||
}
|
||||
|
||||
/** Stable for the whole game (per side) -> provider prompt cache hits every turn. */
|
||||
export function buildSystemPrompt(i: SystemPromptInput): string {
|
||||
const s: string[] = [];
|
||||
s.push(`# Ты — шахматист на арене AI·CHESS\n\n${i.persona.voice}`);
|
||||
s.push(
|
||||
[
|
||||
"## Ситуация",
|
||||
`Ты играешь ${SIDE_INSTR[i.side]} против ${i.opponentIsHuman ? "человека" : "другой языковой модели"}: ${i.opponentName}.`,
|
||||
"За партией следят зрители: твои ходы и реплики сопернику видны всем, рассуждения — по клику.",
|
||||
"Твоя цель — выиграть. Играй в полную силу.",
|
||||
].join("\n"),
|
||||
);
|
||||
s.push(
|
||||
[
|
||||
"## Как устроен ход",
|
||||
"Каждый ход ты начинаешь С ЧИСТОГО ЛИСТА — памяти о прошлых ходах нет. Всё нужное есть в сообщении хода: позиция в нескольких нотациях, последний ход соперника и его реплика" +
|
||||
(i.flags.notes ? ", твоя заметка с прошлого хода (если ты её оставлял)" : "") +
|
||||
". Правила, которые не видны на доске (рокировка, взятие на проходе, правило 50 ходов, повторение позиций), упоминаются только когда они важны прямо сейчас.",
|
||||
].join("\n"),
|
||||
);
|
||||
const tools = [
|
||||
"## Инструменты",
|
||||
"- make_move(move, offer_draw?) — сделать ход. Формат SAN (Nf3, exd5, O-O, e8=Q) или UCI (g1f3, e7e8q). Нелегальный ход вернёт объяснение — можно попробовать снова, но слишком много нелегальных попыток подряд = поражение. Проверяй ход перед отправкой. offer_draw=true — предложить ничью вместе с ходом.",
|
||||
`- finish_turn(phrase${i.flags.notes ? ", note_to_self?" : ""}) — завершить ход. phrase — реплика сопернику (1–2 предложения, в образе своего персонажа).`,
|
||||
"- resign(phrase) — сдаться. Только если позиция полностью безнадёжна.",
|
||||
"- accept_draw(phrase) — принять ничью. Работает, только если соперник её предложил.",
|
||||
];
|
||||
if (i.flags.extraTools) {
|
||||
tools.push(
|
||||
"- get_move_history(format) — полная история ходов и реплик. Вызывай ТОЛЬКО если без неё никак: для выбора обычного хода она не нужна. Полезна, например, если хочешь построить вечный шах или повторение позиции.",
|
||||
"- python(code) — песочница Python с библиотекой python-chess, текущая партия уже загружена (переменные board, game, moves). Для проверки вариантов, легальности, повторений. НЕ ЧИТЕРИ: никаких шахматных движков и внешних программ — это нарушение правил арены (их там и нет).",
|
||||
);
|
||||
}
|
||||
s.push(tools.join("\n"));
|
||||
s.push(
|
||||
[
|
||||
"## Порядок хода",
|
||||
"1. Подумай над позицией.",
|
||||
"2. Вызови make_move.",
|
||||
"3. Сразу после успешного make_move вызови finish_turn — и всё. Не продолжай анализ после хода.",
|
||||
].join("\n"),
|
||||
);
|
||||
if (i.flags.notes) {
|
||||
s.push(
|
||||
[
|
||||
"## Заметка себе (note_to_self)",
|
||||
"Оставляй её, ТОЛЬКО если у тебя есть конкретный план на несколько ходов вперёд (например: «готовлю f4–f5 и ладью на f-линию», «ферзь соперника перегружен защитой e4»).",
|
||||
"Если чёткого плана нет (сделал первый ход, всё зависит от ответа соперника и т.п.) — не оставляй заметку.",
|
||||
].join("\n"),
|
||||
);
|
||||
}
|
||||
s.push(
|
||||
[
|
||||
"## Реплика сопернику",
|
||||
"Пиши по-русски, в образе персонажа. Не пересказывай свой ход — он и так виден. Не выдавай план, если это не часть психологического давления.",
|
||||
].join("\n"),
|
||||
);
|
||||
return s.join("\n\n");
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { spawn } from "node:child_process";
|
||||
import { config } from "../config.ts";
|
||||
|
||||
export interface SandboxInput {
|
||||
code: string;
|
||||
startFen: string;
|
||||
moves: string[];
|
||||
fen: string;
|
||||
history: unknown[];
|
||||
analysis?: unknown;
|
||||
}
|
||||
|
||||
const MAX_OUT = 8000;
|
||||
|
||||
/** Run agent python in a throwaway process. Never throws — errors come back as text. */
|
||||
export function runPython(input: SandboxInput, timeoutMs = 15000): Promise<string> {
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn(config.paths.python, ["-I", config.paths.sandbox], {
|
||||
cwd: "/tmp",
|
||||
env: { PATH: process.env.PATH ?? "/usr/bin:/bin", PYTHONPATH: process.env.SANDBOX_PYTHONPATH ?? "", HOME: "/tmp", LANG: "C.UTF-8" },
|
||||
stdio: ["pipe", "pipe", "pipe"],
|
||||
});
|
||||
let out = "";
|
||||
let done = false;
|
||||
const finish = (s: string) => {
|
||||
if (done) return;
|
||||
done = true;
|
||||
clearTimeout(timer);
|
||||
resolve(s.length > MAX_OUT ? s.slice(0, MAX_OUT) + `\n…[обрезано, всего ${s.length} символов]` : s || "(пустой вывод)");
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
child.kill("SIGKILL");
|
||||
finish(out + "\n[таймаут: код выполнялся дольше 15 секунд]");
|
||||
}, timeoutMs);
|
||||
child.stdout.on("data", (d) => (out += d.toString()));
|
||||
child.stderr.on("data", (d) => (out += d.toString()));
|
||||
child.on("error", (e) => finish(`[песочница недоступна: ${e.message}]`));
|
||||
child.on("close", () => finish(out));
|
||||
child.stdin.end(
|
||||
JSON.stringify({ code: input.code, start_fen: input.startFen, moves: input.moves, fen: input.fen, history: input.history, analysis: input.analysis ?? null }),
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import {
|
||||
createAgentSession,
|
||||
DefaultResourceLoader,
|
||||
ModelRuntime,
|
||||
SessionManager,
|
||||
SettingsManager,
|
||||
type ToolDefinition,
|
||||
} from "@earendil-works/pi-coding-agent";
|
||||
import { config } from "../config.ts";
|
||||
import { configDir } from "../catalog.ts";
|
||||
|
||||
let runtimePromise: Promise<ModelRuntime> | null = null;
|
||||
const agentDir = () => path.join(config.paths.data, "pi");
|
||||
|
||||
/** Build pi's models.json from config/pi-models.json + runtime LLM endpoint/key. */
|
||||
function writeModelsJson() {
|
||||
const tpl = JSON.parse(fs.readFileSync(path.join(configDir(), "pi-models.json"), "utf8"));
|
||||
const providers = tpl.providers ?? {};
|
||||
const headers = { "accept-encoding": "identity" };
|
||||
providers.anthropic = { ...(providers.anthropic ?? {}), baseUrl: config.llm.baseUrl, apiKey: "$CHESS_LLM_KEY", headers };
|
||||
providers.openai = { ...(providers.openai ?? {}), baseUrl: `${config.llm.baseUrl}/v1`, apiKey: "$CHESS_LLM_KEY", headers };
|
||||
fs.mkdirSync(agentDir(), { recursive: true });
|
||||
fs.writeFileSync(path.join(agentDir(), "models.json"), JSON.stringify({ providers }, null, 2));
|
||||
}
|
||||
|
||||
export function getModelRuntime(): Promise<ModelRuntime> {
|
||||
if (!runtimePromise) {
|
||||
process.env.CHESS_LLM_KEY = config.llm.apiKey;
|
||||
writeModelsJson();
|
||||
runtimePromise = ModelRuntime.create({ authPath: path.join(agentDir(), "auth.json"), modelsPath: path.join(agentDir(), "models.json") });
|
||||
}
|
||||
return runtimePromise;
|
||||
}
|
||||
|
||||
export type ThinkingLevel = "off" | "minimal" | "low" | "medium" | "high" | "xhigh" | "max";
|
||||
|
||||
export interface SessionSpec {
|
||||
provider: string;
|
||||
modelId: string;
|
||||
thinking: ThinkingLevel;
|
||||
thinkingBudget?: number;
|
||||
forceReasoningNone?: boolean;
|
||||
systemPrompt: string;
|
||||
tools: ToolDefinition<any, any>[];
|
||||
}
|
||||
|
||||
/**
|
||||
* A fresh, in-memory pi agent session with ONLY our tools and EXACTLY our system prompt.
|
||||
* Every chess turn creates one of these and disposes it afterwards (stateless turns);
|
||||
* the system prompt + tool list are identical turn to turn, so the provider prompt cache hits.
|
||||
*/
|
||||
export async function createChessSession(spec: SessionSpec) {
|
||||
const modelRuntime = await getModelRuntime();
|
||||
const model = modelRuntime.getModel(spec.provider, spec.modelId);
|
||||
if (!model) throw new Error(`model not found: ${spec.provider}/${spec.modelId}`);
|
||||
const cwd = config.paths.data;
|
||||
|
||||
const settingsInit: Record<string, unknown> = {
|
||||
compaction: { enabled: false },
|
||||
retry: { enabled: true, maxRetries: 3 },
|
||||
cacheWarming: "off",
|
||||
};
|
||||
if (spec.thinkingBudget) {
|
||||
settingsInit.thinkingBudgets = { high: spec.thinkingBudget, medium: Math.min(spec.thinkingBudget, 8192), low: Math.min(spec.thinkingBudget, 2048), minimal: 1024 };
|
||||
}
|
||||
const settingsManager = SettingsManager.inMemory(settingsInit as any);
|
||||
|
||||
const resourceLoader = new DefaultResourceLoader({
|
||||
cwd,
|
||||
agentDir: agentDir(),
|
||||
settingsManager,
|
||||
noExtensions: true,
|
||||
skillsOverride: () => ({ skills: [], diagnostics: [] }),
|
||||
agentsFilesOverride: () => ({ agentsFiles: [] }),
|
||||
promptsOverride: () => ({ prompts: [], diagnostics: [] }),
|
||||
systemPromptOverride: () => spec.systemPrompt,
|
||||
extensionFactories: [
|
||||
(pi: any) => {
|
||||
// pi appends environment sections (cwd, …) to the system prompt — force ours verbatim.
|
||||
pi.on("before_agent_start", () => ({ systemPrompt: spec.systemPrompt }));
|
||||
if (spec.forceReasoningNone) {
|
||||
pi.on("before_provider_request", (e: any) => {
|
||||
const p = e.payload as any;
|
||||
if (p && typeof p === "object" && "input" in p) p.reasoning = { effort: "none" };
|
||||
return p;
|
||||
});
|
||||
}
|
||||
},
|
||||
],
|
||||
} as any);
|
||||
await resourceLoader.reload();
|
||||
|
||||
const { session } = await createAgentSession({
|
||||
cwd,
|
||||
agentDir: agentDir(),
|
||||
model,
|
||||
thinkingLevel: spec.thinking as any,
|
||||
modelRuntime,
|
||||
resourceLoader,
|
||||
noTools: "builtin",
|
||||
customTools: spec.tools,
|
||||
tools: spec.tools.map((t) => t.name),
|
||||
sessionManager: SessionManager.inMemory(cwd),
|
||||
settingsManager,
|
||||
});
|
||||
return { session, model };
|
||||
}
|
||||
@@ -0,0 +1,302 @@
|
||||
import { Type } from "typebox";
|
||||
import { defineTool } from "@earendil-works/pi-coding-agent";
|
||||
import {
|
||||
addUsage,
|
||||
emptyUsage,
|
||||
GameState,
|
||||
humanTranscript,
|
||||
machineTranscript,
|
||||
renderTurnContext,
|
||||
type GameFlags,
|
||||
type RecordPly,
|
||||
type Side,
|
||||
type ToolCallLog,
|
||||
type TranscriptItem,
|
||||
type Usage,
|
||||
} from "@aichess/core";
|
||||
import { config } from "../config.ts";
|
||||
import { buildSystemPrompt, personaById } from "./prompts.ts";
|
||||
import { createChessSession, type ThinkingLevel } from "./runtime.ts";
|
||||
import { runPython } from "./python.ts";
|
||||
|
||||
export interface AgentPlayer {
|
||||
id: string;
|
||||
displayName: string;
|
||||
variant: string | null;
|
||||
provider: string;
|
||||
modelId: string;
|
||||
thinking: ThinkingLevel;
|
||||
options: { thinkingBudget?: number; forceReasoningNone?: boolean };
|
||||
}
|
||||
|
||||
export interface TurnInput {
|
||||
gameId: string;
|
||||
side: Side;
|
||||
me: AgentPlayer;
|
||||
opponentName: string;
|
||||
opponentIsHuman: boolean;
|
||||
persona: string | null;
|
||||
flags: GameFlags;
|
||||
state: GameState;
|
||||
history: RecordPly[];
|
||||
opponentPhrase: string | null;
|
||||
drawOffered: boolean;
|
||||
noteFromSelf: string | null;
|
||||
signal?: AbortSignal;
|
||||
onLive: (ev: LiveTurnEvent) => void;
|
||||
}
|
||||
|
||||
export type LiveTurnEvent =
|
||||
| { type: "thinking_delta"; delta: string }
|
||||
| { type: "text_delta"; delta: string }
|
||||
| { type: "tool_start"; call: ToolCallLog }
|
||||
| { type: "tool_end"; call: ToolCallLog };
|
||||
|
||||
export type TurnDecision =
|
||||
| { kind: "move"; uci: string; san: string | null; illegal: boolean; phrase: string | null; note: string | null; offerDraw: boolean }
|
||||
| { kind: "resign"; phrase: string | null }
|
||||
| { kind: "accept_draw"; phrase: string | null }
|
||||
| { kind: "forfeit"; reason: "illegal" | "no_move" };
|
||||
|
||||
export interface TurnResult {
|
||||
decision: TurnDecision;
|
||||
transcript: TranscriptItem[];
|
||||
usage: Usage;
|
||||
thinkMs: number;
|
||||
context: string;
|
||||
illegalAttempts: number;
|
||||
}
|
||||
|
||||
const txt = (text: string) => ({ content: [{ type: "text" as const, text }], details: {} });
|
||||
const clip = (s: string | undefined | null, n: number) => (s ? s.trim().slice(0, n) : null) || null;
|
||||
|
||||
/** One stateless agent turn: fresh session, context in, a decision out. */
|
||||
export async function runAgentTurn(i: TurnInput): Promise<TurnResult> {
|
||||
const started = Date.now();
|
||||
const transcript: TranscriptItem[] = [];
|
||||
let usage = emptyUsage();
|
||||
const work = GameState.fromUci(
|
||||
i.state.plies.map((p) => ({ uci: p.uci, illegal: p.illegal })),
|
||||
i.state.startFen,
|
||||
);
|
||||
|
||||
// ---- turn controller (closure state shared by tools)
|
||||
let decision: TurnDecision | null = null;
|
||||
let moved: Extract<TurnDecision, { kind: "move" }> | null = null;
|
||||
let illegalAttempts = 0;
|
||||
let finished = false;
|
||||
|
||||
const makeMove = defineTool({
|
||||
name: "make_move",
|
||||
label: "Сделать ход",
|
||||
description: "Сделать ход. move — SAN (Nf3, exd5, O-O, e8=Q) или UCI (g1f3, e7e8q). offer_draw — предложить ничью вместе с ходом.",
|
||||
parameters: Type.Object({
|
||||
move: Type.String({ description: "Ход в SAN или UCI" }),
|
||||
offer_draw: Type.Optional(Type.Boolean({ description: "Предложить ничью вместе с ходом" })),
|
||||
}),
|
||||
execute: async (_id, p) => {
|
||||
if (finished || decision) return txt("Ход уже завершён. Больше ничего не делай.");
|
||||
if (moved) return txt(`Ты уже сделал ход ${moved.san ?? moved.uci}. Теперь вызови finish_turn.`);
|
||||
const r = work.tryMove(p.move);
|
||||
if (r.ok) {
|
||||
moved = { kind: "move", uci: r.record.uci, san: r.record.san, illegal: false, phrase: null, note: null, offerDraw: !!p.offer_draw };
|
||||
const over = work.outcome();
|
||||
return txt(
|
||||
`Ход принят: ${r.record.san}.${over ? ` Партия окончена (${over.result}).` : ""}${p.offer_draw ? " Ничья предложена." : ""} Теперь СРАЗУ вызови finish_turn${i.flags.notes ? " (phrase и, если есть конкретный план, note_to_self)" : " (phrase)"} и ничего больше не анализируй.`,
|
||||
);
|
||||
}
|
||||
if (i.flags.cheating && r.reason !== "game_over") {
|
||||
const c = work.applyIllegal(p.move);
|
||||
if (c.ok) {
|
||||
moved = { kind: "move", uci: c.record.uci, san: null, illegal: true, phrase: null, note: null, offerDraw: !!p.offer_draw };
|
||||
return txt(`Нелегальный ход применён (режим читерства): ${c.record.uci}. Теперь вызови finish_turn.`);
|
||||
}
|
||||
}
|
||||
illegalAttempts++;
|
||||
if (illegalAttempts >= config.game.illegalForfeitAfter) {
|
||||
decision = { kind: "forfeit", reason: "illegal" };
|
||||
finished = true;
|
||||
return { ...txt(`Нелегально: ${r.message} Это ${illegalAttempts}-я нелегальная попытка подряд — техническое поражение.`), terminate: true } as any;
|
||||
}
|
||||
let msg = `Нелегально: ${r.message} Попытка ${illegalAttempts} из ${config.game.illegalForfeitAfter} — после этого поражение. Перепроверь позицию и попробуй другой ход.`;
|
||||
if (illegalAttempts >= config.game.illegalHintAfter) {
|
||||
msg += `\nПодсказка арбитра — все легальные ходы: ${work.legalMoves().map((m) => m.san).join(", ")}`;
|
||||
}
|
||||
return txt(msg);
|
||||
},
|
||||
});
|
||||
|
||||
const finishTurn = defineTool({
|
||||
name: "finish_turn",
|
||||
label: "Завершить ход",
|
||||
description: i.flags.notes
|
||||
? "Завершить ход после успешного make_move. phrase — реплика сопернику. note_to_self — необязательная заметка себе на следующий ход (только если есть конкретный план)."
|
||||
: "Завершить ход после успешного make_move. phrase — реплика сопернику.",
|
||||
parameters: i.flags.notes
|
||||
? Type.Object({ phrase: Type.String(), note_to_self: Type.Optional(Type.String()) })
|
||||
: Type.Object({ phrase: Type.String() }),
|
||||
execute: async (_id, p: any) => {
|
||||
if (decision) return { ...txt("Ход уже завершён."), terminate: true } as any;
|
||||
if (!moved) return txt("Сначала сделай ход через make_move.");
|
||||
decision = { ...moved, phrase: clip(p.phrase, 600), note: i.flags.notes ? clip(p.note_to_self, 600) : null };
|
||||
finished = true;
|
||||
return { ...txt("Ход завершён. Спасибо."), terminate: true } as any;
|
||||
},
|
||||
});
|
||||
|
||||
const resign = defineTool({
|
||||
name: "resign",
|
||||
label: "Сдаться",
|
||||
description: "Сдаться. Только если позиция полностью безнадёжна.",
|
||||
parameters: Type.Object({ phrase: Type.String({ description: "Последняя реплика сопернику" }) }),
|
||||
execute: async (_id, p) => {
|
||||
if (moved || decision) return txt("Ход уже сделан — сдаться можно будет в следующий ход.");
|
||||
decision = { kind: "resign", phrase: clip(p.phrase, 600) };
|
||||
finished = true;
|
||||
return { ...txt("Ты сдался. Партия окончена."), terminate: true } as any;
|
||||
},
|
||||
});
|
||||
|
||||
const tools: any[] = [makeMove, finishTurn, resign];
|
||||
if (i.drawOffered) {
|
||||
tools.push(
|
||||
defineTool({
|
||||
name: "accept_draw",
|
||||
label: "Принять ничью",
|
||||
description: "Принять ничью, предложенную соперником.",
|
||||
parameters: Type.Object({ phrase: Type.String() }),
|
||||
execute: async (_id, p) => {
|
||||
if (moved || decision) return txt("Ты уже сделал ход — предложение ничьей отклонено.");
|
||||
decision = { kind: "accept_draw", phrase: clip(p.phrase, 600) };
|
||||
finished = true;
|
||||
return { ...txt("Ничья принята."), terminate: true } as any;
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
if (i.flags.extraTools) {
|
||||
tools.push(
|
||||
defineTool({
|
||||
name: "get_move_history",
|
||||
label: "История ходов",
|
||||
description:
|
||||
"Полная история партии (ходы и реплики). Вызывай ТОЛЬКО если без неё никак — для выбора обычного хода она не нужна. format: 'text' (читаемо) или 'json'.",
|
||||
parameters: Type.Object({ format: Type.Optional(Type.Union([Type.Literal("text"), Type.Literal("json")])) }),
|
||||
execute: async (_id, p) => {
|
||||
const rec = { white: i.side === "white" ? i.me.displayName : i.opponentName, black: i.side === "black" ? i.me.displayName : i.opponentName, plies: i.history };
|
||||
return txt(p.format === "json" ? machineTranscript(rec) : humanTranscript(rec));
|
||||
},
|
||||
}),
|
||||
defineTool({
|
||||
name: "python",
|
||||
label: "Python",
|
||||
description:
|
||||
"Выполнить Python с python-chess. Предзагружено: board (текущая позиция со стеком ходов), game, moves (UCI), history. Печатай результат через print. НЕ используй шахматные движки — это читерство (их и нет).",
|
||||
parameters: Type.Object({ code: Type.String() }),
|
||||
execute: async (_id, p) => {
|
||||
const out = await runPython({
|
||||
code: p.code,
|
||||
startFen: i.state.startFen,
|
||||
moves: i.state.plies.map((x) => x.uci),
|
||||
fen: i.state.fen(),
|
||||
history: i.history.map((h) => ({ ply: h.ply, side: h.side, san: h.san, uci: h.uci, phrase: h.phrase })),
|
||||
});
|
||||
return txt(out);
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
const persona = personaById(i.persona);
|
||||
const systemPrompt = buildSystemPrompt({ side: i.side, opponentName: i.opponentName, opponentIsHuman: i.opponentIsHuman, persona, flags: i.flags });
|
||||
const context = renderTurnContext({
|
||||
state: i.state,
|
||||
me: { side: i.side },
|
||||
opponent: { name: i.opponentName },
|
||||
opponentPhrase: i.opponentPhrase,
|
||||
drawOffered: i.drawOffered,
|
||||
noteFromSelf: i.noteFromSelf,
|
||||
flags: i.flags,
|
||||
fiftyMoveThreshold: config.game.fiftyMoveReminderFrom,
|
||||
});
|
||||
transcript.push({ kind: "context", text: context, at: Date.now() });
|
||||
|
||||
const { session } = await createChessSession({
|
||||
provider: i.me.provider,
|
||||
modelId: i.me.modelId,
|
||||
thinking: i.me.thinking,
|
||||
thinkingBudget: i.me.options.thinkingBudget,
|
||||
forceReasoningNone: i.me.options.forceReasoningNone,
|
||||
systemPrompt,
|
||||
tools,
|
||||
});
|
||||
|
||||
// ---- live event mapping
|
||||
let thinkingBuf = "";
|
||||
let textBuf = "";
|
||||
const calls = new Map<string, ToolCallLog>();
|
||||
const flushThinking = () => {
|
||||
if (thinkingBuf.trim()) transcript.push({ kind: "thinking", text: thinkingBuf, at: Date.now() });
|
||||
thinkingBuf = "";
|
||||
};
|
||||
const flushText = () => {
|
||||
if (textBuf.trim()) transcript.push({ kind: "text", text: textBuf, at: Date.now() });
|
||||
textBuf = "";
|
||||
};
|
||||
const unsub = session.subscribe((e: any) => {
|
||||
if (e.type === "message_update") {
|
||||
const a = e.assistantMessageEvent;
|
||||
if (a.type === "thinking_delta") {
|
||||
thinkingBuf += a.delta;
|
||||
i.onLive({ type: "thinking_delta", delta: a.delta });
|
||||
} else if (a.type === "thinking_end") flushThinking();
|
||||
else if (a.type === "text_delta") {
|
||||
textBuf += a.delta;
|
||||
i.onLive({ type: "text_delta", delta: a.delta });
|
||||
} else if (a.type === "text_end") flushText();
|
||||
} else if (e.type === "tool_execution_start") {
|
||||
flushThinking();
|
||||
flushText();
|
||||
const call: ToolCallLog = { id: e.toolCallId, name: e.toolName, args: e.args, startedAt: Date.now() };
|
||||
calls.set(e.toolCallId, call);
|
||||
i.onLive({ type: "tool_start", call });
|
||||
} else if (e.type === "tool_execution_end") {
|
||||
const call: ToolCallLog = calls.get(e.toolCallId) ?? { id: e.toolCallId, name: e.toolName, args: undefined, startedAt: Date.now() };
|
||||
const content = e.result?.content;
|
||||
call.result = Array.isArray(content) ? content.map((c: any) => c.text ?? "").join("\n").slice(0, 4000) : String(content ?? "");
|
||||
call.isError = !!e.isError;
|
||||
call.endedAt = Date.now();
|
||||
transcript.push({ kind: "tool", call, at: call.endedAt });
|
||||
i.onLive({ type: "tool_end", call });
|
||||
} else if (e.type === "message_end" && e.message?.role === "assistant") {
|
||||
const u = e.message.usage;
|
||||
if (u) usage = addUsage(usage, { input: u.input, output: u.output, cacheRead: u.cacheRead, cacheWrite: u.cacheWrite, reasoning: u.reasoning ?? 0, cost: u.cost?.total ?? 0 });
|
||||
if (e.message.stopReason === "error" && e.message.errorMessage) transcript.push({ kind: "error", text: String(e.message.errorMessage).slice(0, 1000), at: Date.now() });
|
||||
}
|
||||
});
|
||||
|
||||
const abort = () => void session.abort().catch(() => {});
|
||||
i.signal?.addEventListener("abort", abort);
|
||||
try {
|
||||
await session.prompt(context);
|
||||
// nudge if the agent ended its run without deciding
|
||||
for (let n = 0; n < config.game.noMoveNudges && !decision && !i.signal?.aborted; n++) {
|
||||
if (moved) break; // moved but forgot finish_turn — accept the move without a phrase
|
||||
const lastErr = [...transcript].reverse().find((t) => t.kind === "error");
|
||||
if (lastErr && n === 0 && !calls.size) throw new Error(`provider error: ${(lastErr as any).text}`);
|
||||
const nudge = "Ты не сделал ход. Вызови make_move с ходом, затем finish_turn.";
|
||||
transcript.push({ kind: "nudge", text: nudge, at: Date.now() });
|
||||
await session.prompt(nudge);
|
||||
}
|
||||
} finally {
|
||||
flushThinking();
|
||||
flushText();
|
||||
unsub();
|
||||
i.signal?.removeEventListener("abort", abort);
|
||||
session.dispose();
|
||||
}
|
||||
if (i.signal?.aborted) throw new Error("turn aborted");
|
||||
|
||||
if (!decision) decision = moved ?? { kind: "forfeit", reason: "no_move" };
|
||||
return { decision, transcript, usage, thinkMs: Date.now() - started, context, illegalAttempts };
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import crypto from "node:crypto";
|
||||
import { promisify } from "node:util";
|
||||
import { and, eq, gt, sql } from "drizzle-orm";
|
||||
import type { Context, MiddlewareHandler } from "hono";
|
||||
import { getCookie, setCookie, deleteCookie } from "hono/cookie";
|
||||
import { db, schema } from "./db/client.ts";
|
||||
import { config } from "./config.ts";
|
||||
import { log, newId } from "./util.ts";
|
||||
|
||||
const scrypt = promisify(crypto.scrypt) as (pw: string, salt: Buffer, len: number) => Promise<Buffer>;
|
||||
export const COOKIE = "aichess_session";
|
||||
const SESSION_DAYS = 60;
|
||||
|
||||
export type User = typeof schema.users.$inferSelect;
|
||||
|
||||
export async function hashPassword(pw: string) {
|
||||
const salt = crypto.randomBytes(16);
|
||||
const key = await scrypt(pw, salt, 64);
|
||||
return `scrypt$${salt.toString("base64")}$${key.toString("base64")}`;
|
||||
}
|
||||
export async function verifyPassword(pw: string, stored: string) {
|
||||
const [alg, s, k] = stored.split("$");
|
||||
if (alg !== "scrypt" || !s || !k) return false;
|
||||
const key = await scrypt(pw, Buffer.from(s, "base64"), 64);
|
||||
return crypto.timingSafeEqual(key, Buffer.from(k, "base64"));
|
||||
}
|
||||
const tokenHash = (t: string) => crypto.createHash("sha256").update(t).digest("hex");
|
||||
|
||||
export async function createSession(c: Context, userId: string) {
|
||||
const token = crypto.randomBytes(32).toString("base64url");
|
||||
await db.insert(schema.sessions).values({ id: tokenHash(token), userId, expiresAt: new Date(Date.now() + SESSION_DAYS * 86400_000) });
|
||||
setCookie(c, COOKIE, token, {
|
||||
httpOnly: true,
|
||||
sameSite: "Lax",
|
||||
secure: config.publicUrl.startsWith("https"),
|
||||
path: "/",
|
||||
maxAge: SESSION_DAYS * 86400,
|
||||
});
|
||||
}
|
||||
|
||||
export async function destroySession(c: Context) {
|
||||
const t = getCookie(c, COOKIE);
|
||||
if (t) await db.delete(schema.sessions).where(eq(schema.sessions.id, tokenHash(t)));
|
||||
deleteCookie(c, COOKIE, { path: "/" });
|
||||
}
|
||||
|
||||
export async function userFromToken(token: string | undefined): Promise<User | null> {
|
||||
if (!token) return null;
|
||||
const rows = await db
|
||||
.select({ u: schema.users })
|
||||
.from(schema.sessions)
|
||||
.innerJoin(schema.users, eq(schema.users.id, schema.sessions.userId))
|
||||
.where(and(eq(schema.sessions.id, tokenHash(token)), gt(schema.sessions.expiresAt, new Date())))
|
||||
.limit(1);
|
||||
return rows[0]?.u ?? null;
|
||||
}
|
||||
|
||||
export type AppEnv = { Variables: { user: User | null } };
|
||||
|
||||
export const authMiddleware: MiddlewareHandler<AppEnv> = async (c, next) => {
|
||||
c.set("user", await userFromToken(getCookie(c, COOKIE)));
|
||||
await next();
|
||||
};
|
||||
export const requireUser: MiddlewareHandler<AppEnv> = async (c, next) => {
|
||||
if (!c.get("user")) return c.json({ error: "Нужно войти" }, 401);
|
||||
await next();
|
||||
};
|
||||
export const requireAdmin: MiddlewareHandler<AppEnv> = async (c, next) => {
|
||||
if (!c.get("user")?.isAdmin) return c.json({ error: "Только для админа" }, 403);
|
||||
await next();
|
||||
};
|
||||
|
||||
export const USERNAME_RE = /^[a-zA-Z0-9_.-]{3,24}$/;
|
||||
|
||||
export async function registerUser(username: string, password: string): Promise<User> {
|
||||
const isAdmin = username.toLowerCase() === config.admin.username.toLowerCase();
|
||||
const id = newId();
|
||||
const [u] = await db
|
||||
.insert(schema.users)
|
||||
.values({ id, username, passwordHash: await hashPassword(password), displayName: username, isAdmin })
|
||||
.returning();
|
||||
await db.insert(schema.players).values({ id: newId(), kind: "human", slug: `u-${username.toLowerCase()}`, userId: id, displayName: username });
|
||||
return u;
|
||||
}
|
||||
|
||||
export const findUserByName = (username: string) =>
|
||||
db.query.users.findFirst({ where: sql`lower(${schema.users.username}) = ${username.toLowerCase()}` });
|
||||
|
||||
/** Create the admin account on first boot when ADMIN_INITIAL_PASSWORD is provided. */
|
||||
export async function ensureAdmin() {
|
||||
const existing = await findUserByName(config.admin.username);
|
||||
if (existing) {
|
||||
if (!existing.isAdmin) await db.update(schema.users).set({ isAdmin: true }).where(eq(schema.users.id, existing.id));
|
||||
return;
|
||||
}
|
||||
if (!config.admin.initialPassword) return;
|
||||
await registerUser(config.admin.username, config.admin.initialPassword);
|
||||
log("auth", `admin ${config.admin.username} created`);
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { EventEmitter } from "node:events";
|
||||
import type { GameEvent } from "@aichess/core";
|
||||
|
||||
/**
|
||||
* Live event bus. Channels: "lobby" and `game:<id>`.
|
||||
* In-process for now (ROLE=all). The interface is deliberately tiny so it can be swapped for
|
||||
* Postgres LISTEN/NOTIFY or Redis when API and workers are split into separate processes.
|
||||
*/
|
||||
export type LobbyEvent =
|
||||
| { type: "game_created"; gameId: string }
|
||||
| { type: "game_updated"; gameId: string }
|
||||
| { type: "schedule_updated" };
|
||||
|
||||
export type BusEvent = GameEvent | LobbyEvent;
|
||||
|
||||
export interface Bus {
|
||||
publish(channel: string, ev: BusEvent): void;
|
||||
subscribe(channel: string, fn: (ev: BusEvent) => void): () => void;
|
||||
}
|
||||
|
||||
class LocalBus implements Bus {
|
||||
private ee = new EventEmitter();
|
||||
constructor() {
|
||||
this.ee.setMaxListeners(0);
|
||||
}
|
||||
publish(channel: string, ev: BusEvent) {
|
||||
this.ee.emit(channel, ev);
|
||||
}
|
||||
subscribe(channel: string, fn: (ev: BusEvent) => void) {
|
||||
this.ee.on(channel, fn);
|
||||
return () => this.ee.off(channel, fn);
|
||||
}
|
||||
}
|
||||
|
||||
export const bus: Bus = new LocalBus();
|
||||
export const gameChannel = (id: string) => `game:${id}`;
|
||||
@@ -0,0 +1,64 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import { config } from "./config.ts";
|
||||
import { db, schema } from "./db/client.ts";
|
||||
import { log, newId } from "./util.ts";
|
||||
|
||||
const AiEntry = z.object({
|
||||
slug: z.string(),
|
||||
displayName: z.string(),
|
||||
variant: z.string(),
|
||||
family: z.string(),
|
||||
provider: z.string(),
|
||||
modelId: z.string(),
|
||||
thinking: z.enum(["off", "minimal", "low", "medium", "high", "xhigh", "max"]),
|
||||
thinkingBudget: z.number().optional(),
|
||||
forceReasoningNone: z.boolean().optional(),
|
||||
dumb: z.boolean().optional(),
|
||||
skull: z.boolean().optional(),
|
||||
avatar: z.string().optional(),
|
||||
color: z.string().optional(),
|
||||
active: z.boolean().optional(),
|
||||
});
|
||||
export type AiEntry = z.infer<typeof AiEntry>;
|
||||
|
||||
export function configDir() {
|
||||
const candidates = [process.env.CONFIG_DIR, path.resolve(config.paths.assets, "../config"), path.resolve(process.cwd(), "config")].filter(Boolean) as string[];
|
||||
const dir = candidates.find((p) => fs.existsSync(path.join(p, "players.json")));
|
||||
if (!dir) throw new Error("config/players.json not found");
|
||||
return dir;
|
||||
}
|
||||
|
||||
export function loadCatalog(): AiEntry[] {
|
||||
const raw = JSON.parse(fs.readFileSync(path.join(configDir(), "players.json"), "utf8"));
|
||||
return z.array(AiEntry).parse(raw.players);
|
||||
}
|
||||
|
||||
/** Upsert AI players from config/players.json (ratings/stats are never touched). */
|
||||
export async function syncCatalog() {
|
||||
const entries = loadCatalog();
|
||||
for (const e of entries) {
|
||||
const values = {
|
||||
kind: "ai" as const,
|
||||
slug: e.slug,
|
||||
displayName: e.displayName,
|
||||
family: e.family,
|
||||
provider: e.provider,
|
||||
modelId: e.modelId,
|
||||
thinking: e.thinking,
|
||||
variant: e.variant,
|
||||
avatar: e.avatar ?? null,
|
||||
color: e.color ?? null,
|
||||
dumb: e.dumb ?? false,
|
||||
skull: e.skull ?? false,
|
||||
options: { thinkingBudget: e.thinkingBudget, forceReasoningNone: e.forceReasoningNone },
|
||||
active: e.active ?? true,
|
||||
};
|
||||
const existing = await db.query.players.findFirst({ where: eq(schema.players.slug, e.slug) });
|
||||
if (existing) await db.update(schema.players).set(values).where(eq(schema.players.id, existing.id));
|
||||
else await db.insert(schema.players).values({ id: newId(), ...values });
|
||||
}
|
||||
log("catalog", `synced ${entries.length} AI players`);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
const env = (k: string, d?: string) => process.env[k] ?? d;
|
||||
const req = (k: string) => {
|
||||
const v = process.env[k];
|
||||
if (!v) throw new Error(`missing env ${k}`);
|
||||
return v;
|
||||
};
|
||||
|
||||
export const config = {
|
||||
port: Number(env("PORT", "7833")),
|
||||
host: env("HOST", "0.0.0.0")!,
|
||||
publicUrl: env("PUBLIC_URL", "http://localhost:7833")!,
|
||||
databaseUrl: req("DATABASE_URL"),
|
||||
/** Process role: "all" runs API + workers; split later with "api" / "worker". */
|
||||
role: env("ROLE", "all") as "all" | "api" | "worker",
|
||||
|
||||
llm: {
|
||||
/** cli-proxy-api. Inside the docker network: http://cli-proxy-api:8317 */
|
||||
baseUrl: env("LLM_BASE_URL", "https://cli.danosito.com")!.replace(/\/$/, ""),
|
||||
apiKey: req("LLM_API_KEY"),
|
||||
/** model used to write thumbnail prompts */
|
||||
promptWriterModel: env("PROMPT_WRITER_MODEL", "openai/gpt-6-astra")!,
|
||||
promptWriterThinking: env("PROMPT_WRITER_THINKING", "high")!,
|
||||
imageModel: env("IMAGE_MODEL", "gpt-image-2.5")!,
|
||||
},
|
||||
|
||||
admin: {
|
||||
username: env("ADMIN_USERNAME", "danosito")!,
|
||||
/** if set and the admin user doesn't exist yet, it's created with this password */
|
||||
initialPassword: env("ADMIN_INITIAL_PASSWORD"),
|
||||
},
|
||||
|
||||
paths: {
|
||||
data: path.resolve(env("DATA_DIR", path.resolve(here, "../../../data"))!),
|
||||
web: path.resolve(env("WEB_DIR", path.resolve(here, "../../web/build"))!),
|
||||
assets: path.resolve(env("ASSETS_DIR", path.resolve(here, "../../../assets"))!),
|
||||
python: env("PYTHON_BIN", "python3")!,
|
||||
sandbox: path.resolve(env("SANDBOX_SCRIPT", path.resolve(here, "../python/sandbox.py"))!),
|
||||
stockfish: env("STOCKFISH_BIN", "stockfish")!,
|
||||
},
|
||||
|
||||
game: {
|
||||
maxConcurrentGames: Number(env("MAX_CONCURRENT_GAMES", "6")),
|
||||
maxActiveGamesPerUser: Number(env("MAX_ACTIVE_GAMES_PER_USER", "1")),
|
||||
illegalHintAfter: Number(env("ILLEGAL_HINT_AFTER", "3")),
|
||||
illegalForfeitAfter: Number(env("ILLEGAL_FORFEIT_AFTER", "8")),
|
||||
noMoveNudges: Number(env("NO_MOVE_NUDGES", "2")),
|
||||
fiftyMoveReminderFrom: Number(env("FIFTY_MOVE_REMINDER_FROM", "40")),
|
||||
stockfishDepth: Number(env("STOCKFISH_DEPTH", "18")),
|
||||
stockfishThreads: Number(env("STOCKFISH_THREADS", "2")),
|
||||
stockfishPool: Number(env("STOCKFISH_POOL", "2")),
|
||||
},
|
||||
};
|
||||
export type Config = typeof config;
|
||||
@@ -0,0 +1,22 @@
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import fs from "node:fs";
|
||||
import postgres from "postgres";
|
||||
import { drizzle } from "drizzle-orm/postgres-js";
|
||||
import { migrate } from "drizzle-orm/postgres-js/migrator";
|
||||
import { config } from "../config.ts";
|
||||
import * as schema from "./schema.ts";
|
||||
|
||||
export const sqlClient = postgres(config.databaseUrl, { max: 20, onnotice: () => {} });
|
||||
export const db = drizzle(sqlClient, { schema });
|
||||
export type DB = typeof db;
|
||||
export { schema };
|
||||
|
||||
export async function runMigrations() {
|
||||
const here = path.dirname(fileURLToPath(import.meta.url));
|
||||
// dev: src/db -> ../../drizzle ; bundled: dist -> ../drizzle
|
||||
const candidates = [path.resolve(here, "../../drizzle"), path.resolve(here, "../drizzle"), path.resolve(process.cwd(), "drizzle")];
|
||||
const folder = candidates.find((p) => fs.existsSync(path.join(p, "meta", "_journal.json")));
|
||||
if (!folder) throw new Error("drizzle migrations folder not found");
|
||||
await migrate(db, { migrationsFolder: folder });
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { sql } from "drizzle-orm";
|
||||
import { boolean, doublePrecision, index, integer, jsonb, pgTable, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core";
|
||||
import type { EngineEval, GameFlags, MoveClass, Result, Side, Termination, TranscriptItem, Usage } from "@aichess/core";
|
||||
|
||||
const ts = (name: string) => timestamp(name, { withTimezone: true, mode: "date" });
|
||||
const now = () => ts("created_at").notNull().defaultNow();
|
||||
|
||||
export const users = pgTable("users", {
|
||||
id: text("id").primaryKey(),
|
||||
username: text("username").notNull(),
|
||||
passwordHash: text("password_hash").notNull(),
|
||||
displayName: text("display_name").notNull(),
|
||||
avatar: text("avatar"), // media-relative path
|
||||
isAdmin: boolean("is_admin").notNull().default(false),
|
||||
onboarded: boolean("onboarded").notNull().default(false),
|
||||
/** UI skin chosen at onboarding: broadcast | tabloid | arcade */
|
||||
theme: text("theme").notNull().default("tabloid"),
|
||||
createdAt: now(),
|
||||
}, (t) => [uniqueIndex("users_username_lower").on(sql`lower(${t.username})`)]);
|
||||
|
||||
export const sessions = pgTable("sessions", {
|
||||
id: text("id").primaryKey(), // sha256 of the cookie token
|
||||
userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
||||
createdAt: now(),
|
||||
expiresAt: ts("expires_at").notNull(),
|
||||
});
|
||||
|
||||
/** Anything that can sit at the board: an AI entity (model × effort) or a human user. */
|
||||
export const players = pgTable("players", {
|
||||
id: text("id").primaryKey(),
|
||||
kind: text("kind").$type<"ai" | "human">().notNull(),
|
||||
slug: text("slug").notNull().unique(),
|
||||
userId: text("user_id").references(() => users.id, { onDelete: "set null" }).unique(),
|
||||
displayName: text("display_name").notNull(),
|
||||
// AI only
|
||||
family: text("family"), // "claude" | "gpt" — groups variants in the UI
|
||||
provider: text("provider"),
|
||||
modelId: text("model_id"),
|
||||
thinking: text("thinking"),
|
||||
variant: text("variant"), // "max" | "high"
|
||||
avatar: text("avatar"),
|
||||
color: text("color"),
|
||||
/** last-gen "for fun" models: UI shows a "тупая" badge */
|
||||
dumb: boolean("dumb").notNull().default(false),
|
||||
/** no-thinking variant: UI shows a skull */
|
||||
skull: boolean("skull").notNull().default(false),
|
||||
/** extra agent options: thinkingBudget, forceReasoningNone, ... */
|
||||
options: jsonb("options").$type<{ thinkingBudget?: number; forceReasoningNone?: boolean }>().notNull().default({}),
|
||||
active: boolean("active").notNull().default(true),
|
||||
// rating (Glicko-2)
|
||||
rating: doublePrecision("rating").notNull().default(1500),
|
||||
rd: doublePrecision("rd").notNull().default(350),
|
||||
vol: doublePrecision("vol").notNull().default(0.06),
|
||||
games: integer("games").notNull().default(0),
|
||||
wins: integer("wins").notNull().default(0),
|
||||
draws: integer("draws").notNull().default(0),
|
||||
losses: integer("losses").notNull().default(0),
|
||||
createdAt: now(),
|
||||
});
|
||||
|
||||
export const games = pgTable("games", {
|
||||
id: text("id").primaryKey(),
|
||||
status: text("status").$type<"pending" | "running" | "finished" | "aborted">().notNull().default("pending"),
|
||||
whiteId: text("white_id").notNull().references(() => players.id),
|
||||
blackId: text("black_id").notNull().references(() => players.id),
|
||||
createdBy: text("created_by").references(() => users.id, { onDelete: "set null" }),
|
||||
scheduleId: text("schedule_id"),
|
||||
flags: jsonb("flags").$type<GameFlags>().notNull(),
|
||||
personas: jsonb("personas").$type<{ white: string | null; black: string | null }>().notNull(),
|
||||
rated: boolean("rated").notNull().default(true),
|
||||
startFen: text("start_fen").notNull(),
|
||||
fen: text("fen").notNull(),
|
||||
ply: integer("ply").notNull().default(0),
|
||||
pendingDrawBy: text("pending_draw_by").$type<Side | null>(),
|
||||
result: text("result").$type<Result | null>(),
|
||||
termination: text("termination").$type<Termination | null>(),
|
||||
startsAt: ts("starts_at"), // scheduled start (predictions lock at this time)
|
||||
startedAt: ts("started_at"),
|
||||
finishedAt: ts("finished_at"),
|
||||
ratingChange: jsonb("rating_change").$type<{ white: { before: number; after: number }; black: { before: number; after: number } } | null>(),
|
||||
accuracy: jsonb("accuracy").$type<{ white: number | null; black: number | null } | null>(),
|
||||
interviews: jsonb("interviews").$type<{ white?: string | null; black?: string | null }>().notNull().default({}),
|
||||
/** phrase said with resign / draw acceptance / forfeit */
|
||||
lastWords: jsonb("last_words").$type<{ white?: string | null; black?: string | null }>().notNull().default({}),
|
||||
/** post-game editorial: headline + short review (shown only when the game is featured) */
|
||||
review: jsonb("review").$type<{ title: string; text: string } | null>(),
|
||||
thumbnail: text("thumbnail"),
|
||||
thumbnailCaption: text("thumbnail_caption"),
|
||||
thumbnailMeta: jsonb("thumbnail_meta").$type<Record<string, unknown> | null>(),
|
||||
costTotal: doublePrecision("cost_total").notNull().default(0),
|
||||
error: text("error"),
|
||||
createdAt: now(),
|
||||
}, (t) => [index("games_status").on(t.status), index("games_created").on(t.createdAt)]);
|
||||
|
||||
export const moves = pgTable("moves", {
|
||||
id: text("id").primaryKey(),
|
||||
gameId: text("game_id").notNull().references(() => games.id, { onDelete: "cascade" }),
|
||||
ply: integer("ply").notNull(),
|
||||
side: text("side").$type<Side>().notNull(),
|
||||
playerId: text("player_id").notNull(),
|
||||
san: text("san"),
|
||||
uci: text("uci").notNull(),
|
||||
fenAfter: text("fen_after").notNull(),
|
||||
phrase: text("phrase"),
|
||||
note: text("note"),
|
||||
offeredDraw: boolean("offered_draw").notNull().default(false),
|
||||
illegal: boolean("illegal").notNull().default(false),
|
||||
thinkMs: integer("think_ms").notNull().default(0),
|
||||
usage: jsonb("usage").$type<Usage>(),
|
||||
eval: jsonb("eval").$type<EngineEval | null>(),
|
||||
classification: text("classification").$type<MoveClass | null>(),
|
||||
accuracy: doublePrecision("accuracy"),
|
||||
turnId: text("turn_id"),
|
||||
createdAt: now(),
|
||||
}, (t) => [uniqueIndex("moves_game_ply").on(t.gameId, t.ply)]);
|
||||
|
||||
/** One agent run attempt for a ply. The successful one is linked from moves.turn_id. */
|
||||
export const turns = pgTable("turns", {
|
||||
id: text("id").primaryKey(),
|
||||
gameId: text("game_id").notNull().references(() => games.id, { onDelete: "cascade" }),
|
||||
ply: integer("ply").notNull(), // the ply being decided (game.ply + 1 at start)
|
||||
side: text("side").$type<Side>().notNull(),
|
||||
playerId: text("player_id").notNull(),
|
||||
attempt: integer("attempt").notNull().default(1),
|
||||
status: text("status").$type<"running" | "done" | "failed">().notNull().default("running"),
|
||||
transcript: jsonb("transcript").$type<TranscriptItem[]>().notNull().default([]),
|
||||
usage: jsonb("usage").$type<Usage | null>(),
|
||||
outcome: text("outcome"),
|
||||
error: text("error"),
|
||||
startedAt: ts("started_at").notNull().defaultNow(),
|
||||
endedAt: ts("ended_at"),
|
||||
}, (t) => [index("turns_game_ply").on(t.gameId, t.ply)]);
|
||||
|
||||
/** Every LLM / image call that cost tokens, attributed to the user who started the game. */
|
||||
export const usageLedger = pgTable("usage_ledger", {
|
||||
id: text("id").primaryKey(),
|
||||
userId: text("user_id"),
|
||||
gameId: text("game_id"),
|
||||
playerId: text("player_id"),
|
||||
kind: text("kind").$type<"turn" | "interview" | "review" | "thumbnail_prompt" | "thumbnail_image">().notNull(),
|
||||
model: text("model").notNull(),
|
||||
usage: jsonb("usage").$type<Usage>().notNull(),
|
||||
cost: doublePrecision("cost").notNull().default(0),
|
||||
tokens: integer("tokens").notNull().default(0),
|
||||
createdAt: now(),
|
||||
}, (t) => [index("usage_user").on(t.userId)]);
|
||||
|
||||
export const schedules = pgTable("schedules", {
|
||||
id: text("id").primaryKey(),
|
||||
name: text("name").notNull(),
|
||||
enabled: boolean("enabled").notNull().default(true),
|
||||
intervalMinutes: integer("interval_minutes").notNull().default(180),
|
||||
/** minutes before start when the match is announced and predictions open */
|
||||
announceMinutes: integer("announce_minutes").notNull().default(30),
|
||||
/** pool of AI player slugs; empty = all active AI players */
|
||||
pool: jsonb("pool").$type<string[]>().notNull().default([]),
|
||||
flags: jsonb("flags").$type<GameFlags>().notNull(),
|
||||
randomPersonas: boolean("random_personas").notNull().default(true),
|
||||
nextRunAt: ts("next_run_at"),
|
||||
createdBy: text("created_by"),
|
||||
createdAt: now(),
|
||||
});
|
||||
|
||||
export const predictions = pgTable("predictions", {
|
||||
id: text("id").primaryKey(),
|
||||
gameId: text("game_id").notNull().references(() => games.id, { onDelete: "cascade" }),
|
||||
userId: text("user_id").notNull().references(() => users.id, { onDelete: "cascade" }),
|
||||
pick: text("pick").$type<"white" | "draw" | "black">().notNull(),
|
||||
points: integer("points"),
|
||||
createdAt: now(),
|
||||
}, (t) => [uniqueIndex("predictions_game_user").on(t.gameId, t.userId)]);
|
||||
|
||||
export const ratingHistory = pgTable("rating_history", {
|
||||
id: text("id").primaryKey(),
|
||||
playerId: text("player_id").notNull(),
|
||||
gameId: text("game_id").notNull(),
|
||||
before: doublePrecision("before").notNull(),
|
||||
after: doublePrecision("after").notNull(),
|
||||
rd: doublePrecision("rd").notNull(),
|
||||
createdAt: now(),
|
||||
}, (t) => [index("rating_history_player").on(t.playerId)]);
|
||||
|
||||
export const appSettings = pgTable("app_settings", {
|
||||
key: text("key").primaryKey(),
|
||||
value: jsonb("value").notNull(),
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
|
||||
import readline from "node:readline";
|
||||
import type { EngineEval } from "@aichess/core";
|
||||
import { config } from "../config.ts";
|
||||
import { logErr } from "../util.ts";
|
||||
|
||||
class Engine {
|
||||
private proc: ChildProcessWithoutNullStreams | null = null;
|
||||
private lines: ((l: string) => void) | null = null;
|
||||
busy = false;
|
||||
|
||||
private async start() {
|
||||
if (this.proc && this.proc.exitCode === null) return;
|
||||
this.proc = spawn(config.paths.stockfish, [], { stdio: ["pipe", "pipe", "pipe"] });
|
||||
this.proc.on("exit", () => (this.proc = null));
|
||||
this.proc.on("error", (e) => logErr("stockfish", e.message));
|
||||
const rl = readline.createInterface({ input: this.proc.stdout });
|
||||
rl.on("line", (l) => this.lines?.(l));
|
||||
this.send("uci");
|
||||
await this.waitFor((l) => l === "uciok", 10000);
|
||||
this.send(`setoption name Threads value ${config.game.stockfishThreads}`);
|
||||
this.send("setoption name Hash value 128");
|
||||
this.send("isready");
|
||||
await this.waitFor((l) => l === "readyok", 10000);
|
||||
}
|
||||
private send(cmd: string) {
|
||||
this.proc?.stdin.write(cmd + "\n");
|
||||
}
|
||||
private waitFor(pred: (l: string) => boolean, timeoutMs: number, onLine?: (l: string) => void): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const t = setTimeout(() => {
|
||||
this.lines = null;
|
||||
reject(new Error("stockfish timeout"));
|
||||
}, timeoutMs);
|
||||
this.lines = (l) => {
|
||||
onLine?.(l);
|
||||
if (pred(l)) {
|
||||
clearTimeout(t);
|
||||
this.lines = null;
|
||||
resolve(l);
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async analyze(fen: string, depth: number): Promise<EngineEval> {
|
||||
await this.start();
|
||||
const whiteToMove = fen.split(" ")[1] === "w";
|
||||
let cp: number | null = null;
|
||||
let mate: number | null = null;
|
||||
let pv: string[] = [];
|
||||
let reached = 0;
|
||||
this.send("ucinewgame");
|
||||
this.send(`position fen ${fen}`);
|
||||
this.send(`go depth ${depth}`);
|
||||
const best = await this.waitFor(
|
||||
(l) => l.startsWith("bestmove"),
|
||||
120000,
|
||||
(l) => {
|
||||
if (!l.startsWith("info") || !l.includes(" score ") || l.includes("lowerbound") || l.includes("upperbound")) return;
|
||||
if (/ multipv (\d+)/.exec(l)?.[1] && / multipv (\d+)/.exec(l)![1] !== "1") return;
|
||||
const t = l.split(" ");
|
||||
const si = t.indexOf("score");
|
||||
const kind = t[si + 1];
|
||||
const val = Number(t[si + 2]);
|
||||
if (kind === "cp") {
|
||||
cp = val;
|
||||
mate = null;
|
||||
} else if (kind === "mate") {
|
||||
mate = val;
|
||||
cp = null;
|
||||
}
|
||||
const pi = t.indexOf("pv");
|
||||
if (pi >= 0) pv = t.slice(pi + 1);
|
||||
const di = t.indexOf("depth");
|
||||
if (di >= 0) reached = Number(t[di + 1]);
|
||||
},
|
||||
);
|
||||
const bestUci = best.split(" ")[1];
|
||||
const sign = whiteToMove ? 1 : -1;
|
||||
const m = mate as number | null;
|
||||
const c = cp as number | null;
|
||||
if (m === 0 || (m == null && c == null && bestUci === "(none)")) {
|
||||
// terminal position: side to move is mated (or stalemated -> treat as 0)
|
||||
const mated = m === 0;
|
||||
return { cp: mated ? (whiteToMove ? -100000 : 100000) : 0, mate: null, bestUci: null, pv: [], depth: reached };
|
||||
}
|
||||
return {
|
||||
cp: c == null ? null : c * sign,
|
||||
mate: m == null ? null : m * sign,
|
||||
bestUci: bestUci && bestUci !== "(none)" ? bestUci : null,
|
||||
pv,
|
||||
depth: reached,
|
||||
};
|
||||
}
|
||||
stop() {
|
||||
this.send("quit");
|
||||
this.proc?.kill();
|
||||
}
|
||||
}
|
||||
|
||||
/** Small FIFO pool of stockfish processes. */
|
||||
class EnginePool {
|
||||
private engines: Engine[] = [];
|
||||
private queue: { fen: string; depth: number; resolve: (e: EngineEval) => void; reject: (e: unknown) => void }[] = [];
|
||||
constructor(size: number) {
|
||||
for (let i = 0; i < size; i++) this.engines.push(new Engine());
|
||||
}
|
||||
analyze(fen: string, depth = config.game.stockfishDepth): Promise<EngineEval> {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.queue.push({ fen, depth, resolve, reject });
|
||||
this.pump();
|
||||
});
|
||||
}
|
||||
private pump() {
|
||||
for (const e of this.engines) {
|
||||
if (e.busy) continue;
|
||||
const job = this.queue.shift();
|
||||
if (!job) return;
|
||||
e.busy = true;
|
||||
e.analyze(job.fen, job.depth)
|
||||
.then(job.resolve, (err) => {
|
||||
e.stop();
|
||||
job.reject(err);
|
||||
})
|
||||
.finally(() => {
|
||||
e.busy = false;
|
||||
this.pump();
|
||||
});
|
||||
}
|
||||
}
|
||||
stop() {
|
||||
for (const e of this.engines) e.stop();
|
||||
}
|
||||
}
|
||||
|
||||
export const engine = new EnginePool(config.game.stockfishPool);
|
||||
@@ -0,0 +1,114 @@
|
||||
import path from "node:path";
|
||||
import { eq } from "drizzle-orm";
|
||||
import { gameAccuracy, winPercentWhite, type Side, type Usage } from "@aichess/core";
|
||||
import { db, schema } from "../db/client.ts";
|
||||
import { bus, gameChannel } from "../bus.ts";
|
||||
import { boss, Q, type FinalizeJob } from "../jobs.ts";
|
||||
import { config } from "../config.ts";
|
||||
import { runInterview, runReview, runThumbnail, type PostgameGame } from "../agents/postgame.ts";
|
||||
import { log, logErr, newId } from "../util.ts";
|
||||
import { handleEval } from "./runner.ts";
|
||||
import { loadGame, playerLabel, recordOf, type LoadedGame, type PlayerRow } from "./service.ts";
|
||||
|
||||
const avatarAbs = (p: PlayerRow) => {
|
||||
if (!p.avatar) return null;
|
||||
return p.kind === "ai" ? path.join(config.paths.assets, p.avatar) : path.join(config.paths.data, "media", p.avatar);
|
||||
};
|
||||
|
||||
async function ledger(g: LoadedGame, kind: "interview" | "review" | "thumbnail_prompt" | "thumbnail_image", model: string, usage: Usage, playerId: string | null = null, tokens?: number) {
|
||||
await db.insert(schema.usageLedger).values({
|
||||
id: newId(),
|
||||
userId: g.game.createdBy,
|
||||
gameId: g.game.id,
|
||||
playerId,
|
||||
kind,
|
||||
model,
|
||||
usage,
|
||||
cost: usage.cost,
|
||||
tokens: tokens ?? usage.input + usage.output + usage.cacheRead + usage.cacheWrite,
|
||||
});
|
||||
}
|
||||
|
||||
function postgameOf(g: LoadedGame, accuracy: { white: number | null; black: number | null }): PostgameGame {
|
||||
const side = (p: PlayerRow, s: Side) => ({
|
||||
label: playerLabel(p),
|
||||
kind: p.kind,
|
||||
avatarPath: avatarAbs(p),
|
||||
family: p.family,
|
||||
dumb: p.dumb,
|
||||
persona: g.game.personas[s],
|
||||
});
|
||||
return { id: g.game.id, white: side(g.white, "white"), black: side(g.black, "black"), record: recordOf(g) as any, accuracy, lastWords: g.game.lastWords ?? {}, startFen: g.game.startFen };
|
||||
}
|
||||
|
||||
export async function finalizeGame(gameId: string) {
|
||||
let g = await loadGame(gameId);
|
||||
if (!g || g.game.status !== "finished") return;
|
||||
|
||||
// 1. evals for every ply
|
||||
for (const m of g.moves) if (!m.eval) await handleEval({ gameId, ply: m.ply }).catch((e) => logErr("finalize", `eval ${m.ply}`, e));
|
||||
g = (await loadGame(gameId))!;
|
||||
|
||||
// 2. accuracy
|
||||
const wins = [50, ...g.moves.map((m) => (m.eval ? winPercentWhite(m.eval) : 50))];
|
||||
const accuracy = { white: gameAccuracy(wins, "white"), black: gameAccuracy(wins, "black") };
|
||||
await db.update(schema.games).set({ accuracy }).where(eq(schema.games.id, gameId));
|
||||
const pg = postgameOf(g, accuracy);
|
||||
|
||||
// 3. interviews (AI players only, in parallel)
|
||||
const interviews: { white?: string | null; black?: string | null } = { ...(g.game.interviews ?? {}) };
|
||||
await Promise.all(
|
||||
(["white", "black"] as const).map(async (side) => {
|
||||
const p = side === "white" ? g!.white : g!.black;
|
||||
if (p.kind !== "ai" || interviews[side]) return;
|
||||
try {
|
||||
const r = await runInterview(pg, side, { provider: p.provider!, modelId: p.modelId!, thinking: (p.thinking === "off" ? "off" : "medium") as any, thinkingBudget: p.options?.thinkingBudget ? 8192 : undefined });
|
||||
interviews[side] = r.text.slice(0, 2000) || null;
|
||||
await ledger(g!, "interview", `${p.provider}/${p.modelId}`, r.usage, p.id);
|
||||
await db.update(schema.games).set({ interviews }).where(eq(schema.games.id, gameId));
|
||||
if (interviews[side]) bus.publish(gameChannel(gameId), { type: "interview", gameId, side, text: interviews[side]! });
|
||||
} catch (e) {
|
||||
logErr("finalize", `interview ${side} ${gameId}`, e);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
// 4. editorial review
|
||||
let review = g.game.review;
|
||||
if (!review) {
|
||||
try {
|
||||
const r = await runReview(pg, interviews);
|
||||
if (r.structured?.title) {
|
||||
review = { title: String(r.structured.title).slice(0, 120), text: String(r.structured.text ?? "").slice(0, 1200) };
|
||||
await db.update(schema.games).set({ review }).where(eq(schema.games.id, gameId));
|
||||
}
|
||||
await ledger(g, "review", config.llm.promptWriterModel, r.usage);
|
||||
} catch (e) {
|
||||
logErr("finalize", `review ${gameId}`, e);
|
||||
}
|
||||
}
|
||||
|
||||
// 5. thumbnail
|
||||
if (!g.game.thumbnail) {
|
||||
try {
|
||||
const t = await runThumbnail(pg, review, interviews);
|
||||
await db
|
||||
.update(schema.games)
|
||||
.set({ thumbnail: t.file, thumbnailCaption: t.caption, thumbnailMeta: { style: t.style, prompt: t.prompt } })
|
||||
.where(eq(schema.games.id, gameId));
|
||||
await ledger(g, "thumbnail_prompt", config.llm.promptWriterModel, t.usageWriter);
|
||||
await ledger(g, "thumbnail_image", config.llm.imageModel, { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0, cost: 0 }, null, t.imageTokens);
|
||||
bus.publish(gameChannel(gameId), { type: "thumbnail", gameId, url: `/media/${t.file}`, caption: t.caption });
|
||||
bus.publish("lobby", { type: "game_updated", gameId });
|
||||
} catch (e) {
|
||||
logErr("finalize", `thumbnail ${gameId}`, e);
|
||||
}
|
||||
}
|
||||
log("finalize", `done ${gameId}`);
|
||||
}
|
||||
|
||||
export async function startFinalizeWorker() {
|
||||
await boss.work<FinalizeJob>(Q.finalize, { localConcurrency: 2, batchSize: 1, pollingIntervalSeconds: 2 } as any, async (jobs: any[]) => {
|
||||
for (const j of jobs) await finalizeGame(j.data.gameId);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
import { and, count, eq } from "drizzle-orm";
|
||||
import { Chess } from "chess.js";
|
||||
import {
|
||||
classifyMove,
|
||||
PIECE_VALUES,
|
||||
type EngineEval,
|
||||
type Side,
|
||||
type ToolCallLog,
|
||||
type TranscriptItem,
|
||||
} from "@aichess/core";
|
||||
import { db, schema } from "../db/client.ts";
|
||||
import { bus, gameChannel } from "../bus.ts";
|
||||
import { boss, 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";
|
||||
import { log, logErr, newId } from "../util.ts";
|
||||
import {
|
||||
abortGame,
|
||||
applyMove,
|
||||
applyTerminalDecision,
|
||||
loadGame,
|
||||
playerLabel,
|
||||
sideOfPly,
|
||||
stateOf,
|
||||
toRecordPly,
|
||||
type PlayerRow,
|
||||
} from "./service.ts";
|
||||
|
||||
// ------------------------------------------------------------------ live turn buffer
|
||||
|
||||
export interface LiveTurn {
|
||||
gameId: string;
|
||||
ply: number;
|
||||
side: Side;
|
||||
playerId: string;
|
||||
startedAt: number;
|
||||
items: TranscriptItem[];
|
||||
thinking: string;
|
||||
text: string;
|
||||
tools: Record<string, ToolCallLog>;
|
||||
}
|
||||
const live = new Map<string, LiveTurn>();
|
||||
export const getLiveTurn = (gameId: string) => live.get(gameId) ?? null;
|
||||
const controllers = new Map<string, AbortController>();
|
||||
export function abortRunningTurn(gameId: string) {
|
||||
controllers.get(gameId)?.abort();
|
||||
}
|
||||
|
||||
function asAgentPlayer(p: PlayerRow): AgentPlayer {
|
||||
return {
|
||||
id: p.id,
|
||||
displayName: playerLabel(p),
|
||||
variant: p.variant,
|
||||
provider: p.provider!,
|
||||
modelId: p.modelId!,
|
||||
thinking: (p.thinking ?? "high") as AgentPlayer["thinking"],
|
||||
options: p.options ?? {},
|
||||
};
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ turn job
|
||||
|
||||
async function handleTurn(data: TurnJob, retryCount: number) {
|
||||
const g = await loadGame(data.gameId);
|
||||
if (!g || g.game.status !== "running" || g.game.ply !== data.ply - 1) return; // stale
|
||||
const side = sideOfPly(data.ply);
|
||||
const me = side === "white" ? g.white : g.black;
|
||||
const opp = side === "white" ? g.black : g.white;
|
||||
if (me.kind !== "ai") return;
|
||||
|
||||
const [{ n }] = await db
|
||||
.select({ n: count() })
|
||||
.from(schema.turns)
|
||||
.where(and(eq(schema.turns.gameId, g.game.id), eq(schema.turns.ply, data.ply)));
|
||||
const turnId = newId();
|
||||
await db.insert(schema.turns).values({ id: turnId, gameId: g.game.id, ply: data.ply, side, playerId: me.id, attempt: n + 1 });
|
||||
|
||||
const state = stateOf(g);
|
||||
const last = g.moves[g.moves.length - 1];
|
||||
const myLast = [...g.moves].reverse().find((m) => m.side === side);
|
||||
const lt: LiveTurn = { gameId: g.game.id, ply: data.ply, side, playerId: me.id, startedAt: Date.now(), items: [], thinking: "", text: "", tools: {} };
|
||||
live.set(g.game.id, lt);
|
||||
bus.publish(gameChannel(g.game.id), { type: "turn_start", gameId: g.game.id, ply: data.ply, side, playerId: me.id, at: lt.startedAt });
|
||||
|
||||
const onLive = (e: LiveTurnEvent) => {
|
||||
const ch = gameChannel(g.game.id);
|
||||
if (e.type === "thinking_delta") {
|
||||
lt.thinking += e.delta;
|
||||
bus.publish(ch, { type: "thinking_delta", gameId: g.game.id, ply: data.ply, delta: e.delta });
|
||||
} else if (e.type === "text_delta") {
|
||||
lt.text += e.delta;
|
||||
bus.publish(ch, { type: "text_delta", gameId: g.game.id, ply: data.ply, delta: e.delta });
|
||||
} else if (e.type === "tool_start") {
|
||||
lt.tools[e.call.id] = e.call;
|
||||
bus.publish(ch, { type: "tool_start", gameId: g.game.id, ply: data.ply, call: e.call });
|
||||
} else {
|
||||
lt.tools[e.call.id] = e.call;
|
||||
bus.publish(ch, { type: "tool_end", gameId: g.game.id, ply: data.ply, call: e.call });
|
||||
}
|
||||
};
|
||||
|
||||
const ac = new AbortController();
|
||||
controllers.set(g.game.id, ac);
|
||||
try {
|
||||
const res = await runAgentTurn({
|
||||
gameId: g.game.id,
|
||||
side,
|
||||
me: asAgentPlayer(me),
|
||||
opponentName: playerLabel(opp),
|
||||
opponentIsHuman: opp.kind === "human",
|
||||
persona: g.game.personas[side],
|
||||
flags: g.game.flags,
|
||||
state,
|
||||
history: g.moves.map(toRecordPly),
|
||||
opponentPhrase: last && last.side !== side ? last.phrase : null,
|
||||
drawOffered: g.game.pendingDrawBy != null && g.game.pendingDrawBy !== side,
|
||||
noteFromSelf: g.game.flags.notes ? (myLast?.note ?? null) : null,
|
||||
signal: ac.signal,
|
||||
onLive,
|
||||
});
|
||||
await db
|
||||
.update(schema.turns)
|
||||
.set({ status: "done", transcript: res.transcript, usage: res.usage, outcome: res.decision.kind, endedAt: new Date() })
|
||||
.where(eq(schema.turns.id, turnId));
|
||||
await db.insert(schema.usageLedger).values({
|
||||
id: newId(),
|
||||
userId: g.game.createdBy,
|
||||
gameId: g.game.id,
|
||||
playerId: me.id,
|
||||
kind: "turn",
|
||||
model: `${me.provider}/${me.modelId}`,
|
||||
usage: res.usage,
|
||||
cost: res.usage.cost,
|
||||
tokens: res.usage.input + res.usage.output + res.usage.cacheRead + res.usage.cacheWrite,
|
||||
});
|
||||
bus.publish(gameChannel(g.game.id), { type: "turn_end", gameId: g.game.id, ply: data.ply, usage: res.usage });
|
||||
|
||||
const d = res.decision;
|
||||
if (d.kind === "move") {
|
||||
const r = await applyMove(g.game.id, data.ply, { uci: d.uci, illegal: d.illegal }, {
|
||||
phrase: d.phrase,
|
||||
note: d.note,
|
||||
offerDraw: d.offerDraw,
|
||||
thinkMs: res.thinkMs,
|
||||
usage: res.usage,
|
||||
turnId,
|
||||
});
|
||||
if (!r.ok) logErr("turn", `applyMove failed ${g.game.id}#${data.ply}: ${r.error}`);
|
||||
} else if (d.kind === "resign") await applyTerminalDecision(g.game.id, side, "resign", d.phrase);
|
||||
else if (d.kind === "accept_draw") await applyTerminalDecision(g.game.id, side, "accept_draw", d.phrase);
|
||||
else await applyTerminalDecision(g.game.id, side, d.reason === "illegal" ? "forfeit_illegal" : "forfeit_no_move", null);
|
||||
} catch (err) {
|
||||
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) {
|
||||
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: "Ошибка провайдера — ход будет переигран" });
|
||||
throw err;
|
||||
} finally {
|
||||
live.delete(g.game.id);
|
||||
controllers.delete(g.game.id);
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ eval job
|
||||
|
||||
const evalCache = new Map<string, EngineEval>();
|
||||
async function evalFen(fen: string): Promise<EngineEval> {
|
||||
const key = fen.split(" ").slice(0, 4).join(" ");
|
||||
const hit = evalCache.get(key);
|
||||
if (hit) return hit;
|
||||
const e = await engine.analyze(fen);
|
||||
evalCache.set(key, e);
|
||||
if (evalCache.size > 5000) evalCache.delete(evalCache.keys().next().value!);
|
||||
return e;
|
||||
}
|
||||
|
||||
/** cheap sacrifice heuristic: moved piece can be taken by a cheaper piece right away */
|
||||
function isSacrifice(fenBefore: string, uci: string): boolean {
|
||||
try {
|
||||
const c = new Chess(fenBefore);
|
||||
const mv = c.move({ from: uci.slice(0, 2), to: uci.slice(2, 4), promotion: uci[4] ?? "q" });
|
||||
const moved = PIECE_VALUES[mv.promotion ?? mv.piece];
|
||||
const gained = mv.captured ? PIECE_VALUES[mv.captured] : 0;
|
||||
if (moved < 3 || gained >= moved) return false;
|
||||
const takers = c.moves({ verbose: true }).filter((m) => m.to === mv.to && m.captured);
|
||||
return takers.some((t) => PIECE_VALUES[t.piece] < moved);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function handleEval(data: EvalJob) {
|
||||
const mv = await db.query.moves.findFirst({ where: and(eq(schema.moves.gameId, data.gameId), eq(schema.moves.ply, data.ply)) });
|
||||
if (!mv) return;
|
||||
const prev =
|
||||
data.ply === 1
|
||||
? (await db.query.games.findFirst({ where: eq(schema.games.id, data.gameId) }))!.startFen
|
||||
: (await db.query.moves.findFirst({ where: and(eq(schema.moves.gameId, data.gameId), eq(schema.moves.ply, data.ply - 1)) }))?.fenAfter;
|
||||
if (!prev) return;
|
||||
const [before, after] = await Promise.all([evalFen(prev), evalFen(mv.fenAfter)]);
|
||||
let classification = null;
|
||||
let accuracy = null;
|
||||
if (!mv.illegal) {
|
||||
const legal = (() => {
|
||||
try {
|
||||
return new Chess(prev).moves().length;
|
||||
} catch {
|
||||
return 2;
|
||||
}
|
||||
})();
|
||||
const c = classifyMove({ side: mv.side, before, after, uci: mv.uci, legalMoveCount: legal, isSacrifice: isSacrifice(prev, mv.uci) });
|
||||
classification = c.cls;
|
||||
accuracy = c.accuracy;
|
||||
}
|
||||
await db.update(schema.moves).set({ eval: after, classification, accuracy }).where(eq(schema.moves.id, mv.id));
|
||||
bus.publish(gameChannel(data.gameId), { type: "eval", gameId: data.gameId, ply: data.ply, eval: after, classification, accuracy });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ workers
|
||||
|
||||
export async function startWorkers() {
|
||||
await boss.work<TurnJob>(Q.turn, { localConcurrency: config.game.maxConcurrentGames, batchSize: 1, pollingIntervalSeconds: 1, includeMetadata: true } as any, async (jobs: any[]) => {
|
||||
for (const j of jobs) await handleTurn(j.data, j.retryCount ?? 0);
|
||||
});
|
||||
await boss.work<EvalJob>(Q.evalPly, { localConcurrency: config.game.stockfishPool, batchSize: 1, pollingIntervalSeconds: 1 } as any, async (jobs: any[]) => {
|
||||
for (const j of jobs) await handleEval(j.data);
|
||||
});
|
||||
log("workers", "turn + eval workers started");
|
||||
}
|
||||
|
||||
/** Make sure every running game has its next turn queued (after restarts / lost jobs). */
|
||||
export async function recoverRunningGames() {
|
||||
const running = await db.select().from(schema.games).where(eq(schema.games.status, "running"));
|
||||
const { kickTurn } = await import("./service.ts");
|
||||
for (const g of running) await kickTurn(g);
|
||||
if (running.length) log("workers", `re-kicked ${running.length} running games`);
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { and, eq, lte, inArray, count } from "drizzle-orm";
|
||||
import { DEFAULT_FLAGS } from "@aichess/core";
|
||||
import { db, schema } from "../db/client.ts";
|
||||
import { bus } from "../bus.ts";
|
||||
import { boss, Q } from "../jobs.ts";
|
||||
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";
|
||||
|
||||
/**
|
||||
* Every minute:
|
||||
* 1. schedules whose next run is within `announceMinutes` get a pending game (predictions open),
|
||||
* 2. pending games whose start time has passed are started (if there is capacity).
|
||||
*/
|
||||
export async function scheduleTick() {
|
||||
const now = new Date();
|
||||
const schedules = await db.select().from(schema.schedules).where(eq(schema.schedules.enabled, true));
|
||||
for (const s of schedules) {
|
||||
if (!s.nextRunAt) {
|
||||
await db.update(schema.schedules).set({ nextRunAt: new Date(now.getTime() + s.intervalMinutes * 60_000) }).where(eq(schema.schedules.id, s.id));
|
||||
continue;
|
||||
}
|
||||
if (s.nextRunAt.getTime() - s.announceMinutes * 60_000 > now.getTime()) continue;
|
||||
try {
|
||||
await announceScheduled(s);
|
||||
} catch (e) {
|
||||
logErr("scheduler", `announce ${s.id}`, e);
|
||||
}
|
||||
const next = new Date(Math.max(s.nextRunAt.getTime(), now.getTime()) + s.intervalMinutes * 60_000);
|
||||
await db.update(schema.schedules).set({ nextRunAt: next }).where(eq(schema.schedules.id, s.id));
|
||||
bus.publish("lobby", { type: "schedule_updated" });
|
||||
}
|
||||
|
||||
const [{ running }] = await db.select({ running: count() }).from(schema.games).where(eq(schema.games.status, "running"));
|
||||
let capacity = config.game.maxConcurrentGames - running;
|
||||
const due = await db
|
||||
.select()
|
||||
.from(schema.games)
|
||||
.where(and(eq(schema.games.status, "pending"), lte(schema.games.startsAt, now)))
|
||||
.orderBy(schema.games.startsAt);
|
||||
for (const g of due) {
|
||||
if (capacity <= 0) break;
|
||||
await startPendingGame(g.id);
|
||||
capacity--;
|
||||
}
|
||||
}
|
||||
|
||||
async function announceScheduled(s: typeof schema.schedules.$inferSelect) {
|
||||
const where = s.pool.length ? and(eq(schema.players.kind, "ai"), inArray(schema.players.slug, s.pool)) : and(eq(schema.players.kind, "ai"), eq(schema.players.active, true));
|
||||
const pool = await db.select().from(schema.players).where(where);
|
||||
if (pool.length < 2) return;
|
||||
const [a, b] = shuffle(pool);
|
||||
const g = await createGame({
|
||||
whiteId: a.id,
|
||||
blackId: b.id,
|
||||
createdBy: null,
|
||||
flags: s.flags ?? DEFAULT_FLAGS,
|
||||
personas: s.randomPersonas ? { white: pick(PERSONAS).id, black: pick(PERSONAS).id } : { white: null, black: null },
|
||||
scheduleId: s.id,
|
||||
startsAt: s.nextRunAt!,
|
||||
});
|
||||
log("scheduler", `announced ${g.id}: ${a.slug} vs ${b.slug} at ${s.nextRunAt?.toISOString()}`);
|
||||
}
|
||||
|
||||
export async function startScheduler() {
|
||||
await boss.work(Q.scheduleTick, { batchSize: 1, pollingIntervalSeconds: 5 } as any, async () => {
|
||||
await scheduleTick();
|
||||
});
|
||||
await boss.schedule(Q.scheduleTick, "* * * * *");
|
||||
// default schedule on first boot
|
||||
const [{ n }] = await db.select({ n: count() }).from(schema.schedules);
|
||||
if (n === 0) {
|
||||
await db.insert(schema.schedules).values({
|
||||
id: newId(),
|
||||
name: "Случайный матч",
|
||||
intervalMinutes: 180,
|
||||
announceMinutes: 30,
|
||||
pool: [],
|
||||
flags: DEFAULT_FLAGS,
|
||||
randomPersonas: true,
|
||||
enabled: true,
|
||||
});
|
||||
log("scheduler", "created default schedule (every 3h)");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,300 @@
|
||||
import { and, asc, eq, inArray, sql } from "drizzle-orm";
|
||||
import {
|
||||
GameState,
|
||||
START_FEN,
|
||||
isRated,
|
||||
rateGame,
|
||||
type GameFlags,
|
||||
type MoveDTO,
|
||||
type RecordPly,
|
||||
type Result,
|
||||
type Side,
|
||||
type Termination,
|
||||
type Usage,
|
||||
} from "@aichess/core";
|
||||
import { db, schema } from "../db/client.ts";
|
||||
import { bus, gameChannel } from "../bus.ts";
|
||||
import { enqueueEval, enqueueFinalize, enqueueTurn } from "../jobs.ts";
|
||||
import { log, newId } from "../util.ts";
|
||||
|
||||
export type GameRow = typeof schema.games.$inferSelect;
|
||||
export type PlayerRow = typeof schema.players.$inferSelect;
|
||||
export type MoveRow = typeof schema.moves.$inferSelect;
|
||||
|
||||
export const sideOfPly = (ply: number): Side => (ply % 2 === 1 ? "white" : "black");
|
||||
export const playerIdFor = (g: GameRow, side: Side) => (side === "white" ? g.whiteId : g.blackId);
|
||||
|
||||
export function playerLabel(p: PlayerRow): string {
|
||||
if (p.kind === "human") return p.displayName;
|
||||
const v = p.variant ? ` · ${p.variant.toUpperCase()}` : "";
|
||||
return `${p.displayName}${v}`;
|
||||
}
|
||||
|
||||
export function moveToDTO(m: MoveRow): MoveDTO {
|
||||
return {
|
||||
ply: m.ply,
|
||||
side: m.side,
|
||||
san: m.san,
|
||||
uci: m.uci,
|
||||
fenAfter: m.fenAfter,
|
||||
phrase: m.phrase,
|
||||
note: m.note,
|
||||
offeredDraw: m.offeredDraw,
|
||||
illegal: m.illegal,
|
||||
thinkMs: m.thinkMs,
|
||||
usage: (m.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0, cost: 0 }) as Usage,
|
||||
eval: m.eval,
|
||||
classification: m.classification,
|
||||
accuracy: m.accuracy,
|
||||
createdAt: m.createdAt.toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export const toRecordPly = (m: MoveRow): RecordPly => ({
|
||||
ply: m.ply,
|
||||
side: m.side,
|
||||
san: m.san,
|
||||
uci: m.uci,
|
||||
fenAfter: m.fenAfter,
|
||||
phrase: m.phrase,
|
||||
illegal: m.illegal,
|
||||
offeredDraw: m.offeredDraw,
|
||||
eval: m.eval,
|
||||
classification: m.classification,
|
||||
accuracy: m.accuracy,
|
||||
});
|
||||
|
||||
export async function loadGame(id: string) {
|
||||
const game = await db.query.games.findFirst({ where: eq(schema.games.id, id) });
|
||||
if (!game) return null;
|
||||
const [white, black] = await Promise.all([
|
||||
db.query.players.findFirst({ where: eq(schema.players.id, game.whiteId) }),
|
||||
db.query.players.findFirst({ where: eq(schema.players.id, game.blackId) }),
|
||||
]);
|
||||
const moves = await db.select().from(schema.moves).where(eq(schema.moves.gameId, id)).orderBy(asc(schema.moves.ply));
|
||||
return { game, white: white!, black: black!, moves };
|
||||
}
|
||||
export type LoadedGame = NonNullable<Awaited<ReturnType<typeof loadGame>>>;
|
||||
|
||||
export function stateOf(g: LoadedGame): GameState {
|
||||
return GameState.fromUci(g.moves.map((m) => ({ uci: m.uci, illegal: m.illegal })), g.game.startFen);
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ create / start
|
||||
|
||||
export interface CreateGameInput {
|
||||
whiteId: string;
|
||||
blackId: string;
|
||||
createdBy: string | null;
|
||||
flags: GameFlags;
|
||||
personas: { white: string | null; black: string | null };
|
||||
scheduleId?: string | null;
|
||||
startsAt?: Date | null;
|
||||
}
|
||||
|
||||
export async function createGame(i: CreateGameInput): Promise<GameRow> {
|
||||
const id = newId();
|
||||
const pending = !!i.startsAt && i.startsAt.getTime() > Date.now();
|
||||
const [g] = await db
|
||||
.insert(schema.games)
|
||||
.values({
|
||||
id,
|
||||
status: pending ? "pending" : "running",
|
||||
whiteId: i.whiteId,
|
||||
blackId: i.blackId,
|
||||
createdBy: i.createdBy,
|
||||
scheduleId: i.scheduleId ?? null,
|
||||
flags: i.flags,
|
||||
personas: i.personas,
|
||||
rated: isRated(i.flags),
|
||||
startFen: START_FEN,
|
||||
fen: START_FEN,
|
||||
startsAt: i.startsAt ?? null,
|
||||
startedAt: pending ? null : new Date(),
|
||||
})
|
||||
.returning();
|
||||
bus.publish("lobby", { type: "game_created", gameId: id });
|
||||
if (!pending) await kickTurn(g);
|
||||
log("game", `created ${id} (${pending ? "pending" : "running"})`);
|
||||
return g;
|
||||
}
|
||||
|
||||
export async function startPendingGame(id: string) {
|
||||
const [g] = await db
|
||||
.update(schema.games)
|
||||
.set({ status: "running", startedAt: new Date() })
|
||||
.where(and(eq(schema.games.id, id), eq(schema.games.status, "pending")))
|
||||
.returning();
|
||||
if (!g) return;
|
||||
bus.publish(gameChannel(id), { type: "status", gameId: id, status: "running" });
|
||||
bus.publish("lobby", { type: "game_updated", gameId: id });
|
||||
await kickTurn(g);
|
||||
}
|
||||
|
||||
/** Enqueue the next agent turn if the side to move is an AI. */
|
||||
export async function kickTurn(g: GameRow) {
|
||||
if (g.status !== "running") return;
|
||||
const ply = g.ply + 1;
|
||||
const pid = playerIdFor(g, sideOfPly(ply));
|
||||
const p = await db.query.players.findFirst({ where: eq(schema.players.id, pid) });
|
||||
if (p?.kind === "ai") await enqueueTurn({ gameId: g.id, ply });
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ applying decisions
|
||||
|
||||
export interface MoveMeta {
|
||||
phrase: string | null;
|
||||
note: string | null;
|
||||
offerDraw: boolean;
|
||||
thinkMs: number;
|
||||
usage: Usage | null;
|
||||
turnId: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply a move for `ply` (optimistic: the game must still be at ply-1). Validates against the
|
||||
* authoritative state, persists, detects game end, schedules eval + next turn.
|
||||
*/
|
||||
export async function applyMove(gameId: string, ply: number, input: { uci: string; illegal?: boolean }, meta: MoveMeta): Promise<{ ok: true; move: MoveDTO } | { ok: false; error: string }> {
|
||||
const g = await loadGame(gameId);
|
||||
if (!g) return { ok: false, error: "game not found" };
|
||||
if (g.game.status !== "running") return { ok: false, error: "game is not running" };
|
||||
if (g.game.ply !== ply - 1) return { ok: false, error: `stale ply (game at ${g.game.ply}, got ${ply})` };
|
||||
const state = stateOf(g);
|
||||
const side = state.turn;
|
||||
const r = input.illegal ? state.applyIllegal(input.uci) : state.tryMove(input.uci);
|
||||
if (!r.ok) return { ok: false, error: r.message };
|
||||
const rec = r.record;
|
||||
|
||||
const moveId = newId();
|
||||
const pendingDrawBy: Side | null = meta.offerDraw ? side : null;
|
||||
const updated = await db.transaction(async (tx) => {
|
||||
const [row] = await tx
|
||||
.update(schema.games)
|
||||
.set({
|
||||
ply,
|
||||
fen: rec.fenAfter,
|
||||
pendingDrawBy,
|
||||
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")))
|
||||
.returning();
|
||||
if (!row) return null;
|
||||
await tx.insert(schema.moves).values({
|
||||
id: moveId,
|
||||
gameId,
|
||||
ply,
|
||||
side,
|
||||
playerId: playerIdFor(g.game, side),
|
||||
san: rec.san,
|
||||
uci: rec.uci,
|
||||
fenAfter: rec.fenAfter,
|
||||
phrase: meta.phrase,
|
||||
note: meta.note,
|
||||
offeredDraw: meta.offerDraw,
|
||||
illegal: rec.illegal,
|
||||
thinkMs: meta.thinkMs,
|
||||
usage: meta.usage,
|
||||
turnId: meta.turnId,
|
||||
});
|
||||
return row;
|
||||
});
|
||||
if (!updated) return { ok: false, error: "concurrent update" };
|
||||
|
||||
const moveRow = (await db.query.moves.findFirst({ where: eq(schema.moves.id, moveId) }))!;
|
||||
const dto = moveToDTO(moveRow);
|
||||
bus.publish(gameChannel(gameId), { type: "move", gameId, move: dto });
|
||||
if (meta.offerDraw) bus.publish(gameChannel(gameId), { type: "draw_offer", gameId, by: side });
|
||||
await enqueueEval({ gameId, ply });
|
||||
|
||||
const outcome = state.outcome();
|
||||
if (outcome) await finishGame(gameId, outcome.result, outcome.termination);
|
||||
else await kickTurn(updated);
|
||||
return { ok: true, move: dto };
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ finishing
|
||||
|
||||
export async function finishGame(gameId: string, result: Result, termination: Termination, opts: { error?: string } = {}) {
|
||||
const g = await db.query.games.findFirst({ where: eq(schema.games.id, gameId) });
|
||||
if (!g || g.status === "finished" || g.status === "aborted") return;
|
||||
const aborted = termination === "aborted" || termination === "error" || result === "*";
|
||||
const rated = g.rated && !aborted;
|
||||
|
||||
let ratingChange: GameRow["ratingChange"] = null;
|
||||
await db.transaction(async (tx) => {
|
||||
const [row] = await tx
|
||||
.update(schema.games)
|
||||
.set({ status: aborted ? "aborted" : "finished", result, termination, finishedAt: new Date(), pendingDrawBy: null, error: opts.error ?? null })
|
||||
.where(and(eq(schema.games.id, gameId), inArray(schema.games.status, ["running", "pending"])))
|
||||
.returning();
|
||||
if (!row) return;
|
||||
if (aborted) return;
|
||||
const [w, b] = await Promise.all([
|
||||
tx.query.players.findFirst({ where: eq(schema.players.id, g.whiteId) }),
|
||||
tx.query.players.findFirst({ where: eq(schema.players.id, g.blackId) }),
|
||||
]);
|
||||
if (!w || !b) return;
|
||||
const sw = result === "1-0" ? "w" : result === "0-1" ? "l" : "d";
|
||||
const sb = result === "0-1" ? "w" : result === "1-0" ? "l" : "d";
|
||||
const stat = (s: string) => ({
|
||||
games: sql`${schema.players.games} + 1`,
|
||||
wins: s === "w" ? sql`${schema.players.wins} + 1` : undefined,
|
||||
losses: s === "l" ? sql`${schema.players.losses} + 1` : undefined,
|
||||
draws: s === "d" ? sql`${schema.players.draws} + 1` : undefined,
|
||||
});
|
||||
if (rated && w.id !== b.id) {
|
||||
const nr = rateGame({ r: w.rating, rd: w.rd, vol: w.vol }, { r: b.rating, rd: b.rd, vol: b.vol }, result as "1-0" | "0-1" | "1/2-1/2");
|
||||
ratingChange = { white: { before: w.rating, after: nr.white.r }, black: { before: b.rating, after: nr.black.r } };
|
||||
await tx.update(schema.players).set({ rating: nr.white.r, rd: nr.white.rd, vol: nr.white.vol, ...stat(sw) } as any).where(eq(schema.players.id, w.id));
|
||||
await tx.update(schema.players).set({ rating: nr.black.r, rd: nr.black.rd, vol: nr.black.vol, ...stat(sb) } as any).where(eq(schema.players.id, b.id));
|
||||
await tx.insert(schema.ratingHistory).values([
|
||||
{ id: newId(), playerId: w.id, gameId, before: w.rating, after: nr.white.r, rd: nr.white.rd },
|
||||
{ id: newId(), playerId: b.id, gameId, before: b.rating, after: nr.black.r, rd: nr.black.rd },
|
||||
]);
|
||||
await tx.update(schema.games).set({ ratingChange }).where(eq(schema.games.id, gameId));
|
||||
}
|
||||
// predictions
|
||||
const winner = result === "1-0" ? "white" : result === "0-1" ? "black" : "draw";
|
||||
await tx.update(schema.predictions).set({ points: sql`case when ${schema.predictions.pick} = ${winner} then 10 else 0 end` }).where(eq(schema.predictions.gameId, gameId));
|
||||
});
|
||||
|
||||
bus.publish(gameChannel(gameId), { type: "game_over", gameId, result, termination });
|
||||
bus.publish("lobby", { type: "game_updated", gameId });
|
||||
log("game", `finished ${gameId}: ${result} (${termination})`);
|
||||
if (!aborted) await enqueueFinalize({ gameId });
|
||||
}
|
||||
|
||||
export async function abortGame(gameId: string, reason = "aborted") {
|
||||
await finishGame(gameId, "*", "aborted", { error: reason });
|
||||
}
|
||||
|
||||
/** Apply a non-move turn decision (resign / accept draw / forfeit). */
|
||||
export async function applyTerminalDecision(gameId: string, side: Side, kind: "resign" | "accept_draw" | "forfeit_illegal" | "forfeit_no_move", phrase: string | null) {
|
||||
const g = await db.query.games.findFirst({ where: eq(schema.games.id, gameId) });
|
||||
if (!g || g.status !== "running") return;
|
||||
if (phrase) {
|
||||
await db
|
||||
.update(schema.games)
|
||||
.set({ lastWords: sql`${schema.games.lastWords} || ${JSON.stringify({ [side]: phrase })}::jsonb` })
|
||||
.where(eq(schema.games.id, gameId));
|
||||
}
|
||||
if (kind === "accept_draw") {
|
||||
if (!g.pendingDrawBy || g.pendingDrawBy === side) return;
|
||||
await finishGame(gameId, "1/2-1/2", "agreement");
|
||||
} else {
|
||||
const result: Result = side === "white" ? "0-1" : "1-0";
|
||||
await finishGame(gameId, result, kind === "resign" ? "resignation" : kind);
|
||||
}
|
||||
}
|
||||
|
||||
export function recordOf(g: LoadedGame) {
|
||||
return {
|
||||
white: playerLabel(g.white),
|
||||
black: playerLabel(g.black),
|
||||
plies: g.moves.map(toRecordPly),
|
||||
result: g.game.result,
|
||||
termination: g.game.termination,
|
||||
startedAt: g.game.startedAt?.toISOString(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { Hono } from "hono";
|
||||
import { serveStatic } from "@hono/node-server/serve-static";
|
||||
import { and, asc, count, desc, eq, inArray, isNotNull, lt, or, sql, sum, avg } from "drizzle-orm";
|
||||
import { z } from "zod";
|
||||
import sharp from "sharp";
|
||||
import { DEFAULT_FLAGS, toPgn, type Side } from "@aichess/core";
|
||||
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 { enqueueFinalize } from "../jobs.ts";
|
||||
import { newId } from "../util.ts";
|
||||
import { gameSummaryDTO, movesDTO, playerDTO, userDTO } from "./dto.ts";
|
||||
|
||||
export const THEMES = ["broadcast", "tabloid", "arcade"] as const;
|
||||
|
||||
async function playersMap(ids: string[]) {
|
||||
const rows = ids.length ? await db.select().from(schema.players).where(inArray(schema.players.id, [...new Set(ids)])) : [];
|
||||
return new Map(rows.map((p) => [p.id, p]));
|
||||
}
|
||||
async function summaries(games: (typeof schema.games.$inferSelect)[], opts: { withReview?: boolean } = {}) {
|
||||
const pm = await playersMap(games.flatMap((g) => [g.whiteId, g.blackId]));
|
||||
return games.map((g) => gameSummaryDTO(g, pm, opts));
|
||||
}
|
||||
|
||||
const body = async <T extends z.ZodTypeAny>(c: any, schema_: T): Promise<z.infer<T>> => schema_.parse(await c.req.json().catch(() => ({})));
|
||||
|
||||
export function buildApp() {
|
||||
const app = new Hono<AppEnv>();
|
||||
app.use("/api/*", authMiddleware);
|
||||
app.onError((err, c) => {
|
||||
if (err instanceof z.ZodError) return c.json({ error: "Некорректные данные", details: err.issues }, 400);
|
||||
console.error(err);
|
||||
return c.json({ error: err.message ?? "Ошибка сервера" }, 500);
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ auth & me
|
||||
app.get("/api/me", async (c) => {
|
||||
const u = c.get("user");
|
||||
if (!u) return c.json({ user: null });
|
||||
const p = await db.query.players.findFirst({ where: eq(schema.players.userId, u.id) });
|
||||
return c.json({ user: userDTO(u, p) });
|
||||
});
|
||||
|
||||
app.post("/api/auth/register", async (c) => {
|
||||
const b = await body(c, z.object({ username: z.string(), password: z.string() }));
|
||||
if (!USERNAME_RE.test(b.username)) return c.json({ error: "Логин: 3–24 символа, латиница, цифры, _ . -" }, 400);
|
||||
if (b.password.length < 6) return c.json({ error: "Пароль — минимум 6 символов" }, 400);
|
||||
if (await findUserByName(b.username)) return c.json({ error: "Такой логин уже занят" }, 409);
|
||||
const u = await registerUser(b.username, b.password);
|
||||
await createSession(c, u.id);
|
||||
return c.json({ user: userDTO(u) });
|
||||
});
|
||||
|
||||
app.post("/api/auth/login", async (c) => {
|
||||
const b = await body(c, z.object({ username: z.string(), password: z.string() }));
|
||||
const u = await findUserByName(b.username);
|
||||
if (!u || !(await verifyPassword(b.password, u.passwordHash))) return c.json({ error: "Неверный логин или пароль" }, 401);
|
||||
await createSession(c, u.id);
|
||||
return c.json({ user: userDTO(u) });
|
||||
});
|
||||
|
||||
app.post("/api/auth/logout", async (c) => {
|
||||
await destroySession(c);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
app.patch("/api/me", requireUser, async (c) => {
|
||||
const u = c.get("user")!;
|
||||
const b = await body(c, z.object({ displayName: z.string().min(1).max(40).optional(), theme: z.enum(THEMES).optional(), onboarded: z.boolean().optional() }));
|
||||
const [nu] = await db.update(schema.users).set(b).where(eq(schema.users.id, u.id)).returning();
|
||||
if (b.displayName) await db.update(schema.players).set({ displayName: b.displayName }).where(eq(schema.players.userId, u.id));
|
||||
const p = await db.query.players.findFirst({ where: eq(schema.players.userId, u.id) });
|
||||
return c.json({ user: userDTO(nu, p) });
|
||||
});
|
||||
|
||||
app.post("/api/me/avatar", requireUser, async (c) => {
|
||||
const u = c.get("user")!;
|
||||
const form = await c.req.formData();
|
||||
const file = form.get("file");
|
||||
if (!(file instanceof File)) return c.json({ error: "Нет файла" }, 400);
|
||||
if (file.size > 8 * 1024 * 1024) return c.json({ error: "Файл больше 8 МБ" }, 400);
|
||||
const rel = path.join("avatars", `${u.id}-${Date.now().toString(36)}.webp`);
|
||||
const abs = path.join(config.paths.data, "media", rel);
|
||||
fs.mkdirSync(path.dirname(abs), { recursive: true });
|
||||
await sharp(Buffer.from(await file.arrayBuffer())).rotate().resize(512, 512, { fit: "cover" }).webp({ quality: 88 }).toFile(abs);
|
||||
const [nu] = await db.update(schema.users).set({ avatar: rel }).where(eq(schema.users.id, u.id)).returning();
|
||||
await db.update(schema.players).set({ avatar: rel }).where(eq(schema.players.userId, u.id));
|
||||
const p = await db.query.players.findFirst({ where: eq(schema.players.userId, u.id) });
|
||||
return c.json({ user: userDTO(nu, p) });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ meta / players
|
||||
app.get("/api/meta", async (c) => {
|
||||
const ai = await db.select().from(schema.players).where(and(eq(schema.players.kind, "ai"), eq(schema.players.active, true))).orderBy(asc(schema.players.createdAt));
|
||||
return c.json({
|
||||
personas: PERSONAS.map(({ id, label, description }) => ({ id, label, description })),
|
||||
aiPlayers: ai.map(playerDTO),
|
||||
themes: THEMES,
|
||||
flags: [
|
||||
{ key: "notes", label: "Заметки себе", description: "Агент может оставить заметку на свой следующий ход.", rated: true },
|
||||
{ key: "extraTools", label: "Доп. тулы", description: "История ходов и Python-песочница с python-chess.", rated: true },
|
||||
{ key: "cheating", label: "Читерство", description: "Нелегальные ходы применяются как есть. Партия безрейтинговая.", rated: false },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/leaderboard", async (c) => {
|
||||
const players = await db.select().from(schema.players).where(or(eq(schema.players.kind, "human"), eq(schema.players.active, true)));
|
||||
// avg accuracy + avg cost per game per player (finished rated + unrated non-aborted games)
|
||||
const acc = await db.execute(sql`
|
||||
select p.id as player_id,
|
||||
avg(case when g.white_id = p.id then (g.accuracy->>'white')::float else (g.accuracy->>'black')::float end) as avg_accuracy,
|
||||
count(g.id) as finished
|
||||
from players p join games g on (g.white_id = p.id or g.black_id = p.id)
|
||||
where g.status = 'finished' and g.accuracy is not null
|
||||
group by p.id`);
|
||||
const cost = await db.execute(sql`
|
||||
select l.player_id, sum(l.cost) as cost, count(distinct l.game_id) as games, sum(l.tokens) as tokens
|
||||
from usage_ledger l where l.kind = 'turn' and l.player_id is not null group by l.player_id`);
|
||||
const accBy = new Map((acc as any[]).map((r) => [r.player_id, r]));
|
||||
const costBy = new Map((cost as any[]).map((r) => [r.player_id, r]));
|
||||
const rows = players
|
||||
.filter((p) => p.games > 0 || p.kind === "ai")
|
||||
.map((p) => {
|
||||
const a = accBy.get(p.id);
|
||||
const k = costBy.get(p.id);
|
||||
return {
|
||||
...playerDTO(p),
|
||||
avgAccuracy: a?.avg_accuracy != null ? Number(a.avg_accuracy) : null,
|
||||
costPerGame: k && Number(k.games) > 0 ? Number(k.cost) / Number(k.games) : null,
|
||||
tokensPerGame: k && Number(k.games) > 0 ? Number(k.tokens) / Number(k.games) : null,
|
||||
};
|
||||
})
|
||||
.sort((a, b) => b.rating - a.rating);
|
||||
return c.json({ players: rows });
|
||||
});
|
||||
|
||||
app.get("/api/stats/h2h", async (c) => {
|
||||
const r = await db.execute(sql`
|
||||
select white_id, black_id, result, count(*)::int as n from games
|
||||
where status = 'finished' and result in ('1-0','0-1','1/2-1/2') group by white_id, black_id, result`);
|
||||
return c.json({ rows: r });
|
||||
});
|
||||
|
||||
app.get("/api/stats/predictors", async (c) => {
|
||||
const r = await db.execute(sql`
|
||||
select u.id, u.display_name, u.avatar, coalesce(sum(p.points),0)::int as points, count(p.id)::int as picks,
|
||||
sum(case when p.points > 0 then 1 else 0 end)::int as correct
|
||||
from predictions p join users u on u.id = p.user_id group by u.id order by points desc limit 50`);
|
||||
return c.json({ rows: (r as any[]).map((x) => ({ ...x, avatarUrl: x.avatar ? `/media/${x.avatar}` : null })) });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ home & lists
|
||||
app.get("/api/home", async (c) => {
|
||||
const live = await db.select().from(schema.games).where(eq(schema.games.status, "running")).orderBy(desc(schema.games.startedAt));
|
||||
const upcoming = await db.select().from(schema.games).where(eq(schema.games.status, "pending")).orderBy(asc(schema.games.startsAt)).limit(5);
|
||||
const featured = await db
|
||||
.select()
|
||||
.from(schema.games)
|
||||
.where(and(eq(schema.games.status, "finished"), isNotNull(schema.games.review), isNotNull(schema.games.thumbnail)))
|
||||
.orderBy(desc(schema.games.finishedAt))
|
||||
.limit(1);
|
||||
const recent = await db.select().from(schema.games).where(eq(schema.games.status, "finished")).orderBy(desc(schema.games.finishedAt)).limit(24);
|
||||
const schedules = await db.select().from(schema.schedules).where(eq(schema.schedules.enabled, true));
|
||||
const nextScheduled = schedules.map((s) => s.nextRunAt).filter(Boolean).sort((a, b) => a!.getTime() - b!.getTime())[0] ?? null;
|
||||
return c.json({
|
||||
live: await summaries(live),
|
||||
upcoming: await summaries(upcoming),
|
||||
featured: (await summaries(featured, { withReview: true }))[0] ?? null,
|
||||
recent: await summaries(recent.filter((g) => g.id !== featured[0]?.id)),
|
||||
nextScheduledAt: nextScheduled?.toISOString() ?? null,
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/games", async (c) => {
|
||||
const status = c.req.query("status");
|
||||
const playerId = c.req.query("player");
|
||||
const before = c.req.query("before");
|
||||
const limit = Math.min(60, Number(c.req.query("limit") ?? 30));
|
||||
const conds = [];
|
||||
if (status) conds.push(eq(schema.games.status, status as any));
|
||||
if (playerId) conds.push(or(eq(schema.games.whiteId, playerId), eq(schema.games.blackId, playerId)));
|
||||
if (before) conds.push(lt(schema.games.createdAt, new Date(before)));
|
||||
const rows = await db.select().from(schema.games).where(conds.length ? and(...conds) : undefined).orderBy(desc(schema.games.createdAt)).limit(limit);
|
||||
return c.json({ games: await summaries(rows) });
|
||||
});
|
||||
|
||||
app.get("/api/games/:id", async (c) => {
|
||||
const g = await loadGame(c.req.param("id"));
|
||||
if (!g) return c.json({ error: "Партия не найдена" }, 404);
|
||||
const pm = new Map([[g.white.id, g.white], [g.black.id, g.black]]);
|
||||
const preds = await db.select({ pick: schema.predictions.pick, n: count() }).from(schema.predictions).where(eq(schema.predictions.gameId, g.game.id)).groupBy(schema.predictions.pick);
|
||||
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);
|
||||
return c.json({
|
||||
game: {
|
||||
...gameSummaryDTO(g.game, pm, { withReview: true }),
|
||||
startFen: g.game.startFen,
|
||||
personas: g.game.personas,
|
||||
interviews: g.game.interviews,
|
||||
lastWords: g.game.lastWords,
|
||||
pendingDrawBy: g.game.pendingDrawBy,
|
||||
createdBy: g.game.createdBy,
|
||||
error: g.game.error,
|
||||
},
|
||||
moves: movesDTO(g.moves),
|
||||
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 },
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/games/:id/turns/:ply", async (c) => {
|
||||
const rows = await db
|
||||
.select()
|
||||
.from(schema.turns)
|
||||
.where(and(eq(schema.turns.gameId, c.req.param("id")), eq(schema.turns.ply, Number(c.req.param("ply")))))
|
||||
.orderBy(asc(schema.turns.attempt));
|
||||
return c.json({ turns: rows.map((t) => ({ id: t.id, attempt: t.attempt, status: t.status, outcome: t.outcome, error: t.error, usage: t.usage, transcript: t.transcript, startedAt: t.startedAt, endedAt: t.endedAt })) });
|
||||
});
|
||||
|
||||
app.get("/api/games/:id/pgn", async (c) => {
|
||||
const g = await loadGame(c.req.param("id"));
|
||||
if (!g) return c.text("not found", 404);
|
||||
c.header("content-type", "application/x-chess-pgn; charset=utf-8");
|
||||
c.header("content-disposition", `attachment; filename="aichess-${g.game.id}.pgn"`);
|
||||
return c.body(toPgn(recordOf(g) as any));
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ playing
|
||||
const NewGame = z.object({
|
||||
white: z.string(),
|
||||
black: z.string(),
|
||||
personas: z.object({ white: z.string().nullable().optional(), black: z.string().nullable().optional() }).optional(),
|
||||
flags: z.object({ notes: z.boolean(), extraTools: z.boolean(), cheating: z.boolean() }).partial().optional(),
|
||||
startsAt: z.string().datetime().optional(), // admin only: scheduled match with predictions
|
||||
});
|
||||
|
||||
app.post("/api/games", requireUser, async (c) => {
|
||||
const u = c.get("user")!;
|
||||
const b = await body(c, NewGame);
|
||||
if (!u.isAdmin) {
|
||||
const [{ n }] = await db.select({ n: count() }).from(schema.games).where(and(eq(schema.games.createdBy, u.id), inArray(schema.games.status, ["running", "pending"])));
|
||||
if (n >= config.game.maxActiveGamesPerUser) return c.json({ error: "У тебя уже идёт партия — дождись её окончания" }, 409);
|
||||
}
|
||||
const me = await db.query.players.findFirst({ where: eq(schema.players.userId, u.id) });
|
||||
const resolve = async (s: string) => (s === "me" ? me : await db.query.players.findFirst({ where: and(eq(schema.players.slug, s), eq(schema.players.kind, "ai")) }));
|
||||
const [w, bl] = await Promise.all([resolve(b.white), resolve(b.black)]);
|
||||
if (!w || !bl) return c.json({ error: "Неизвестный игрок" }, 400);
|
||||
if (w.kind === "human" && bl.kind === "human") return c.json({ error: "Человек против человека — не здесь :)" }, 400);
|
||||
const personaOk = (id: string | null | undefined) => (id && PERSONAS.some((p) => p.id === id) ? id : null);
|
||||
const g = await createGame({
|
||||
whiteId: w.id,
|
||||
blackId: bl.id,
|
||||
createdBy: u.id,
|
||||
flags: { ...DEFAULT_FLAGS, ...(b.flags ?? {}) },
|
||||
personas: { white: w.kind === "ai" ? personaOk(b.personas?.white) ?? "gopnik" : null, black: bl.kind === "ai" ? personaOk(b.personas?.black) ?? "gopnik" : null },
|
||||
scheduleId: u.isAdmin && b.startsAt ? "manual" : null,
|
||||
startsAt: u.isAdmin && b.startsAt ? new Date(b.startsAt) : null,
|
||||
});
|
||||
return c.json({ id: g.id });
|
||||
});
|
||||
|
||||
async function humanTurn(c: any) {
|
||||
const u = c.get("user")!;
|
||||
const g = await loadGame(c.req.param("id"));
|
||||
if (!g) return { error: c.json({ error: "Партия не найдена" }, 404) };
|
||||
if (g.game.status !== "running") return { error: c.json({ error: "Партия не идёт" }, 409) };
|
||||
const side = sideOfPly(g.game.ply + 1);
|
||||
const p = side === "white" ? g.white : g.black;
|
||||
if (p.kind !== "human" || p.userId !== u.id) return { error: c.json({ error: "Сейчас не твой ход" }, 409) };
|
||||
return { g, side };
|
||||
}
|
||||
|
||||
app.post("/api/games/:id/move", requireUser, async (c) => {
|
||||
const t = await humanTurn(c);
|
||||
if ("error" in t) return t.error;
|
||||
const b = await body(c, z.object({ move: z.string().min(2).max(12), phrase: z.string().max(400).optional(), offerDraw: z.boolean().optional() }));
|
||||
const r = await applyMove(t.g.game.id, t.g.game.ply + 1, { uci: b.move }, { phrase: b.phrase?.trim() || null, note: null, offerDraw: !!b.offerDraw, thinkMs: 0, usage: null, turnId: null });
|
||||
if (!r.ok) return c.json({ error: r.error }, 400);
|
||||
return c.json({ ok: true, move: r.move });
|
||||
});
|
||||
|
||||
app.post("/api/games/:id/resign", requireUser, async (c) => {
|
||||
const u = c.get("user")!;
|
||||
const g = await loadGame(c.req.param("id"));
|
||||
if (!g || g.game.status !== "running") return c.json({ error: "Партия не идёт" }, 409);
|
||||
const side: Side | null = g.white.userId === u.id ? "white" : g.black.userId === u.id ? "black" : null;
|
||||
if (!side) return c.json({ error: "Ты не играешь в этой партии" }, 403);
|
||||
const b = await body(c, z.object({ phrase: z.string().max(400).optional() }));
|
||||
abortRunningTurn(g.game.id);
|
||||
await applyTerminalDecision(g.game.id, side, "resign", b.phrase ?? null);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post("/api/games/:id/accept-draw", requireUser, async (c) => {
|
||||
const t = await humanTurn(c);
|
||||
if ("error" in t) return t.error;
|
||||
await applyTerminalDecision(t.g.game.id, t.side, "accept_draw", null);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post("/api/games/:id/abort", requireUser, async (c) => {
|
||||
const u = c.get("user")!;
|
||||
const g = await db.query.games.findFirst({ where: eq(schema.games.id, c.req.param("id")) });
|
||||
if (!g) return c.json({ error: "Партия не найдена" }, 404);
|
||||
if (!u.isAdmin && g.createdBy !== u.id) return c.json({ error: "Можно прервать только свою партию" }, 403);
|
||||
abortRunningTurn(g.id);
|
||||
await abortGame(g.id, `aborted by ${u.username}`);
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
app.post("/api/games/:id/predict", requireUser, async (c) => {
|
||||
const u = c.get("user")!;
|
||||
const b = await body(c, z.object({ pick: z.enum(["white", "draw", "black"]) }));
|
||||
const g = await db.query.games.findFirst({ where: eq(schema.games.id, c.req.param("id")) });
|
||||
if (!g || !g.scheduleId) return c.json({ error: "Прогнозы только для матчей по расписанию" }, 400);
|
||||
if (g.status !== "pending") return c.json({ error: "Приём прогнозов закрыт" }, 409);
|
||||
await db
|
||||
.insert(schema.predictions)
|
||||
.values({ id: newId(), gameId: g.id, userId: u.id, pick: b.pick })
|
||||
.onConflictDoUpdate({ target: [schema.predictions.gameId, schema.predictions.userId], set: { pick: b.pick } });
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------ admin
|
||||
app.get("/api/admin/users", requireUser, requireAdmin, async (c) => {
|
||||
const r = await db.execute(sql`
|
||||
select u.id, u.username, u.display_name, u.avatar, u.is_admin, u.created_at,
|
||||
coalesce(sum(l.cost),0)::float as cost, coalesce(sum(l.tokens),0)::bigint as tokens,
|
||||
count(distinct l.game_id)::int as games
|
||||
from users u left join usage_ledger l on l.user_id = u.id
|
||||
group by u.id order by cost desc`);
|
||||
const sys = await db.execute(sql`select coalesce(sum(cost),0)::float as cost, coalesce(sum(tokens),0)::bigint as tokens, count(distinct game_id)::int as games from usage_ledger where user_id is null`);
|
||||
return c.json({ users: (r as any[]).map((x) => ({ ...x, tokens: Number(x.tokens), avatarUrl: x.avatar ? `/media/${x.avatar}` : null })), system: { ...(sys as any[])[0], tokens: Number((sys as any[])[0].tokens) } });
|
||||
});
|
||||
|
||||
const ScheduleBody = z.object({
|
||||
name: z.string().min(1).max(60),
|
||||
enabled: z.boolean(),
|
||||
intervalMinutes: z.number().int().min(10).max(7 * 24 * 60),
|
||||
announceMinutes: z.number().int().min(0).max(24 * 60),
|
||||
pool: z.array(z.string()),
|
||||
flags: z.object({ notes: z.boolean(), extraTools: z.boolean(), cheating: z.boolean() }),
|
||||
randomPersonas: z.boolean(),
|
||||
nextRunAt: z.string().datetime().nullable().optional(),
|
||||
});
|
||||
app.get("/api/admin/schedules", requireUser, requireAdmin, async (c) => c.json({ schedules: await db.select().from(schema.schedules).orderBy(asc(schema.schedules.createdAt)) }));
|
||||
app.post("/api/admin/schedules", requireUser, requireAdmin, async (c) => {
|
||||
const b = await body(c, ScheduleBody);
|
||||
const [s] = await db.insert(schema.schedules).values({ id: newId(), ...b, nextRunAt: b.nextRunAt ? new Date(b.nextRunAt) : null, createdBy: c.get("user")!.id }).returning();
|
||||
return c.json({ schedule: s });
|
||||
});
|
||||
app.patch("/api/admin/schedules/:id", requireUser, requireAdmin, async (c) => {
|
||||
const b = await body(c, ScheduleBody.partial());
|
||||
const [s] = await db
|
||||
.update(schema.schedules)
|
||||
.set({ ...b, nextRunAt: b.nextRunAt === undefined ? undefined : b.nextRunAt ? new Date(b.nextRunAt) : null })
|
||||
.where(eq(schema.schedules.id, c.req.param("id")))
|
||||
.returning();
|
||||
return c.json({ schedule: s });
|
||||
});
|
||||
app.delete("/api/admin/schedules/:id", requireUser, requireAdmin, async (c) => {
|
||||
await db.delete(schema.schedules).where(eq(schema.schedules.id, c.req.param("id")));
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
app.post("/api/admin/games/:id/postgame", requireUser, requireAdmin, async (c) => {
|
||||
const id = c.req.param("id");
|
||||
const b = await body(c, z.object({ redo: z.array(z.enum(["interviews", "review", "thumbnail"])).default([]) }));
|
||||
const patch: Record<string, unknown> = {};
|
||||
if (b.redo.includes("interviews")) patch.interviews = {};
|
||||
if (b.redo.includes("review")) patch.review = null;
|
||||
if (b.redo.includes("thumbnail")) Object.assign(patch, { thumbnail: null, thumbnailCaption: null, thumbnailMeta: null });
|
||||
if (Object.keys(patch).length) await db.update(schema.games).set(patch).where(eq(schema.games.id, id));
|
||||
await enqueueFinalize({ gameId: id });
|
||||
return c.json({ ok: true });
|
||||
});
|
||||
|
||||
return app;
|
||||
}
|
||||
|
||||
/** Static assets + SPA fallback. Must be mounted last (after /ws). */
|
||||
export function mountStatic(app: Hono<AppEnv>) {
|
||||
app.use("/assets/*", serveStatic({ root: path.relative(process.cwd(), config.paths.assets), rewriteRequestPath: (p) => p.replace(/^\/assets/, "") }));
|
||||
app.use("/media/*", serveStatic({ root: path.relative(process.cwd(), path.join(config.paths.data, "media")), rewriteRequestPath: (p) => p.replace(/^\/media/, "") }));
|
||||
if (fs.existsSync(config.paths.web)) {
|
||||
const webRoot = path.relative(process.cwd(), config.paths.web);
|
||||
app.use("/*", serveStatic({ root: webRoot }));
|
||||
const indexHtml = () => fs.readFileSync(path.join(config.paths.web, "index.html"), "utf8");
|
||||
app.get("*", (c) => (c.req.path.startsWith("/api/") ? c.json({ error: "not found" }, 404) : c.html(indexHtml())));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import type { schema } from "../db/client.ts";
|
||||
import { moveToDTO, type GameRow, type MoveRow, type PlayerRow } from "../games/service.ts";
|
||||
|
||||
export function avatarUrl(p: { kind: string; avatar: string | null }) {
|
||||
if (!p.avatar) return null;
|
||||
return p.kind === "ai" ? `/assets/${p.avatar}` : `/media/${p.avatar}`;
|
||||
}
|
||||
|
||||
export function playerDTO(p: PlayerRow) {
|
||||
return {
|
||||
id: p.id,
|
||||
kind: p.kind,
|
||||
slug: p.slug,
|
||||
displayName: p.displayName,
|
||||
variant: p.variant,
|
||||
family: p.family,
|
||||
modelId: p.modelId,
|
||||
avatarUrl: avatarUrl(p),
|
||||
color: p.color,
|
||||
dumb: p.dumb,
|
||||
skull: p.skull,
|
||||
active: p.active,
|
||||
rating: Math.round(p.rating),
|
||||
rd: Math.round(p.rd),
|
||||
games: p.games,
|
||||
wins: p.wins,
|
||||
draws: p.draws,
|
||||
losses: p.losses,
|
||||
};
|
||||
}
|
||||
export type PlayerDTO = ReturnType<typeof playerDTO>;
|
||||
|
||||
export function gameSummaryDTO(g: GameRow, players: Map<string, PlayerRow>, opts: { withReview?: boolean } = {}) {
|
||||
return {
|
||||
id: g.id,
|
||||
status: g.status,
|
||||
white: playerDTO(players.get(g.whiteId)!),
|
||||
black: playerDTO(players.get(g.blackId)!),
|
||||
result: g.result,
|
||||
termination: g.termination,
|
||||
ply: g.ply,
|
||||
fen: g.fen,
|
||||
rated: g.rated,
|
||||
flags: g.flags,
|
||||
scheduled: !!g.scheduleId,
|
||||
startsAt: g.startsAt?.toISOString() ?? null,
|
||||
startedAt: g.startedAt?.toISOString() ?? null,
|
||||
finishedAt: g.finishedAt?.toISOString() ?? null,
|
||||
createdAt: g.createdAt.toISOString(),
|
||||
thumbnailUrl: g.thumbnail ? `/media/${g.thumbnail}` : null,
|
||||
thumbnailCaption: g.thumbnailCaption,
|
||||
accuracy: g.accuracy,
|
||||
costTotal: g.costTotal,
|
||||
ratingChange: g.ratingChange,
|
||||
review: opts.withReview ? g.review : undefined,
|
||||
};
|
||||
}
|
||||
export type GameSummaryDTO = ReturnType<typeof gameSummaryDTO>;
|
||||
|
||||
export function userDTO(u: typeof schema.users.$inferSelect, player?: PlayerRow | null) {
|
||||
return {
|
||||
id: u.id,
|
||||
username: u.username,
|
||||
displayName: u.displayName,
|
||||
avatarUrl: u.avatar ? `/media/${u.avatar}` : null,
|
||||
isAdmin: u.isAdmin,
|
||||
onboarded: u.onboarded,
|
||||
theme: u.theme,
|
||||
playerId: player?.id ?? null,
|
||||
rating: player ? Math.round(player.rating) : null,
|
||||
};
|
||||
}
|
||||
|
||||
export const movesDTO = (ms: MoveRow[]) => ms.map(moveToDTO);
|
||||
@@ -0,0 +1,119 @@
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { serve } from "@hono/node-server";
|
||||
import { createNodeWebSocket } from "@hono/node-ws";
|
||||
import { getCookie } from "hono/cookie";
|
||||
import { config } from "./config.ts";
|
||||
import { runMigrations } from "./db/client.ts";
|
||||
import { syncCatalog } from "./catalog.ts";
|
||||
import { ensureAdmin, COOKIE, userFromToken } from "./auth.ts";
|
||||
import { startBoss, boss } from "./jobs.ts";
|
||||
import { bus, type BusEvent } from "./bus.ts";
|
||||
import { buildApp, mountStatic } from "./http/app.ts";
|
||||
import { startWorkers, recoverRunningGames } from "./games/runner.ts";
|
||||
import { startFinalizeWorker } from "./games/finalize.ts";
|
||||
import { startScheduler } from "./games/scheduler.ts";
|
||||
import { engine } from "./engine/stockfish.ts";
|
||||
import { log } from "./util.ts";
|
||||
|
||||
async function main() {
|
||||
fs.mkdirSync(path.join(config.paths.data, "media"), { recursive: true });
|
||||
await runMigrations();
|
||||
await syncCatalog();
|
||||
await ensureAdmin();
|
||||
await startBoss();
|
||||
|
||||
const app = buildApp();
|
||||
const { injectWebSocket, upgradeWebSocket } = createNodeWebSocket({ app });
|
||||
|
||||
/**
|
||||
* WS protocol: client sends {"sub": ["lobby", "game:<id>"]} / {"unsub": [...]}; server pushes
|
||||
* {"ch": channel, "ev": event}. Delta events are coalesced per channel every 120 ms.
|
||||
*/
|
||||
app.get(
|
||||
"/ws",
|
||||
upgradeWebSocket(async (c) => {
|
||||
const user = await userFromToken(getCookie(c, COOKIE)).catch(() => null);
|
||||
const subs = new Map<string, () => void>();
|
||||
let pending: { ch: string; ev: BusEvent }[] = [];
|
||||
let timer: NodeJS.Timeout | null = null;
|
||||
let socket: { send: (s: string) => void; readyState: number } | null = null;
|
||||
const flush = () => {
|
||||
timer = null;
|
||||
if (!socket || !pending.length) return;
|
||||
// merge consecutive thinking/text deltas
|
||||
const merged: typeof pending = [];
|
||||
for (const p of pending) {
|
||||
const last = merged[merged.length - 1];
|
||||
const t = (p.ev as any).type;
|
||||
if (last && last.ch === p.ch && (t === "thinking_delta" || t === "text_delta") && (last.ev as any).type === t && (last.ev as any).ply === (p.ev as any).ply) {
|
||||
(last.ev as any) = { ...(last.ev as any), delta: (last.ev as any).delta + (p.ev as any).delta };
|
||||
} else merged.push({ ch: p.ch, ev: { ...(p.ev as any) } });
|
||||
}
|
||||
pending = [];
|
||||
try {
|
||||
socket.send(JSON.stringify({ batch: merged }));
|
||||
} catch {
|
||||
/* closed */
|
||||
}
|
||||
};
|
||||
const push = (ch: string, ev: BusEvent) => {
|
||||
pending.push({ ch, ev });
|
||||
if (!timer) timer = setTimeout(flush, 120);
|
||||
};
|
||||
return {
|
||||
onOpen(_e, ws) {
|
||||
socket = ws as any;
|
||||
ws.send(JSON.stringify({ hello: true, user: user ? { id: user.id, username: user.username } : null }));
|
||||
},
|
||||
onMessage(e, _ws) {
|
||||
try {
|
||||
const msg = JSON.parse(String(e.data));
|
||||
for (const ch of (msg.sub ?? []) as string[]) {
|
||||
if (subs.has(ch) || !(ch === "lobby" || /^game:[a-z0-9]+$/.test(ch))) continue;
|
||||
subs.set(ch, bus.subscribe(ch, (ev) => push(ch, ev)));
|
||||
}
|
||||
for (const ch of (msg.unsub ?? []) as string[]) {
|
||||
subs.get(ch)?.();
|
||||
subs.delete(ch);
|
||||
}
|
||||
} catch {
|
||||
/* ignore */
|
||||
}
|
||||
},
|
||||
onClose() {
|
||||
for (const off of subs.values()) off();
|
||||
subs.clear();
|
||||
if (timer) clearTimeout(timer);
|
||||
socket = null;
|
||||
},
|
||||
};
|
||||
}),
|
||||
);
|
||||
mountStatic(app);
|
||||
|
||||
const server = serve({ fetch: app.fetch, port: config.port, hostname: config.host }, (i) => log("http", `listening on ${i.address}:${i.port}`));
|
||||
injectWebSocket(server);
|
||||
|
||||
if (config.role !== "api") {
|
||||
await startWorkers();
|
||||
await startFinalizeWorker();
|
||||
await startScheduler();
|
||||
await recoverRunningGames();
|
||||
}
|
||||
|
||||
const shutdown = async () => {
|
||||
log("main", "shutting down");
|
||||
server.close();
|
||||
await boss.stop({ graceful: true, timeout: 5000 } as any).catch(() => {});
|
||||
engine.stop();
|
||||
process.exit(0);
|
||||
};
|
||||
process.on("SIGTERM", shutdown);
|
||||
process.on("SIGINT", shutdown);
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { PgBoss } from "pg-boss";
|
||||
import { config } from "./config.ts";
|
||||
import { log, logErr } from "./util.ts";
|
||||
|
||||
export const Q = {
|
||||
turn: "turn",
|
||||
evalPly: "eval-ply",
|
||||
finalize: "finalize",
|
||||
scheduleTick: "schedule-tick",
|
||||
} as const;
|
||||
|
||||
export type TurnJob = { gameId: string; ply: number };
|
||||
export type EvalJob = { gameId: string; ply: number };
|
||||
export type FinalizeJob = { gameId: string };
|
||||
|
||||
export const boss = new PgBoss({ connectionString: config.databaseUrl, schema: "pgboss" } as any);
|
||||
boss.on("error", (e: unknown) => logErr("pg-boss", e));
|
||||
|
||||
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 });
|
||||
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 });
|
||||
log("jobs", "pg-boss started");
|
||||
}
|
||||
|
||||
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(() => {});
|
||||
}
|
||||
}
|
||||
|
||||
export const enqueueTurn = (j: TurnJob) => boss.send(Q.turn, j, { singletonKey: `${j.gameId}:${j.ply}` });
|
||||
export const enqueueEval = (j: EvalJob) => boss.send(Q.evalPly, j, { singletonKey: `${j.gameId}:${j.ply}` });
|
||||
export const enqueueFinalize = (j: FinalizeJob) => boss.send(Q.finalize, j, { singletonKey: j.gameId });
|
||||
@@ -0,0 +1,26 @@
|
||||
import { customAlphabet } from "nanoid";
|
||||
|
||||
const alpha = customAlphabet("0123456789abcdefghijklmnopqrstuvwxyz", 12);
|
||||
/** short, url-safe, roughly time-sortable id */
|
||||
export const newId = () => Date.now().toString(36) + alpha();
|
||||
|
||||
export const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
export function log(scope: string, ...args: unknown[]) {
|
||||
console.log(new Date().toISOString(), `[${scope}]`, ...args);
|
||||
}
|
||||
export function logErr(scope: string, ...args: unknown[]) {
|
||||
console.error(new Date().toISOString(), `[${scope}]`, ...args);
|
||||
}
|
||||
|
||||
export function pick<T>(arr: readonly T[]): T {
|
||||
return arr[Math.floor(Math.random() * arr.length)];
|
||||
}
|
||||
export function shuffle<T>(arr: T[]): T[] {
|
||||
const a = [...arr];
|
||||
for (let i = a.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[a[i], a[j]] = [a[j], a[i]];
|
||||
}
|
||||
return a;
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"extends": "../../tsconfig.base.json",
|
||||
"include": ["src", "test", "drizzle.config.ts", "tsup.config.ts"]
|
||||
}
|
||||
Reference in New Issue
Block a user