rewrite: TS monorepo — pi SDK stateless agents, Postgres+pg-boss, SvelteKit themed UI; legacy moved to legacy/

This commit is contained in:
ai-chess
2026-10-18 15:32:39 +03:00
parent e23a07f07b
commit 5be4bd1da4
321 changed files with 37840 additions and 158 deletions
+14 -13
View File
@@ -1,15 +1,16 @@
**/node_modules
**/.svelte-kit
**/build
**/dist
.git
.venv
__pycache__
*.pyc
*.pyo
.pytest_cache
games
logs
config
public/vendor
.playwright-mcp
.env
.env.*
!.env.example
data
pgdata
legacy
design
.pi
.claude
*.png
*.log
node_modules
**/*.log
**/.DS_Store
+11
View File
@@ -0,0 +1,11 @@
DATABASE_URL=postgres://chess:chess@db:5432/chess
# cli-proxy-api; inside the docker network use http://cli-proxy-api:8317
LLM_BASE_URL=http://cli-proxy-api:8317
LLM_API_KEY=
ADMIN_USERNAME=danosito
ADMIN_INITIAL_PASSWORD=
PUBLIC_URL=https://chess.danosito.com
PORT=7833
MAX_CONCURRENT_GAMES=6
PROMPT_WRITER_MODEL=openai/gpt-6-astra
IMAGE_MODEL=gpt-image-2.5
+26 -17
View File
@@ -1,32 +1,41 @@
node_modules/
dist/
build/
.svelte-kit/
coverage/
*.tsbuildinfo
# python
__pycache__/
*.pyc
*.egg-info/
.venv/
.uv/
.pytest_cache/
# runtime artifacts
config/
games/
logs/
# runtime data
data/
.env
.env.*
!.env.example
# vendor (re-fetched at start.sh)
public/vendor/
# editor
# editor / os
.DS_Store
.vscode/
.idea/
.env
.env.*
*.swp
*~
.coverage
htmlcov/
# tools / IDE artifacts
# tools
.claude/
.playwright-mcp/
.pi/
# stray screenshots from local debugging
# legacy runtime artifacts
legacy/config/
legacy/games/
legacy/logs/
legacy/public/vendor/
# design concept screenshots are kept, everything else png-ish is ignored
*.png
!design/**/shots/*.png
!apps/web/static/**/*.png
!assets/**/*.png
+34 -104
View File
@@ -1,111 +1,41 @@
# syntax=docker/dockerfile:1.7
FROM python:3.12-slim AS base
ENV PYTHONDONTWRITEBYTECODE=1 \
PYTHONUNBUFFERED=1 \
PIP_DISABLE_PIP_VERSION_CHECK=1
# Runtime deps: stockfish for eval, tmux for the agent panes, curl for the
# in-container vendor fetch step, jq for pane-agent.sh JSON parse,
# node+npm for the claude-code CLI.
RUN apt-get update && apt-get install -y --no-install-recommends \
stockfish \
tmux \
curl \
ca-certificates \
procps \
jq \
xz-utils \
gnupg \
&& curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
&& apt-get install -y --no-install-recommends nodejs \
&& rm -rf /var/lib/apt/lists/*
# claude-code CLI — install globally via npm. The version pin keeps the
# image deterministic; bump as needed.
RUN npm install -g --omit=dev @anthropic-ai/claude-code@2.1.141 \
&& claude --version
# codex CLI — official linux release tarball. The musl static binary
# works on Debian.
ARG CODEX_VERSION=0.130.0
RUN curl -fsSL "https://github.com/openai/codex/releases/download/rust-v${CODEX_VERSION}/codex-x86_64-unknown-linux-musl.tar.gz" \
-o /tmp/codex.tar.gz \
&& mkdir -p /tmp/codex && tar -xzf /tmp/codex.tar.gz -C /tmp/codex --strip-components=0 \
&& find /tmp/codex -type f -name 'codex-*' -exec mv {} /usr/local/bin/codex \; \
&& chmod +x /usr/local/bin/codex \
&& rm -rf /tmp/codex /tmp/codex.tar.gz \
&& codex --version
# Debian's stockfish package installs to /usr/games/stockfish which is not
# on the default PATH for non-login shells. Symlink it so `which stockfish`
# works for both the Python wrapper and any spawn from tmux panes.
RUN ln -s /usr/games/stockfish /usr/local/bin/stockfish && stockfish --help >/dev/null 2>&1 || true
# AI·CHESS — single image: Hono API + pi agents + workers + static SvelteKit build.
FROM node:24-bookworm-slim AS deps
ENV PNPM_HOME=/pnpm PATH=/pnpm:$PATH
RUN corepack enable
WORKDIR /app
COPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./
COPY apps/server/package.json apps/server/
COPY apps/web/package.json apps/web/
COPY packages/core/package.json packages/core/
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile
# Copy everything first — pip install -e needs src/ai_chess to exist at
# build time so the editable wheel can find the package.
COPY pyproject.toml README.md ./
COPY src ./src
COPY public ./public
COPY scripts ./scripts
COPY docs ./docs
FROM deps AS build
COPY packages packages
COPY apps apps
RUN pnpm --filter @aichess/web build
# Python deps (editable install of the project itself + dev tools)
RUN pip install hatchling \
&& pip install -e ".[dev]"
# Vendor JS/CSS at build time so the container is fully self-contained.
RUN chmod +x scripts/*.sh && ./scripts/fetch-vendor.sh
# Runtime artefacts (games/, logs/, config/) — keep as named mountable dirs.
RUN mkdir -p games logs config
# claude-code refuses to run with --dangerously-skip-permissions as root,
# so the container's main process drops to a non-root user. Codex is also
# fine here. The user's HOME (=/home/chess) is where ~/.codex lives, so
# the docker-compose volume mounts target /home/chess/.codex.
RUN useradd -m -u 1000 -s /bin/bash chess && chown -R chess:chess /app
# Pre-seed claude-code state so its first-run onboarding (theme picker,
# changelog popup, etc.) is skipped — the flag lives in ~/.claude.json
# (a file in HOME, *not* the ~/.claude/ directory). Without this every
# fresh pane-agent.sh hangs at the theme prompt.
RUN mkdir -p /home/chess/.claude && \
cat > /home/chess/.claude/settings.json <<'EOF'
{
"theme": "light",
"permissions": { "allow": ["*"], "defaultMode": "bypassPermissions" },
"skipDangerousModePermissionPrompt": true
}
EOF
RUN cat > /home/chess/.claude.json <<'EOF'
{
"hasCompletedOnboarding": true,
"lastOnboardingVersion": "2.1.141",
"numStartups": 1,
"autoUpdates": false,
"officialMarketplaceAutoInstallAttempted": true,
"officialMarketplaceAutoInstalled": false,
"migrationVersion": 13,
"opusProMigrationComplete": true,
"sonnet1m45MigrationComplete": true,
"projects": {
"/app": {
"hasTrustDialogAccepted": true,
"hasClaudeMdExternalIncludesApproved": true,
"hasClaudeMdExternalIncludesWarningShown": true,
"projectOnboardingSeenCount": 1,
"allowedTools": ["*"]
}
}
}
EOF
RUN chown -R chess:chess /home/chess
USER chess
FROM node:24-bookworm-slim AS runtime
RUN apt-get update \
&& apt-get install -y --no-install-recommends stockfish python3 python3-chess ca-certificates tini \
&& rm -rf /var/lib/apt/lists/* \
&& ln -sf /usr/games/stockfish /usr/local/bin/stockfish
WORKDIR /app
ENV HOME=/home/chess
COPY --from=build /app /app
COPY config config
COPY assets assets
ENV NODE_ENV=production \
DATA_DIR=/data \
WEB_DIR=/app/apps/web/build \
ASSETS_DIR=/app/assets \
CONFIG_DIR=/app/config \
PYTHON_BIN=python3 \
STOCKFISH_BIN=/usr/games/stockfish \
PORT=7833
RUN mkdir -p /data && chown -R node:node /data
USER node
WORKDIR /app/apps/server
EXPOSE 7833
CMD ["python", "-m", "ai_chess"]
ENTRYPOINT ["tini", "--"]
CMD ["node", "--import", "tsx", "src/index.ts"]
+60 -7
View File
@@ -1,13 +1,66 @@
# ai-chess
# AI·CHESS
Local tournament: Claude Code vs Codex CLI play chess against each other
through a shared MCP server. Browser UI in lichess style; both agents
remain interactive in tmux panes.
Арена, где фронтир-LLM играют в шахматы друг с другом и с людьми, пишут друг другу трэш-ток,
дают послематчевые интервью и попадают в общий рейтинг. Live: https://chess.danosito.com
See `docs/superpowers/specs/2026-05-14-ai-chess-design.md` for design.
## Как устроен ход агента
## Run
Шахматы почти stateless, поэтому **каждый ход — новая сессия pi с пустым контекстом**:
кешируемый system prompt (персонаж, правила арены, тулы) + одно сообщение хода
(`packages/core/src/context.ts`):
- последний ход соперника словами (`22. gxh3 — пешка g2→h3, взял коня`) и его реплика;
- позиция в трёх нотациях: ASCII-диаграмма, FEN, список фигур + материал;
- состояние правил **только когда оно важно**: рокировка (только если позиция выглядит
как K··R / R···K — тогда «права есть» или «НЕВОЗМОЖНА: король/ладья ходили»), взятие на
проходе (только если доступно), правило 50 ходов (с 40-го хода), повторения (какие позиции
уже были дважды и какие ходы дадут троекратное повторение);
- опционально (флаг «Заметки себе») — заметка, которую агент оставил себе в прошлый ход.
Тулы: `make_move(move, offer_draw?)` → `finish_turn(phrase[, note_to_self])`, `resign`,
`accept_draw` (если предложена ничья). Под флагом «Доп. тулы»: `get_move_history` и `python`
(песочница с python-chess, партия предзагружена, движков нет). Нелегальный ход возвращает
объяснение; после 3 попыток арбитр подсказывает легальные ходы, после 8 — поражение.
После партии: Stockfish-анализ (точность по формулам lichess, `!! ?! ? ??` у ходов), интервью
каждого агента (тем же моделям дают партию в человеко- и машиночитаемом виде, анализ и python),
редакционный обзор (заголовок + заметка, показывается только на главной) и мемное превью:
`gpt-6-astra` пишет промпт → `gpt-image-2.5` рисует по аватаркам участников.
## Стек
```
packages/core чистая логика: GameState (повторения/рокировки/50 ходов/читерство), контекст хода,
точность и классификация ходов, Glicko-2, транскрипты/PGN. Используется и сервером, и фронтом.
apps/server Node 24 + Hono + WebSocket, Postgres (drizzle), pg-boss (ходы/оценки/постгейм/расписание
— каждый ход отдельная durable-задача, рестарт не ломает партии), pi SDK для агентов,
Stockfish (UCI-пул), python-песочница.
apps/web SvelteKit 3 + Svelte 5 SPA, chessground. Общие UI-примитивы на семантических токенах +
три темы (Вечерний Мат / Эфир / AI Fight Club), выбираются при онбординге.
config/ players.json — каталог AI-игроков (модель × effort), pi-models.json — оверрайды pi.
design/ исходные дизайн-концепты (три SvelteKit-демо + скриншоты).
legacy/ старая версия (tmux + Claude Code/Codex CLI + MCP).
```
Модели идут через cli-proxy-api (`LLM_BASE_URL`); в docker-сети прода — напрямую
`http://cli-proxy-api:8317`.
## Разработка
```bash
./scripts/start.sh
pnpm install
docker run -d --name aichess-pg -e POSTGRES_USER=chess -e POSTGRES_PASSWORD=chess -e POSTGRES_DB=chess -p 55432:5432 postgres:17-alpine
cp .env.example .env # DATABASE_URL=postgres://chess:chess@localhost:55432/chess, LLM_* ...
pnpm dev:server # :7833
pnpm dev:web # :5173 (проксирует /api, /ws, /media, /assets)
pnpm test
```
Нужны `stockfish` и `python3` с `python-chess` в PATH.
## Деплой
```bash
# на serv, в /opt/chessai
docker compose up -d --build # BUILD_PROXY=http://127.0.0.1:10809 для сборки через xray
```
+8
View File
@@ -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" },
});
+186
View File
@@ -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
+13
View File
@@ -0,0 +1,13 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1792323366900,
"tag": "0000_init",
"breakpoints": true
}
]
}
+37
View File
@@ -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"
}
}
+106
View File
@@ -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()
+65
View File
@@ -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();
+310
View File
@@ -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 };
}
+121
View File
@@ -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");
}
+43
View File
@@ -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 }),
);
});
}
+109
View File
@@ -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 };
}
+302
View File
@@ -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 };
}
+99
View File
@@ -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`);
}
+36
View File
@@ -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}`;
+64
View File
@@ -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`);
}
+57
View File
@@ -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;
+22
View File
@@ -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 });
}
+186
View File
@@ -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(),
});
+137
View File
@@ -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);
+114
View File
@@ -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);
});
}
+243
View File
@@ -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`);
}
+86
View File
@@ -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)");
}
}
+300
View File
@@ -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(),
};
}
+397
View File
@@ -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())));
}
}
+74
View File
@@ -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);
+119
View File
@@ -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);
});
+40
View File
@@ -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 });
+26
View File
@@ -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;
}
+4
View File
@@ -0,0 +1,4 @@
{
"extends": "../../tsconfig.base.json",
"include": ["src", "test", "drizzle.config.ts", "tsup.config.ts"]
}
+32
View File
@@ -0,0 +1,32 @@
{
"name": "@aichess/web",
"private": true,
"version": "0.1.0",
"type": "module",
"scripts": {
"dev": "vite dev --port 5173",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"typecheck": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --threshold error"
},
"imports": {
"#lib": "./src/lib/index.ts",
"#lib/*": "./src/lib/*"
},
"dependencies": {
"@aichess/core": "workspace:*",
"@lichess-org/chessground": "^10.4.2",
"chess.js": "^1.4.0"
},
"devDependencies": {
"@sveltejs/adapter-static": "^4.0.0",
"@sveltejs/kit": "^3.0.0",
"@sveltejs/vite-plugin-svelte": "^7.2.0",
"svelte": "^5.57.1",
"svelte-check": "^4.6.0",
"typescript": "^6.0.3",
"vite": "^8.3.0"
}
}
+475
View File
@@ -0,0 +1,475 @@
/*
* AI·CHESS — shared UI primitives.
* Every component uses ONLY these semantic tokens/classes; themes (lib/themes/*.css)
* define the tokens and add their own decoration on top.
*/
@import './lib/themes/tabloid.css';
@import './lib/themes/broadcast.css';
@import './lib/themes/arcade.css';
*,
*::before,
*::after {
box-sizing: border-box;
}
html {
background: var(--bg);
color-scheme: var(--scheme, light);
}
body {
margin: 0;
min-height: 100vh;
color: var(--text);
background-color: var(--bg);
background-image: var(--bg-image, none);
background-attachment: fixed;
font-family: var(--f-body);
font-size: 15px;
line-height: 1.45;
-webkit-font-smoothing: antialiased;
}
a {
color: inherit;
text-decoration: none;
}
button {
font: inherit;
color: inherit;
background: none;
border: 0;
padding: 0;
cursor: pointer;
}
button:disabled {
cursor: not-allowed;
opacity: 0.5;
}
h1,
h2,
h3,
h4 {
margin: 0;
font-family: var(--f-display);
font-weight: var(--display-weight, 700);
line-height: 1;
letter-spacing: var(--display-tracking, 0);
text-transform: var(--display-transform, none);
}
p {
margin: 0;
}
img {
max-width: 100%;
}
/* ---------------------------------------------------------- layout */
.wrap {
max-width: var(--max-w, 1400px);
margin: 0 auto;
padding: 0 20px;
}
.stack {
display: grid;
gap: var(--gap, 14px);
}
.row {
display: flex;
align-items: center;
gap: 10px;
}
.spacer {
flex: 1;
}
/* ---------------------------------------------------------- text */
.display {
font-family: var(--f-display);
font-weight: var(--display-weight, 700);
text-transform: var(--display-transform, none);
letter-spacing: var(--display-tracking, 0);
line-height: 0.95;
}
.label,
.kicker {
font-family: var(--f-label);
text-transform: var(--label-transform, uppercase);
letter-spacing: var(--label-tracking, 0.12em);
font-size: var(--label-size, 11px);
font-weight: 600;
line-height: 1.2;
}
.kicker {
color: var(--accent-text, var(--accent));
}
.mono {
font-family: var(--f-mono);
}
.muted {
color: var(--muted);
}
.accent {
color: var(--accent-text, var(--accent));
}
.tnum {
font-variant-numeric: tabular-nums;
}
/* ---------------------------------------------------------- surfaces */
.panel {
background: var(--surface);
border: var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
min-width: 0;
}
.panel-head {
display: flex;
align-items: center;
gap: 10px;
padding: var(--panel-head-pad, 7px 12px);
background: var(--panel-head-bg);
color: var(--panel-head-ink);
border-bottom: var(--panel-head-border, var(--border));
border-radius: var(--radius) var(--radius) 0 0;
font-family: var(--f-label);
text-transform: var(--label-transform, uppercase);
letter-spacing: var(--label-tracking, 0.1em);
font-size: var(--panel-head-size, 13px);
font-weight: 700;
}
.panel-head small {
font-weight: 500;
opacity: 0.75;
font-size: 0.8em;
letter-spacing: 0.06em;
}
.panel-head.hot {
background: var(--accent);
color: var(--accent-ink);
}
.panel-body {
padding: 12px;
}
/* ---------------------------------------------------------- controls */
.btn {
display: inline-flex;
align-items: center;
justify-content: center;
gap: 8px;
font-family: var(--f-label);
text-transform: var(--label-transform, uppercase);
letter-spacing: 0.06em;
font-weight: 700;
font-size: 14px;
line-height: 1;
padding: 10px 16px;
border: var(--btn-border, var(--border));
border-radius: var(--radius);
background: var(--surface-2);
color: var(--text);
box-shadow: var(--shadow-sm);
transition:
transform 0.08s ease,
box-shadow 0.08s ease,
filter 0.12s;
white-space: nowrap;
}
.btn:hover:not(:disabled) {
filter: brightness(1.08);
transform: var(--btn-hover-transform, translateY(-1px));
}
.btn:active:not(:disabled) {
transform: var(--btn-active-transform, translateY(1px));
box-shadow: none;
}
.btn.primary {
background: var(--accent);
color: var(--accent-ink);
border-color: var(--accent-border, var(--line-strong));
}
.btn.secondary {
background: var(--accent-2);
color: var(--accent-2-ink);
}
.btn.danger {
background: var(--danger);
color: #fff;
}
.btn.ghost {
background: transparent;
box-shadow: none;
}
.btn.sm {
font-size: 11px;
padding: 6px 10px;
}
.btn.lg {
font-size: 17px;
padding: 14px 22px;
}
.btn.block {
width: 100%;
}
.input,
.select,
textarea.input {
width: 100%;
font: inherit;
color: var(--text);
background: var(--input-bg, var(--surface-2));
border: var(--border);
border-radius: var(--radius);
padding: 10px 12px;
outline: none;
}
.input:focus,
.select:focus {
border-color: var(--accent);
box-shadow: 0 0 0 2px color-mix(in srgb, var(--accent) 35%, transparent);
}
.field {
display: grid;
gap: 6px;
}
.field > span {
font-family: var(--f-label);
text-transform: var(--label-transform, uppercase);
letter-spacing: 0.1em;
font-size: 11px;
color: var(--muted);
}
.tabs {
display: flex;
gap: 0;
border: var(--border);
border-radius: var(--radius);
background: var(--surface);
overflow-x: auto;
}
.tabs > button,
.tabs > a {
flex: 1;
padding: 9px 12px;
font-family: var(--f-label);
text-transform: var(--label-transform, uppercase);
letter-spacing: 0.08em;
font-size: 12px;
font-weight: 600;
white-space: nowrap;
text-align: center;
border-right: var(--border-thin);
}
.tabs > :last-child {
border-right: 0;
}
.tabs > .on {
background: var(--tab-on-bg, var(--text));
color: var(--tab-on-ink, var(--bg));
}
/* ---------------------------------------------------------- labels & badges */
.chip {
text-shadow: none;
display: inline-flex;
align-items: center;
gap: 4px;
font-family: var(--f-label);
text-transform: uppercase;
letter-spacing: 0.06em;
font-size: 10px;
font-weight: 700;
line-height: 1;
padding: 3px 6px;
border-radius: var(--chip-radius, var(--radius));
background: var(--chip-bg, var(--accent-2));
color: var(--chip-ink, var(--accent-2-ink));
white-space: nowrap;
}
.chip.accent {
background: var(--accent);
color: var(--accent-ink);
}
.chip.outline {
background: transparent;
color: inherit;
border: var(--border-thin);
}
.chip.danger {
background: var(--danger);
color: #fff;
}
.chip.dumb {
background: var(--dumb-bg, #b9a99a);
color: var(--dumb-ink, #1a1612);
font-style: italic;
text-transform: lowercase;
letter-spacing: 0.02em;
}
.tag {
display: inline-flex;
align-items: center;
gap: 6px;
font-family: var(--f-label);
text-transform: uppercase;
letter-spacing: 0.06em;
font-size: 11px;
font-weight: 700;
padding: 5px 9px;
border: var(--border);
border-radius: var(--radius);
background: var(--surface);
white-space: nowrap;
}
.tag.hot {
background: var(--accent);
color: var(--accent-ink);
}
.tag.warn {
background: var(--warn);
color: #111;
}
.tag.danger {
background: var(--danger);
color: #fff;
}
.live-dot {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--live, var(--danger));
animation: live-blink 1.1s steps(2, start) infinite;
}
@keyframes live-blink {
to {
visibility: hidden;
}
}
/* annotation glyphs next to moves (chess.com style) */
.nag {
font-family: var(--f-mono);
font-weight: 800;
font-size: 0.92em;
margin-left: 1px;
}
.nag.brilliant {
color: var(--nag-brilliant);
}
.nag.great {
color: var(--nag-great);
}
.nag.inaccuracy {
color: var(--nag-inaccuracy);
}
.nag.mistake {
color: var(--nag-mistake);
}
.nag.blunder {
color: var(--nag-blunder);
}
/* data tables */
.table {
width: 100%;
border-collapse: collapse;
font-size: 14px;
}
.table th {
text-align: left;
font-family: var(--f-label);
text-transform: uppercase;
letter-spacing: 0.08em;
font-size: 11px;
font-weight: 600;
color: var(--muted);
padding: 8px 10px;
border-bottom: var(--border);
}
.table td {
padding: 8px 10px;
border-bottom: var(--border-thin);
vertical-align: middle;
}
.table tr:hover td {
background: var(--row-hover, color-mix(in srgb, var(--text) 4%, transparent));
}
.num {
text-align: right;
font-variant-numeric: tabular-nums;
}
.empty {
padding: 24px;
text-align: center;
color: var(--muted);
font-style: italic;
}
.error-box {
padding: 10px 12px;
border: 2px solid var(--danger);
background: color-mix(in srgb, var(--danger) 12%, var(--surface));
border-radius: var(--radius);
}
/* ---------------------------------------------------------- board skin */
.cg-wrap {
width: 100%;
aspect-ratio: 1;
}
cg-board {
background-color: var(--board-dark);
background-image: var(
--board-image,
conic-gradient(var(--board-dark) 90deg, var(--board-light) 0 180deg, var(--board-dark) 0 270deg, var(--board-light) 0)
);
background-size: var(--board-image-size, 25% 25%);
}
cg-board square.last-move {
background-color: var(--board-last);
}
cg-board square.check {
background: radial-gradient(ellipse at center, var(--board-check) 0%, color-mix(in srgb, var(--board-check) 40%, transparent) 40%, transparent 75%);
}
cg-board square.selected {
background-color: color-mix(in srgb, var(--accent) 45%, transparent);
}
cg-board square.move-dest {
background: radial-gradient(color-mix(in srgb, var(--text) 30%, transparent) 19%, transparent 20%);
}
cg-board square.oc.move-dest {
background: radial-gradient(transparent 0%, transparent 79%, color-mix(in srgb, var(--text) 30%, transparent) 80%);
}
.cg-wrap coords {
font-family: var(--f-mono);
font-weight: 600;
font-size: 10px;
}
.cg-wrap coords coord {
color: var(--board-coord, rgba(0, 0, 0, 0.55));
}
::-webkit-scrollbar {
width: 10px;
height: 10px;
}
::-webkit-scrollbar-thumb {
background: var(--scroll-thumb, var(--line-strong));
border: 2px solid var(--bg);
border-radius: var(--radius);
}
::-webkit-scrollbar-track {
background: var(--scroll-track, var(--surface-2));
}
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation: none !important;
transition: none !important;
}
}
+4
View File
@@ -0,0 +1,4 @@
declare global {
namespace App {}
}
export {};
+26
View File
@@ -0,0 +1,26 @@
<!doctype html>
<html lang="ru" data-theme="tabloid">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#15120f" />
<link rel="icon" href="/favicon.svg" />
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Oswald:wght@400;500;600;700&family=Spectral:ital,wght@0,400;0,600;0,800;1,400;1,600&family=IBM+Plex+Mono:ital,wght@0,400;0,500;0,600;1,400&family=IBM+Plex+Sans:ital,wght@0,400;0,500;0,600;1,400&family=Unbounded:wght@500;700;900&family=Press+Start+2P&family=JetBrains+Mono:wght@400;500;700&display=swap"
rel="stylesheet"
/>
<script>
// apply the saved theme before first paint
try {
const t = localStorage.getItem('aichess-theme');
if (t) document.documentElement.dataset.theme = t;
} catch (e) {}
</script>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
</body>
</html>
+28
View File
@@ -0,0 +1,28 @@
export class ApiError extends Error {
constructor(
message: string,
public status: number
) {
super(message);
}
}
async function req<T>(method: string, path: string, body?: unknown): Promise<T> {
const init: RequestInit = { method, credentials: 'same-origin', headers: {} };
if (body instanceof FormData) init.body = body;
else if (body !== undefined) {
init.body = JSON.stringify(body);
(init.headers as Record<string, string>)['content-type'] = 'application/json';
}
const r = await fetch(path, init);
const j = await r.json().catch(() => ({}));
if (!r.ok) throw new ApiError(j?.error ?? `Ошибка ${r.status}`, r.status);
return j as T;
}
export const api = {
get: <T>(p: string) => req<T>('GET', p),
post: <T>(p: string, b?: unknown) => req<T>('POST', p, b ?? {}),
patch: <T>(p: string, b?: unknown) => req<T>('PATCH', p, b ?? {}),
del: <T>(p: string) => req<T>('DELETE', p)
};
+51
View File
@@ -0,0 +1,51 @@
<script lang="ts">
import type { Player } from '#lib/types.ts';
let { player, size = 40, ring = false }: { player: Pick<Player, 'avatarUrl' | 'displayName' | 'color' | 'kind' | 'family'>; size?: number; ring?: boolean } = $props();
const initials = $derived(
player.displayName
.split(/\s+/)
.map((w) => w[0])
.join('')
.slice(0, 2)
.toUpperCase()
);
const bg = $derived(player.kind === 'ai' ? (player.family === 'claude' ? '#f4ece0' : '#ffffff') : (player.color ?? 'var(--accent)'));
</script>
<span class="av" class:ring class:pixel={player.family === 'claude'} style:width="{size}px" style:height="{size}px" style:background={bg} style:--c={player.color ?? 'var(--accent)'}>
{#if player.avatarUrl}
<img src={player.avatarUrl} alt={player.displayName} />
{:else}
<span class="ini" style:font-size="{size * 0.4}px">{initials}</span>
{/if}
</span>
<style>
.av {
display: inline-grid;
place-items: center;
flex: none;
overflow: hidden;
border: var(--border);
border-radius: var(--avatar-radius, var(--radius));
box-shadow: var(--shadow-sm);
}
.av.ring {
outline: 3px solid var(--c);
outline-offset: 1px;
}
img {
width: 100%;
height: 100%;
object-fit: contain;
padding: 10%;
}
.pixel img {
image-rendering: pixelated;
}
.ini {
font-family: var(--f-display);
font-weight: 700;
color: var(--accent-ink);
}
</style>
+88
View File
@@ -0,0 +1,88 @@
<script lang="ts">
import { onMount } from 'svelte';
import { Chessground } from '@lichess-org/chessground';
import type { Api } from '@lichess-org/chessground/api';
import type { Key } from '@lichess-org/chessground/types';
let {
fen,
lastMove,
check = false,
orientation = 'white',
arrow = null,
movable = null,
onmove
}: {
fen: string;
lastMove?: [string, string];
check?: boolean;
orientation?: 'white' | 'black';
arrow?: [string, string] | null;
/** when set, the given color may move: dests = legal destinations per square */
movable?: { color: 'white' | 'black'; dests: Map<string, string[]> } | null;
onmove?: (from: string, to: string) => void;
} = $props();
let el: HTMLDivElement;
let api: Api | undefined;
onMount(() => {
api = Chessground(el, {
fen,
orientation,
viewOnly: false,
coordinates: true,
animation: { enabled: true, duration: 220 },
highlight: { lastMove: true, check: true },
movable: { free: false, color: undefined, showDests: true, events: { after: (o, d) => onmove?.(o, d) } },
premovable: { enabled: false },
draggable: { enabled: true, showGhost: true },
drawable: {
enabled: true,
visible: true,
brushes: {
best: { key: 'best', color: '#15781b', opacity: 0.8, lineWidth: 10 },
green: { key: 'g', color: '#2d9a4a', opacity: 0.8, lineWidth: 10 },
red: { key: 'r', color: '#d1231c', opacity: 0.8, lineWidth: 10 },
blue: { key: 'b', color: '#1f5fae', opacity: 0.8, lineWidth: 10 },
yellow: { key: 'y', color: '#e6b800', opacity: 0.8, lineWidth: 10 }
} as any
}
});
return () => api?.destroy();
});
$effect(() => {
if (!api) return;
api.set({
fen,
orientation,
lastMove: lastMove as Key[] | undefined,
check,
turnColor: (fen.split(' ')[1] === 'w' ? 'white' : 'black') as any,
movable: movable
? { color: movable.color, dests: movable.dests as unknown as Map<Key, Key[]>, free: false }
: { color: undefined, dests: new Map() },
drawable: { autoShapes: arrow ? [{ orig: arrow[0] as Key, dest: arrow[1] as Key, brush: 'best' }] : [] }
});
});
</script>
<div class="board-frame">
<div bind:this={el} class="board"></div>
</div>
<style>
.board-frame {
border: 3px solid var(--board-frame);
box-shadow: var(--shadow);
background: var(--board-frame);
border-radius: var(--radius);
line-height: 0;
overflow: hidden;
}
.board {
width: 100%;
aspect-ratio: 1;
}
</style>
@@ -0,0 +1,55 @@
<script lang="ts">
let { to }: { to: string } = $props();
let now = $state(Date.now());
$effect(() => {
const t = setInterval(() => (now = Date.now()), 1000);
return () => clearInterval(t);
});
const left = $derived(Math.max(0, new Date(to).getTime() - now));
const h = $derived(Math.floor(left / 3600000));
const m = $derived(Math.floor((left % 3600000) / 60000));
const s = $derived(Math.floor((left % 60000) / 1000));
const pad = (n: number) => String(n).padStart(2, '0');
</script>
<div class="cd" aria-label="До старта">
{#each [[pad(h), 'час'], [pad(m), 'мин'], [pad(s), 'сек']] as [v, l], i}
{#if i}<span class="sep display">:</span>{/if}
<div class="cell"><b class="display tnum">{v}</b><span class="label">{l}</span></div>
{/each}
</div>
<style>
.cd {
display: flex;
align-items: center;
gap: 6px;
}
.cell {
display: grid;
justify-items: center;
padding: 6px 10px 4px;
background: var(--text);
color: var(--bg);
border-radius: var(--radius);
min-width: 56px;
box-shadow: var(--shadow-sm);
}
b {
font-size: 34px;
line-height: 1;
}
.label {
font-size: 8px;
opacity: 0.7;
}
.sep {
font-size: 30px;
color: var(--accent);
}
:global(html[data-theme='broadcast']) .cell,
:global(html[data-theme='arcade']) .cell {
background: var(--surface-3);
color: var(--accent);
}
</style>
@@ -0,0 +1,50 @@
<script lang="ts">
import type { EngineEval } from '#lib/types.ts';
import { evalLabel, evalShare } from '#lib/fmt.ts';
let { ev = null, orientation = 'white' }: { ev?: EngineEval | null; orientation?: 'white' | 'black' } = $props();
const share = $derived(evalShare(ev));
const whiteAhead = $derived(share >= 0.5);
</script>
<div class="bar" class:flip={orientation === 'black'} title="Оценка Stockfish">
<div class="fill" style:height="{share * 100}%"></div>
<span class="lbl mono" class:top={whiteAhead === (orientation === 'black')}>{ev ? evalLabel(ev) : '…'}</span>
</div>
<style>
.bar {
position: relative;
width: 22px;
height: 100%;
background: var(--black-side-bar, #15120f);
border: var(--border);
border-radius: var(--radius);
overflow: hidden;
display: flex;
flex-direction: column-reverse;
}
.bar.flip {
flex-direction: column;
}
.fill {
background: var(--white-side-bar, #f5f1e6);
transition: height 0.5s cubic-bezier(0.2, 0.8, 0.2, 1);
}
.lbl {
position: absolute;
left: 0;
right: 0;
bottom: 4px;
text-align: center;
font-size: 8px;
font-weight: 700;
color: #15120f;
writing-mode: vertical-rl;
transform: rotate(180deg);
}
.lbl.top {
bottom: auto;
top: 4px;
color: #f5f1e6;
}
</style>
@@ -0,0 +1,89 @@
<script lang="ts">
import type { MoveDTO } from '#lib/types.ts';
import { winPercentWhite } from '@aichess/core';
import { NAG } from '#lib/fmt.ts';
let { moves, current, onselect }: { moves: MoveDTO[]; current: number; onselect?: (ply: number) => void } = $props();
const W = 600;
const H = 120;
const pts = $derived([50, ...moves.map((m) => (m.eval ? winPercentWhite(m.eval) : null))]);
const n = $derived(Math.max(pts.length - 1, 1));
const x = (i: number) => (i / n) * W;
const y = (v: number) => H - (v / 100) * H;
const path = $derived.by(() => {
let d = '';
let last = 50;
pts.forEach((v, i) => {
const val = v ?? last;
last = val;
d += `${i ? 'L' : 'M'}${x(i).toFixed(1)},${y(val).toFixed(1)}`;
});
return d;
});
const area = $derived(`${path}L${W},${H}L0,${H}Z`);
const marks = $derived(moves.filter((m) => m.classification && NAG[m.classification] && m.classification !== 'great'));
function click(e: MouseEvent) {
const r = (e.currentTarget as SVGElement).getBoundingClientRect();
onselect?.(Math.round(((e.clientX - r.left) / r.width) * n));
}
</script>
<svg viewBox="0 0 {W} {H}" preserveAspectRatio="none" class="graph" onclick={click} role="img" aria-label="График оценки">
<rect width={W} height={H} class="bg" />
<path d={area} class="area" />
<line x1="0" x2={W} y1={H / 2} y2={H / 2} class="mid" />
<path d={path} class="line" />
{#each marks as m (m.ply)}
<circle cx={x(m.ply)} cy={y(m.eval ? winPercentWhite(m.eval) : 50)} r="4" class="mk {m.classification}" />
{/each}
{#if current > 0}<line x1={x(current)} x2={x(current)} y1="0" y2={H} class="cur" />{/if}
</svg>
<style>
.graph {
display: block;
width: 100%;
height: 110px;
cursor: crosshair;
}
.bg {
fill: var(--graph-black, #2a2622);
}
.area {
fill: var(--graph-white, #f5f1e6);
}
.mid {
stroke: var(--muted);
stroke-dasharray: 3 3;
stroke-width: 1;
}
.line {
fill: none;
stroke: var(--accent);
stroke-width: 2;
vector-effect: non-scaling-stroke;
}
.cur {
stroke: var(--accent);
stroke-width: 2;
vector-effect: non-scaling-stroke;
}
.mk {
stroke: #000;
stroke-width: 1;
vector-effect: non-scaling-stroke;
}
.mk.blunder {
fill: var(--nag-blunder);
}
.mk.mistake {
fill: var(--nag-mistake);
}
.mk.inaccuracy {
fill: var(--nag-inaccuracy);
}
.mk.brilliant {
fill: var(--nag-brilliant);
}
</style>
+130
View File
@@ -0,0 +1,130 @@
<script lang="ts">
import type { GameSummary } from '#lib/types.ts';
import { TERMINATION_RU, resultLabel, fmtAgo } from '#lib/fmt.ts';
import Avatar from './Avatar.svelte';
import MiniBoard from './MiniBoard.svelte';
import PlayerName from './PlayerName.svelte';
let { g }: { g: GameSummary } = $props();
const moves = $derived(Math.ceil(g.ply / 2));
</script>
<a class="gcard" href="/match/{g.id}">
<div class="thumb">
{#if g.thumbnailUrl}
<img src={g.thumbnailUrl} alt={g.thumbnailCaption ?? ''} loading="lazy" />
{:else}
<div class="ph t-halftone">
<Avatar player={g.white} size={64} />
<span class="vs display">VS</span>
<Avatar player={g.black} size={64} />
<div class="mini"><MiniBoard fen={g.fen} size={84} /></div>
<span class="drawing label">{g.status === 'finished' ? 'превью рисуется…' : g.status === 'aborted' ? 'прервана' : 'идёт'}</span>
</div>
{/if}
<span class="dur mono">{moves} ход.</span>
{#if !g.rated}<span class="unr chip danger">без рейтинга</span>{/if}
</div>
<div class="info">
<span class="res display">{resultLabel(g.result)}</span>
<div class="names">
<div class="title"><PlayerName player={g.white} short /> <span class="muted">—</span> <PlayerName player={g.black} short /></div>
<div class="sub mono">{g.termination ? TERMINATION_RU[g.termination] : ''}{g.finishedAt ? ` · ${fmtAgo(g.finishedAt)}` : ''}</div>
</div>
</div>
</a>
<style>
.gcard {
display: grid;
gap: 8px;
min-width: 0;
}
.thumb {
position: relative;
aspect-ratio: 16 / 9;
overflow: hidden;
border: var(--border);
border-radius: var(--radius);
box-shadow: var(--shadow);
background: var(--surface-3);
transition: transform 0.15s;
}
.gcard:hover .thumb {
transform: translateY(-3px) rotate(var(--card-tilt, 0deg));
}
img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.ph {
position: absolute;
inset: 0;
display: flex;
align-items: center;
justify-content: center;
gap: 12px;
background: linear-gradient(135deg, var(--surface-2), var(--surface-3));
}
.vs {
font-size: 28px;
color: var(--accent);
}
.mini {
position: absolute;
right: 10px;
bottom: 10px;
opacity: 0.85;
transform: rotate(4deg);
}
.drawing {
position: absolute;
left: 10px;
bottom: 10px;
color: var(--muted);
font-size: 9px;
}
.dur {
position: absolute;
right: 6px;
top: 6px;
background: rgba(0, 0, 0, 0.8);
color: #fff;
font-size: 11px;
padding: 2px 6px;
border-radius: 3px;
}
.unr {
position: absolute;
left: 6px;
top: 6px;
}
.info {
display: grid;
grid-template-columns: auto 1fr;
gap: 10px;
align-items: start;
}
.res {
font-size: 22px;
color: var(--accent-text, var(--accent));
min-width: 38px;
}
.title {
font-weight: 600;
font-size: 14px;
line-height: 1.3;
}
.sub {
font-size: 10px;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.06em;
margin-top: 2px;
}
:global(html[data-theme='tabloid']) .gcard {
--card-tilt: -0.6deg;
}
</style>
+295
View File
@@ -0,0 +1,295 @@
<script lang="ts">
import { page } from '$app/state';
import { session } from '#lib/session.svelte.ts';
import { live } from '#lib/ws.ts';
import { api } from '#lib/api.ts';
import type { HomeData } from '#lib/types.ts';
import Avatar from './Avatar.svelte';
let liveCount = $state(0);
let refreshT: ReturnType<typeof setTimeout> | null = null;
const refresh = () => {
if (refreshT) clearTimeout(refreshT);
refreshT = setTimeout(() => api.get<HomeData>('/api/home').then((h) => (liveCount = h.live.length)).catch(() => {}), 300);
};
$effect(() => {
refresh();
return live.subscribe('lobby', refresh);
});
const nav = $derived([
{ href: '/', label: 'Главная' },
{ href: '/live', label: 'Live', count: liveCount },
{ href: '/leaderboard', label: 'Таблица' },
{ href: '/games', label: 'Архив' },
...(session.user?.isAdmin ? [{ href: '/admin', label: 'Админка' }] : [])
]);
const active = (href: string) => (href === '/' ? page.url.pathname === '/' : page.url.pathname.startsWith(href));
const today = new Date().toLocaleDateString('ru-RU', { weekday: 'long', day: 'numeric', month: 'long', year: 'numeric' });
const userPlayer = $derived(session.user ? { avatarUrl: session.user.avatarUrl, displayName: session.user.displayName, color: null, kind: 'human' as const, family: null } : null);
</script>
{#snippet user()}
{#if session.user}
<a class="me" href="/me" title="Профиль">
<Avatar player={userPlayer!} size={30} />
<span class="me-name">{session.user.displayName}</span>
</a>
{:else if session.loaded}
<a class="btn sm ghost login" href="/login">Войти</a>
{/if}
{/snippet}
{#snippet links()}
{#each nav as n}
<a href={n.href} class:on={active(n.href)}>
{#if n.href === '/live' && n.count}<span class="live-dot"></span>{/if}{n.label}{#if n.count}<span class="cnt">{n.count}</span>{/if}
</a>
{/each}
{/snippet}
{#if session.theme === 'tabloid'}
<header class="tabloid wrap">
<div class="dateline mono">
<span>№ {Math.floor((Date.now() - Date.UTC(2023, 0, 1)) / 864e5)} · {today}</span>
{#if liveCount}<span class="tag hot flat">экстренный выпуск · {liveCount} в эфире</span>{/if}
<span>цена: ваши токены</span>
</div>
<div class="mast">
<a href="/" class="logo display">Вечерний <span class="red">Мат</span><sup class="chip">18+</sup></a>
<p class="slogan display">Газета о том, как нейросети зевают фигуры</p>
<span class="spacer"></span>
{#if session.user}<a class="btn primary" href="/new">+ Новый матч</a>{/if}
</div>
<nav>
{@render links()}
<span class="spacer"></span>
{@render user()}
</nav>
</header>
{:else if session.theme === 'broadcast'}
<header class="broadcast">
<div class="wrap bar">
<a href="/" class="logo display">AI<span>·</span>CHESS <span class="tag hot flat"><span class="live-dot" style="background:#fff"></span> эфир</span></a>
<nav>{@render links()}</nav>
<span class="spacer"></span>
{#if liveCount}<span class="on-air mono"><b>{liveCount}</b> в эфире</span>{/if}
{#if session.user}<a class="btn primary sm" href="/new"><span>Новый матч</span></a>{/if}
{@render user()}
</div>
</header>
{:else}
<header class="arcade">
<div class="wrap bar">
<a href="/" class="logo display">AI <span>FIGHT</span> CLUB</a>
<nav>{@render links()}</nav>
<span class="spacer"></span>
{#if session.user}<a class="btn primary" href="/new">+ Новый матч</a>{/if}
{@render user()}
</div>
</header>
{/if}
<style>
nav {
display: flex;
align-items: center;
}
nav a {
display: inline-flex;
align-items: center;
gap: 6px;
font-family: var(--f-label);
text-transform: uppercase;
letter-spacing: 0.08em;
font-weight: 600;
}
.cnt {
font-family: var(--f-mono);
font-size: 10px;
background: var(--danger);
color: #fff;
padding: 1px 5px;
border-radius: 3px;
}
.me {
display: inline-flex;
align-items: center;
gap: 8px;
font-weight: 600;
}
.me-name {
max-width: 140px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* ---- tabloid masthead ---- */
.tabloid {
padding-top: 10px;
margin-bottom: 18px;
}
.dateline {
display: flex;
justify-content: space-between;
align-items: center;
gap: 10px;
font-size: 11px;
text-transform: uppercase;
letter-spacing: 0.06em;
padding-bottom: 6px;
border-bottom: 1px solid var(--line);
}
.mast {
display: flex;
align-items: center;
gap: 22px;
padding: 12px 0 10px;
}
.tabloid .logo {
font-size: clamp(40px, 6vw, 76px);
line-height: 0.85;
position: relative;
white-space: nowrap;
}
.tabloid .logo .red {
background: var(--accent);
color: var(--accent-ink);
padding: 0 8px;
}
.tabloid .logo sup {
position: absolute;
top: -6px;
right: -18px;
transform: rotate(10deg);
border: 2px solid var(--text);
}
.slogan {
max-width: 18ch;
font-size: 16px;
line-height: 1;
border-left: 2px solid var(--line);
padding-left: 14px;
}
.tabloid nav {
border-top: 2px solid var(--line);
border-bottom: 4px double var(--line);
gap: 0;
}
.tabloid nav a {
padding: 9px 16px;
font-size: 15px;
border-right: 1px solid var(--line);
}
.tabloid nav a.on {
background: var(--text);
color: var(--bg);
}
.tabloid nav a.on:first-child {
background: var(--text);
}
.tabloid nav a:hover:not(.on) {
background: var(--accent-2);
}
.tabloid .me,
.tabloid .login {
padding: 4px 10px;
}
/* ---- broadcast top bar ---- */
.broadcast {
position: sticky;
top: 0;
z-index: 50;
background: rgba(6, 7, 11, 0.92);
backdrop-filter: blur(10px);
border-bottom: 1px solid var(--line);
margin-bottom: 18px;
}
.bar {
display: flex;
align-items: center;
gap: 18px;
height: 56px;
}
.broadcast .logo {
font-size: 24px;
display: inline-flex;
align-items: center;
gap: 10px;
color: var(--accent);
}
.broadcast .logo > span:first-child {
color: var(--text);
}
.broadcast nav {
gap: 4px;
}
.broadcast nav a {
padding: 6px 12px;
font-size: 14px;
color: var(--muted);
border-bottom: 2px solid transparent;
}
.broadcast nav a.on,
.broadcast nav a:hover {
color: var(--text);
border-bottom-color: var(--accent);
}
.on-air {
font-size: 12px;
color: var(--live);
text-transform: uppercase;
}
/* ---- arcade bar ---- */
.arcade {
background: #000;
border-bottom: 2px solid var(--accent);
margin-bottom: 18px;
}
.arcade .logo {
font-size: 20px;
color: var(--accent);
letter-spacing: -0.02em;
}
.arcade .logo span {
color: var(--text);
}
.arcade nav {
gap: 6px;
}
.arcade nav a {
padding: 8px 10px;
font-size: 10px;
color: var(--muted);
}
.arcade nav a.on {
color: var(--accent);
box-shadow: inset 0 -3px 0 var(--accent);
}
@media (max-width: 860px) {
.slogan,
.dateline span:last-child,
.me-name {
display: none;
}
.tabloid nav {
overflow-x: auto;
}
.tabloid nav a {
padding: 8px 10px;
font-size: 13px;
}
.bar {
gap: 10px;
overflow-x: auto;
}
.broadcast nav a,
.arcade nav a {
padding: 6px 6px;
}
}
</style>
+126
View File
@@ -0,0 +1,126 @@
<script lang="ts">
/** Live game = lineup only (thumbnails, titles & interviews only exist after the game). */
import type { GameSummary } from '#lib/types.ts';
import { fmtAgo } from '#lib/fmt.ts';
import Avatar from './Avatar.svelte';
import PlayerName from './PlayerName.svelte';
import MiniBoard from './MiniBoard.svelte';
let { g, compact = false }: { g: GameSummary; compact?: boolean } = $props();
const toMove = $derived(g.ply % 2 === 0 ? 'white' : 'black');
</script>
<a class="lc panel" class:compact href="/match/{g.id}">
<div class="side" class:moving={toMove === 'white'}>
<Avatar player={g.white} size={compact ? 36 : 48} />
<div class="nm"><PlayerName player={g.white} short /><span class="mono rt">{g.white.rating}</span></div>
</div>
<div class="mid">
<span class="tag hot flat"><span class="live-dot"></span> live</span>
<span class="display vs">VS</span>
<span class="mono mv">ход {Math.ceil((g.ply + 1) / 2)}</span>
</div>
<div class="side right" class:moving={toMove === 'black'}>
<div class="nm"><PlayerName player={g.black} short /><span class="mono rt">{g.black.rating}</span></div>
<Avatar player={g.black} size={compact ? 36 : 48} />
</div>
{#if !compact}
<div class="board"><MiniBoard fen={g.fen} size={78} /></div>
<div class="foot mono">
{#if g.flags.cheating}<span class="chip danger">читерство</span>{/if}
{#if g.flags.notes}<span class="chip outline">заметки</span>{/if}
{#if g.flags.extraTools}<span class="chip outline">тулы</span>{/if}
<span class="spacer"></span><span>{g.startedAt ? `начата ${fmtAgo(g.startedAt)}` : ''}</span>
</div>
{/if}
</a>
<style>
.lc {
display: grid;
grid-template-columns: 1fr auto 1fr auto;
grid-template-areas: 'w mid b board' 'foot foot foot foot';
align-items: center;
gap: 12px;
padding: 12px 14px;
transition: transform 0.12s;
}
.lc.compact {
grid-template-columns: 1fr auto 1fr;
grid-template-areas: 'w mid b';
padding: 8px 10px;
}
.lc:hover {
transform: translateY(-2px);
}
.side {
grid-area: w;
display: flex;
align-items: center;
gap: 10px;
min-width: 0;
opacity: 0.75;
}
.side.right {
grid-area: b;
justify-content: flex-end;
text-align: right;
}
.side.moving {
opacity: 1;
}
.side.moving :global(.av) {
outline: 3px solid var(--accent);
outline-offset: 1px;
}
.nm {
display: grid;
gap: 2px;
font-weight: 600;
min-width: 0;
}
.right .nm {
justify-items: end;
}
.rt {
font-size: 11px;
color: var(--muted);
}
.mid {
grid-area: mid;
display: grid;
justify-items: center;
gap: 4px;
}
.vs {
font-size: 22px;
color: var(--accent-text, var(--accent));
}
.mv {
font-size: 10px;
color: var(--muted);
}
.board {
grid-area: board;
}
.foot {
grid-area: foot;
display: flex;
gap: 6px;
align-items: center;
font-size: 10px;
color: var(--muted);
}
@media (max-width: 640px) {
.lc {
grid-template-columns: 1fr auto 1fr;
grid-template-areas: 'w mid b' 'foot foot foot';
}
.board {
display: none;
}
.side :global(.chip) {
display: none;
}
}
</style>
+126
View File
@@ -0,0 +1,126 @@
<script lang="ts">
/** A single live game embedded on the home page (when exactly one game is on air). */
import { GameView } from '#lib/game.svelte.ts';
import { evalLabel, moveNo } from '#lib/fmt.ts';
import Board from './Board.svelte';
import EvalBar from './EvalBar.svelte';
import Avatar from './Avatar.svelte';
import PlayerName from './PlayerName.svelte';
let { id }: { id: string } = $props();
const view = $derived(new GameView(id));
$effect(() => {
const v = view;
v.start();
return () => v.stop();
});
const pos = $derived(view.positions.at(-1));
const last = $derived(view.moves.at(-1));
const lastPhrase = $derived([...view.moves].reverse().find((m) => m.phrase));
</script>
{#if view.game && pos}
{@const g = view.game}
<div class="hero">
<div class="board-row">
<EvalBar ev={last?.eval} />
<Board fen={pos.fen} lastMove={pos.lastMove} check={pos.check} />
</div>
<div class="side">
<div class="kicker">ход {Math.ceil((view.moves.length + 1) / 2)} · {view.sideToMove === 'white' ? 'белые' : 'чёрные'} {view.player(view.sideToMove).kind === 'human' ? 'ходят' : 'думают'}{last ? ` · ${evalLabel(last.eval)}` : ''}</div>
<div class="lineup">
{#each ['white', 'black'] as const as s}
<div class="who" class:moving={view.sideToMove === s}>
<Avatar player={view.player(s)} size={44} />
<div><div class="display nm"><PlayerName player={view.player(s)} /></div><div class="mono muted">{view.player(s).rating} · {s === 'white' ? 'белые' : 'чёрные'}</div></div>
</div>
{#if s === 'white'}<div class="display vs">VS</div>{/if}
{/each}
</div>
{#if lastPhrase}
<blockquote class="panel">
<p>«{lastPhrase.phrase}»</p>
<footer class="mono muted">— {view.player(lastPhrase.side).displayName}, после {moveNo(lastPhrase.ply)} {lastPhrase.san}</footer>
</blockquote>
{/if}
{#if view.turn?.thinking}
<p class="thinking muted">💭 {view.turn.thinking.slice(-220)}</p>
{/if}
<a class="btn primary lg" href="/match/{id}">Смотреть live →</a>
</div>
</div>
{/if}
<style>
.hero {
display: grid;
grid-template-columns: minmax(260px, 380px) 1fr;
gap: 22px;
align-items: start;
}
.board-row {
display: grid;
grid-template-columns: 18px 1fr;
gap: 8px;
}
.side {
display: grid;
gap: 14px;
align-content: start;
}
.lineup {
display: grid;
gap: 8px;
}
.who {
display: flex;
align-items: center;
gap: 12px;
opacity: 0.7;
}
.who.moving {
opacity: 1;
}
.nm {
font-size: clamp(22px, 2.6vw, 34px);
}
.vs {
font-size: 20px;
color: var(--accent-text, var(--accent));
padding-left: 14px;
}
blockquote {
margin: 0;
padding: 12px 14px;
background: var(--text);
color: var(--bg);
}
blockquote p {
font-size: 17px;
font-style: italic;
}
blockquote footer {
font-size: 10px;
margin-top: 6px;
text-transform: uppercase;
color: inherit;
opacity: 0.6;
}
.thinking {
font-style: italic;
font-size: 13px;
display: -webkit-box;
-webkit-line-clamp: 3;
line-clamp: 3;
-webkit-box-orient: vertical;
overflow: hidden;
}
.btn {
justify-self: start;
}
@media (max-width: 760px) {
.hero {
grid-template-columns: 1fr;
}
}
</style>
@@ -0,0 +1,60 @@
<script lang="ts">
/** Lightweight static board (no chessground): unicode pieces on a CSS grid. */
let { fen, size = 120, lastMove = null }: { fen: string; size?: number; lastMove?: [string, string] | null } = $props();
const GLYPH: Record<string, string> = { k: '♚', q: '♛', r: '♜', b: '♝', n: '♞', p: '♟', K: '♚', Q: '♛', R: '♜', B: '♝', N: '♞', P: '♟' };
const cells = $derived.by(() => {
const rows = (fen.split(' ')[0] ?? '').split('/');
const out: { sq: string; piece: string | null; white: boolean; light: boolean }[] = [];
rows.forEach((row, r) => {
let f = 0;
for (const ch of row) {
if (/\d/.test(ch)) {
for (let k = 0; k < Number(ch); k++, f++) out.push({ sq: 'abcdefgh'[f] + (8 - r), piece: null, white: false, light: (r + f) % 2 === 0 });
} else {
out.push({ sq: 'abcdefgh'[f] + (8 - r), piece: GLYPH[ch], white: ch === ch.toUpperCase(), light: (r + f) % 2 === 0 });
f++;
}
}
});
return out;
});
</script>
<div class="mb" style:width="{size}px" style:height="{size}px" style:font-size="{size / 9}px">
{#each cells as c (c.sq)}
<span class="sq" class:light={c.light} class:hl={lastMove?.includes(c.sq)}>{#if c.piece}<i class:w={c.white}>{c.piece}</i>{/if}</span>
{/each}
</div>
<style>
.mb {
display: grid;
grid-template-columns: repeat(8, 1fr);
border: var(--border);
border-radius: var(--radius);
overflow: hidden;
flex: none;
line-height: 1;
}
.sq {
display: grid;
place-items: center;
background: var(--board-dark);
}
.sq.light {
background: var(--board-light);
}
.sq.hl {
box-shadow: inset 0 0 0 99px var(--board-last);
}
i {
font-style: normal;
color: #111;
text-shadow: 0 0 1px #fff;
}
i.w {
color: #fff;
-webkit-text-stroke: 0.6px #111;
text-shadow: none;
}
</style>
+215
View File
@@ -0,0 +1,215 @@
<script lang="ts">
import { tick } from 'svelte';
import type { MoveDTO, LiveTurn } from '#lib/types.ts';
import { NAG, CLS_LABEL, evalLabel, fmtDuration } from '#lib/fmt.ts';
import Thoughts from './Thoughts.svelte';
let {
gameId,
moves,
current,
turn = null,
humanSides = [],
onselect
}: {
gameId: string;
moves: MoveDTO[];
current: number;
turn?: LiveTurn | null;
humanSides?: ('white' | 'black')[];
onselect: (ply: number) => void;
} = $props();
let expanded = $state<number | null>(null);
let list: HTMLDivElement;
const rows = $derived.by(() => {
const out: { no: number; w?: MoveDTO; b?: MoveDTO }[] = [];
for (const m of moves) {
const no = Math.ceil(m.ply / 2);
let r = out.find((x) => x.no === no);
if (!r) out.push((r = { no }));
if (m.side === 'white') r.w = m;
else r.b = m;
}
return out;
});
const pendingRow = $derived(turn ? Math.ceil(turn.ply / 2) : null);
$effect(() => {
current;
moves.length;
tick().then(() => {
const el = list?.querySelector('.cur') as HTMLElement | null;
if (!el || !list || expanded !== null) return;
const top = el.offsetTop - list.offsetTop;
if (top < list.scrollTop + 10 || top + el.offsetHeight > list.scrollTop + list.clientHeight - 10) list.scrollTop = top - list.clientHeight / 2;
});
});
function toggle(ply: number) {
expanded = expanded === ply ? null : ply;
if (expanded !== null && expanded <= moves.length) onselect(ply);
}
</script>
{#snippet cell(m: MoveDTO | undefined, side: 'white' | 'black', no: number)}
{#if m}
<div class="cell" class:cur={current === m.ply} class:open={expanded === m.ply}>
<button class="mv" onclick={() => onselect(m.ply)} title={m.classification ? CLS_LABEL[m.classification] : ''}>
<span class="san" class:illegal={m.illegal}>{m.san ?? m.uci}</span>{#if m.classification && NAG[m.classification]}<span class="nag {m.classification}">{NAG[m.classification]}</span>{/if}
{#if m.offeredDraw}<span class="draw" title="Предложил ничью">½?</span>{/if}
</button>
<span class="ev mono">{evalLabel(m.eval)}</span>
<span class="t mono">{m.thinkMs ? fmtDuration(m.thinkMs) : ''}</span>
{#if !humanSides.includes(side)}
<button class="think" class:on={expanded === m.ply} onclick={() => toggle(m.ply)} title="Мысли агента" aria-expanded={expanded === m.ply}>💭</button>
{:else}<span></span>{/if}
</div>
{:else if turn && pendingRow === no && turn.side === side}
<div class="cell pending">
<button class="mv" onclick={() => toggle(turn.ply)}><span class="dots">думает<span>.</span><span>.</span><span>.</span></span></button>
<span></span><span></span>
<button class="think on-live" class:on={expanded === turn.ply} onclick={() => toggle(turn.ply)} title="Мысли в прямом эфире">💭</button>
</div>
{:else}
<div class="cell empty"></div>
{/if}
{/snippet}
<div class="moves" bind:this={list}>
{#each rows as r (r.no)}
<div class="row">
<span class="no mono">{r.no}</span>
{@render cell(r.w, 'white', r.no)}
{@render cell(r.b, 'black', r.no)}
</div>
{#if expanded !== null && Math.ceil(expanded / 2) === r.no}
<div class="dossier"><Thoughts {gameId} ply={expanded} live={turn?.ply === expanded ? turn : null} move={moves.find((m) => m.ply === expanded) ?? null} onclose={() => (expanded = null)} /></div>
{/if}
{/each}
{#if turn && pendingRow && !rows.some((r) => r.no === pendingRow)}
<div class="row">
<span class="no mono">{pendingRow}</span>
{@render cell(undefined, 'white', pendingRow)}
{@render cell(undefined, 'black', pendingRow)}
</div>
{#if expanded === turn.ply}
<div class="dossier"><Thoughts {gameId} ply={turn.ply} live={turn} move={null} onclose={() => (expanded = null)} /></div>
{/if}
{/if}
{#if !moves.length && !turn}<div class="empty">Ходов пока нет</div>{/if}
</div>
<style>
.moves {
overflow-y: auto;
max-height: var(--moves-max-h, 460px);
position: relative;
}
.row {
display: grid;
grid-template-columns: 34px 1fr 1fr;
border-bottom: var(--border-thin);
}
.no {
display: grid;
place-items: center;
font-size: 11px;
color: var(--muted);
background: var(--surface-2);
border-right: var(--border-thin);
}
.cell {
display: grid;
grid-template-columns: 1fr auto auto 28px;
align-items: center;
gap: 6px;
padding: 0 4px 0 8px;
min-height: 34px;
border-right: var(--border-thin);
}
.cell:last-child {
border-right: 0;
}
.cell.cur {
background: color-mix(in srgb, var(--accent) 22%, transparent);
}
.cell.open {
background: color-mix(in srgb, var(--accent) 35%, transparent);
}
.mv {
text-align: left;
display: inline-flex;
align-items: baseline;
gap: 1px;
padding: 6px 0;
font-family: var(--f-mono);
font-weight: 600;
font-size: 14px;
}
.san.illegal {
text-decoration: line-through wavy var(--danger);
}
.draw {
margin-left: 5px;
font-size: 10px;
color: var(--muted);
}
.ev {
font-size: 11px;
color: var(--text-2);
}
.t {
font-size: 10px;
color: var(--muted);
min-width: 34px;
text-align: right;
}
.think {
font-size: 14px;
opacity: 0.35;
filter: grayscale(1);
padding: 4px;
}
.think:hover,
.think.on {
opacity: 1;
filter: none;
}
.think.on-live {
opacity: 1;
filter: none;
animation: pulse 1.6s ease-in-out infinite;
}
@keyframes pulse {
50% {
transform: scale(1.2);
}
}
.pending .dots {
font-family: var(--f-body);
font-style: italic;
font-weight: 400;
font-size: 13px;
color: var(--muted);
}
.dots span {
animation: dot 1.2s infinite;
}
.dots span:nth-child(2) {
animation-delay: 0.2s;
}
.dots span:nth-child(3) {
animation-delay: 0.4s;
}
@keyframes dot {
50% {
opacity: 0;
}
}
.dossier {
border-bottom: var(--border);
background: var(--surface-2);
}
</style>
@@ -0,0 +1,231 @@
<script lang="ts">
import type { Player, Side } from '#lib/types.ts';
import { fmtClock, fmtTokens, fmtUsd } from '#lib/fmt.ts';
import Avatar from './Avatar.svelte';
import PlayerName from './PlayerName.svelte';
let {
player,
side,
persona = null,
accuracy = null,
cost = 0,
tokens = 0,
thinkingSince = null,
result = null,
ratingDelta = null,
cls = null
}: {
player: Player;
side: Side;
persona?: string | null;
accuracy?: number | null;
cost?: number;
tokens?: number;
thinkingSince?: number | null;
result?: 'win' | 'loss' | 'draw' | null;
ratingDelta?: number | null;
cls?: Record<string, number> | null;
} = $props();
let now = $state(Date.now());
$effect(() => {
if (!thinkingSince) return;
const t = setInterval(() => (now = Date.now()), 1000);
return () => clearInterval(t);
});
const elapsed = $derived(thinkingSince ? now - thinkingSince : 0);
</script>
<article class="pcard panel side-{side}" class:thinking={!!thinkingSince} class:win={result === 'win'} class:loss={result === 'loss'}>
{#if thinkingSince}<div class="flag label">{player.kind === 'human' ? 'твой ход' : 'думает'}</div>{/if}
{#if result}<div class="flag label res">{result === 'win' ? 'победа' : result === 'loss' ? 'поражение' : 'ничья'}</div>{/if}
<div class="top">
<Avatar {player} size={52} />
<div class="who">
<div class="name display"><PlayerName {player} /></div>
<div class="meta">
<span class="side-dot"></span>
<span class="mono tnum">{player.rating}</span>
{#if ratingDelta != null}<span class="mono delta" class:up={ratingDelta >= 0}>{ratingDelta >= 0 ? '+' : ''}{Math.round(ratingDelta)}</span>{/if}
{#if persona}<span class="persona">«{persona}»</span>{/if}
</div>
</div>
</div>
<div class="acc-bar" style:--acc="{accuracy ?? 0}%"><span></span></div>
<div class="stats">
<div class="stat"><b class="tnum">{accuracy != null ? accuracy.toFixed(1) : '—'}<small>%</small></b><span class="label">точность</span></div>
{#if player.kind === 'ai'}
<div class="stat money"><b class="tnum">{fmtUsd(cost)}</b><span class="label">{fmtTokens(tokens)} ток.</span></div>
{/if}
<div class="stat clock" class:on={!!thinkingSince}>
<b class="tnum">{thinkingSince ? fmtClock(elapsed) : '—'}</b><span class="label">{thinkingSince ? 'на ходу' : 'ждёт'}</span>
</div>
</div>
{#if cls}
<div class="cls mono">
{#if cls.brilliant}<span><b class="nag brilliant">!!</b>{cls.brilliant}</span>{/if}
<span title="лучших ходов">★{cls.best ?? 0}</span>
<span><b class="nag inaccuracy">?!</b>{cls.inaccuracy ?? 0}</span>
<span><b class="nag mistake">?</b>{cls.mistake ?? 0}</span>
<span><b class="nag blunder">??</b>{cls.blunder ?? 0}</span>
</div>
{/if}
</article>
<style>
.pcard {
position: relative;
overflow: visible;
}
.pcard.thinking {
outline: 3px solid var(--accent);
outline-offset: -1px;
}
.flag {
position: absolute;
top: -10px;
left: 10px;
background: var(--accent);
color: var(--accent-ink);
padding: 3px 7px;
border-radius: var(--radius);
z-index: 1;
}
.flag.res {
left: auto;
right: 10px;
background: var(--text);
color: var(--bg);
}
.win .flag.res {
background: var(--ok);
color: #fff;
}
.top {
display: flex;
gap: 12px;
align-items: center;
padding: 14px 12px 10px;
}
.who {
min-width: 0;
display: grid;
gap: 4px;
}
.name {
font-size: 22px;
line-height: 1;
}
.meta {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
font-size: 13px;
}
.side-dot {
width: 11px;
height: 11px;
border-radius: 50%;
border: 2px solid var(--text);
}
.side-white .side-dot {
background: #fff;
}
.side-black .side-dot {
background: #111;
}
.persona {
font-style: italic;
color: var(--muted);
}
.delta {
font-size: 12px;
color: var(--danger);
}
.delta.up {
color: var(--ok);
}
.acc-bar {
display: var(--acc-bar-display, none);
height: 10px;
margin: 0 12px 8px;
background: var(--surface-3);
border: var(--border-thin);
}
.acc-bar span {
display: block;
height: 100%;
width: var(--acc);
background: var(--side-color, var(--ok));
transition: width 0.6s;
}
.stats {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(0, 1fr));
grid-auto-flow: column;
border-top: var(--border-thin);
}
.stat {
display: grid;
gap: 2px;
padding: 8px 12px;
border-right: var(--border-thin);
}
.stat:last-child {
border-right: 0;
}
.stat b {
font-family: var(--f-display);
font-size: 22px;
line-height: 1;
}
.stat small {
font-size: 0.6em;
margin-left: 1px;
}
.stat .label {
color: var(--muted);
font-size: 9px;
}
.stat.clock.on {
background: var(--accent);
color: var(--accent-ink);
}
.stat.clock.on .label {
color: inherit;
opacity: 0.8;
}
.cls {
display: flex;
gap: 12px;
padding: 6px 12px;
border-top: var(--border-thin);
font-size: 12px;
color: var(--muted);
}
.cls b {
margin-right: 2px;
}
:global(html[data-theme='arcade']) .pcard {
--acc-bar-display: block;
}
:global(html[data-theme='arcade']) .side-white {
--side-color: var(--white-side);
border-top: 3px solid var(--white-side);
}
:global(html[data-theme='arcade']) .side-black {
--side-color: var(--black-side);
border-top: 3px solid var(--black-side);
}
:global(html[data-theme='broadcast']) .side-white {
border-left: 4px solid var(--white-side);
}
:global(html[data-theme='broadcast']) .side-black {
border-left: 4px solid var(--black-side);
}
:global(html[data-theme='arcade']) .name {
font-size: 16px;
}
</style>
@@ -0,0 +1,38 @@
<script lang="ts">
import type { Player } from '#lib/types.ts';
import { VARIANT_LABEL } from '#lib/fmt.ts';
let { player, short = false, rating = false }: { player: Player; short?: boolean; rating?: boolean } = $props();
const name = $derived(short && player.kind === 'ai' ? player.displayName.replace(/^Claude /, '') : player.displayName);
</script>
<span class="pn">
<span class="nm">{name}</span>
{#if player.kind === 'ai' && player.variant}
<span class="chip" class:accent={player.variant === 'max'} title="Режим рассуждений">{VARIANT_LABEL[player.variant] ?? player.variant}</span>
{/if}
{#if player.skull}<span class="skull" title="Без рассуждений вообще">💀</span>{/if}
{#if player.dumb}<span class="chip dumb" title="Модель прошлого поколения — для смеха">тупая</span>{/if}
{#if rating}<span class="mono rt">{player.rating}</span>{/if}
</span>
<style>
.pn {
display: inline-flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
min-width: 0;
}
.nm {
overflow: hidden;
text-overflow: ellipsis;
}
.skull {
font-size: 0.95em;
line-height: 1;
}
.rt {
font-size: 0.8em;
color: var(--muted);
}
</style>
@@ -0,0 +1,129 @@
<script lang="ts">
import { api } from '#lib/api.ts';
import { session } from '#lib/session.svelte.ts';
import type { Player } from '#lib/types.ts';
type Pick = 'white' | 'draw' | 'black';
let { gameId, open, white, black, counts, mine, onchange }: { gameId: string; open: boolean; white: Player; black: Player; counts: Partial<Record<Pick, number>>; mine: Pick | null; onchange?: () => void } = $props();
let busy = $state(false);
let err = $state<string | null>(null);
const total = $derived((counts.white ?? 0) + (counts.draw ?? 0) + (counts.black ?? 0));
const pct = (k: Pick) => (total ? Math.round(((counts[k] ?? 0) / total) * 100) : 0);
async function pick(k: Pick) {
if (!session.user) {
location.href = '/login';
return;
}
busy = true;
err = null;
try {
await api.post(`/api/games/${gameId}/predict`, { pick: k });
onchange?.();
} catch (e) {
err = (e as Error).message;
} finally {
busy = false;
}
}
const opts = $derived([
{ k: 'white' as Pick, label: white.displayName, sub: 'белые' },
{ k: 'draw' as Pick, label: 'Ничья', sub: 'скука' },
{ k: 'black' as Pick, label: black.displayName, sub: 'чёрные' }
]);
</script>
<div class="pred">
<div class="split">
{#each opts as o}<span class="seg {o.k}" style:flex-grow={Math.max(pct(o.k), 4)}></span>{/each}
</div>
<div class="opts">
{#each opts as o}
<button class="opt {o.k}" class:mine={mine === o.k} disabled={!open || busy} onclick={() => pick(o.k)}>
<b class="display tnum">{pct(o.k)}%</b>
<span class="label">{o.sub}</span>
<small>{o.label}</small>
{#if mine === o.k}<span class="chip accent your">твой</span>{/if}
</button>
{/each}
</div>
<p class="foot mono">
{total} голосов · очки, не деньги · {open ? 'приём до старта партии' : 'приём закрыт'}{#if !session.user && open} · <a href="/login" class="accent">войди, чтобы голосовать</a>{/if}
</p>
{#if err}<div class="error-box">{err}</div>{/if}
</div>
<style>
.pred {
display: grid;
gap: 10px;
}
.split {
display: flex;
height: 10px;
border: var(--border-thin);
}
.seg.white {
background: var(--white-side);
}
.seg.draw {
background: var(--muted);
}
.seg.black {
background: var(--black-side);
}
:global(html[data-theme='tabloid']) .seg.white {
background: #fbf7ec;
}
:global(html[data-theme='tabloid']) .seg.black {
background: #15120f;
}
.opts {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
gap: 8px;
}
.opt {
position: relative;
display: grid;
gap: 2px;
text-align: left;
padding: 8px 10px;
border: var(--border);
border-radius: var(--radius);
background: var(--surface-2);
}
.opt:hover:not(:disabled) {
border-color: var(--accent);
}
.opt.mine {
outline: 3px solid var(--accent);
outline-offset: -2px;
}
.opt b {
font-size: 26px;
line-height: 1;
}
.opt small {
font-size: 11px;
color: var(--muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.your {
position: absolute;
top: -8px;
right: 6px;
}
.opt:disabled {
opacity: 1;
cursor: default;
}
.foot {
font-size: 10px;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.06em;
}
</style>
@@ -0,0 +1,128 @@
<script lang="ts">
import { api } from '#lib/api.ts';
import { session, THEMES } from '#lib/session.svelte.ts';
import type { User } from '#lib/types.ts';
import Avatar from './Avatar.svelte';
let { submitLabel = 'Сохранить', ondone }: { submitLabel?: string; ondone?: () => void } = $props();
let name = $state(session.user?.displayName ?? '');
let busy = $state(false);
let err = $state<string | null>(null);
let fileInput: HTMLInputElement;
const SWATCH: Record<string, string[]> = {
tabloid: ['#efe6cf', '#15120f', '#d1231c', '#ffd41c'],
broadcast: ['#06070b', '#10131b', '#ffc93c', '#ff2a3c'],
arcade: ['#08080c', '#ffe14d', '#ff3b5c', '#4cff5e']
};
async function upload(e: Event) {
const f = (e.target as HTMLInputElement).files?.[0];
if (!f) return;
const fd = new FormData();
fd.append('file', f);
busy = true;
err = null;
try {
session.user = (await api.post<{ user: User }>('/api/me/avatar', fd)).user;
} catch (e) {
err = (e as Error).message;
} finally {
busy = false;
}
}
async function save(e: Event) {
e.preventDefault();
busy = true;
err = null;
try {
session.user = (await api.patch<{ user: User }>('/api/me', { displayName: name.trim(), theme: session.theme, onboarded: true })).user;
ondone?.();
} catch (e) {
err = (e as Error).message;
} finally {
busy = false;
}
}
</script>
<form class="stack pf" onsubmit={save}>
<div class="ava-row">
{#if session.user}<Avatar player={{ avatarUrl: session.user.avatarUrl, displayName: name || session.user.username, color: null, kind: 'human', family: null }} size={96} />{/if}
<div class="stack">
<p>Аватарка попадёт на превью партий: генератор картинок нарисует тебя по ней (мультяшно).</p>
<div class="row">
<button type="button" class="btn" onclick={() => fileInput.click()} disabled={busy}>Загрузить фото</button>
<input bind:this={fileInput} type="file" accept="image/*" hidden onchange={upload} />
</div>
</div>
</div>
<label class="field"><span>имя на арене</span><input class="input" bind:value={name} maxlength="40" required /></label>
<div class="field">
<span>оформление (можно сменить в любой момент)</span>
<div class="themes">
{#each THEMES as t}
<button type="button" class="theme" class:on={session.theme === t.id} onclick={() => session.applyTheme(t.id, false)}>
<span class="sw">{#each SWATCH[t.id] as c}<i style:background={c}></i>{/each}</span>
<b class="display">{t.name}</b>
<small>{t.tagline}</small>
</button>
{/each}
</div>
</div>
{#if err}<div class="error-box">{err}</div>{/if}
<button class="btn primary lg" disabled={busy || !name.trim()}>{submitLabel}</button>
</form>
<style>
.pf {
--gap: 20px;
}
.ava-row {
display: grid;
grid-template-columns: auto 1fr;
gap: 18px;
align-items: center;
}
.themes {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
}
.theme {
display: grid;
gap: 8px;
text-align: left;
padding: 12px;
border: var(--border);
border-radius: var(--radius);
background: var(--surface-2);
}
.theme.on {
outline: 3px solid var(--accent);
outline-offset: 2px;
}
.sw {
display: flex;
height: 34px;
border: 1px solid #000;
}
.sw i {
flex: 1;
}
.theme b {
font-size: 18px;
}
.theme small {
font-size: 12px;
color: var(--muted);
line-height: 1.3;
}
@media (max-width: 640px) {
.themes {
grid-template-columns: 1fr;
}
}
</style>
@@ -0,0 +1,85 @@
<script lang="ts">
import type { MoveDTO, Player } from '#lib/types.ts';
import { moveNo } from '#lib/fmt.ts';
import Avatar from './Avatar.svelte';
let { moves, white, black, current, lastWords = {}, onpick }: { moves: MoveDTO[]; white: Player; black: Player; current: number; lastWords?: { white?: string | null; black?: string | null }; onpick?: (ply: number) => void } = $props();
const lines = $derived(
[...moves]
.filter((m) => m.phrase)
.reverse()
.map((m) => ({ ...m, p: m.side === 'white' ? white : black }))
);
const last = $derived(Object.entries(lastWords).filter(([, v]) => v) as ['white' | 'black', string][]);
</script>
<div class="feed">
{#each last as [side, text]}
<div class="line last side-{side}">
<Avatar player={side === 'white' ? white : black} size={28} />
<div><div class="label who">{side === 'white' ? white.displayName : black.displayName} · последнее слово</div><p>{text}</p></div>
</div>
{/each}
{#each lines as l (l.ply)}
<button class="line side-{l.side}" class:cur={l.ply === current} onclick={() => onpick?.(l.ply)}>
<Avatar player={l.p} size={28} />
<div>
<div class="label who">{l.p.displayName} <span class="mono">{moveNo(l.ply)} {l.san ?? l.uci}</span></div>
<p>{l.phrase}</p>
</div>
</button>
{/each}
{#if !lines.length && !last.length}<div class="empty">Пока тихо. Даже слишком.</div>{/if}
</div>
<style>
.feed {
display: grid;
gap: 0;
max-height: var(--feed-max-h, 520px);
overflow-y: auto;
}
.line {
display: grid;
grid-template-columns: 28px 1fr;
gap: 10px;
align-items: start;
text-align: left;
padding: 10px 12px;
border-bottom: var(--border-thin);
width: 100%;
}
.line:hover,
.line.cur {
background: color-mix(in srgb, var(--accent) 12%, transparent);
}
.line.last {
background: color-mix(in srgb, var(--danger) 10%, transparent);
}
.who {
color: var(--muted);
margin-bottom: 3px;
font-size: 10px;
}
.who .mono {
margin-left: 6px;
text-transform: none;
}
p {
font-size: 15px;
line-height: 1.4;
}
:global(html[data-theme='tabloid']) p {
font-style: italic;
}
:global(html[data-theme='arcade']) .who {
font-family: var(--f-mono);
font-size: 10px;
}
:global(html[data-theme='arcade']) .side-white {
border-left: 3px solid var(--white-side);
}
:global(html[data-theme='arcade']) .side-black {
border-left: 3px solid var(--black-side);
}
</style>
+195
View File
@@ -0,0 +1,195 @@
<script lang="ts">
import { api } from '#lib/api.ts';
import type { LiveTurn, MoveDTO, ToolCallLog, TranscriptItem, TurnAttempt } from '#lib/types.ts';
import { fmtDuration, fmtTokens, fmtUsd, moveNo } from '#lib/fmt.ts';
let { gameId, ply, live = null, move = null, onclose }: { gameId: string; ply: number; live?: LiveTurn | null; move?: MoveDTO | null; onclose?: () => void } = $props();
let attempts = $state<TurnAttempt[] | null>(null);
let err = $state<string | null>(null);
$effect(() => {
const p = ply;
const isLive = !!live;
attempts = null;
err = null;
if (isLive && !move) return;
api
.get<{ turns: TurnAttempt[] }>(`/api/games/${gameId}/turns/${p}`)
.then((r) => (attempts = r.turns))
.catch((e) => (err = e.message));
});
const done = $derived(attempts?.find((a) => a.status === 'done') ?? attempts?.at(-1) ?? null);
const failed = $derived(attempts?.filter((a) => a.status === 'failed') ?? []);
/** live transcript built from streaming state */
const liveItems = $derived.by<TranscriptItem[]>(() => {
if (!live) return [];
const items: TranscriptItem[] = [];
if (live.thinking) items.push({ kind: 'thinking', text: live.thinking, at: live.startedAt });
for (const t of live.tools) items.push({ kind: 'tool', call: t, at: t.startedAt });
if (live.text) items.push({ kind: 'text', text: live.text, at: live.startedAt });
return items;
});
const items = $derived(live && !move ? liveItems : (done?.transcript ?? []));
const context = $derived(items.find((i) => i.kind === 'context') as Extract<TranscriptItem, { kind: 'context' }> | undefined);
const TOOL_RU: Record<string, string> = {
make_move: 'ход',
finish_turn: 'завершить ход',
resign: 'сдаться',
accept_draw: 'принять ничью',
get_move_history: 'история ходов',
python: 'python'
};
function argText(c: ToolCallLog) {
const a = c.args as any;
if (!a) return '';
if (c.name === 'python') return a.code ?? '';
if (c.name === 'make_move') return `${a.move ?? ''}${a.offer_draw ? ' + предложение ничьей' : ''}`;
if (c.name === 'finish_turn') return [a.phrase ? `«${a.phrase}»` : '', a.note_to_self ? `заметка себе: ${a.note_to_self}` : ''].filter(Boolean).join('\n');
return JSON.stringify(a);
}
</script>
<div class="thoughts">
<header>
<span class="label">💭 мысли · {moveNo(ply)} {move?.san ?? (live ? 'в эфире' : '')}</span>
<span class="spacer"></span>
{#if done?.usage}<span class="mono meta">{fmtTokens(done.usage.input + done.usage.output + done.usage.cacheRead)} ток · {fmtUsd(done.usage.cost, 3)}{#if move?.thinkMs} · {fmtDuration(move.thinkMs)}{/if}</span>{/if}
{#if onclose}<button class="x" onclick={onclose} aria-label="Закрыть">✕</button>{/if}
</header>
{#if err}<div class="error-box">{err}</div>{/if}
{#if !live && !attempts && !err}<div class="empty">Загружаю…</div>{/if}
{#if failed.length && move}
<div class="note mono">⟲ {failed.length} {failed.length === 1 ? 'попытка' : 'попытки'} упали (ошибка провайдера) — ход переигран с чистого листа</div>
{/if}
{#if context}
<details class="ctx">
<summary class="label">что агент видел на входе</summary>
<pre class="mono">{context.text}</pre>
</details>
{/if}
<div class="items">
{#each items as it, i (i)}
{#if it.kind === 'thinking'}
<div class="it thinking"><pre>{it.text}</pre></div>
{:else if it.kind === 'text'}
<div class="it text"><pre>{it.text}</pre></div>
{:else if it.kind === 'tool'}
<div class="it tool" class:err={it.call.isError}>
<div class="tool-head"><span class="chip outline mono">{it.call.name}</span><span class="muted">{TOOL_RU[it.call.name] ?? ''}</span>{#if !it.call.endedAt}<span class="live-dot"></span>{/if}</div>
{#if argText(it.call)}<pre class="mono args">{argText(it.call)}</pre>{/if}
{#if it.call.result && it.call.name !== 'finish_turn'}<pre class="mono res">{it.call.result}</pre>{/if}
</div>
{:else if it.kind === 'nudge'}
<div class="it nudge mono">арбитр: {it.text}</div>
{:else if it.kind === 'error'}
<div class="it nudge mono">ошибка: {it.text}</div>
{/if}
{/each}
{#if live && !move && !items.length}<div class="empty">Агент начал думать… (часть моделей не показывает рассуждения до конца хода)</div>{/if}
{#if !live && attempts && !items.filter((i) => i.kind !== 'context').length}<div class="empty">Модель не раскрыла рассуждения на этом ходу.</div>{/if}
</div>
</div>
<style>
.thoughts {
padding: 10px 12px 12px;
display: grid;
gap: 8px;
font-size: 13px;
}
header {
display: flex;
align-items: center;
gap: 8px;
}
.meta {
font-size: 11px;
color: var(--muted);
}
.x {
font-size: 13px;
padding: 2px 6px;
}
.note {
font-size: 11px;
color: var(--muted);
}
.ctx summary {
cursor: pointer;
color: var(--accent-text, var(--accent));
}
pre {
margin: 0;
white-space: pre-wrap;
word-break: break-word;
font-family: inherit;
}
.ctx pre {
margin-top: 6px;
padding: 8px;
max-height: 340px;
overflow: auto;
font-size: 11px;
background: var(--surface);
border: var(--border-thin);
}
.items {
display: grid;
gap: 8px;
max-height: 520px;
overflow: auto;
}
.it.thinking pre {
font-style: italic;
color: var(--text-2);
line-height: 1.5;
border-left: 3px solid var(--muted);
padding-left: 10px;
}
.it.text pre {
border-left: 3px solid var(--accent);
padding-left: 10px;
}
.tool {
border: var(--border-thin);
background: var(--surface);
padding: 6px 8px;
display: grid;
gap: 4px;
}
.tool.err {
border-color: var(--danger);
}
.tool-head {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
}
.args {
font-size: 12px;
font-weight: 600;
}
.res {
font-size: 11px;
color: var(--text-2);
max-height: 200px;
overflow: auto;
border-top: 1px dashed var(--line);
padding-top: 4px;
}
.tool.err .res {
color: var(--danger);
}
.nudge {
font-size: 11px;
color: var(--danger);
}
</style>
+105
View File
@@ -0,0 +1,105 @@
import type { EngineEval, MoveClass, Player, Termination } from './types.ts';
/** chess.com-style annotation glyph shown right next to the move */
export const NAG: Partial<Record<MoveClass, string>> = {
brilliant: '!!',
great: '!',
inaccuracy: '?!',
mistake: '?',
blunder: '??'
};
export const CLS_LABEL: Record<MoveClass, string> = {
best: 'лучший ход',
brilliant: 'блестяще',
great: 'отлично',
good: 'нормально',
inaccuracy: 'неточность',
mistake: 'ошибка',
blunder: 'зевок',
book: 'теория',
forced: 'единственный ход'
};
export function evalLabel(e?: EngineEval | null): string {
if (!e) return '';
if (e.mate != null) return `#${e.mate > 0 ? '' : '-'}${Math.abs(e.mate)}`;
const cp = e.cp ?? 0;
if (Math.abs(cp) >= 10000) return cp > 0 ? '1-0' : '0-1';
const v = cp / 100;
return (v > 0 ? '+' : v < 0 ? '−' : '') + Math.abs(v).toFixed(1);
}
/** 0..1 share of the eval bar for white */
export function evalShare(e?: EngineEval | null): number {
if (!e) return 0.5;
if (e.mate != null) return e.mate > 0 ? 0.97 : 0.03;
const cp = Math.max(-1000, Math.min(1000, e.cp ?? 0));
return Math.min(0.97, Math.max(0.03, 1 / (1 + Math.exp(-cp / 250))));
}
export function fmtDuration(ms: number): string {
const s = Math.round(ms / 1000);
if (s < 60) return `${s} с`;
const m = Math.floor(s / 60);
const r = s % 60;
if (m < 60) return r ? `${m}:${String(r).padStart(2, '0')}` : `${m} мин`;
return `${Math.floor(m / 60)} ч ${m % 60} мин`;
}
export function fmtClock(ms: number): string {
const s = Math.max(0, Math.floor(ms / 1000));
const m = Math.floor(s / 60);
return `${m}:${String(s % 60).padStart(2, '0')}`;
}
export function fmtTokens(t: number): string {
if (t >= 1_000_000) return (t / 1_000_000).toFixed(1) + 'M';
if (t >= 1000) return (t / 1000).toFixed(1) + 'k';
return String(Math.round(t));
}
export function fmtUsd(v: number | null | undefined, digits = 2): string {
if (v == null) return '—';
if (v > 0 && v < 0.01 && digits <= 2) return '<$0.01';
return '$' + v.toFixed(digits);
}
export function moveNo(ply: number): string {
const n = Math.ceil(ply / 2);
return ply % 2 === 1 ? `${n}.` : `${n}…`;
}
export function fmtAgo(iso: string | null | undefined): string {
if (!iso) return '';
const d = (Date.now() - new Date(iso).getTime()) / 1000;
if (d < 60) return 'только что';
if (d < 3600) return `${Math.floor(d / 60)} мин назад`;
if (d < 86400) return `${Math.floor(d / 3600)} ч назад`;
return new Date(iso).toLocaleDateString('ru-RU', { day: 'numeric', month: 'short' });
}
export const TERMINATION_RU: Record<Termination, string> = {
checkmate: 'мат',
stalemate: 'пат',
insufficient_material: 'мало материала',
threefold_repetition: 'троекратное повторение',
fifty_move_rule: 'правило 50 ходов',
resignation: 'сдача',
agreement: 'ничья по соглашению',
forfeit_illegal: 'нелегальные ходы',
forfeit_no_move: 'не сделал ход',
king_captured: 'съел короля',
aborted: 'прервана',
error: 'техническая ошибка'
};
export const VARIANT_LABEL: Record<string, string> = { max: 'MAX', high: 'HIGH', 'no-think': 'NO THINK', minimal: 'MINIMAL' };
export function playerTitle(p: Pick<Player, 'displayName' | 'variant' | 'kind'>): string {
return p.kind === 'human' || !p.variant ? p.displayName : `${p.displayName} · ${VARIANT_LABEL[p.variant] ?? p.variant.toUpperCase()}`;
}
export function shortName(p: Pick<Player, 'displayName' | 'kind'>): string {
if (p.kind === 'human') return p.displayName;
return p.displayName.replace(/^Claude /, '').replace(/^GPT-/, 'GPT-');
}
export function resultFor(side: 'white' | 'black', result: string | null): 'win' | 'loss' | 'draw' | null {
if (!result || result === '*') return null;
if (result === '1/2-1/2') return 'draw';
return (result === '1-0') === (side === 'white') ? 'win' : 'loss';
}
export const resultLabel = (r: string | null) => (r === '1/2-1/2' ? '½–½' : r === '1-0' ? '1–0' : r === '0-1' ? '0–1' : '—');
+160
View File
@@ -0,0 +1,160 @@
import { GameState, otherSide, type MoveDTO, type Side, type ToolCallLog } from '@aichess/core';
import { api } from './api.ts';
import { live } from './ws.ts';
import type { GameDetail, GameResponse, LiveTurn } from './types.ts';
export interface Position {
ply: number;
fen: string;
lastMove?: [string, string];
check: boolean;
}
/** Reactive view of one game: snapshot from REST + live deltas from the websocket. */
export class GameView {
id: string;
game = $state<GameDetail | null>(null);
moves = $state<MoveDTO[]>([]);
turn = $state<LiveTurn | null>(null);
predictions = $state<GameResponse['predictions']>({ counts: {}, mine: null });
error = $state<string | null>(null);
private offs: (() => void)[] = [];
constructor(id: string) {
this.id = id;
}
async load() {
try {
const r = await api.get<GameResponse>(`/api/games/${this.id}`);
this.game = r.game;
this.moves = r.moves;
this.turn = r.live ? { ...r.live, tools: [...r.live.tools] } : null;
this.predictions = r.predictions;
this.error = null;
} catch (e) {
this.error = (e as Error).message;
}
}
start() {
this.offs.push(live.subscribe(`game:${this.id}`, (ev) => this.onEvent(ev)));
this.offs.push(live.onReconnect(() => this.load()));
return this.load();
}
stop() {
this.offs.forEach((f) => f());
this.offs = [];
}
private onEvent(ev: any) {
const t = this.turn;
switch (ev.type) {
case 'turn_start':
this.turn = { ply: ev.ply, side: ev.side, startedAt: ev.at, thinking: '', text: '', tools: [] };
break;
case 'thinking_delta':
if (t && t.ply === ev.ply) t.thinking += ev.delta;
break;
case 'text_delta':
if (t && t.ply === ev.ply) t.text += ev.delta;
break;
case 'tool_start':
case 'tool_end': {
if (!t || t.ply !== ev.ply) break;
const i = t.tools.findIndex((x: ToolCallLog) => x.id === ev.call.id);
if (i >= 0) t.tools[i] = ev.call;
else t.tools.push(ev.call);
break;
}
case 'move':
if (!this.moves.some((m) => m.ply === ev.move.ply)) this.moves.push(ev.move);
if (this.game) {
this.game.ply = ev.move.ply;
this.game.fen = ev.move.fenAfter;
this.game.pendingDrawBy = ev.move.offeredDraw ? ev.move.side : null;
}
if (this.turn && this.turn.ply <= ev.move.ply) this.turn = null;
break;
case 'eval': {
const m = this.moves.find((x) => x.ply === ev.ply);
if (m) {
m.eval = ev.eval;
m.classification = ev.classification ?? null;
m.accuracy = ev.accuracy ?? null;
}
break;
}
case 'turn_end':
break;
case 'interview':
if (this.game) this.game.interviews = { ...this.game.interviews, [ev.side]: ev.text };
break;
case 'thumbnail':
if (this.game) {
this.game.thumbnailUrl = ev.url;
this.game.thumbnailCaption = ev.caption;
}
break;
case 'game_over':
case 'status':
this.turn = null;
this.load();
break;
}
}
// ------------------------------------------------------------ derived
get state(): GameState {
const g = this.game;
try {
return GameState.fromUci(this.moves.map((m) => ({ uci: m.uci, illegal: m.illegal })), g?.startFen);
} catch {
return new GameState(g?.startFen);
}
}
positions = $derived.by<Position[]>(() => {
const st = new GameState(this.game?.startFen);
const out: Position[] = [{ ply: 0, fen: st.fen(), check: false }];
for (const m of this.moves) {
const r = m.illegal ? st.applyIllegal(m.uci) : st.tryMove(m.uci);
if (!r.ok) break;
out.push({ ply: m.ply, fen: r.record.fenAfter, lastMove: [m.uci.slice(0, 2), m.uci.slice(2, 4)], check: st.inCheck() });
}
return out;
});
get running() {
return this.game?.status === 'running';
}
get finished() {
return this.game?.status === 'finished' || this.game?.status === 'aborted';
}
get sideToMove(): Side {
return this.moves.length % 2 === 0 ? 'white' : 'black';
}
player(side: Side) {
return side === 'white' ? this.game!.white : this.game!.black;
}
stats(side: Side) {
const mine = this.moves.filter((m) => m.side === side);
const cost = mine.reduce((a, m) => a + (m.usage?.cost ?? 0), 0);
const tokens = mine.reduce((a, m) => a + (m.usage ? m.usage.input + m.usage.output + m.usage.cacheRead + m.usage.cacheWrite : 0), 0);
const accs = mine.map((m) => m.accuracy).filter((x): x is number => x != null);
const official = this.game?.accuracy?.[side];
const accuracy = official ?? (accs.length ? accs.reduce((a, b) => a + b, 0) / accs.length : null);
const thinkMs = mine.reduce((a, m) => a + m.thinkMs, 0);
const cls = { brilliant: 0, best: 0, inaccuracy: 0, mistake: 0, blunder: 0 } as Record<string, number>;
for (const m of mine) if (m.classification && m.classification in cls) cls[m.classification]++;
return { cost, tokens, accuracy, thinkMs, moves: mine.length, cls };
}
/** the trash-talk line the given side last received */
lastPhraseTo(side: Side) {
return [...this.moves].reverse().find((m) => m.side === otherSide(side) && m.phrase)?.phrase ?? null;
}
}
+52
View File
@@ -0,0 +1,52 @@
import { api } from './api.ts';
import type { Meta, Theme, User } from './types.ts';
export const THEMES: { id: Theme; name: string; tagline: string }[] = [
{ id: 'tabloid', name: 'Вечерний Мат', tagline: 'Жёлтая пресса: кричащие заголовки, газетная бумага, красные чернила' },
{ id: 'broadcast', name: 'Эфир', tagline: 'Ночная спортивная трансляция: скорбаги, бегущая строка, прожекторы' },
{ id: 'arcade', name: 'AI Fight Club', tagline: 'Файтинг-аркада: VS-экраны, полоски здоровья, неон' }
];
class Session {
user = $state<User | null>(null);
meta = $state<Meta | null>(null);
theme = $state<Theme>((typeof localStorage !== 'undefined' && (localStorage.getItem('aichess-theme') as Theme)) || 'tabloid');
loaded = $state(false);
async load() {
const [me, meta] = await Promise.all([api.get<{ user: User | null }>('/api/me'), api.get<Meta>('/api/meta')]);
this.user = me.user;
this.meta = meta;
if (me.user?.theme) this.applyTheme(me.user.theme, false);
this.loaded = true;
}
applyTheme(t: Theme, persist = true) {
this.theme = t;
document.documentElement.dataset.theme = t;
try {
localStorage.setItem('aichess-theme', t);
} catch {}
if (persist && this.user) api.patch<{ user: User }>('/api/me', { theme: t }).then((r) => (this.user = r.user));
}
async login(username: string, password: string) {
const r = await api.post<{ user: User }>('/api/auth/login', { username, password });
this.user = r.user;
if (r.user.theme) this.applyTheme(r.user.theme, false);
return r.user;
}
async register(username: string, password: string) {
const r = await api.post<{ user: User }>('/api/auth/register', { username, password });
this.user = r.user;
// keep the theme the visitor was already using
this.applyTheme(this.theme, true);
return r.user;
}
async logout() {
await api.post('/api/auth/logout');
this.user = null;
}
}
export const session = new Session();
+111
View File
@@ -0,0 +1,111 @@
/* «AI FIGHT CLUB» — fighting-game arcade: P1 yellow (white) vs P2 red (black), neon, pixel labels */
html[data-theme='arcade'] {
--scheme: dark;
--bg: #08080c;
--bg-image: linear-gradient(rgba(255, 255, 255, 0.018) 1px, transparent 1px), linear-gradient(90deg, rgba(255, 255, 255, 0.018) 1px, transparent 1px);
--surface: #14141c;
--surface-2: #1a1a24;
--surface-3: #262634;
--text: #f3efe4;
--text-2: #cfcbbf;
--muted: #8e8d9c;
--line: #262634;
--line-strong: #343446;
--accent: #ffe14d;
--accent-ink: #08080c;
--accent-text: #ffe14d;
--accent-2: #262634;
--accent-2-ink: #f3efe4;
--danger: #ff3b5c;
--ok: #4cff5e;
--warn: #ffd23f;
--info: #42e8ff;
--live: #ff3b5c;
--white-side: #ffe14d;
--black-side: #ff3b5c;
--f-display: 'Unbounded', 'Arial Black', sans-serif;
--f-body: 'IBM Plex Sans', system-ui, sans-serif;
--f-mono: 'JetBrains Mono', ui-monospace, monospace;
--f-label: 'Press Start 2P', monospace;
--display-transform: uppercase;
--display-weight: 900;
--label-size: 9px;
--label-tracking: 0.04em;
--radius: 4px;
--border: 2px solid #262634;
--border-thin: 1px solid #262634;
--shadow: 0 0 0 1px rgba(255, 225, 77, 0.04), 0 8px 24px rgba(0, 0, 0, 0.5);
--shadow-sm: 0 3px 0 #000;
--panel-head-bg: #0f0f16;
--panel-head-ink: #8e8d9c;
--panel-head-size: 10px;
--panel-head-pad: 10px 12px;
--tab-on-bg: #ffe14d;
--tab-on-ink: #08080c;
--chip-bg: #ffe14d;
--chip-ink: #08080c;
--input-bg: #0f0f16;
--row-hover: rgba(255, 225, 77, 0.05);
--nag-brilliant: #42e8ff;
--nag-great: #4cff5e;
--nag-inaccuracy: #ffd23f;
--nag-mistake: #ff8c42;
--nag-blunder: #ff3b3b;
--board-light: #e9e4d4;
--board-dark: #4b5a8a;
--board-last: rgba(255, 225, 77, 0.55);
--board-check: #ff3b5c;
--board-frame: #000;
--board-coord: rgba(8, 8, 12, 0.6);
--scroll-thumb: #343446;
--scroll-track: #0f0f16;
--dumb-bg: #ffe14d;
--dumb-ink: #08080c;
}
html[data-theme='arcade'] body::after {
/* CRT scanlines, very subtle */
content: '';
position: fixed;
inset: 0;
pointer-events: none;
z-index: 1000;
background: repeating-linear-gradient(0deg, rgba(0, 0, 0, 0.12) 0 1px, transparent 1px 3px);
mix-blend-mode: multiply;
}
html[data-theme='arcade'] body {
background-size: 32px 32px;
}
html[data-theme='arcade'] .btn {
font-size: 10px;
letter-spacing: 0.02em;
box-shadow: 0 4px 0 #000;
}
html[data-theme='arcade'] .btn.primary {
box-shadow: 0 4px 0 #b89a00;
}
html[data-theme='arcade'] .btn.lg {
font-size: 12px;
}
html[data-theme='arcade'] .tabs > button,
html[data-theme='arcade'] .tabs > a {
font-size: 9px;
}
html[data-theme='arcade'] .chip,
html[data-theme='arcade'] .tag {
font-family: 'JetBrains Mono', monospace;
font-weight: 700;
}
html[data-theme='arcade'] .panel-head {
border-bottom: 2px solid #262634;
}
html[data-theme='arcade'] .panel-head.hot {
background: #ff3b5c;
color: #fff;
}
html[data-theme='arcade'] .display {
text-shadow: 3px 3px 0 #000;
}
+105
View File
@@ -0,0 +1,105 @@
/* «ЭФИР» — night sports broadcast: dark stage, scorebugs, gold & live red, ice (white) vs fire (black) */
html[data-theme='broadcast'] {
--scheme: dark;
--bg: #06070b;
--bg-image: radial-gradient(1200px 600px at 50% -10%, rgba(124, 199, 255, 0.08), transparent 60%), radial-gradient(900px 500px at 100% 0%, rgba(255, 93, 58, 0.06), transparent 60%);
--surface: #10131b;
--surface-2: #161a24;
--surface-3: #1d2230;
--text: #eef1f6;
--text-2: #c3c9d6;
--muted: #8a92a6;
--line: #232838;
--line-strong: #2e3447;
--accent: #ffc93c;
--accent-ink: #0b0d14;
--accent-text: #ffc93c;
--accent-2: #1d2230;
--accent-2-ink: #eef1f6;
--danger: #ff2a3c;
--ok: #42d989;
--warn: #ffb347;
--info: #7cc7ff;
--live: #ff2a3c;
--white-side: #7cc7ff;
--black-side: #ff5d3a;
--f-display: 'Oswald', 'Arial Narrow', sans-serif;
--f-body: 'IBM Plex Sans', system-ui, sans-serif;
--f-mono: 'IBM Plex Mono', ui-monospace, monospace;
--f-label: 'Oswald', 'Arial Narrow', sans-serif;
--display-transform: uppercase;
--display-tracking: 0.01em;
--label-tracking: 0.14em;
--radius: 3px;
--border: 1px solid #232838;
--border-thin: 1px solid #1b2030;
--shadow: 0 10px 30px rgba(0, 0, 0, 0.35);
--shadow-sm: none;
--panel-head-bg: linear-gradient(90deg, #161a24, #10131b);
--panel-head-ink: #c3c9d6;
--panel-head-border: 1px solid #232838;
--tab-on-bg: #ffc93c;
--tab-on-ink: #0b0d14;
--chip-bg: #ffc93c;
--chip-ink: #0b0d14;
--input-bg: #0b0d14;
--nag-brilliant: #42e8ff;
--nag-great: #7cc7ff;
--nag-inaccuracy: #ffd23f;
--nag-mistake: #ff8c42;
--nag-blunder: #ff4757;
--board-light: #c7cede;
--board-dark: #3a4256;
--board-last: rgba(255, 201, 60, 0.45);
--board-check: #ff2a3c;
--board-frame: #0b0d14;
--board-coord: rgba(11, 13, 20, 0.6);
--scroll-thumb: #2e3447;
--scroll-track: #0b0d14;
--dumb-bg: #2e3447;
--dumb-ink: #c3c9d6;
}
html[data-theme='broadcast'] .panel-head {
position: relative;
padding-left: 18px;
}
html[data-theme='broadcast'] .panel-head::before {
content: '';
position: absolute;
left: 8px;
top: 25%;
bottom: 25%;
width: 3px;
background: #ffc93c;
transform: skewX(-12deg);
}
html[data-theme='broadcast'] .panel-head.hot {
background: linear-gradient(90deg, #ff2a3c, #b3101f);
color: #fff;
}
html[data-theme='broadcast'] .panel-head.hot::before {
background: #fff;
}
html[data-theme='broadcast'] .btn.primary {
transform: skewX(-8deg);
}
html[data-theme='broadcast'] .btn.primary > * {
transform: skewX(8deg);
}
html[data-theme='broadcast'] .tag {
background: #161a24;
border-color: #2e3447;
color: #c3c9d6;
}
html[data-theme='broadcast'] .tag.hot {
background: #ff2a3c;
color: #fff;
border-color: #ff2a3c;
}
html[data-theme='broadcast'] .display {
text-shadow: 0 2px 30px rgba(255, 201, 60, 0.12);
}
+103
View File
@@ -0,0 +1,103 @@
/* «ВЕЧЕРНИЙ МАТ» — loud chess tabloid: newsprint, black ink, red & yellow */
html[data-theme='tabloid'] {
--scheme: light;
--bg: #efe6cf;
--bg-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='240' height='240'%3E%3Cfilter id='n'%3E%3CfeTurbulence type='fractalNoise' baseFrequency='.9' numOctaves='2' stitchTiles='stitch'/%3E%3CfeColorMatrix values='0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .14 0'/%3E%3C/filter%3E%3Crect width='100%25' height='100%25' filter='url(%23n)'/%3E%3C/svg%3E"),
linear-gradient(180deg, #f3ecd8 0%, #efe6cf 30%, #e9dfc6 100%);
--surface: #fbf7ec;
--surface-2: #f3ecd8;
--surface-3: #e4d9bc;
--text: #15120f;
--text-2: #4a4238;
--muted: #857a69;
--line: #15120f;
--line-strong: #15120f;
--accent: #d1231c;
--accent-ink: #fbf7ec;
--accent-text: #d1231c;
--accent-2: #ffd41c;
--accent-2-ink: #15120f;
--danger: #d1231c;
--ok: #2d7a3a;
--warn: #ffd41c;
--info: #1f5fae;
--live: #d1231c;
--white-side: #fbf7ec;
--black-side: #15120f;
--f-display: 'Oswald', 'Arial Narrow', sans-serif;
--f-body: 'Spectral', Georgia, serif;
--f-mono: 'IBM Plex Mono', Menlo, monospace;
--f-label: 'Oswald', 'Arial Narrow', sans-serif;
--display-transform: uppercase;
--display-tracking: -0.01em;
--radius: 0;
--border: 2px solid #15120f;
--border-thin: 1px solid #15120f;
--shadow: 4px 4px 0 #15120f;
--shadow-sm: 3px 3px 0 #15120f;
--btn-hover-transform: translate(-1px, -1px);
--btn-active-transform: translate(3px, 3px);
--panel-head-bg: #15120f;
--panel-head-ink: #efe6cf;
--panel-head-border: 0;
--tab-on-bg: #15120f;
--tab-on-ink: #ffd41c;
--chip-bg: #ffd41c;
--chip-ink: #15120f;
--nag-brilliant: #1a8ca8;
--nag-great: #1f5fae;
--nag-inaccuracy: #b98600;
--nag-mistake: #e06c00;
--nag-blunder: #d1231c;
--board-light: #f3eacf;
--board-dark: #c2271f;
--board-last: rgba(255, 212, 28, 0.65);
--board-check: #ffdc28;
--board-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8' shape-rendering='crispEdges'%3E%3Cdefs%3E%3Cpattern id='h' width='.25' height='.25' patternUnits='userSpaceOnUse'%3E%3Ccircle cx='.125' cy='.125' r='.05' fill='%2315120f' opacity='.16'/%3E%3C/pattern%3E%3C/defs%3E%3Crect width='8' height='8' fill='%23f3eacf'/%3E%3Crect width='8' height='8' fill='url(%23h)'/%3E%3Cg fill='%23c2271f'%3E%3Cpath d='M1 0h1v1H1zM3 0h1v1H3zM5 0h1v1H5zM7 0h1v1H7zM0 1h1v1H0zM2 1h1v1H2zM4 1h1v1H4zM6 1h1v1H6zM1 2h1v1H1zM3 2h1v1H3zM5 2h1v1H5zM7 2h1v1H7zM0 3h1v1H0zM2 3h1v1H2zM4 3h1v1H4zM6 3h1v1H6zM1 4h1v1H1zM3 4h1v1H3zM5 4h1v1H5zM7 4h1v1H7zM0 5h1v1H0zM2 5h1v1H2zM4 5h1v1H4zM6 5h1v1H6zM1 6h1v1H1zM3 6h1v1H3zM5 6h1v1H5zM7 6h1v1H7zM0 7h1v1H0zM2 7h1v1H2zM4 7h1v1H4zM6 7h1v1H6z'/%3E%3C/g%3E%3C/svg%3E");
--board-image-size: 100% 100%;
--board-frame: #15120f;
--board-coord: #fbf7ec;
--scroll-thumb: #15120f;
--scroll-track: #e4d9bc;
--dumb-bg: #e4d9bc;
--dumb-ink: #15120f;
}
html[data-theme='tabloid'] .panel-head {
font-size: 15px;
letter-spacing: 0.06em;
}
html[data-theme='tabloid'] .tag {
box-shadow: 3px 3px 0 #15120f;
transform: rotate(-1.5deg);
}
html[data-theme='tabloid'] .tag.flat {
transform: none;
box-shadow: none;
}
html[data-theme='tabloid'] .chip.accent {
box-shadow: 2px 2px 0 #15120f;
}
html[data-theme='tabloid'] .display {
letter-spacing: -0.01em;
}
html[data-theme='tabloid'] .t-halftone {
position: relative;
}
html[data-theme='tabloid'] .t-halftone::after {
content: '';
position: absolute;
inset: 0;
pointer-events: none;
background-image: radial-gradient(#15120f 1px, transparent 1.2px);
background-size: 5px 5px;
opacity: 0.1;
mix-blend-mode: multiply;
}
html[data-theme='tabloid'] blockquote.quote::before {
content: '«';
color: #d1231c;
}
+125
View File
@@ -0,0 +1,125 @@
import type { EngineEval, GameFlags, MoveClass, MoveDTO, Result, Side, Termination, ToolCallLog, TranscriptItem, Usage } from '@aichess/core';
export type { EngineEval, GameFlags, MoveClass, MoveDTO, Result, Side, Termination, ToolCallLog, TranscriptItem, Usage };
export type Theme = 'tabloid' | 'broadcast' | 'arcade';
export interface Player {
id: string;
kind: 'ai' | 'human';
slug: string;
displayName: string;
variant: string | null;
family: string | null;
modelId: string | null;
avatarUrl: string | null;
color: string | null;
dumb: boolean;
skull: boolean;
active: boolean;
rating: number;
rd: number;
games: number;
wins: number;
draws: number;
losses: number;
}
export interface LeaderRow extends Player {
avgAccuracy: number | null;
costPerGame: number | null;
tokensPerGame: number | null;
}
export interface GameSummary {
id: string;
status: 'pending' | 'running' | 'finished' | 'aborted';
white: Player;
black: Player;
result: Result | null;
termination: Termination | null;
ply: number;
fen: string;
rated: boolean;
flags: GameFlags;
scheduled: boolean;
startsAt: string | null;
startedAt: string | null;
finishedAt: string | null;
createdAt: string;
thumbnailUrl: string | null;
thumbnailCaption: string | null;
accuracy: { white: number | null; black: number | null } | null;
costTotal: number;
ratingChange: { white: { before: number; after: number }; black: { before: number; after: number } } | null;
review?: { title: string; text: string } | null;
}
export interface GameDetail extends GameSummary {
startFen: string;
personas: { white: string | null; black: string | null };
interviews: { white?: string | null; black?: string | null };
lastWords: { white?: string | null; black?: string | null };
pendingDrawBy: Side | null;
createdBy: string | null;
error: string | null;
}
export interface LiveTurn {
ply: number;
side: Side;
startedAt: number;
thinking: string;
text: string;
tools: ToolCallLog[];
}
export interface GameResponse {
game: GameDetail;
moves: MoveDTO[];
live: LiveTurn | null;
predictions: { counts: Partial<Record<'white' | 'draw' | 'black', number>>; mine: 'white' | 'draw' | 'black' | null };
}
export interface User {
id: string;
username: string;
displayName: string;
avatarUrl: string | null;
isAdmin: boolean;
onboarded: boolean;
theme: Theme;
playerId: string | null;
rating: number | null;
}
export interface Persona {
id: string;
label: string;
description: string;
}
export interface Meta {
personas: Persona[];
aiPlayers: Player[];
themes: Theme[];
flags: { key: keyof GameFlags; label: string; description: string; rated: boolean }[];
}
export interface HomeData {
live: GameSummary[];
upcoming: GameSummary[];
featured: GameSummary | null;
recent: GameSummary[];
nextScheduledAt: string | null;
}
export interface TurnAttempt {
id: string;
attempt: number;
status: 'running' | 'done' | 'failed';
outcome: string | null;
error: string | null;
usage: Usage | null;
transcript: TranscriptItem[];
startedAt: string;
endedAt: string | null;
}
+65
View File
@@ -0,0 +1,65 @@
/**
* Single shared websocket. subscribe('game:<id>' | 'lobby', handler) → unsubscribe.
* Reconnects with backoff and re-subscribes; `onReconnect` lets views refetch snapshots.
*/
type Handler = (ev: any) => void;
class Live {
private ws: WebSocket | null = null;
private handlers = new Map<string, Set<Handler>>();
private reconnectHandlers = new Set<() => void>();
private backoff = 500;
private connectedOnce = false;
private connect() {
if (this.ws && this.ws.readyState <= 1) return;
const proto = location.protocol === 'https:' ? 'wss' : 'ws';
const ws = new WebSocket(`${proto}://${location.host}/ws`);
this.ws = ws;
ws.onopen = () => {
this.backoff = 500;
const chans = [...this.handlers.keys()];
if (chans.length) ws.send(JSON.stringify({ sub: chans }));
if (this.connectedOnce) this.reconnectHandlers.forEach((f) => f());
this.connectedOnce = true;
};
ws.onmessage = (m) => {
let msg: any;
try {
msg = JSON.parse(m.data);
} catch {
return;
}
for (const item of msg.batch ?? []) this.handlers.get(item.ch)?.forEach((h) => h(item.ev));
};
ws.onclose = () => {
this.ws = null;
if (!this.handlers.size) return;
setTimeout(() => this.connect(), this.backoff);
this.backoff = Math.min(this.backoff * 2, 10_000);
};
}
subscribe(channel: string, h: Handler): () => void {
let set = this.handlers.get(channel);
const fresh = !set;
if (!set) this.handlers.set(channel, (set = new Set()));
set.add(h);
this.connect();
if (fresh && this.ws?.readyState === 1) this.ws.send(JSON.stringify({ sub: [channel] }));
return () => {
set!.delete(h);
if (!set!.size) {
this.handlers.delete(channel);
if (this.ws?.readyState === 1) this.ws.send(JSON.stringify({ unsub: [channel] }));
}
};
}
onReconnect(f: () => void) {
this.reconnectHandlers.add(f);
return () => this.reconnectHandlers.delete(f);
}
}
export const live = new Live();
+50
View File
@@ -0,0 +1,50 @@
<script lang="ts">
import '@lichess-org/chessground/assets/chessground.base.css';
import '@lichess-org/chessground/assets/chessground.cburnett.css';
import '../app.css';
import { onMount } from 'svelte';
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { session } from '#lib/session.svelte.ts';
import Header from '#lib/components/Header.svelte';
let { children } = $props();
onMount(() => {
session.load().catch(() => (session.loaded = true));
});
$effect(() => {
if (session.user && !session.user.onboarded && !['/onboarding', '/login'].includes(page.url.pathname)) goto('/onboarding');
});
</script>
<svelte:head><title>AI·CHESS — нейросети играют в шахматы</title></svelte:head>
<Header />
<main class="wrap">
{@render children()}
</main>
<footer class="wrap foot mono">
<span>AI·CHESS · chess.danosito.com · оценки — Stockfish, ходы и трэш-ток — нейросети</span>
<span>агенты на pi · каждый ход с чистого листа</span>
</footer>
<style>
main {
min-height: 60vh;
}
.foot {
display: flex;
justify-content: space-between;
gap: 16px;
flex-wrap: wrap;
margin-top: 48px;
padding-top: 10px;
padding-bottom: 28px;
border-top: var(--border);
font-size: 11px;
color: var(--muted);
text-transform: uppercase;
letter-spacing: 0.05em;
}
</style>
+2
View File
@@ -0,0 +1,2 @@
export const ssr = false;
export const prerender = false;
+281
View File
@@ -0,0 +1,281 @@
<script lang="ts">
import { api } from '#lib/api.ts';
import { live } from '#lib/ws.ts';
import { session } from '#lib/session.svelte.ts';
import type { HomeData, LeaderRow, GameResponse } from '#lib/types.ts';
import { resultLabel, TERMINATION_RU, fmtAgo } from '#lib/fmt.ts';
import LiveCard from '#lib/components/LiveCard.svelte';
import LiveHero from '#lib/components/LiveHero.svelte';
import GameCard from '#lib/components/GameCard.svelte';
import Countdown from '#lib/components/Countdown.svelte';
import Predictions from '#lib/components/Predictions.svelte';
import Avatar from '#lib/components/Avatar.svelte';
import PlayerName from '#lib/components/PlayerName.svelte';
let home = $state<HomeData | null>(null);
let top = $state<LeaderRow[]>([]);
let next = $state<GameResponse | null>(null);
async function load() {
const [h, lb] = await Promise.all([api.get<HomeData>('/api/home'), api.get<{ players: LeaderRow[] }>('/api/leaderboard')]);
home = h;
top = lb.players.filter((p) => p.games > 0).slice(0, 5);
next = h.upcoming[0] ? await api.get<GameResponse>(`/api/games/${h.upcoming[0].id}`) : null;
}
let t: ReturnType<typeof setTimeout> | null = null;
$effect(() => {
load();
return live.subscribe('lobby', () => {
if (t) clearTimeout(t);
t = setTimeout(load, 400);
});
});
const f = $derived(home?.featured ?? null);
</script>
<svelte:head><title>AI·CHESS — нейросети играют в шахматы</title></svelte:head>
{#if !home}
<div class="empty">Свежий номер печатается…</div>
{:else}
<div class="home">
<div class="main">
<!-- ───── on air ───── -->
<section class="panel onair">
<div class="panel-head hot">
{#if home.live.length}<span class="live-dot" style="background:currentColor"></span>{/if}
Сейчас в эфире <span class="spacer"></span><small>{home.live.length ? `${home.live.length} ${home.live.length === 1 ? 'партия' : 'партии'}` : 'тишина'}</small>
</div>
<div class="panel-body">
{#if home.live.length === 1}
<LiveHero id={home.live[0].id} />
{:else if home.live.length > 1}
<div class="stack">
{#each home.live as g (g.id)}<LiveCard {g} />{/each}
</div>
{:else}
<div class="quiet">
<p class="display">В эфире тишина.</p>
<p class="muted">{home.nextScheduledAt ? 'Следующий бой по расписанию — справа.' : ''} {session.user ? 'Можешь устроить матч сам — кнопка в шапке.' : 'Войди, чтобы устроить матч.'}</p>
</div>
{/if}
</div>
</section>
<!-- ───── featured story (editorial review shows ONLY here) ───── -->
{#if f}
<section class="story panel">
<a class="story-thumb" href="/match/{f.id}"><img src={f.thumbnailUrl} alt={f.thumbnailCaption ?? ''} /></a>
<div class="story-text">
<div class="kicker">главная партия · {resultLabel(f.result)} · {f.termination ? TERMINATION_RU[f.termination] : ''} · {fmtAgo(f.finishedAt)}</div>
<h1 class="display">{f.review?.title ?? f.thumbnailCaption}</h1>
{#if f.review?.text}<p class="lede">{f.review.text}</p>{/if}
<div class="byline">
<Avatar player={f.white} size={26} /><PlayerName player={f.white} short />
<span class="muted">vs</span>
<Avatar player={f.black} size={26} /><PlayerName player={f.black} short />
</div>
<a class="btn" href="/match/{f.id}">Реплей и интервью →</a>
</div>
</section>
{/if}
</div>
<!-- ───── sidebar ───── -->
<aside class="side">
{#if next}
<section class="panel">
<div class="panel-head">Следующий бой <span class="spacer"></span><small>{new Date(next.game.startsAt!).toLocaleTimeString('ru-RU', { hour: '2-digit', minute: '2-digit' })}</small></div>
<div class="panel-body stack">
<div class="fight">
{#each [next.game.white, next.game.black] as p, i}
{#if i}<span class="display vs">VS</span>{/if}
<a class="fighter" href="/leaderboard"><Avatar player={p} size={56} /><span class="display"><PlayerName player={p} short /></span><span class="mono muted">{p.rating}</span></a>
{/each}
</div>
<div class="cd-row"><span class="label">до старта</span><Countdown to={next.game.startsAt!} /></div>
<Predictions gameId={next.game.id} open white={next.game.white} black={next.game.black} counts={next.predictions.counts} mine={next.predictions.mine} onchange={load} />
</div>
</section>
{:else if home.nextScheduledAt}
<section class="panel">
<div class="panel-head">Следующий бой</div>
<div class="panel-body stack">
<p class="muted">Соперников объявят за полчаса до старта — тогда откроется приём прогнозов.</p>
<Countdown to={home.nextScheduledAt} />
</div>
</section>
{/if}
<section class="panel">
<div class="panel-head">Таблица · топ-5 <span class="spacer"></span><a href="/leaderboard"><small>вся таблица →</small></a></div>
<ol class="top">
{#each top as p, i (p.id)}
<li>
<span class="display n">{i + 1}</span>
<Avatar player={p} size={24} />
<span class="nm"><PlayerName player={p} short /></span>
<b class="mono">{p.rating}</b>
</li>
{:else}
<li class="muted">Пока никто не сыграл</li>
{/each}
</ol>
</section>
{#if !session.user && session.loaded}
<section class="panel cta">
<div class="panel-body stack">
<p class="display">Хочешь свою драку?</p>
<p>Зарегистрируйся — выбирай бойцов, персонажей, режимы. Или садись играть против нейросети сам.</p>
<a class="btn primary" href="/login?mode=register">Регистрация</a>
</div>
</section>
{/if}
</aside>
<!-- ───── archive ───── -->
<section class="archive">
<div class="panel-head">Архив позора <span class="spacer"></span><small>превью рисует нейросеть после партии</small></div>
<div class="grid">
{#each home.recent as g (g.id)}<GameCard {g} />{/each}
{#if !home.recent.length}<div class="empty">Ещё ни одной партии. Будь первым.</div>{/if}
</div>
{#if home.recent.length >= 12}<a class="btn more" href="/games">Весь архив →</a>{/if}
</section>
</div>
{/if}
<style>
.home {
display: grid;
grid-template-columns: minmax(0, 1fr) 360px;
gap: 22px;
align-items: start;
}
.main,
.side {
display: grid;
gap: 22px;
min-width: 0;
}
.quiet {
padding: 28px 10px;
display: grid;
gap: 8px;
}
.quiet .display {
font-size: 34px;
}
.story {
display: grid;
grid-template-columns: minmax(0, 1.1fr) minmax(0, 1fr);
overflow: hidden;
}
.story-thumb img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
aspect-ratio: 16/9;
}
.story-text {
padding: 18px 20px;
display: grid;
gap: 12px;
align-content: start;
}
.story h1 {
font-size: clamp(28px, 3vw, 46px);
}
.lede {
font-size: 16px;
line-height: 1.5;
}
.byline {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
font-weight: 600;
font-size: 14px;
}
.story .btn {
justify-self: start;
}
.fight {
display: grid;
grid-template-columns: 1fr auto 1fr;
align-items: center;
gap: 8px;
text-align: center;
}
.fighter {
display: grid;
justify-items: center;
gap: 6px;
}
.fighter .display {
font-size: 16px;
}
.vs {
font-size: 26px;
color: var(--accent-text, var(--accent));
}
.cd-row {
display: grid;
gap: 6px;
}
.top {
list-style: none;
margin: 0;
padding: 0;
}
.top li {
display: grid;
grid-template-columns: 26px auto 1fr auto;
gap: 10px;
align-items: center;
padding: 8px 12px;
border-bottom: var(--border-thin);
}
.top li:last-child {
border-bottom: 0;
}
.n {
font-size: 22px;
color: var(--accent-text, var(--accent));
}
.nm {
font-weight: 600;
font-size: 14px;
min-width: 0;
}
.cta .display {
font-size: 26px;
}
.archive {
grid-column: 1 / -1;
display: grid;
gap: 16px;
}
.archive .panel-head {
border-radius: var(--radius);
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 22px 18px;
}
.more {
justify-self: center;
}
@media (max-width: 1000px) {
.home {
grid-template-columns: 1fr;
}
.story {
grid-template-columns: 1fr;
}
}
</style>
+194
View File
@@ -0,0 +1,194 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { api } from '#lib/api.ts';
import { session } from '#lib/session.svelte.ts';
import { fmtUsd, fmtTokens, fmtAgo } from '#lib/fmt.ts';
import Avatar from '#lib/components/Avatar.svelte';
type Sched = { id: string; name: string; enabled: boolean; intervalMinutes: number; announceMinutes: number; pool: string[]; flags: { notes: boolean; extraTools: boolean; cheating: boolean }; randomPersonas: boolean; nextRunAt: string | null };
let users = $state<any[]>([]);
let system = $state<any>(null);
let schedules = $state<Sched[]>([]);
let msg = $state<string | null>(null);
$effect(() => {
if (session.loaded && !session.user?.isAdmin) goto('/');
});
async function load() {
const u = await api.get<{ users: any[]; system: any }>('/api/admin/users');
users = u.users;
system = u.system;
schedules = (await api.get<{ schedules: Sched[] }>('/api/admin/schedules')).schedules;
}
$effect(() => {
if (session.user?.isAdmin) load();
});
const ai = $derived(session.meta?.aiPlayers ?? []);
const totalCost = $derived(users.reduce((a, u) => a + u.cost, 0) + (system?.cost ?? 0));
async function saveSched(s: Sched) {
const { id, ...body } = s;
await api.patch(`/api/admin/schedules/${id}`, body);
msg = `Расписание «${s.name}» сохранено`;
load();
}
async function addSched() {
await api.post('/api/admin/schedules', { name: 'Новое расписание', enabled: false, intervalMinutes: 180, announceMinutes: 30, pool: [], flags: { notes: false, extraTools: false, cheating: false }, randomPersonas: true });
load();
}
async function delSched(s: Sched) {
if (!confirm(`Удалить «${s.name}»?`)) return;
await api.del(`/api/admin/schedules/${s.id}`);
load();
}
// one-off scheduled match (predictions open until start)
let one = $state({ white: 'opus-5.5-max', black: 'astra-6-max', at: new Date(Date.now() + 3600_000).toISOString().slice(0, 16) });
async function createOne() {
const r = await api.post<{ id: string }>('/api/games', { white: one.white, black: one.black, startsAt: new Date(one.at).toISOString(), personas: { white: 'gopnik', black: 'professor' } });
goto(`/match/${r.id}`);
}
let redoId = $state('');
async function redo(kind: string[]) {
await api.post(`/api/admin/games/${redoId.trim()}/postgame`, { redo: kind });
msg = 'Постгейм поставлен в очередь';
}
</script>
<svelte:head><title>Админка · AI·CHESS</title></svelte:head>
{#if session.user?.isAdmin}
<section class="stack">
<h1 class="display title">Админка</h1>
{#if msg}<div class="panel"><div class="panel-body accent">{msg}</div></div>{/if}
<div class="panel">
<div class="panel-head">Пользователи и твои токены <span class="spacer"></span><small>всего потрачено {fmtUsd(totalCost)} (по прайс-листу)</small></div>
<table class="table">
<thead><tr><th>Пользователь</th><th class="num">Партий</th><th class="num">Токены</th><th class="num">$</th><th>С нами</th></tr></thead>
<tbody>
{#if system}
<tr><td><b>⚙ расписание / система</b></td><td class="num">{system.games}</td><td class="num mono">{fmtTokens(system.tokens)}</td><td class="num"><b>{fmtUsd(system.cost)}</b></td><td></td></tr>
{/if}
{#each users as u (u.id)}
<tr>
<td><span class="who"><Avatar player={{ avatarUrl: u.avatarUrl, displayName: u.display_name, color: null, kind: 'human', family: null }} size={26} />{u.display_name} <span class="mono muted">@{u.username}</span>{#if u.is_admin}<span class="chip accent">админ</span>{/if}</span></td>
<td class="num">{u.games}</td>
<td class="num mono">{fmtTokens(u.tokens)}</td>
<td class="num"><b>{fmtUsd(u.cost)}</b></td>
<td class="muted">{fmtAgo(u.created_at)}</td>
</tr>
{/each}
</tbody>
</table>
</div>
<div class="panel">
<div class="panel-head">Матчи по расписанию <span class="spacer"></span><button class="btn sm" onclick={addSched}>+ расписание</button></div>
<div class="panel-body stack">
{#each schedules as s (s.id)}
<div class="sched">
<div class="row wrap">
<input class="input name" bind:value={s.name} />
<label class="row"><input type="checkbox" bind:checked={s.enabled} /> включено</label>
<label class="row">каждые <input class="input n" type="number" min="10" bind:value={s.intervalMinutes} /> мин</label>
<label class="row">анонс за <input class="input n" type="number" min="0" bind:value={s.announceMinutes} /> мин</label>
<label class="row"><input type="checkbox" bind:checked={s.randomPersonas} /> случайные характеры</label>
</div>
<div class="row wrap">
<span class="label muted">пул (пусто = все):</span>
{#each ai as p (p.slug)}
<label class="poolp"><input type="checkbox" checked={s.pool.includes(p.slug)} onchange={(e) => (s.pool = (e.target as HTMLInputElement).checked ? [...s.pool, p.slug] : s.pool.filter((x) => x !== p.slug))} />{p.slug}</label>
{/each}
</div>
<div class="row wrap">
<label class="row"><input type="checkbox" bind:checked={s.flags.notes} /> заметки</label>
<label class="row"><input type="checkbox" bind:checked={s.flags.extraTools} /> доп. тулы</label>
<label class="row"><input type="checkbox" bind:checked={s.flags.cheating} /> читерство</label>
<span class="spacer"></span>
<span class="mono muted">следующий: {s.nextRunAt ? new Date(s.nextRunAt).toLocaleString('ru-RU') : '—'}</span>
<button class="btn sm primary" onclick={() => saveSched(s)}>Сохранить</button>
<button class="btn sm danger" onclick={() => delSched(s)}>Удалить</button>
</div>
</div>
{/each}
</div>
</div>
<div class="grid2">
<div class="panel">
<div class="panel-head">Разовый матч с прогнозами</div>
<div class="panel-body stack">
<div class="row wrap">
<select class="select" bind:value={one.white}>{#each ai as p}<option value={p.slug}>{p.slug}</option>{/each}</select>
<span class="display">vs</span>
<select class="select" bind:value={one.black}>{#each ai as p}<option value={p.slug}>{p.slug}</option>{/each}</select>
</div>
<label class="field"><span>старт</span><input class="input" type="datetime-local" bind:value={one.at} /></label>
<button class="btn primary" onclick={createOne}>Анонсировать</button>
</div>
</div>
<div class="panel">
<div class="panel-head">Перегенерировать постгейм</div>
<div class="panel-body stack">
<input class="input" placeholder="id партии" bind:value={redoId} />
<div class="row wrap">
<button class="btn sm" onclick={() => redo(['thumbnail'])}>превью</button>
<button class="btn sm" onclick={() => redo(['review', 'thumbnail'])}>обзор + превью</button>
<button class="btn sm" onclick={() => redo(['interviews', 'review', 'thumbnail'])}>всё</button>
</div>
</div>
</div>
</div>
</section>
{/if}
<style>
.title {
font-size: 44px;
}
.who {
display: inline-flex;
align-items: center;
gap: 8px;
font-weight: 600;
}
.sched {
display: grid;
gap: 8px;
padding: 12px;
border: var(--border-thin);
border-radius: var(--radius);
}
.wrap {
flex-wrap: wrap;
font-size: 13px;
}
.input.name {
max-width: 240px;
}
.input.n {
width: 80px;
padding: 6px;
}
.poolp {
display: inline-flex;
gap: 4px;
align-items: center;
font-family: var(--f-mono);
font-size: 11px;
}
.grid2 {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 16px;
}
.grid2 .select {
max-width: 200px;
}
@media (max-width: 800px) {
.grid2 {
grid-template-columns: 1fr;
}
}
</style>
+62
View File
@@ -0,0 +1,62 @@
<script lang="ts">
import { page } from '$app/state';
import { api } from '#lib/api.ts';
import { session } from '#lib/session.svelte.ts';
import type { GameSummary } from '#lib/types.ts';
import GameCard from '#lib/components/GameCard.svelte';
let games = $state<GameSummary[]>([]);
let done = $state(false);
let loading = $state(false);
const player = $derived(page.url.searchParams.get('player') ?? '');
async function more(reset = false) {
if (loading) return;
loading = true;
const before = reset || !games.length ? '' : `&before=${encodeURIComponent(games.at(-1)!.createdAt)}`;
const r = await api.get<{ games: GameSummary[] }>(`/api/games?status=finished&limit=30${player ? `&player=${player}` : ''}${before}`);
games = reset ? r.games : [...games, ...r.games];
done = r.games.length < 30;
loading = false;
}
$effect(() => {
player;
more(true);
});
const allPlayers = $derived(session.meta?.aiPlayers ?? []);
</script>
<svelte:head><title>Архив · AI·CHESS</title></svelte:head>
<section class="stack">
<div class="row head">
<h1 class="display title">Архив</h1>
<span class="spacer"></span>
<select class="select filter" value={player} onchange={(e) => (location.search = (e.target as HTMLSelectElement).value ? `?player=${(e.target as HTMLSelectElement).value}` : '')}>
<option value="">все игроки</option>
{#each allPlayers as p}<option value={p.id}>{p.displayName} · {p.variant}</option>{/each}
</select>
</div>
<div class="grid">
{#each games as g (g.id)}<GameCard {g} />{/each}
</div>
{#if !games.length && !loading}<div class="empty">Пусто.</div>{/if}
{#if !done}<button class="btn more" onclick={() => more()} disabled={loading}>{loading ? '…' : 'Ещё'}</button>{/if}
</section>
<style>
.title {
font-size: 44px;
}
.filter {
max-width: 280px;
}
.grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
gap: 22px 18px;
}
.more {
justify-self: center;
}
</style>
@@ -0,0 +1,270 @@
<script lang="ts">
import { api } from '#lib/api.ts';
import type { LeaderRow } from '#lib/types.ts';
import { fmtUsd, fmtTokens } from '#lib/fmt.ts';
import Avatar from '#lib/components/Avatar.svelte';
import PlayerName from '#lib/components/PlayerName.svelte';
let tab = $state<'rating' | 'price' | 'h2h' | 'predictors'>('rating');
let rows = $state<LeaderRow[]>([]);
let h2h = $state<{ white_id: string; black_id: string; result: string; n: number }[]>([]);
let predictors = $state<any[]>([]);
$effect(() => {
api.get<{ players: LeaderRow[] }>('/api/leaderboard').then((r) => (rows = r.players));
api.get<{ rows: any[] }>('/api/stats/h2h').then((r) => (h2h = r.rows));
api.get<{ rows: any[] }>('/api/stats/predictors').then((r) => (predictors = r.rows));
});
const played = $derived(rows.filter((r) => r.games > 0));
const unplayed = $derived(rows.filter((r) => r.games === 0));
// ---- price vs elo
const priced = $derived(played.filter((r) => r.kind === 'ai' && r.costPerGame != null && r.costPerGame > 0));
const W = 760;
const H = 380;
const PAD = 50;
const xMin = $derived(Math.log10(Math.max(0.001, Math.min(...priced.map((r) => r.costPerGame!)) * 0.6)));
const xMax = $derived(Math.log10(Math.max(...priced.map((r) => r.costPerGame!), 0.01) * 1.6));
const yMin = $derived(Math.min(...priced.map((r) => r.rating), 1400) - 40);
const yMax = $derived(Math.max(...priced.map((r) => r.rating), 1600) + 40);
const px = (c: number) => PAD + ((Math.log10(c) - xMin) / Math.max(0.0001, xMax - xMin)) * (W - PAD * 2);
const py = (r: number) => H - PAD - ((r - yMin) / Math.max(1, yMax - yMin)) * (H - PAD * 2);
const value = $derived([...priced].sort((a, b) => (b.rating - 1000) / b.costPerGame! - (a.rating - 1000) / a.costPerGame!));
// ---- head to head: score of row-player against column-player
const ids = $derived(played.map((r) => r.id));
const cell = $derived.by(() => {
const m = new Map<string, { w: number; d: number; l: number }>();
const add = (a: string, b: string, k: 'w' | 'd' | 'l', n: number) => {
const key = `${a}|${b}`;
const c = m.get(key) ?? { w: 0, d: 0, l: 0 };
c[k] += n;
m.set(key, c);
};
for (const r of h2h) {
if (r.result === '1-0') {
add(r.white_id, r.black_id, 'w', r.n);
add(r.black_id, r.white_id, 'l', r.n);
} else if (r.result === '0-1') {
add(r.white_id, r.black_id, 'l', r.n);
add(r.black_id, r.white_id, 'w', r.n);
} else {
add(r.white_id, r.black_id, 'd', r.n);
add(r.black_id, r.white_id, 'd', r.n);
}
}
return m;
});
const score = (c: { w: number; d: number; l: number }) => (c.w + c.d / 2) / Math.max(1, c.w + c.d + c.l);
</script>
<svelte:head><title>Таблица · AI·CHESS</title></svelte:head>
<section class="stack">
<h1 class="display title">Таблица</h1>
<div class="tabs">
<button class:on={tab === 'rating'} onclick={() => (tab = 'rating')}>Рейтинг</button>
<button class:on={tab === 'price'} onclick={() => (tab = 'price')}>Сколько стоит рейтинг</button>
<button class:on={tab === 'h2h'} onclick={() => (tab = 'h2h')}>Личные встречи</button>
<button class:on={tab === 'predictors'} onclick={() => (tab = 'predictors')}>Прогнозисты</button>
</div>
{#if tab === 'rating'}
<div class="panel">
<table class="table">
<thead><tr><th>#</th><th>Игрок</th><th class="num">Рейтинг</th><th class="num">Партии</th><th class="num">В / Н / П</th><th class="num">Точность</th><th class="num">$ за партию</th></tr></thead>
<tbody>
{#each played as r, i (r.id)}
<tr>
<td class="display n">{i + 1}</td>
<td><a class="who" href="/games?player={r.id}"><Avatar player={r} size={30} /><PlayerName player={r} /></a></td>
<td class="num"><b class="display big">{r.rating}</b> <small class="muted">±{2 * r.rd}</small></td>
<td class="num">{r.games}</td>
<td class="num mono">{r.wins} / {r.draws} / {r.losses}</td>
<td class="num">{r.avgAccuracy != null ? r.avgAccuracy.toFixed(1) + '%' : '—'}</td>
<td class="num">{r.kind === 'ai' ? fmtUsd(r.costPerGame) : '—'}</td>
</tr>
{/each}
</tbody>
</table>
{#if unplayed.length}
<p class="panel-body muted">Ещё не играли: {unplayed.map((r) => `${r.displayName} ${r.variant ?? ''}`).join(', ')}</p>
{/if}
</div>
<p class="muted small">Рейтинг — Glicko-2, ± — неуверенность (2σ). Читерские партии в рейтинг не идут. Люди и модели — в одной таблице.</p>
{:else if tab === 'price'}
<div class="panel">
<div class="panel-head">Рейтинг против цены партии <span class="spacer"></span><small>ось X — логарифм $ за партию</small></div>
{#if priced.length}
<svg viewBox="0 0 {W} {H}" class="scatter">
<line x1={PAD} x2={W - PAD} y1={H - PAD} y2={H - PAD} class="axis" />
<line x1={PAD} x2={PAD} y1={PAD / 2} y2={H - PAD} class="axis" />
<text x={W / 2} y={H - 12} class="lbl" text-anchor="middle">$ за партию →</text>
<text x={14} y={H / 2} class="lbl" transform="rotate(-90 14 {H / 2})" text-anchor="middle">рейтинг →</text>
{#each priced as r (r.id)}
<g transform="translate({px(r.costPerGame!)} {py(r.rating)})">
<circle r="9" fill={r.color ?? 'var(--accent)'} class="dot" />
<text x="13" y="4" class="name">{r.displayName.replace('Claude ', '')} {r.variant?.toUpperCase()} · {fmtUsd(r.costPerGame)}</text>
</g>
{/each}
</svg>
{:else}
<div class="empty">Нужны сыгранные партии моделей.</div>
{/if}
</div>
<div class="panel">
<div class="panel-head">Выгоднее всего <span class="spacer"></span><small>очков рейтинга сверх 1000 за $1 партии</small></div>
<table class="table">
<tbody>
{#each value as r, i (r.id)}
<tr>
<td class="display n">{i + 1}</td>
<td><span class="who"><Avatar player={r} size={26} /><PlayerName player={r} /></span></td>
<td class="num mono">{fmtUsd(r.costPerGame)} · {fmtTokens(r.tokensPerGame ?? 0)} ток.</td>
<td class="num"><b class="display big">{Math.round((r.rating - 1000) / r.costPerGame!)}</b> <small class="muted">эло/$</small></td>
</tr>
{/each}
</tbody>
</table>
</div>
{:else if tab === 'h2h'}
<div class="panel h2h-wrap">
<div class="panel-head">Кто кого <span class="spacer"></span><small>строка против столбца · % набранных очков</small></div>
{#if h2h.length}
<div class="h2h" style:--n={ids.length}>
<span></span>
{#each played as c (c.id)}<span class="colh" title={c.displayName}><Avatar player={c} size={26} /><small>{c.variant ?? ''}</small></span>{/each}
{#each played as r (r.id)}
<span class="rowh"><Avatar player={r} size={26} /><PlayerName player={r} short /></span>
{#each played as c (c.id)}
{@const v = cell.get(`${r.id}|${c.id}`)}
{#if r.id === c.id}
<span class="c self"></span>
{:else if v}
<span class="c" style:--s={score(v)} title="{r.displayName} против {c.displayName}: {v.w}В {v.d}Н {v.l}П">
<b>{Math.round(score(v) * 100)}</b><small>{v.w}-{v.d}-{v.l}</small>
</span>
{:else}
<span class="c none">·</span>
{/if}
{/each}
{/each}
</div>
{:else}
<div class="empty">Пока никто ни с кем не играл.</div>
{/if}
</div>
{:else}
<div class="panel">
<div class="panel-head">Лучшие прогнозисты <span class="spacer"></span><small>10 очков за угаданный исход матча по расписанию</small></div>
<table class="table">
<tbody>
{#each predictors as p, i (p.id)}
<tr>
<td class="display n">{i + 1}</td>
<td><span class="who"><Avatar player={{ avatarUrl: p.avatarUrl, displayName: p.display_name, color: null, kind: 'human', family: null }} size={26} />{p.display_name}</span></td>
<td class="num mono">{p.correct}/{p.picks} угадано</td>
<td class="num"><b class="display big">{p.points}</b></td>
</tr>
{:else}
<tr><td class="empty">Прогнозов пока нет — они открываются за полчаса до матчей по расписанию.</td></tr>
{/each}
</tbody>
</table>
</div>
{/if}
</section>
<style>
.title {
font-size: 44px;
}
.n {
width: 40px;
font-size: 22px;
color: var(--accent-text, var(--accent));
}
.who {
display: inline-flex;
align-items: center;
gap: 10px;
font-weight: 600;
}
.big {
font-size: 22px;
}
.small {
font-size: 12px;
}
.scatter {
width: 100%;
display: block;
}
.axis {
stroke: var(--muted);
stroke-width: 1.5;
}
.lbl {
fill: var(--muted);
font-size: 12px;
font-family: var(--f-label);
text-transform: uppercase;
}
.dot {
stroke: var(--text);
stroke-width: 2;
}
.name {
fill: var(--text);
font-size: 12px;
font-family: var(--f-mono);
}
.h2h-wrap {
overflow-x: auto;
}
.h2h {
display: grid;
grid-template-columns: 180px repeat(var(--n), minmax(54px, 1fr));
gap: 3px;
padding: 12px;
min-width: max-content;
}
.colh {
display: grid;
justify-items: center;
gap: 2px;
font-size: 9px;
text-transform: uppercase;
}
.rowh {
display: flex;
align-items: center;
gap: 8px;
font-size: 12px;
font-weight: 600;
}
.c {
display: grid;
place-items: center;
aspect-ratio: 1;
border-radius: var(--radius);
background: color-mix(in srgb, var(--ok) calc(var(--s) * 100%), var(--danger));
color: #fff;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
}
.c b {
font-size: 15px;
line-height: 1;
}
.c small {
font-size: 9px;
opacity: 0.85;
}
.c.self {
background: repeating-linear-gradient(45deg, var(--surface-3) 0 4px, transparent 4px 8px);
}
.c.none {
background: var(--surface-2);
color: var(--muted);
text-shadow: none;
}
</style>
+57
View File
@@ -0,0 +1,57 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { api } from '#lib/api.ts';
import { live } from '#lib/ws.ts';
import type { HomeData } from '#lib/types.ts';
import LiveCard from '#lib/components/LiveCard.svelte';
import Countdown from '#lib/components/Countdown.svelte';
let home = $state<HomeData | null>(null);
async function load() {
home = await api.get<HomeData>('/api/home');
// only one game on air — go straight to it
if (home.live.length === 1) goto(`/match/${home.live[0].id}`, { replaceState: true });
}
$effect(() => {
load();
return live.subscribe('lobby', () => load());
});
</script>
<svelte:head><title>Live · AI·CHESS</title></svelte:head>
<section class="stack">
<h1 class="display title">В эфире</h1>
{#if !home}
<div class="empty">…</div>
{:else if home.live.length > 1}
{#each home.live as g (g.id)}<LiveCard {g} />{/each}
{:else if !home.live.length}
<div class="panel"><div class="panel-body empty">Сейчас никто не играет.</div></div>
{/if}
{#if home?.upcoming.length}
<h2 class="display sub">Скоро</h2>
{#each home.upcoming as g (g.id)}
<div class="row upcoming">
<LiveCard {g} compact />
{#if g.startsAt}<Countdown to={g.startsAt} />{/if}
</div>
{/each}
{/if}
</section>
<style>
.title {
font-size: 44px;
}
.sub {
font-size: 26px;
margin-top: 12px;
}
.upcoming {
align-items: stretch;
}
.upcoming :global(.lc) {
flex: 1;
}
</style>
+61
View File
@@ -0,0 +1,61 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { page } from '$app/state';
import { session } from '#lib/session.svelte.ts';
let mode = $state<'login' | 'register'>(page.url.searchParams.get('mode') === 'register' ? 'register' : 'login');
let username = $state('');
let password = $state('');
let err = $state<string | null>(null);
let busy = $state(false);
async function submit(e: Event) {
e.preventDefault();
busy = true;
err = null;
try {
const u = mode === 'login' ? await session.login(username, password) : await session.register(username, password);
goto(u.onboarded ? '/' : '/onboarding');
} catch (e) {
err = (e as Error).message;
} finally {
busy = false;
}
}
</script>
<svelte:head><title>Вход · AI·CHESS</title></svelte:head>
<div class="auth panel">
<div class="tabs">
<button class:on={mode === 'login'} onclick={() => (mode = 'login')}>Вход</button>
<button class:on={mode === 'register'} onclick={() => (mode = 'register')}>Регистрация</button>
</div>
<form class="panel-body stack" onsubmit={submit}>
<h1 class="display">{mode === 'login' ? 'С возвращением' : 'Добро пожаловать на арену'}</h1>
<p class="muted">{mode === 'login' ? 'Смотреть можно и без входа. Чтобы устраивать матчи, играть и голосовать — войди.' : 'Регистрация открыта. Дальше — аватарка и тема оформления.'}</p>
<label class="field"><span>логин</span><input class="input" autocomplete="username" bind:value={username} required minlength="3" maxlength="24" /></label>
<label class="field"><span>пароль</span><input class="input" type="password" autocomplete={mode === 'login' ? 'current-password' : 'new-password'} bind:value={password} required minlength="6" /></label>
{#if err}<div class="error-box">{err}</div>{/if}
<button class="btn primary lg" disabled={busy}>{mode === 'login' ? 'Войти' : 'Создать аккаунт'}</button>
</form>
</div>
<style>
.auth {
max-width: 460px;
margin: 40px auto;
}
.auth .tabs {
border: 0;
border-bottom: var(--border);
border-radius: var(--radius) var(--radius) 0 0;
}
h1 {
font-size: 34px;
}
form {
padding: 22px;
--gap: 16px;
}
</style>
+623
View File
@@ -0,0 +1,623 @@
<script lang="ts">
import { page } from '$app/state';
import { Chess } from 'chess.js';
import { GameState, otherSide, type Side } from '@aichess/core';
import { GameView } from '#lib/game.svelte.ts';
import { session } from '#lib/session.svelte.ts';
import { api } from '#lib/api.ts';
import { TERMINATION_RU, resultFor, resultLabel, fmtUsd, fmtTokens, moveNo, evalLabel, playerTitle } from '#lib/fmt.ts';
import Board from '#lib/components/Board.svelte';
import EvalBar from '#lib/components/EvalBar.svelte';
import EvalGraph from '#lib/components/EvalGraph.svelte';
import PlayerCard from '#lib/components/PlayerCard.svelte';
import MoveList from '#lib/components/MoveList.svelte';
import TalkFeed from '#lib/components/TalkFeed.svelte';
import Predictions from '#lib/components/Predictions.svelte';
import Countdown from '#lib/components/Countdown.svelte';
import Avatar from '#lib/components/Avatar.svelte';
import PlayerName from '#lib/components/PlayerName.svelte';
const view = $derived(new GameView(page.params.id!));
$effect(() => {
const v = view;
v.start();
return () => v.stop();
});
const g = $derived(view.game);
let current = $state(0);
let follow = $state(true); // stick to the latest move while live
$effect(() => {
const n = view.moves.length;
if (follow) current = n;
});
function go(n: number) {
current = Math.max(0, Math.min(view.moves.length, n));
follow = current === view.moves.length;
}
function key(e: KeyboardEvent) {
if ((e.target as HTMLElement)?.closest('input,textarea')) return;
if (e.key === 'ArrowLeft') go(current - 1);
if (e.key === 'ArrowRight') go(current + 1);
if (e.key === 'Home') go(0);
if (e.key === 'End') go(view.moves.length);
if (e.key === 'f') flipped = !flipped;
}
// ---- me as a participant
const mySide = $derived.by<Side | null>(() => {
if (!g || !session.user?.playerId) return null;
if (g.white.id === session.user.playerId) return 'white';
if (g.black.id === session.user.playerId) return 'black';
return null;
});
let flipped = $state(false);
$effect(() => {
if (mySide === 'black') flipped = true;
});
const orientation = $derived<'white' | 'black'>(flipped ? 'black' : 'white');
const top = $derived<Side>(orientation === 'white' ? 'black' : 'white');
const bottom = $derived<Side>(otherSide(top));
let showBest = $state(typeof localStorage !== 'undefined' ? localStorage.getItem('aichess-best') !== '0' : true);
$effect(() => localStorage.setItem('aichess-best', showBest ? '1' : '0'));
const pos = $derived(view.positions[Math.min(current, view.positions.length - 1)] ?? view.positions[0]);
const atLive = $derived(current === view.moves.length);
const shownMove = $derived(current > 0 ? view.moves[current - 1] : null);
const shownEval = $derived(shownMove?.eval ?? null);
const arrow = $derived.by<[string, string] | null>(() => {
if (!showBest || !shownEval?.bestUci) return null;
if (g?.status === 'running' && atLive && mySide && view.sideToMove === mySide) return null; // no hints for humans
return [shownEval.bestUci.slice(0, 2), shownEval.bestUci.slice(2, 4)];
});
// ---- human move input
const myTurn = $derived(!!mySide && g?.status === 'running' && view.sideToMove === mySide && atLive);
const dests = $derived.by(() => {
if (!myTurn) return null;
const c = new Chess(g!.fen);
const m = new Map<string, string[]>();
for (const mv of c.moves({ verbose: true })) m.set(mv.from, [...(m.get(mv.from) ?? []), mv.to]);
return { color: mySide!, dests: m };
});
let phrase = $state('');
let offerDraw = $state(false);
let moveErr = $state<string | null>(null);
async function humanMove(from: string, to: string) {
moveErr = null;
const piece = new Chess(g!.fen).get(from as any);
const promo = piece?.type === 'p' && (to[1] === '8' || to[1] === '1') ? 'q' : '';
try {
await api.post(`/api/games/${view.id}/move`, { move: from + to + promo, phrase: phrase.trim() || undefined, offerDraw });
phrase = '';
offerDraw = false;
} catch (e) {
moveErr = (e as Error).message;
view.load();
}
}
async function resign() {
if (!confirm('Точно сдаёшься?')) return;
await api.post(`/api/games/${view.id}/resign`, { phrase: phrase.trim() || undefined });
}
async function acceptDraw() {
await api.post(`/api/games/${view.id}/accept-draw`);
}
async function abort() {
if (!confirm('Прервать партию? Она не пойдёт в рейтинг.')) return;
await api.post(`/api/games/${view.id}/abort`);
}
// ---- what the agent sees (rule state at the live position)
const ruleNotes = $derived.by(() => {
if (!g || g.status !== 'running') return [] as string[];
const st: GameState = view.state;
const side = st.turn;
const out: string[] = [];
const castle = st.castlingNotes(side);
out.push(castle.length ? castle.map((c) => c.split(':')[0]).join(' · ') : 'рокировки не актуальны');
out.push(`50 ходов: ${Math.floor(st.halfmoveClock() / 2)}/50`);
const rep = st.repetitionInfo();
out.push(rep.drawingMoves.length ? `⚠ ходы на повторение: ${rep.drawingMoves.join(', ')}` : `повторений: ${rep.currentCount - 1}`);
if (st.enPassantNote()) out.push('взятие на проходе доступно');
return out;
});
const repetitionHot = $derived(ruleNotes.some((n) => n.startsWith('⚠')));
const statsW = $derived(view.moves.length || g ? view.stats('white') : null);
const statsB = $derived(view.moves.length || g ? view.stats('black') : null);
const humanSides = $derived(g ? (['white', 'black'] as Side[]).filter((s) => view.player(s).kind === 'human') : []);
const canAbort = $derived(!!g && (g.status === 'running' || g.status === 'pending') && (session.user?.isAdmin || g.createdBy === session.user?.id));
let tab = $state<'moves' | 'talk' | 'graph' | 'more'>('moves');
const personaLabel = (id: string | null) => session.meta?.personas.find((p) => p.id === id)?.label ?? null;
</script>
<svelte:window onkeydown={key} />
<svelte:head><title>{g ? `${g.status === 'running' ? 'LIVE · ' : ''}${playerTitle(g.white)} — ${playerTitle(g.black)} · AI·CHESS` : 'AI·CHESS'}</title></svelte:head>
{#if view.error}
<div class="error-box">{view.error}</div>
{:else if !g}
<div class="empty">Загружаю партию…</div>
{:else}
<div class="match" class:over={view.finished}>
<!-- ───── lead ───── -->
<section class="lead">
<div class="lead-text">
<div class="tags">
{#if g.status === 'running'}
<span class="tag hot"><span class="live-dot" style="background:currentColor"></span> live</span>
<span class="tag">ход {Math.ceil((view.moves.length + 1) / 2)} · {view.sideToMove === 'white' ? 'белые' : 'чёрные'} {view.player(view.sideToMove).kind === 'human' ? 'ходят' : 'думают'}</span>
{:else if g.status === 'pending'}
<span class="tag warn">анонс</span>
{:else}
<span class="tag hot">итог {resultLabel(g.result)}</span>
{#if g.termination}<span class="tag">{TERMINATION_RU[g.termination]}</span>{/if}
{/if}
{#if g.scheduled}<span class="tag flat">по расписанию</span>{/if}
{#if g.flags.notes}<span class="tag flat">✎ заметки себе</span>{/if}
{#if g.flags.extraTools}<span class="tag flat">⚙ доп. тулы</span>{/if}
{#if g.flags.cheating}<span class="tag danger">☠ читерство · без рейтинга</span>{:else}<span class="tag flat">рейтинговая</span>{/if}
</div>
<h1 class="display headline">
{#if view.finished && g.thumbnailCaption}{g.thumbnailCaption}{:else}<PlayerName player={g.white} /> <span class="vs">vs</span> <PlayerName player={g.black} />{/if}
</h1>
{#if g.status === 'pending' && g.startsAt}
<div class="row"><span class="label">до старта</span><Countdown to={g.startsAt} /></div>
{/if}
{#if g.error && g.status === 'aborted'}<p class="muted mono">{g.error}</p>{/if}
</div>
{#if view.finished && g.thumbnailUrl}
<a class="lead-thumb" href={g.thumbnailUrl} target="_blank" rel="noreferrer"><img src={g.thumbnailUrl} alt={g.thumbnailCaption ?? ''} /></a>
{/if}
</section>
<div class="grid">
<!-- ───── left ───── -->
<aside class="col-left">
{#each [top, bottom] as s (s)}
{@const st = s === 'white' ? statsW : statsB}
<PlayerCard
player={view.player(s)}
side={s}
persona={personaLabel(g.personas[s])}
accuracy={st?.accuracy ?? null}
cost={st?.cost ?? 0}
tokens={st?.tokens ?? 0}
thinkingSince={g.status === 'running' && view.sideToMove === s ? (view.turn?.startedAt ?? (view.player(s).kind === 'human' ? Date.parse(view.moves.at(-1)?.createdAt ?? g.startedAt ?? '') || null : null)) : null}
result={view.finished ? resultFor(s, g.result) : null}
ratingDelta={g.ratingChange ? g.ratingChange[s].after - g.ratingChange[s].before : null}
cls={view.finished ? (st?.cls ?? null) : null}
/>
{/each}
<div class="panel talk" class:on={tab === 'talk'}>
<div class="panel-head hot">Трэш-ток <span class="spacer"></span><small>реплики сопернику</small></div>
<TalkFeed moves={view.moves} white={g.white} black={g.black} {current} lastWords={g.lastWords} onpick={go} />
</div>
</aside>
<!-- ───── center ───── -->
<section class="col-board">
{#if g.status === 'running' && atLive}
<div class="notes mono" class:hot={repetitionHot}><span class="label">агент видит:</span> {ruleNotes.join(' · ')}</div>
{:else if !atLive}
<div class="notes mono">
<span class="label">просмотр:</span>
{shownMove ? `${moveNo(current)} ${shownMove.san ?? shownMove.uci} · ${evalLabel(shownEval)}` : 'начальная позиция'}
<button class="btn sm" onclick={() => go(view.moves.length)}>→ к последнему</button>
</div>
{:else if view.finished}
<div class="notes mono done">
<b>{resultLabel(g.result)}</b> · {g.termination ? TERMINATION_RU[g.termination] : ''}
</div>
{/if}
<div class="board-row">
<EvalBar ev={shownEval} {orientation} />
<Board fen={pos.fen} lastMove={pos.lastMove} check={pos.check} {orientation} {arrow} movable={dests} onmove={humanMove} />
</div>
<div class="controls">
<div class="nav">
<button onclick={() => go(0)} title="В начало (Home)">⏮</button>
<button onclick={() => go(current - 1)} title="Назад (←)">◀</button>
<span class="pos mono">{current > 0 ? `${moveNo(current)} ${shownMove?.san ?? shownMove?.uci}` : 'старт'} <i>/ {view.moves.length}</i></span>
<button onclick={() => go(current + 1)} title="Вперёд (→)">▶</button>
<button onclick={() => go(view.moves.length)} title="В конец (End)">⏭</button>
</div>
<div class="row">
<button class="btn sm" class:primary={showBest} onclick={() => (showBest = !showBest)}>→ лучший ход</button>
<button class="btn sm" onclick={() => (flipped = !flipped)}>⟲ перевернуть</button>
</div>
</div>
{#if mySide && g.status === 'running'}
<div class="panel play">
<div class="panel-head">{myTurn ? 'Твой ход' : 'Ход соперника'} <span class="spacer"></span><small>ты играешь {mySide === 'white' ? 'белыми' : 'чёрными'}</small></div>
<div class="panel-body stack">
<input class="input" placeholder="Реплика сопернику (уйдёт вместе со следующим ходом)" maxlength="400" bind:value={phrase} />
<div class="row wrap-row">
<label class="row"><input type="checkbox" bind:checked={offerDraw} /> предложить ничью с ходом</label>
<span class="spacer"></span>
{#if g.pendingDrawBy && g.pendingDrawBy !== mySide}<button class="btn sm secondary" onclick={acceptDraw}>Принять ничью</button>{/if}
<button class="btn sm danger" onclick={resign}>Сдаться</button>
</div>
{#if moveErr}<div class="error-box">{moveErr}</div>{/if}
</div>
</div>
{/if}
<div class="panel graph" class:on={tab === 'graph'}>
<div class="panel-head">Stockfish <span class="spacer"></span><small>шансы на победу, клик — к ходу</small></div>
<EvalGraph moves={view.moves} {current} onselect={go} />
</div>
</section>
<!-- ───── right ───── -->
<aside class="col-right">
<div class="panel moves" class:on={tab === 'moves'}>
<div class="panel-head">Ходы <span class="spacer"></span><small>!! блестяще · ?! неточность · ? ошибка · ?? зевок · 💭 мысли</small></div>
<MoveList gameId={view.id} moves={view.moves} {current} turn={view.turn} {humanSides} onselect={go} />
</div>
{#if g.scheduled}
<div class="panel more" class:on={tab === 'more'}>
<div class="panel-head">Прогноз трибун <span class="spacer"></span><small>{g.status === 'pending' ? 'приём открыт' : 'закрыт'}</small></div>
<div class="panel-body">
<Predictions gameId={view.id} open={g.status === 'pending'} white={g.white} black={g.black} counts={view.predictions.counts} mine={view.predictions.mine} onchange={() => view.load()} />
</div>
</div>
{/if}
<div class="panel more cost" class:on={tab === 'more'}>
<div class="panel-head">Счётчик <span class="spacer"></span><small>токены и $ за партию</small></div>
<div class="panel-body costs">
{#each [{ s: 'white' as Side, st: statsW }, { s: 'black' as Side, st: statsB }] as r}
{#if view.player(r.s).kind === 'ai'}
<div class="cost-row">
<Avatar player={view.player(r.s)} size={22} />
<span class="cn">{view.player(r.s).displayName}</span>
<span class="mono muted">{fmtTokens(r.st?.tokens ?? 0)}</span>
<b class="display">{fmtUsd(r.st?.cost ?? 0)}</b>
</div>
{/if}
{/each}
<div class="cost-total"><span class="label">итого</span><b class="display">{fmtUsd((statsW?.cost ?? 0) + (statsB?.cost ?? 0))}</b></div>
{#if canAbort}<button class="btn sm ghost abort" onclick={abort}>прервать партию</button>{/if}
<a class="btn sm ghost" href="/api/games/{view.id}/pgn">скачать PGN</a>
</div>
</div>
</aside>
</div>
<!-- mobile tabs -->
<div class="tabs mtabs">
{#each [['moves', 'Ходы'], ['talk', 'Трэш-ток'], ['graph', 'График'], ['more', 'Ещё']] as [k, l]}
<button class:on={tab === k} onclick={() => (tab = k as typeof tab)}>{l}</button>
{/each}
</div>
{#if view.finished && (g.interviews.white || g.interviews.black || g.status === 'finished')}
<section class="presser">
<div class="panel-head hot">Пресс-конференция <span class="spacer"></span><small>сразу после партии · без подготовки</small></div>
<div class="iv-grid panel">
{#each ['white', 'black'] as const as s}
{@const p = view.player(s)}
{#if p.kind === 'ai'}
<article class="iv">
<div class="iv-head">
<Avatar player={p} size={64} />
<div>
<div class="display iv-name"><PlayerName player={p} /></div>
<div class="label accent">🎤 {resultFor(s, g.result) === 'win' ? 'победитель' : resultFor(s, g.result) === 'loss' ? 'проигравший' : 'ничья'}</div>
</div>
</div>
{#if g.interviews[s]}
<blockquote class="quote">{g.interviews[s]}</blockquote>
{:else}
<p class="muted">Журналисты ещё ловят спикера у выхода… (интервью генерируется)</p>
{/if}
</article>
{/if}
{/each}
</div>
</section>
{/if}
</div>
{/if}
<style>
.match {
display: grid;
gap: 14px;
}
.lead {
display: grid;
grid-template-columns: 1fr;
gap: 20px;
align-items: end;
border-bottom: var(--border);
padding-bottom: 12px;
}
.over .lead:has(.lead-thumb) {
grid-template-columns: 1fr 320px;
align-items: center;
}
.tags {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 10px;
}
.headline {
font-size: clamp(28px, 3.4vw, 50px);
line-height: 1;
}
.headline :global(.chip) {
font-size: 12px;
vertical-align: middle;
}
.vs {
color: var(--accent-text, var(--accent));
font-size: 0.7em;
}
.lead-thumb img {
display: block;
border: var(--border);
box-shadow: var(--shadow);
border-radius: var(--radius);
}
.grid {
display: grid;
grid-template-columns: 300px minmax(0, 1fr) 400px;
gap: 18px;
align-items: start;
}
.col-left,
.col-right,
.col-board {
display: grid;
gap: 14px;
min-width: 0;
}
.col-board {
--bw: min(100%, 560px);
justify-items: center;
}
.board-row {
display: grid;
grid-template-columns: 22px minmax(0, 1fr);
gap: 10px;
width: var(--bw);
}
.notes,
.controls,
.play,
.graph {
width: var(--bw);
}
.notes {
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
padding: 6px 10px;
font-size: 12px;
background: var(--surface);
border: var(--border);
border-radius: var(--radius);
}
.notes .label {
color: var(--accent-text, var(--accent));
}
.notes.hot {
background: var(--warn);
color: #111;
}
.notes.done {
background: var(--text);
color: var(--bg);
}
.notes .btn {
margin-left: auto;
}
.controls {
display: flex;
justify-content: space-between;
gap: 10px;
flex-wrap: wrap;
}
.nav {
display: inline-flex;
border: var(--border);
border-radius: var(--radius);
background: var(--surface);
overflow: hidden;
}
.nav button {
padding: 6px 12px;
border-right: var(--border-thin);
}
.nav button:hover {
background: var(--text);
color: var(--bg);
}
.nav .pos {
padding: 6px 12px;
border-right: var(--border-thin);
font-size: 12px;
font-weight: 600;
min-width: 120px;
text-align: center;
}
.nav .pos i {
font-style: normal;
opacity: 0.5;
}
.nav button:last-child {
border-right: 0;
}
.wrap-row {
flex-wrap: wrap;
font-size: 13px;
}
.moves :global(.moves) {
--moves-max-h: 520px;
}
.costs {
display: grid;
gap: 8px;
}
.cost-row {
display: grid;
grid-template-columns: auto 1fr auto auto;
gap: 10px;
align-items: center;
font-size: 13px;
}
.cost-row b {
font-size: 20px;
}
.cn {
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.cost-total {
display: flex;
justify-content: space-between;
align-items: baseline;
border-top: var(--border);
padding-top: 6px;
}
.cost-total b {
font-size: 26px;
}
.mtabs {
display: none;
}
.presser {
margin-top: 8px;
}
.iv-grid {
display: grid;
grid-template-columns: 1fr 1fr;
border-top: 0;
border-radius: 0 0 var(--radius) var(--radius);
}
.iv {
padding: 20px 24px;
display: grid;
gap: 14px;
align-content: start;
}
.iv + .iv {
border-left: var(--border);
}
.iv-head {
display: flex;
gap: 14px;
align-items: center;
}
.iv-name {
font-size: 24px;
margin-bottom: 4px;
}
blockquote {
margin: 0;
font-size: 18px;
line-height: 1.5;
white-space: pre-wrap;
}
blockquote::before {
content: '«';
font-family: var(--f-display);
font-size: 40px;
line-height: 0;
vertical-align: -12px;
margin-right: 4px;
color: var(--accent-text, var(--accent));
}
@media (max-width: 1200px) {
.grid {
grid-template-columns: 260px minmax(0, 1fr) 340px;
gap: 12px;
}
}
@media (max-width: 980px) {
.lead,
.over .lead:has(.lead-thumb) {
grid-template-columns: 1fr;
}
.grid,
.col-left,
.col-right,
.col-board {
display: contents;
}
.match {
grid-template-columns: minmax(0, 1fr);
}
.lead {
order: 0;
}
.notes {
order: 1;
}
.board-row {
order: 2;
}
.controls {
order: 3;
}
.play {
order: 4;
}
.col-left :global(.pcard) {
order: 5;
}
.mtabs {
display: flex;
order: 6;
position: sticky;
top: 0;
z-index: 5;
}
.panel.talk,
.panel.graph,
.panel.moves,
.panel.more {
display: none;
order: 7;
}
.panel.on {
display: block;
}
.presser {
order: 8;
}
.board-row,
.notes,
.controls,
.play,
.graph {
width: 100%;
}
.board-row {
grid-template-columns: 16px minmax(0, 1fr);
gap: 6px;
}
.iv-grid {
grid-template-columns: 1fr;
}
.iv + .iv {
border-left: 0;
border-top: var(--border);
}
.headline {
font-size: 26px;
}
}
</style>
+40
View File
@@ -0,0 +1,40 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { session } from '#lib/session.svelte.ts';
import ProfileForm from '#lib/components/ProfileForm.svelte';
let saved = $state(false);
$effect(() => {
if (session.loaded && !session.user) goto('/login');
});
</script>
<svelte:head><title>Профиль · AI·CHESS</title></svelte:head>
{#if session.user}
<div class="me">
<div class="row">
<h1 class="display">{session.user.displayName}</h1>
<span class="mono muted">@{session.user.username}{#if session.user.rating} · рейтинг {session.user.rating}{/if}</span>
<span class="spacer"></span>
{#if session.user.playerId}<a class="btn sm" href="/games?player={session.user.playerId}">мои партии</a>{/if}
<button class="btn sm danger" onclick={() => session.logout().then(() => goto('/'))}>Выйти</button>
</div>
<div class="panel"><div class="panel-body"><ProfileForm ondone={() => (saved = true)} /></div></div>
{#if saved}<p class="accent">Сохранено.</p>{/if}
</div>
{/if}
<style>
.me {
max-width: 820px;
margin: 20px auto;
display: grid;
gap: 16px;
}
h1 {
font-size: 38px;
}
.panel-body {
padding: 22px;
}
</style>
+242
View File
@@ -0,0 +1,242 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { api } from '#lib/api.ts';
import { session } from '#lib/session.svelte.ts';
import type { GameFlags, Player } from '#lib/types.ts';
import Avatar from '#lib/components/Avatar.svelte';
import PlayerName from '#lib/components/PlayerName.svelte';
type Seat = { who: string; persona: string };
let white = $state<Seat>({ who: 'opus-5.5-high', persona: 'gopnik' });
let black = $state<Seat>({ who: 'sol-6.1-high', persona: 'professor' });
let flags = $state<GameFlags>({ notes: false, extraTools: false, cheating: false });
let err = $state<string | null>(null);
let busy = $state(false);
$effect(() => {
if (session.loaded && !session.user) goto('/login');
});
const ai = $derived(session.meta?.aiPlayers ?? []);
const frontier = $derived(ai.filter((p) => !p.dumb));
const dumb = $derived(ai.filter((p) => p.dumb));
const personas = $derived(session.meta?.personas ?? []);
const byslug = (s: string) => ai.find((p) => p.slug === s);
const meTaken = $derived(white.who === 'me' || black.who === 'me');
function choose(seat: Seat, other: Seat, slug: string) {
if (slug === 'me' && other.who === 'me') other.who = frontier[0]?.slug ?? '';
seat.who = slug;
}
function swap() {
[white, black] = [black, white];
}
function random() {
const pool = [...ai];
const a = pool.splice(Math.floor(Math.random() * pool.length), 1)[0];
const b = pool[Math.floor(Math.random() * pool.length)];
const rp = () => personas[Math.floor(Math.random() * personas.length)]?.id ?? 'gopnik';
white = { who: a.slug, persona: rp() };
black = { who: b.slug, persona: rp() };
}
async function start() {
busy = true;
err = null;
try {
const r = await api.post<{ id: string }>('/api/games', {
white: white.who,
black: black.who,
personas: { white: white.who === 'me' ? null : white.persona, black: black.who === 'me' ? null : black.persona },
flags
});
goto(`/match/${r.id}`);
} catch (e) {
err = (e as Error).message;
} finally {
busy = false;
}
}
</script>
<svelte:head><title>Новый матч · AI·CHESS</title></svelte:head>
{#snippet seatPicker(label: string, side: 'white' | 'black', seat: Seat, other: Seat)}
<section class="panel seat side-{side}">
<div class="panel-head">{label}</div>
<div class="panel-body stack">
<button class="pick me" class:on={seat.who === 'me'} onclick={() => choose(seat, other, 'me')}>
{#if session.user}<Avatar player={{ avatarUrl: session.user.avatarUrl, displayName: session.user.displayName, color: null, kind: 'human', family: null }} size={34} />{/if}
<span><b>Я сам</b><small>играю на доске, могу писать реплики</small></span>
</button>
<div class="label muted">фронтир</div>
<div class="list">
{#each frontier as p (p.slug)}
<button class="pick" class:on={seat.who === p.slug} onclick={() => choose(seat, other, p.slug)}>
<Avatar player={p} size={30} />
<span class="pn"><PlayerName player={p} short /></span>
<span class="mono rt">{p.rating}</span>
</button>
{/each}
</div>
{#if dumb.length}
<div class="label muted">детский сад (для смеха)</div>
<div class="list">
{#each dumb as p (p.slug)}
<button class="pick" class:on={seat.who === p.slug} onclick={() => choose(seat, other, p.slug)}>
<Avatar player={p} size={30} />
<span class="pn"><PlayerName player={p} short /></span>
<span class="mono rt">{p.rating}</span>
</button>
{/each}
</div>
{/if}
{#if seat.who !== 'me'}
<label class="field">
<span>характер в трэш-токе</span>
<select class="select" bind:value={seat.persona}>
{#each personas as p}<option value={p.id}>{p.label} — {p.description}</option>{/each}
</select>
</label>
{/if}
</div>
</section>
{/snippet}
<div class="new stack">
<div class="row">
<h1 class="display">Новый матч</h1>
<span class="spacer"></span>
<button class="btn sm" onclick={swap}>⇄ поменять цвета</button>
<button class="btn sm" onclick={random}>🎲 случайно</button>
</div>
<div class="seats">
{@render seatPicker('Белые', 'white', white, black)}
<div class="vs display">VS</div>
{@render seatPicker('Чёрные', 'black', black, white)}
</div>
<section class="panel">
<div class="panel-head">Экспериментальные режимы</div>
<div class="panel-body flags">
{#each session.meta?.flags ?? [] as f}
<label class="flag" class:danger={!f.rated}>
<input type="checkbox" bind:checked={flags[f.key]} />
<span><b>{f.label}</b>{#if !f.rated}<span class="chip danger">без рейтинга</span>{/if}<small>{f.description}</small></span>
</label>
{/each}
</div>
</section>
{#if err}<div class="error-box">{err}</div>{/if}
<div class="row go">
<p class="muted summary">
{white.who === 'me' ? 'Ты' : byslug(white.who)?.displayName} ({white.who === 'me' ? 'белые' : byslug(white.who)?.variant}) против {black.who === 'me' ? 'тебя' : byslug(black.who)?.displayName} ({black.who === 'me' ? 'чёрные' : byslug(black.who)?.variant}).
{flags.cheating ? 'Партия не пойдёт в рейтинг.' : 'Рейтинговая партия.'}
{meTaken ? 'Время на ход не ограничено — думай сколько хочешь.' : ''}
</p>
<span class="spacer"></span>
<button class="btn primary lg" onclick={start} disabled={busy || white.who === black.who && white.who === 'me'}>В бой →</button>
</div>
</div>
<style>
h1 {
font-size: 44px;
}
.seats {
display: grid;
grid-template-columns: 1fr auto 1fr;
gap: 16px;
align-items: start;
}
.vs {
align-self: center;
font-size: 40px;
color: var(--accent-text, var(--accent));
}
.list {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 6px;
}
.pick {
display: flex;
align-items: center;
gap: 8px;
text-align: left;
padding: 7px 9px;
border: var(--border-thin);
border-radius: var(--radius);
background: var(--surface-2);
min-width: 0;
}
.pick:hover {
border-color: var(--accent);
}
.pick.on {
outline: 3px solid var(--accent);
outline-offset: -1px;
background: color-mix(in srgb, var(--accent) 15%, var(--surface-2));
}
.pick.me span {
display: grid;
}
.pick.me small {
font-size: 11px;
color: var(--muted);
}
.pn {
flex: 1;
min-width: 0;
font-weight: 600;
font-size: 13px;
}
.rt {
font-size: 11px;
color: var(--muted);
}
.flags {
display: grid;
grid-template-columns: repeat(3, 1fr);
gap: 12px;
}
.flag {
display: flex;
gap: 10px;
align-items: flex-start;
padding: 10px;
border: var(--border-thin);
border-radius: var(--radius);
cursor: pointer;
}
.flag span {
display: grid;
gap: 4px;
}
.flag small {
color: var(--muted);
font-size: 12px;
}
.flag.danger:has(input:checked) {
border-color: var(--danger);
background: color-mix(in srgb, var(--danger) 10%, transparent);
}
.go {
align-items: center;
}
.summary {
max-width: 70ch;
}
@media (max-width: 900px) {
.seats {
grid-template-columns: 1fr;
}
.flags {
grid-template-columns: 1fr;
}
.list {
grid-template-columns: 1fr;
}
}
</style>
@@ -0,0 +1,35 @@
<script lang="ts">
import { goto } from '$app/navigation';
import { session } from '#lib/session.svelte.ts';
import ProfileForm from '#lib/components/ProfileForm.svelte';
$effect(() => {
if (session.loaded && !session.user) goto('/login');
});
</script>
<svelte:head><title>Добро пожаловать · AI·CHESS</title></svelte:head>
{#if session.user}
<div class="panel ob">
<div class="panel-head hot">Регистрация на арене · шаг 2 из 2</div>
<div class="panel-body">
<h1 class="display">Как тебя показывать?</h1>
<ProfileForm submitLabel="На арену →" ondone={() => goto('/')} />
</div>
</div>
{/if}
<style>
.ob {
max-width: 820px;
margin: 30px auto;
}
.panel-body {
padding: 22px;
display: grid;
gap: 18px;
}
h1 {
font-size: 38px;
}
</style>
+1
View File
@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><rect width="32" height="32" rx="6" fill="#15120f"/><path d="M11 25h10l-1-3h-8zM12 21h8l-1.5-7c1.6-.8 2.5-2.3 2.5-4a4 4 0 1 0-8 0c0 1.7.9 3.2 2.5 4z" fill="#ffd41c"/></svg>

After

Width:  |  Height:  |  Size: 233 B

+8
View File
@@ -0,0 +1,8 @@
{
"extends": "$app/tsconfig",
"compilerOptions": {
"strict": true,
"allowImportingTsExtensions": true
},
"include": ["src", "vite.config.ts"]
}
+24
View File
@@ -0,0 +1,24 @@
import adapter from '@sveltejs/adapter-static';
import { sveltekit } from '@sveltejs/kit/vite';
import { defineConfig } from 'vite';
const backend = process.env.BACKEND_URL ?? 'http://localhost:7833';
export default defineConfig({
plugins: [
sveltekit({
compilerOptions: {
runes: ({ filename }) => (filename.split(/[/\\]/).includes('node_modules') ? undefined : true)
},
adapter: adapter({ fallback: 'index.html', strict: false })
})
],
server: {
proxy: {
'/api': backend,
'/media': backend,
'/assets': backend,
'/ws': { target: backend.replace(/^http/, 'ws'), ws: true }
}
}
});
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.0 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

+14
View File
@@ -0,0 +1,14 @@
{
"$comment": "pi models.json template. baseUrl/apiKey/headers are injected at runtime from LLM_BASE_URL / LLM_API_KEY. Overrides mirror what works against cli-proxy-api.",
"providers": {
"anthropic": {
"modelOverrides": {
"claude-opus-5-5": { "compat": { "supportsMidConvoToolChanges": false } },
"claude-fable-5-1": { "compat": { "allowedFallbackModels": [], "forceAdaptiveThinking": false, "supportsMidConvoEffort": false } }
}
},
"openai": {
"compat": { "supportsExplicitPromptCacheMode": false }
}
}
}
+18
View File
@@ -0,0 +1,18 @@
{
"$comment": "AI entities. Add a model or effort variant here — it is upserted by slug on startup. `active: false` hides it from pickers and schedules but keeps its history.",
"players": [
{ "slug": "opus-5.5-max", "displayName": "Claude Opus 5.5", "variant": "max", "family": "claude", "provider": "anthropic", "modelId": "claude-opus-5-5", "thinking": "max", "avatar": "avatars/claude.png", "color": "#D97757" },
{ "slug": "opus-5.5-high", "displayName": "Claude Opus 5.5", "variant": "high", "family": "claude", "provider": "anthropic", "modelId": "claude-opus-5-5", "thinking": "high", "avatar": "avatars/claude.png", "color": "#D97757" },
{ "slug": "fable-5.1-max", "displayName": "Claude Fable 5.1", "variant": "max", "family": "claude", "provider": "anthropic", "modelId": "claude-fable-5-1", "thinking": "high", "thinkingBudget": 64000, "avatar": "avatars/claude.png", "color": "#C2603F" },
{ "slug": "fable-5.1-high", "displayName": "Claude Fable 5.1", "variant": "high", "family": "claude", "provider": "anthropic", "modelId": "claude-fable-5-1", "thinking": "high", "thinkingBudget": 16384, "avatar": "avatars/claude.png", "color": "#C2603F" },
{ "slug": "sol-6.1-max", "displayName": "GPT-6.1 Sol", "variant": "max", "family": "gpt", "provider": "openai", "modelId": "gpt-6.1-sol", "thinking": "max", "avatar": "avatars/openai.png", "color": "#10A37F" },
{ "slug": "sol-6.1-high", "displayName": "GPT-6.1 Sol", "variant": "high", "family": "gpt", "provider": "openai", "modelId": "gpt-6.1-sol", "thinking": "high", "avatar": "avatars/openai.png", "color": "#10A37F" },
{ "slug": "astra-6-max", "displayName": "GPT-6 Astra", "variant": "max", "family": "gpt", "provider": "openai", "modelId": "gpt-6-astra", "thinking": "max", "avatar": "avatars/openai.png", "color": "#5B6CFF" },
{ "slug": "astra-6-high", "displayName": "GPT-6 Astra", "variant": "high", "family": "gpt", "provider": "openai", "modelId": "gpt-6-astra", "thinking": "high", "avatar": "avatars/openai.png", "color": "#5B6CFF" },
{ "slug": "haiku-4.5-nothink", "displayName": "Claude Haiku 4.5", "variant": "no-think", "family": "claude", "provider": "anthropic", "modelId": "claude-haiku-4-5-20251001", "thinking": "off", "dumb": true, "skull": true, "avatar": "avatars/claude.png", "color": "#B9A99A" },
{ "slug": "haiku-4.5-minimal", "displayName": "Claude Haiku 4.5", "variant": "minimal", "family": "claude", "provider": "anthropic", "modelId": "claude-haiku-4-5-20251001", "thinking": "minimal", "dumb": true, "avatar": "avatars/claude.png", "color": "#B9A99A" },
{ "slug": "luna-5.6-nothink", "displayName": "GPT-5.6 Luna", "variant": "no-think", "family": "gpt", "provider": "openai", "modelId": "gpt-5.6-luna", "thinking": "off", "forceReasoningNone": true, "dumb": true, "skull": true, "avatar": "avatars/openai.png", "color": "#9AA5B1" },
{ "slug": "luna-5.6-minimal", "displayName": "GPT-5.6 Luna", "variant": "minimal", "family": "gpt", "provider": "openai", "modelId": "gpt-5.6-luna", "thinking": "minimal", "dumb": true, "avatar": "avatars/openai.png", "color": "#9AA5B1" }
]
}
+110
View File
@@ -0,0 +1,110 @@
# AI·CHESS — design brief for frontend concepts
You are designing the **new frontend** for AI·CHESS: an arena where frontier LLM agents
play chess against each other (and against humans), trash-talk each other, and get
rated on a public leaderboard. Live at chess.danosito.com. Audience: devs/AI nerds and
their friends, Russian-speaking. Vibe: fun, a bit edgy/meme-y, but must stay **readable
and fast to scan** — it is a spectator product first.
UI language: **Russian** (short English accents/labels are fine if they fit the concept).
## Tech constraints (mandatory)
- **SvelteKit 3 + Svelte 5 (runes) + TypeScript**, `@sveltejs/adapter-static` (SPA, `fallback: 'index.html'`).
- Board: **`@lichess-org/chessground`** (+ its base CSS; pick/skin a board theme & piece set that fits your concept).
Use **`chess.js`** to replay the mock game into positions.
- Provider marks: use SVG paths from the **`simple-icons`** npm package (`siClaude`, `siOpenai`, `siAnthropic`).
- Keep deps light. No big component kits. Scoped Svelte styles / vanilla CSS / Tailwind 4 — your call.
Charts: hand-rolled SVG preferred.
- Mock data only (no backend). Put mock data in `src/lib/mock.ts` with realistic content (see below).
- Must pass `npm run build`. Must be viewable with `npm run preview -- --port <your port>`.
- Desktop-first (1440×900), but the **live match page must be usable on mobile (390×844)** for spectators.
## Domain facts (so the UI is honest)
Players ("entities") on the leaderboard:
- 4 models × 2 variants each = 8 AI entities:
- Claude Opus 5.5 (`claude-opus-5-5`), Claude Fable 5.1 (`claude-fable-5-1`) — Anthropic
- GPT-6.1 Sol (`gpt-6.1-sol`), GPT-6 Astra (`gpt-6-astra`) — OpenAI
- Variant **MAX** (max reasoning effort, slow, expensive) and **HIGH** (a.k.a. «быстрый»).
- Humans (registered users with avatars) are on the **same** leaderboard.
How a game works (show this, it is the product's soul):
- Every move the agent gets a **fresh context** (no memory): the board in a few notations
(ASCII diagram, FEN, piece list), the opponent's last move, the opponent's **trash-talk line**,
and only the *relevant* rule state: castling notes (only when it looks possible), "40/50 moves
toward 50-move draw", "this position already repeated twice".
- The agent may call tools (logged): `make_move`, `finish_turn` (trash-talk line to opponent +
optional **note to its future self**), and — under the experimental flag — `get_move_history`
and a `python` sandbox with python-chess.
- **Thoughts** (reasoning summary + tool calls + the exact context it received) are **hidden by
default and expand on click** per move. Design this interaction carefully — it should feel great.
- Experimental flags per match: «Заметки себе» (note to future self), «Доп. тулы» (history + python),
«Читерство» (illegal moves allowed → **unrated**, marked loudly).
- Stockfish runs on every position: eval bar, eval graph, best-move arrow (toggle),
per-move classification (best ★, brilliant !!, inaccuracy ?!, mistake ?, blunder ??),
**live accuracy %** per player. The old UI did this badly — make it great and legible.
- Cost tracking: tokens and $ per move, per player, per game.
- Scheduled matches (set by admin) have **spectator predictions** (white / draw / black, points not
money; locked at game start) and a countdown on the home page.
- After the game: **post-game interview** — each agent gives a short, emotional, human
(not nerdy) 3–6 sentence comment. Show it like a press-conference / post-fight interview.
- Each finished match gets an **AI-generated meme thumbnail** (YouTube/GothamChess-style clickbait:
two participants' avatars/logos, board, huge caption with a double meaning). Archive/home show
them as a YouTube-like grid. You can't generate images — compose convincing placeholders
(CSS/SVG composition with the caption, logos, a mini-board), so the grid looks real.
Caption ideas: «ЗАБЫЛ КАК ХОДИТ КОНЬ», «ДУМАЛ 4 МИНУТЫ — ЗЕВНУЛ МАТ В 1», «ЖЕРТВА ФЕРЗЯ (СЛУЧАЙНАЯ)»,
«ЧЕЛОВЕК ПРОТИВ МАШИНЫ: МАШИНА ОБИДЕЛАСЬ», «ВЫРВАЛ ОЧКО», «GPT ПОПРОСИЛ НИЧЬЮ. 3 РАЗА».
- Users: open registration, login; onboarding includes **avatar upload**. Admin sees all users and
how many tokens/$ each spent.
## Screens
Required (must be polished):
1. **Live match** `/match/demo` — the hero screen. Board + eval bar, both player cards (logo/avatar,
model, variant, rating, persona, thinking timer when it's their turn), move list with
classifications, accuracy, eval graph, trash-talk feed, expandable thoughts per move,
rule-state banners (repetition / 50-move), cost meter, predictions widget (scheduled match).
Also a **game-over state** `/match/demo?over=1` with result + both interviews + thumbnail.
2. **Home** `/` — live now (can be several concurrent games), next scheduled match with countdown
and predictions, recent matches as a thumbnail grid, CTA «Новый матч» (logged in).
3. **Leaderboard** `/leaderboard` — Elo table (AI + humans), W/D/L, games, avg accuracy, $ per game,
**price vs Elo** view («сколько стоит рейтинг»), and an optional head-to-head matrix only if you can
make it genuinely fun/readable.
Nice to have (if time allows, lower polish OK):
4. New match setup `/new` — pick white/black (AI entity or «Я сам»), persona preset
(Уличный гопник / Профессор / Поэт / Молчун / Шут), experimental flags with warnings.
5. Login/registration + onboarding with avatar `/login`.
6. Admin `/admin` — users table with tokens/$ spent, scheduled matches.
7. Archive/replay `/games`.
## Mock game (use this; it's legal — replay with chess.js)
PGN (in progress, Black to move after a knight sac on h3):
```
1. e4 e5 2. Nf3 Nc6 3. Bc4 Bc5 4. c3 Nf6 5. d3 d6 6. O-O a6 7. a4 O-O 8. h3 Ba7
9. Re1 h6 10. Nbd2 Re8 11. Nf1 Be6 12. Bxe6 Rxe6 13. Ng3 d5 14. exd5 Qxd5 15. Be3 Rd8
16. Qc2 Bxe3 17. Rxe3 Qd7 18. Rae1 Rde8 19. b4 Nd5 20. R3e2 Nf4 21. Re4 Nxh3+ 22. gxh3
```
White: **GPT-6.1 Sol · MAX** (persona: Профессор). Black: **Claude Opus 5.5 · MAX** (persona: Уличный гопник).
Invent plausible evals/classifications (e.g. 21...Nxh3+ is a dubious "?!" sac, eval swings), costs,
think times (20 s – 4 min), ratings (~1700–2100), trash-talk lines in Russian matching personas, e.g.:
- Black (гопник): «Конь на h3 — это не жертва, это инвестиция. Считай, братан.»
- White (профессор): «Любопытная идея. Ботвинник назвал бы её некорректной — и был бы прав.»
Sample thought (collapsed by default): reasoning summary «Белые перегрузили e-линию… после gxh3 ферзь
идёт на h3 через e6? Нет, ладья мешает — сначала Rg6…», tool calls: `python(...)` → output snippet,
`make_move("Nxh3+")` → ok, `finish_turn(phrase, note_to_self="Атака по g-линии, не меняй ферзей")`.
## Deliverables (in your own directory `design/<your-name>/`)
- A working SvelteKit app (own `package.json`, run `npm install` there).
- `README.md`: concept name, one-paragraph idea, palette, fonts, key interaction decisions.
- Screenshots `shots/*.png`: every required screen at 1440×900 (full page where useful),
the expanded-thoughts state, the game-over state, and the live match at 390×844.
Use the **browser-cli** skill to take them; **look at your own screenshots and iterate at least
once** to fix ugliness before you finish.
- Do not touch anything outside `design/<your-name>/`.
Avoid generic AI-slop: no purple-gradient SaaS, no Inter/Roboto, no cookie-cutter card grids.
Commit to a bold, coherent direction and execute it precisely.
+23
View File
@@ -0,0 +1,23 @@
node_modules
# Output
.output
.vercel
.netlify
.wrangler
/.svelte-kit
/build
# OS
.DS_Store
Thumbs.db
# Env
.env
.env.*
!.env.example
!.env.test
# Vite
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
+1
View File
@@ -0,0 +1 @@
engine-strict=true
+71
View File
@@ -0,0 +1,71 @@
# AI FIGHT CLUB — arcade concept for AI·CHESS
**Концепт.** Матч двух LLM — это не «партия», это бой в аркадном файтинге. Живой матч
оформлен как HUD из Street Fighter / KOF: сверху две **полоски здоровья** (это вероятность
победы по Stockfish, с «призрачным» хвостом урона, как в файтингах), таймер «THINKING» у того,
чей ход, персона и accuracy под именем. Ошибки и маты — **стингеры**: на зевке над доской
слэмится «BLUNDER!!», на сомнительной жертве — «RISKY?!», на мате — «K.O.» и экран
трясёт. Выбор моделей — **character select** с P1/P2 рамками, тэглайнами и персонами.
После боя — «пресс-конференция»: два интервью как после-матчевые цитаты и мем-превью
(собрано CSS/SVG: аватары бойцов, перечёркнутый проигравший, мини-доска, кликбейт-подпись).
Пиксель/CRT-акценты (Press Start 2P, сканлайны) используются только на стингерах,
HUD-центре и «кабинете» логина — **доска всегда чистая** (cburnett + свой стальной скин).
## Палитра
| токен | цвет | роль |
|---|---|---|
| `--bg` | `#08080c` | кабинет, фон |
| `--panel` / `--line` | `#14141c` / `#262634` | панели |
| `--p1` | `#ffe14d` | игрок 1 (белые), CTA |
| `--p2` | `#ff3b5c` | игрок 2 (чёрные), LIVE, K.O. |
| `--hp` / `--hp-mid` / `--hp-low` | `#4cff5e` / `#ffd23f` / `#ff3b3b` | полоски здоровья |
| `--c-best` ★ / `--c-brill` !! / `--c-inacc` ?! / `--c-mistake` ? / `--c-blunder` ?? | green / cyan / yellow / orange / red | классификация ходов |
| доска | `#e7e2d2` / `#5a6b86` | «стальной кабинет», высокий контраст под cburnett |
## Шрифты (Google Fonts)
- **Unbounded 700/900** — дисплей: имена бойцов, заголовки, VS, стингеры, подписи мемов (кириллица родная).
- **Press Start 2P** — пиксельные ярлыки: P1/P2, панельные заголовки, «INSERT COIN», таймеры.
- **JetBrains Mono** — ходы, оценки, токены, $, контекст агента.
- **IBM Plex Sans** — текст треш-тока, интервью, описания.
## Ключевые интеракции
- **Health bars = eval.** Процент — win-probability из centipawns (lichess-сигмоида). При
падении полоска красит «призрак» и догоняет с задержкой — урон читается мгновенно.
- **Мысли агента** скрыты; клик по ходу в COMBO LOG → доска прыгает на позицию, под строкой
«включается» панель (CRT power-on), с табами **Мысли / Тулы / Контекст**: reasoning summary с
мигающим курсором, логи `python(...)`, `make_move`, `finish_turn(..., note_to_self)`,
и точный fresh-контекст (FEN + ASCII + реплика соперника + rule state), собранный
из позиции через chess.js. Аккордеон: одна панель за раз, `✕` или повторный клик закрывает.
- **Стингеры по классификации**: навигация на ?? → «BLUNDER!!», на ! ! → «BRILLIANT!!», на
жертву ?! → «RISKY?!»; при загрузке — «ROUND 22 / FIGHT!», в `?over=1` — «K.O.».
- **Навигация:** ←/→, Home/End, `f` — flip; клик по графику / по треш-току тоже ведёт к ходу.
Кнопка «LIVE ▶» возвращает в текущую позицию; в replay над доской — плашка.
- **Best-move arrow** (toggle) рисуется chessground `autoShapes`; для «лучших» ходов — сам ход,
для ошибок — альтернатива движка из мока.
- **Rule state** (повторения / 50 ходов / рокировки) — в HUD-центре и в табе «Контекст»
ровно в том виде, в каком его видит агент.
- **Прогнозы** — очки, не деньги; на главной открыты, в матче «ставки закрыты» + моя ставка.
- **Cost meter** — $ и токены на игрока, на ход, суммарно.
- **Мобила (390×844):** HUD в столбик, доска во всю ширину, нижние табы Ходы / Треш-ток / Инфо.
## Экраны
`/` главная · `/match/demo` live · `/match/demo?over=1` game over + интервью + мем ·
`/leaderboard` (Рейтинг / «Сколько стоит рейтинг» scatter MAX↔HIGH / «Кто кого» матрица) ·
`/new` character select · `/login` вход/регистрация/аватар · `/admin` · `/games` архив.
## Запуск
```bash
npm install
npm run build
npm run preview -- --port 5183
```
Скриншоты — `shots/*.png`. Мок-данные — `src/lib/mock.ts` (PGN из брифа продолжен до
легального мата 31…Qxh4#, проверено chess.js). `siOpenai` в simple-icons v16 отсутствует
(убран из пакета), поэтому для OpenAI нарисован свой шестигранный знак в той же 24-сетке;
`siClaude` / `siAnthropic` — из пакета.
+1367
View File
File diff suppressed because it is too large Load Diff
+32
View File
@@ -0,0 +1,32 @@
{
"name": "arcade",
"private": true,
"version": "0.0.1",
"type": "module",
"scripts": {
"dev": "vite dev",
"build": "vite build",
"preview": "vite preview",
"prepare": "svelte-kit sync || echo ''",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch"
},
"devDependencies": {
"@sveltejs/adapter-static": "^4.0.0",
"@sveltejs/kit": "^3.0.0",
"@sveltejs/vite-plugin-svelte": "^7.2.0",
"svelte": "^5.57.1",
"svelte-check": "^4.6.0",
"typescript": "^6.0.3",
"vite": "^8.3.0"
},
"imports": {
"#lib": "./src/lib/index.js",
"#lib/*": "./src/lib/*"
},
"dependencies": {
"@lichess-org/chessground": "^10.4.2",
"chess.js": "^1.4.0",
"simple-icons": "^16.35.0"
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 773 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 102 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 619 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 153 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 236 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 123 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 276 KiB

Some files were not shown because too many files have changed in this diff Show More