From e4b5b8ada5feec5373ef8b06fc7378885579e030 Mon Sep 17 00:00:00 2001 From: ai-chess Date: Sun, 18 Oct 2026 17:23:15 +0300 Subject: [PATCH] premoves (server-side, survive closed tab), provider outages pause games instead of aborting, turn watchdog, lock race fix, overthinking experiment harness --- apps/server/drizzle/0001_premove.sql | 2 + apps/server/drizzle/meta/0001_snapshot.json | 1305 +++++++++++++++++++ apps/server/drizzle/meta/_journal.json | 7 + apps/server/scripts/think-exp.ts | 136 ++ apps/server/src/agents/turn.ts | 8 +- apps/server/src/db/schema.ts | 11 + apps/server/src/games/runner.ts | 51 +- apps/server/src/games/scheduler.ts | 2 + apps/server/src/games/service.ts | 55 +- apps/server/src/http/app.ts | 51 +- apps/server/src/jobs.ts | 20 +- apps/web/src/lib/api.ts | 1 + apps/web/src/lib/components/Board.svelte | 38 +- apps/web/src/lib/components/MoveList.svelte | 6 +- apps/web/src/lib/game.svelte.ts | 9 + apps/web/src/lib/types.ts | 4 + apps/web/src/routes/match/[id]/+page.svelte | 95 +- packages/core/src/position.ts | 7 + packages/core/src/types.ts | 3 + 19 files changed, 1788 insertions(+), 23 deletions(-) create mode 100644 apps/server/drizzle/0001_premove.sql create mode 100644 apps/server/drizzle/meta/0001_snapshot.json create mode 100644 apps/server/scripts/think-exp.ts diff --git a/apps/server/drizzle/0001_premove.sql b/apps/server/drizzle/0001_premove.sql new file mode 100644 index 0000000..889a989 --- /dev/null +++ b/apps/server/drizzle/0001_premove.sql @@ -0,0 +1,2 @@ +ALTER TABLE "games" ADD COLUMN "premove" jsonb;--> statement-breakpoint +ALTER TABLE "moves" ADD COLUMN "premoved" boolean DEFAULT false NOT NULL; \ No newline at end of file diff --git a/apps/server/drizzle/meta/0001_snapshot.json b/apps/server/drizzle/meta/0001_snapshot.json new file mode 100644 index 0000000..f0c08ce --- /dev/null +++ b/apps/server/drizzle/meta/0001_snapshot.json @@ -0,0 +1,1305 @@ +{ + "id": "8ae53e91-d462-498d-a2a0-b0c0d8636676", + "prevId": "039fb91d-ed56-4b78-8ee4-4732638e763a", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.app_settings": { + "name": "app_settings", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "jsonb", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.games": { + "name": "games", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "white_id": { + "name": "white_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "black_id": { + "name": "black_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "schedule_id": { + "name": "schedule_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "flags": { + "name": "flags", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "personas": { + "name": "personas", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "rated": { + "name": "rated", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "start_fen": { + "name": "start_fen", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "fen": { + "name": "fen", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ply": { + "name": "ply", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "pending_draw_by": { + "name": "pending_draw_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "premove": { + "name": "premove", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "result": { + "name": "result", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "termination": { + "name": "termination", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "starts_at": { + "name": "starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "rating_change": { + "name": "rating_change", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "accuracy": { + "name": "accuracy", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "interviews": { + "name": "interviews", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "last_words": { + "name": "last_words", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "review": { + "name": "review", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "thumbnail": { + "name": "thumbnail", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "thumbnail_caption": { + "name": "thumbnail_caption", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "thumbnail_meta": { + "name": "thumbnail_meta", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "cost_total": { + "name": "cost_total", + "type": "double precision", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "games_status": { + "name": "games_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "games_created": { + "name": "games_created", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "games_white_id_players_id_fk": { + "name": "games_white_id_players_id_fk", + "tableFrom": "games", + "tableTo": "players", + "columnsFrom": [ + "white_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "games_black_id_players_id_fk": { + "name": "games_black_id_players_id_fk", + "tableFrom": "games", + "tableTo": "players", + "columnsFrom": [ + "black_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "games_created_by_users_id_fk": { + "name": "games_created_by_users_id_fk", + "tableFrom": "games", + "tableTo": "users", + "columnsFrom": [ + "created_by" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.moves": { + "name": "moves", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "game_id": { + "name": "game_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ply": { + "name": "ply", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "side": { + "name": "side", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "player_id": { + "name": "player_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "san": { + "name": "san", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "uci": { + "name": "uci", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "fen_after": { + "name": "fen_after", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "phrase": { + "name": "phrase", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "offered_draw": { + "name": "offered_draw", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "illegal": { + "name": "illegal", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "premoved": { + "name": "premoved", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "think_ms": { + "name": "think_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "usage": { + "name": "usage", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "eval": { + "name": "eval", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "classification": { + "name": "classification", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "accuracy": { + "name": "accuracy", + "type": "double precision", + "primaryKey": false, + "notNull": false + }, + "turn_id": { + "name": "turn_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "moves_game_ply": { + "name": "moves_game_ply", + "columns": [ + { + "expression": "game_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "ply", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "moves_game_id_games_id_fk": { + "name": "moves_game_id_games_id_fk", + "tableFrom": "moves", + "tableTo": "games", + "columnsFrom": [ + "game_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.players": { + "name": "players", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "family": { + "name": "family", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model_id": { + "name": "model_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "thinking": { + "name": "thinking", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "variant": { + "name": "variant", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "avatar": { + "name": "avatar", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "dumb": { + "name": "dumb", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "skull": { + "name": "skull", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "options": { + "name": "options", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "active": { + "name": "active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "rating": { + "name": "rating", + "type": "double precision", + "primaryKey": false, + "notNull": true, + "default": 1500 + }, + "rd": { + "name": "rd", + "type": "double precision", + "primaryKey": false, + "notNull": true, + "default": 350 + }, + "vol": { + "name": "vol", + "type": "double precision", + "primaryKey": false, + "notNull": true, + "default": 0.06 + }, + "games": { + "name": "games", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "wins": { + "name": "wins", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "draws": { + "name": "draws", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "losses": { + "name": "losses", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "players_user_id_users_id_fk": { + "name": "players_user_id_users_id_fk", + "tableFrom": "players", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "players_slug_unique": { + "name": "players_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + }, + "players_user_id_unique": { + "name": "players_user_id_unique", + "nullsNotDistinct": false, + "columns": [ + "user_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.predictions": { + "name": "predictions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "game_id": { + "name": "game_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pick": { + "name": "pick", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "points": { + "name": "points", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "predictions_game_user": { + "name": "predictions_game_user", + "columns": [ + { + "expression": "game_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "predictions_game_id_games_id_fk": { + "name": "predictions_game_id_games_id_fk", + "tableFrom": "predictions", + "tableTo": "games", + "columnsFrom": [ + "game_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "predictions_user_id_users_id_fk": { + "name": "predictions_user_id_users_id_fk", + "tableFrom": "predictions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.rating_history": { + "name": "rating_history", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "player_id": { + "name": "player_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "game_id": { + "name": "game_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "before": { + "name": "before", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "after": { + "name": "after", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "rd": { + "name": "rd", + "type": "double precision", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "rating_history_player": { + "name": "rating_history_player", + "columns": [ + { + "expression": "player_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.schedules": { + "name": "schedules", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "enabled": { + "name": "enabled", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "interval_minutes": { + "name": "interval_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 180 + }, + "announce_minutes": { + "name": "announce_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 30 + }, + "pool": { + "name": "pool", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "flags": { + "name": "flags", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "random_personas": { + "name": "random_personas", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "next_run_at": { + "name": "next_run_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.sessions": { + "name": "sessions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "sessions_user_id_users_id_fk": { + "name": "sessions_user_id_users_id_fk", + "tableFrom": "sessions", + "tableTo": "users", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.turns": { + "name": "turns", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "game_id": { + "name": "game_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "ply": { + "name": "ply", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "side": { + "name": "side", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "player_id": { + "name": "player_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempt": { + "name": "attempt", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'running'" + }, + "transcript": { + "name": "transcript", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'[]'::jsonb" + }, + "usage": { + "name": "usage", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "outcome": { + "name": "outcome", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ended_at": { + "name": "ended_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "turns_game_ply": { + "name": "turns_game_ply", + "columns": [ + { + "expression": "game_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "ply", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "turns_game_id_games_id_fk": { + "name": "turns_game_id_games_id_fk", + "tableFrom": "turns", + "tableTo": "games", + "columnsFrom": [ + "game_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.usage_ledger": { + "name": "usage_ledger", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "game_id": { + "name": "game_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "player_id": { + "name": "player_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "usage": { + "name": "usage", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "cost": { + "name": "cost", + "type": "double precision", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "tokens": { + "name": "tokens", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "usage_user": { + "name": "usage_user", + "columns": [ + { + "expression": "user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.users": { + "name": "users", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "password_hash": { + "name": "password_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "avatar": { + "name": "avatar", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "is_admin": { + "name": "is_admin", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "onboarded": { + "name": "onboarded", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "theme": { + "name": "theme", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'tabloid'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "users_username_lower": { + "name": "users_username_lower", + "columns": [ + { + "expression": "lower(\"username\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/apps/server/drizzle/meta/_journal.json b/apps/server/drizzle/meta/_journal.json index 5b8c6bc..0cb09c6 100644 --- a/apps/server/drizzle/meta/_journal.json +++ b/apps/server/drizzle/meta/_journal.json @@ -8,6 +8,13 @@ "when": 1792323366900, "tag": "0000_init", "breakpoints": true + }, + { + "idx": 1, + "version": "7", + "when": 1792332661442, + "tag": "0001_premove", + "breakpoints": true } ] } \ No newline at end of file diff --git a/apps/server/scripts/think-exp.ts b/apps/server/scripts/think-exp.ts new file mode 100644 index 0000000..edd65c4 --- /dev/null +++ b/apps/server/scripts/think-exp.ts @@ -0,0 +1,136 @@ +/** + * Overthinking experiment: replay real positions where Opus thought for minutes, with prompt variants. + * node --env-file=../../.env --import tsx scripts/think-exp.ts /tmp/exp-moves.json /tmp/think-exp + * Writes /results.jsonl (+ one thinking dump per run). + */ +import { mkdirSync, readFileSync, writeFileSync, appendFileSync } from "node:fs"; +import { GameState, type GameFlags, type Side } from "@aichess/core"; +import { runAgentTurn, type AgentPlayer } from "../src/agents/turn.ts"; +import { engine } from "../src/engine/stockfish.ts"; + +type Row = { game: string; ply: number; uci: string; san: string; phrase: string | null; note: string | null }; +const [, , movesPath = "/tmp/exp-moves.json", outDir = "/tmp/think-exp"] = process.argv; +const rows: Row[] = JSON.parse(readFileSync(movesPath, "utf8")); +mkdirSync(outDir, { recursive: true }); + +const POSITIONS = [ + { id: "H8", game: "mvdvvxxmhlsqkmnbbvuq", ply: 8, persona: "professor", opp: "artsaf", oppHuman: true, flags: { notes: false, extraTools: false, cheating: false } }, + { id: "H10", game: "mvdvvxxmhlsqkmnbbvuq", ply: 10, persona: "professor", opp: "artsaf", oppHuman: true, flags: { notes: false, extraTools: false, cheating: false } }, + { id: "A29", game: "mvdtmab5ef49hb4wkb6n", ply: 29, persona: "gopnik", opp: "GPT-6.1 Sol MAX", oppHuman: false, flags: { notes: true, extraTools: false, cheating: false } }, +]; + +const DISCIPLINE = [ + "## Как думать над ходом", + "Ты играешь с контролем времени — рапид: на ход у тебя примерно 1–3 минуты, не больше.", + "- Играй позицию на доске. Не восстанавливай порядок ходов и не пытайся дословно вспомнить теорию — если позиция знакома, доверься общему пониманию.", + "- Сначала форсирующее: шахи, взятия, угрозы — свои и соперника. Убедись, что у тебя ничего не висит.", + "- Выбери 2–3 кандидата и доведи расчёт каждого до спокойной позиции. Не прыгай между кандидатами: сначала вывод по одному, потом следующий.", + "- Когда ход выбран и проверен на зевок — сразу делай его. Не перепроверяй уже проверенное; смутное «а вдруг» без конкретного ответа соперника — не повод думать дальше.", +].join("\n"); + +const opus = (variant: "max" | "high"): AgentPlayer => ({ + id: `opus-${variant}`, + displayName: "Claude Opus 5.5", + variant, + provider: "anthropic", + modelId: "claude-opus-5-5", + thinking: variant, + options: {}, +}); + +const VARIANTS = [ + { id: "base", me: opus("max"), hist: false, disc: false }, + { id: "hist", me: opus("max"), hist: true, disc: false }, + { id: "disc", me: opus("max"), hist: false, disc: true }, + { id: "hist+disc", me: opus("max"), hist: true, disc: true }, + { id: "high", me: opus("high"), hist: false, disc: false }, +]; +const REPS = Number(process.env.REPS ?? 2); +const CONC = Number(process.env.CONC ?? 5); + +function movetext(plies: Row[]) { + const parts: string[] = []; + plies.forEach((r, k) => parts.push(k % 2 === 0 ? `${k / 2 + 1}. ${r.san}` : r.san)); + return parts.join(" "); +} + +const evalCache = new Map>(); +/** eval in centipawns from the POV of `pov` (mate = ±10000) */ +function evalFor(fen: string, pov: Side): Promise { + const k = `${fen}|${pov}`; + if (!evalCache.has(k)) + evalCache.set( + k, + engine.analyze(fen, 20).then((e) => { + const white = e.mate != null ? Math.sign(e.mate) * 10000 : (e.cp ?? 0); + return pov === "white" ? white : -white; + }), + ); + return evalCache.get(k)!; +} + +type Job = { pos: (typeof POSITIONS)[number]; v: (typeof VARIANTS)[number]; rep: number }; +const jobs: Job[] = []; +for (let rep = 1; rep <= REPS; rep++) for (const pos of POSITIONS) for (const v of VARIANTS) jobs.push({ pos, v, rep }); + +async function runJob({ pos, v, rep }: Job) { + const plies = rows.filter((r) => r.game === pos.game && r.ply < pos.ply).sort((a, b) => a.ply - b.ply); + const state = GameState.fromUci(plies.map((p) => ({ uci: p.uci }))); + const side: Side = pos.ply % 2 === 1 ? "white" : "black"; + const last = plies[plies.length - 1]; + const myLast = [...plies].reverse().find((p) => (p.ply % 2 === 1 ? "white" : "black") === side); + const tag = `${pos.id}/${v.id}/r${rep}`; + const t0 = Date.now(); + try { + const res = await runAgentTurn({ + gameId: `exp-${tag}`, + side, + me: v.me, + opponentName: pos.opp, + opponentIsHuman: pos.oppHuman, + persona: pos.persona, + flags: pos.flags as GameFlags, + state, + history: [], + opponentPhrase: last?.phrase ?? null, + drawOffered: false, + noteFromSelf: pos.flags.notes ? (myLast?.note ?? null) : null, + onLive: () => {}, + tweaks: { + system: v.disc ? DISCIPLINE : undefined, + context: v.hist ? `## Ходы партии\n${movetext(plies)}` : undefined, + }, + }); + const d = res.decision; + let san: string | null = null; + let loss: number | null = null; + if (d.kind === "move") { + san = d.san; + const before = await evalFor(state.fen(), side); + const after = GameState.fromUci([...plies.map((p) => ({ uci: p.uci })), { uci: d.uci }]); + const afterEval = await evalFor(after.fen(), side); + loss = Math.max(0, before - afterEval); + } + const thinking = res.transcript.filter((t) => t.kind === "thinking").map((t: any) => t.text).join("\n\n"); + writeFileSync(`${outDir}/${tag.replaceAll("/", "_")}.txt`, `${res.context}\n\n=====THINKING=====\n${thinking}`); + const out = { + pos: pos.id, variant: v.id, rep, decision: d.kind, san, cpLoss: loss, + secs: Math.round((Date.now() - t0) / 1000), reasoning: res.usage.reasoning, output: res.usage.output, + cost: Number(res.usage.cost.toFixed(3)), thinkChars: thinking.length, + }; + appendFileSync(`${outDir}/results.jsonl`, JSON.stringify(out) + "\n"); + console.log(JSON.stringify(out)); + } catch (e) { + console.log(JSON.stringify({ pos: pos.id, variant: v.id, rep, error: String(e).slice(0, 300) })); + } +} + +let next = 0; +await Promise.all( + Array.from({ length: CONC }, async () => { + while (next < jobs.length) await runJob(jobs[next++]); + }), +); +engine.stop(); +console.log("done"); +process.exit(0); diff --git a/apps/server/src/agents/turn.ts b/apps/server/src/agents/turn.ts index dcda2dd..f14d218 100644 --- a/apps/server/src/agents/turn.ts +++ b/apps/server/src/agents/turn.ts @@ -44,6 +44,8 @@ export interface TurnInput { noteFromSelf: string | null; signal?: AbortSignal; onLive: (ev: LiveTurnEvent) => void; + /** experiments only (scripts/think-exp.ts): extra text appended to the system prompt / turn message */ + tweaks?: { system?: string; context?: string }; } export type LiveTurnEvent = @@ -208,8 +210,9 @@ export async function runAgentTurn(i: TurnInput): Promise { } const persona = personaById(i.persona); - const systemPrompt = buildSystemPrompt({ side: i.side, opponentName: i.opponentName, opponentIsHuman: i.opponentIsHuman, persona, flags: i.flags }); - const context = renderTurnContext({ + let systemPrompt = buildSystemPrompt({ side: i.side, opponentName: i.opponentName, opponentIsHuman: i.opponentIsHuman, persona, flags: i.flags }); + if (i.tweaks?.system) systemPrompt += "\n\n" + i.tweaks.system; + let context = renderTurnContext({ state: i.state, me: { side: i.side }, opponent: { name: i.opponentName }, @@ -219,6 +222,7 @@ export async function runAgentTurn(i: TurnInput): Promise { flags: i.flags, fiftyMoveThreshold: config.game.fiftyMoveReminderFrom, }); + if (i.tweaks?.context) context = context.replace("\n\n## \u0422\u0432\u043e\u044f \u0437\u0430\u0434\u0430\u0447\u0430", `\n\n${i.tweaks.context}\n\n## \u0422\u0432\u043e\u044f \u0437\u0430\u0434\u0430\u0447\u0430`); transcript.push({ kind: "context", text: context, at: Date.now() }); const { session } = await createChessSession({ diff --git a/apps/server/src/db/schema.ts b/apps/server/src/db/schema.ts index b98cc9e..f7267c1 100644 --- a/apps/server/src/db/schema.ts +++ b/apps/server/src/db/schema.ts @@ -58,6 +58,13 @@ export const players = pgTable("players", { createdAt: now(), }); +export interface Premove { + side: Side; + uci: string; + ply: number; + phrase: string | null; +} + export const games = pgTable("games", { id: text("id").primaryKey(), status: text("status").$type<"pending" | "running" | "finished" | "aborted">().notNull().default("pending"), @@ -72,6 +79,8 @@ export const games = pgTable("games", { fen: text("fen").notNull(), ply: integer("ply").notNull().default(0), pendingDrawBy: text("pending_draw_by").$type(), + /** a human's queued move, played the instant the AI replies (`ply` = the ply it is meant for) */ + premove: jsonb("premove").$type(), result: text("result").$type(), termination: text("termination").$type(), startsAt: ts("starts_at"), // scheduled start (predictions lock at this time) @@ -105,6 +114,8 @@ export const moves = pgTable("moves", { note: text("note"), offeredDraw: boolean("offered_draw").notNull().default(false), illegal: boolean("illegal").notNull().default(false), + /** played automatically from a human's premove */ + premoved: boolean("premoved").notNull().default(false), thinkMs: integer("think_ms").notNull().default(0), usage: jsonb("usage").$type(), eval: jsonb("eval").$type(), diff --git a/apps/server/src/games/runner.ts b/apps/server/src/games/runner.ts index 55fd255..b111215 100644 --- a/apps/server/src/games/runner.ts +++ b/apps/server/src/games/runner.ts @@ -10,7 +10,7 @@ import { } from "@aichess/core"; import { db, schema, sqlClient } from "../db/client.ts"; import { bus, gameChannel } from "../bus.ts"; -import { boss, Q, type EvalJob, type TurnJob } from "../jobs.ts"; +import { boss, enqueueTurn, hasLiveTurnJob, Q, type EvalJob, type TurnJob } from "../jobs.ts"; import { config } from "../config.ts"; import { engine } from "../engine/stockfish.ts"; import { runAgentTurn, type AgentPlayer, type LiveTurnEvent } from "../agents/turn.ts"; @@ -70,8 +70,15 @@ async function handleTurn(data: TurnJob, retryCount: number) { const conn = await sqlClient.reserve(); const key = `turn:${data.gameId}`; try { - const [row] = await conn`select pg_try_advisory_lock(hashtext(${key})) as ok`; - if (!row?.ok) { + // The previous ply's handler enqueues this job from inside its own locked section and releases the + // lock a few ms later \u2014 so wait briefly before concluding that a genuine duplicate is running. + let ok = false; + for (let t = 0; t < 60 && !ok; t++) { + const [row] = await conn`select pg_try_advisory_lock(hashtext(${key})) as ok`; + ok = !!row?.ok; + if (!ok) await new Promise((r) => setTimeout(r, 250)); + } + if (!ok) { log("turn", `${data.gameId}#${data.ply}: another worker holds the game — skipping duplicate`); return; } @@ -178,12 +185,14 @@ async function runTurnLocked(data: TurnJob, retryCount: number) { const msg = err instanceof Error ? err.message : String(err); await db.update(schema.turns).set({ status: "failed", error: msg.slice(0, 2000), endedAt: new Date() }).where(eq(schema.turns.id, turnId)); if (ac.signal.aborted) return; - logErr("turn", `${g.game.id}#${data.ply} attempt ${n + 1} failed: ${msg}`); - if (retryCount >= 4) { + const transient = isTransientProviderError(msg); + logErr("turn", `${g.game.id}#${data.ply} attempt ${n + 1} failed (${transient ? "transient" : "fatal?"}): ${msg}`); + // provider outages never kill a game — the job keeps retrying (backoff ≤ 5 min) until it comes back + if (!transient && retryCount >= 4) { await abortGame(g.game.id, `agent turn failed repeatedly: ${msg}`); return; } - bus.publish(gameChannel(g.game.id), { type: "status", gameId: g.game.id, status: "running", note: "Ошибка провайдера — ход будет переигран" }); + bus.publish(gameChannel(g.game.id), { type: "status", gameId: g.game.id, status: "running", note: providerNote(msg, me.provider) }); throw err; } finally { live.delete(g.game.id); @@ -259,6 +268,36 @@ export async function startWorkers() { } /** Make sure every running game has its next turn queued (after restarts / lost jobs). */ +const TRANSIENT_RE = + /provider error|\b5\d\d\b|\b429\b|\b401\b|overload|rate.?limit|auth_unavailable|revoked|unauthori|timed? ?out|ECONN|ETIMEDOUT|EAI_AGAIN|fetch failed|socket|network|stream ended|model fallback|terminated/i; +export const isTransientProviderError = (msg: string) => TRANSIENT_RE.test(msg); + +const PROVIDER_RU: Record = { anthropic: "Anthropic (Claude)", openai: "OpenAI" }; +/** human-readable status line for spectators while a turn is being retried */ +export function providerNote(msg: string, provider?: string | null) { + const who = (provider && PROVIDER_RU[provider]) || "Провайдер модели"; + if (/auth_unavailable|revoked|unauthori|\b401\b/i.test(msg)) return `${who} временно недоступен (слетела авторизация) — партия на паузе, ход будет переигран автоматически`; + if (/\b429\b|rate.?limit|overload/i.test(msg)) return `${who} перегружен — ход будет переигран автоматически`; + return `${who}: ошибка — ход будет переигран автоматически`; +} + +/** + * Watchdog (every scheduler tick): a running game whose side to move is an AI must have a live turn + * job. Jobs can disappear (retries exhausted, failed during a restart…) — re-enqueue them. + */ +export async function reviveStalledGames() { + const running = await db.select().from(schema.games).where(eq(schema.games.status, "running")); + for (const g of running) { + const ply = g.ply + 1; + const pid = sideOfPly(ply) === "white" ? g.whiteId : g.blackId; + const p = await db.query.players.findFirst({ where: eq(schema.players.id, pid) }); + if (p?.kind !== "ai" || live.has(g.id)) continue; + if (await hasLiveTurnJob(g.id, ply)) continue; + log("watchdog", `no live turn job for ${g.id}#${ply} — re-enqueueing`); + await enqueueTurn({ gameId: g.id, ply }); + } +} + export async function recoverRunningGames() { const running = await db.select().from(schema.games).where(eq(schema.games.status, "running")); const { kickTurn } = await import("./service.ts"); diff --git a/apps/server/src/games/scheduler.ts b/apps/server/src/games/scheduler.ts index cb2f2b8..c4d15dd 100644 --- a/apps/server/src/games/scheduler.ts +++ b/apps/server/src/games/scheduler.ts @@ -7,6 +7,7 @@ import { config } from "../config.ts"; import { PERSONAS } from "../agents/prompts.ts"; import { log, logErr, newId, pick, shuffle } from "../util.ts"; import { createGame, startPendingGame } from "./service.ts"; +import { reviveStalledGames } from "./runner.ts"; /** * Every minute: @@ -66,6 +67,7 @@ async function announceScheduled(s: typeof schema.schedules.$inferSelect) { export async function startScheduler() { await boss.work(Q.scheduleTick, { batchSize: 1, pollingIntervalSeconds: 5 } as any, async () => { await scheduleTick(); + await reviveStalledGames().catch((e) => logErr("watchdog", e)); }); await boss.schedule(Q.scheduleTick, "* * * * *"); // default schedule on first boot diff --git a/apps/server/src/games/service.ts b/apps/server/src/games/service.ts index 026677e..37394c4 100644 --- a/apps/server/src/games/service.ts +++ b/apps/server/src/games/service.ts @@ -13,6 +13,7 @@ import { type Usage, } from "@aichess/core"; import { db, schema } from "../db/client.ts"; +import type { Premove } from "../db/schema.ts"; import { bus, gameChannel } from "../bus.ts"; import { enqueueEval, enqueueFinalize, enqueueTurn } from "../jobs.ts"; import { log, newId } from "../util.ts"; @@ -41,6 +42,7 @@ export function moveToDTO(m: MoveRow): MoveDTO { note: m.note, offeredDraw: m.offeredDraw, illegal: m.illegal, + premoved: m.premoved, thinkMs: m.thinkMs, usage: (m.usage ?? { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, reasoning: 0, cost: 0 }) as Usage, eval: m.eval, @@ -149,6 +151,7 @@ export interface MoveMeta { thinkMs: number; usage: Usage | null; turnId: string | null; + premoved?: boolean; } /** @@ -168,13 +171,18 @@ export async function applyMove(gameId: string, ply: number, input: { uci: strin const moveId = newId(); const pendingDrawBy: Side | null = meta.offerDraw ? side : null; + let premove: Premove | null = null; const updated = await db.transaction(async (tx) => { + // any move consumes the queued premove; grab it under the row lock so a concurrent PUT can't slip between + const [locked] = await tx.select({ premove: schema.games.premove }).from(schema.games).where(eq(schema.games.id, gameId)).for("update"); + premove = locked?.premove ?? null; const [row] = await tx .update(schema.games) .set({ ply, fen: rec.fenAfter, pendingDrawBy, + premove: null, costTotal: sql`${schema.games.costTotal} + ${meta.usage?.cost ?? 0}`, }) .where(and(eq(schema.games.id, gameId), eq(schema.games.ply, ply - 1), eq(schema.games.status, "running"))) @@ -193,6 +201,7 @@ export async function applyMove(gameId: string, ply: number, input: { uci: strin note: meta.note, offeredDraw: meta.offerDraw, illegal: rec.illegal, + premoved: !!meta.premoved, thinkMs: meta.thinkMs, usage: meta.usage, turnId: meta.turnId, @@ -208,11 +217,53 @@ export async function applyMove(gameId: string, ply: number, input: { uci: strin await enqueueEval({ gameId, ply }); const outcome = state.outcome(); - if (outcome) await finishGame(gameId, outcome.result, outcome.termination); - else await kickTurn(updated); + if (outcome) { + await finishGame(gameId, outcome.result, outcome.termination); + return { ok: true, move: dto }; + } + const pm = premove as Premove | null; + if (pm && pm.ply === ply + 1 && pm.side === sideOfPly(ply + 1)) { + const r = await applyMove(gameId, ply + 1, { uci: pm.uci }, { phrase: pm.phrase, note: null, offerDraw: false, thinkMs: 0, usage: null, turnId: null, premoved: true }); + if (r.ok) return { ok: true, move: dto }; + bus.publish(gameChannel(gameId), { type: "premove_dropped", gameId, side: pm.side, uci: pm.uci, reason: r.error }); + } + await kickTurn(updated); return { ok: true, move: dto }; } +// ------------------------------------------------------------------ premoves + +/** + * Queue a premove for the human whose opponent (AI) is thinking. If the AI has already replied by the + * time this lands, the move is simply played. Returns whether it was queued or played. + */ +export async function setPremove(gameId: string, side: Side, uci: string, phrase: string | null): Promise<{ ok: true; played: boolean } | { ok: false; error: string }> { + const g = await loadGame(gameId); + if (!g || g.game.status !== "running") return { ok: false, error: "\u041f\u0430\u0440\u0442\u0438\u044f \u043d\u0435 \u0438\u0434\u0451\u0442" }; + const nextSide = sideOfPly(g.game.ply + 1); + if (nextSide === side) { + const r = await applyMove(gameId, g.game.ply + 1, { uci }, { phrase, note: null, offerDraw: false, thinkMs: 0, usage: null, turnId: null }); + return r.ok ? { ok: true, played: true } : { ok: false, error: r.error }; + } + // must at least move one of my own pieces + const piece = stateOf(g).pieceAt(uci.slice(0, 2)); + if (!piece || piece.side !== side) return { ok: false, error: "\u041d\u0430 \u044d\u0442\u043e\u0439 \u043a\u043b\u0435\u0442\u043a\u0435 \u043d\u0435\u0442 \u0442\u0432\u043e\u0435\u0439 \u0444\u0438\u0433\u0443\u0440\u044b" }; + const [row] = await db + .update(schema.games) + .set({ premove: { side, uci, ply: g.game.ply + 2, phrase } }) + .where(and(eq(schema.games.id, gameId), eq(schema.games.ply, g.game.ply), eq(schema.games.status, "running"))) + .returning({ id: schema.games.id }); + if (row) return { ok: true, played: false }; + return setPremove(gameId, side, uci, phrase); // the AI moved in between \u2014 retry against the new state +} + +export async function clearPremove(gameId: string, side: Side) { + await db + .update(schema.games) + .set({ premove: null }) + .where(and(eq(schema.games.id, gameId), sql`${schema.games.premove}->>'side' = ${side}`)); +} + // ------------------------------------------------------------------ finishing export async function finishGame(gameId: string, result: Result, termination: Termination, opts: { error?: string } = {}) { diff --git a/apps/server/src/http/app.ts b/apps/server/src/http/app.ts index 4e60c8c..1e32210 100644 --- a/apps/server/src/http/app.ts +++ b/apps/server/src/http/app.ts @@ -10,8 +10,8 @@ import { config } from "../config.ts"; import { db, schema } from "../db/client.ts"; import { authMiddleware, createSession, destroySession, findUserByName, registerUser, requireAdmin, requireUser, USERNAME_RE, verifyPassword, type AppEnv } from "../auth.ts"; import { PERSONAS } from "../agents/prompts.ts"; -import { abortGame, applyMove, applyTerminalDecision, createGame, loadGame, playerIdFor, recordOf, sideOfPly } from "../games/service.ts"; -import { abortRunningTurn, getLiveTurn } from "../games/runner.ts"; +import { abortGame, applyMove, applyTerminalDecision, clearPremove, createGame, loadGame, playerIdFor, recordOf, setPremove, sideOfPly } from "../games/service.ts"; +import { abortRunningTurn, getLiveTurn, providerNote } from "../games/runner.ts"; import { enqueueFinalize } from "../jobs.ts"; import { newId } from "../util.ts"; import { gameSummaryDTO, movesDTO, playerDTO, userDTO } from "./dto.ts"; @@ -198,6 +198,20 @@ export function buildApp() { const me = c.get("user"); const mine = me ? await db.query.predictions.findFirst({ where: and(eq(schema.predictions.gameId, g.game.id), eq(schema.predictions.userId, me.id)) }) : null; const lt = getLiveTurn(g.game.id); + // a failed attempt with no retry running yet = the game is paused waiting for the provider + let stall: { note: string; at: string; attempts: number } | null = null; + if (g.game.status === "running" && !lt) { + const [t] = await db + .select() + .from(schema.turns) + .where(and(eq(schema.turns.gameId, g.game.id), eq(schema.turns.ply, g.game.ply + 1))) + .orderBy(desc(schema.turns.attempt)) + .limit(1); + if (t?.status === "failed") { + const p = t.side === "white" ? g.white : g.black; + stall = { note: providerNote(t.error ?? "", p.provider), at: (t.endedAt ?? t.startedAt).toISOString(), attempts: t.attempt }; + } + } return c.json({ game: { ...gameSummaryDTO(g.game, pm, { withReview: true }), @@ -206,10 +220,16 @@ export function buildApp() { interviews: g.game.interviews, lastWords: g.game.lastWords, pendingDrawBy: g.game.pendingDrawBy, + // a premove is private to the human who queued it + premove: + me && g.game.premove && (g.game.premove.side === "white" ? g.white : g.black).userId === me.id + ? { uci: g.game.premove.uci, phrase: g.game.premove.phrase } + : null, createdBy: g.game.createdBy, error: g.game.error, }, moves: movesDTO(g.moves), + stall, live: lt ? { ply: lt.ply, side: lt.side, startedAt: lt.startedAt, thinking: lt.thinking, text: lt.text, tools: Object.values(lt.tools) } : null, predictions: { counts: Object.fromEntries(preds.map((p) => [p.pick, p.n])), mine: mine?.pick ?? null }, }); @@ -286,6 +306,33 @@ export function buildApp() { return c.json({ ok: true, move: r.move }); }); + /** the human participant's side (any turn), or an error response */ + async function participant(c: any) { + const u = c.get("user")!; + const g = await loadGame(c.req.param("id")); + if (!g || g.game.status !== "running") return { error: c.json({ error: "\u041f\u0430\u0440\u0442\u0438\u044f \u043d\u0435 \u0438\u0434\u0451\u0442" }, 409) }; + const side: Side | null = g.white.kind === "human" && g.white.userId === u.id ? "white" : g.black.kind === "human" && g.black.userId === u.id ? "black" : null; + if (!side) return { error: c.json({ error: "\u0422\u044b \u043d\u0435 \u0438\u0433\u0440\u0430\u0435\u0448\u044c \u0432 \u044d\u0442\u043e\u0439 \u043f\u0430\u0440\u0442\u0438\u0438" }, 403) }; + return { g, side }; + } + + // premove: queued while the AI thinks, played server-side the instant it replies (tab may be closed) + app.put("/api/games/:id/premove", requireUser, async (c) => { + const t = await participant(c); + if ("error" in t) return t.error; + const b = await body(c, z.object({ move: z.string().regex(/^[a-h][1-8][a-h][1-8][qrbn]?$/), phrase: z.string().max(400).optional() })); + const r = await setPremove(t.g.game.id, t.side, b.move, b.phrase?.trim() || null); + if (!r.ok) return c.json({ error: r.error }, 400); + return c.json({ ok: true, played: r.played }); + }); + + app.delete("/api/games/:id/premove", requireUser, async (c) => { + const t = await participant(c); + if ("error" in t) return t.error; + await clearPremove(t.g.game.id, t.side); + return c.json({ ok: true }); + }); + app.post("/api/games/:id/resign", requireUser, async (c) => { const u = c.get("user")!; const g = await loadGame(c.req.param("id")); diff --git a/apps/server/src/jobs.ts b/apps/server/src/jobs.ts index a30b335..08687ad 100644 --- a/apps/server/src/jobs.ts +++ b/apps/server/src/jobs.ts @@ -1,5 +1,6 @@ import { PgBoss } from "pg-boss"; import { config } from "./config.ts"; +import { sqlClient } from "./db/client.ts"; import { log, logErr } from "./util.ts"; export const Q = { @@ -20,7 +21,9 @@ export async function startBoss() { await boss.start(); // agent turns can take very long (MAX thinking) — generous expiry, a few retries // heartbeat: a crashed/restarted worker's job is retried within ~a minute instead of waiting for expiry - await ensureQueue(Q.turn, { expireInSeconds: 3 * 3600, retryLimit: 4, retryDelay: 20, retryBackoff: true, heartbeatSeconds: 60 }); + // Provider outages (revoked auth, 5xx) can last hours: keep retrying with backoff capped at 5 min; + // the runner itself decides when a non-transient error should abort the game. + await ensureQueue(Q.turn, { expireInSeconds: 3 * 3600, retryLimit: 500, retryDelay: 20, retryBackoff: true, retryDelayMax: 300, heartbeatSeconds: 60 }); await ensureQueue(Q.evalPly, { expireInSeconds: 600, retryLimit: 3, retryDelay: 5 }); await ensureQueue(Q.finalize, { expireInSeconds: 3600, retryLimit: 2, retryDelay: 30, heartbeatSeconds: 60 }); await ensureQueue(Q.scheduleTick, { expireInSeconds: 120, retryLimit: 0 }); @@ -28,11 +31,16 @@ export async function startBoss() { } async function ensureQueue(name: string, opts: Record) { - try { - await boss.createQueue(name, opts as any); - } catch { - await boss.updateQueue(name, opts as any).catch(() => {}); - } + // createQueue is a no-op for an existing queue — always push the current options too + await boss.createQueue(name, opts as any).catch(() => {}); + const { heartbeatSeconds: _h, ...upd } = opts; + await boss.updateQueue(name, upd as any).catch((e: unknown) => logErr("pg-boss", `updateQueue ${name}`, e)); +} + +/** is there a live (queued / retrying / running) turn job for this game+ply? */ +export async function hasLiveTurnJob(gameId: string, ply: number): Promise { + const rows = await sqlClient`select 1 from pgboss.job where name = ${Q.turn} and singleton_key = ${`${gameId}:${ply}`} and state in ('created','retry','active') limit 1`; + return rows.length > 0; } export const enqueueTurn = (j: TurnJob) => boss.send(Q.turn, j, { singletonKey: `${j.gameId}:${j.ply}` }); diff --git a/apps/web/src/lib/api.ts b/apps/web/src/lib/api.ts index b94829f..2257c98 100644 --- a/apps/web/src/lib/api.ts +++ b/apps/web/src/lib/api.ts @@ -24,5 +24,6 @@ export const api = { get: (p: string) => req('GET', p), post: (p: string, b?: unknown) => req('POST', p, b ?? {}), patch: (p: string, b?: unknown) => req('PATCH', p, b ?? {}), + put: (p: string, b?: unknown) => req('PUT', p, b ?? {}), del: (p: string) => req('DELETE', p) }; diff --git a/apps/web/src/lib/components/Board.svelte b/apps/web/src/lib/components/Board.svelte index e7d9981..9083215 100644 --- a/apps/web/src/lib/components/Board.svelte +++ b/apps/web/src/lib/components/Board.svelte @@ -11,7 +11,10 @@ orientation = 'white', arrow = null, movable = null, - onmove + onmove, + premove = null, + onpremove, + onpremoveunset }: { fen: string; lastMove?: [string, string]; @@ -21,10 +24,18 @@ /** when set, the given color may move: dests = legal destinations per square */ movable?: { color: 'white' | 'black'; dests: Map } | null; onmove?: (from: string, to: string) => void; + /** queued premove to display (owned by the page; null = none) */ + premove?: [string, string] | null; + /** user dragged a piece while it was the opponent's turn (requires movable.color = my side) */ + onpremove?: (from: string, to: string) => void; + onpremoveunset?: () => void; } = $props(); let el: HTMLDivElement; let api: Api | undefined; + let lastFen = ''; + // chessground fires premove callbacks async (setTimeout) \u2014 count our own cancels to swallow them + let silentUnsets = 0; onMount(() => { api = Chessground(el, { @@ -35,7 +46,18 @@ animation: { enabled: true, duration: 220 }, highlight: { lastMove: true, check: true }, movable: { free: false, color: undefined, showDests: true, events: { after: (o, d) => onmove?.(o, d) } }, - premovable: { enabled: false }, + premovable: { + enabled: true, + showDests: true, + castle: true, + events: { + set: (o, d) => onpremove?.(o, d), + unset: () => { + if (silentUnsets > 0) silentUnsets--; + else onpremoveunset?.(); + } + } + }, draggable: { enabled: true, showGhost: true }, drawable: { enabled: true, @@ -65,6 +87,18 @@ : { color: undefined, dests: new Map() }, drawable: { autoShapes: arrow ? [{ orig: arrow[0] as Key, dest: arrow[1] as Key, brush: 'best' }] : [] } }); + const fenChanged = fen !== lastFen; + lastFen = fen; + const cur = api.state.premovable.current; + if (premove) { + if (!cur || cur[0] !== premove[0] || cur[1] !== premove[1]) { + api.state.premovable.current = premove as Key[] as [Key, Key]; + api.state.dom.redraw(); + } + } else if (cur && fenChanged) { + silentUnsets++; + api.cancelPremove(); + } }); diff --git a/apps/web/src/lib/components/MoveList.svelte b/apps/web/src/lib/components/MoveList.svelte index 9345d9c..04f988c 100644 --- a/apps/web/src/lib/components/MoveList.svelte +++ b/apps/web/src/lib/components/MoveList.svelte @@ -57,7 +57,7 @@ {#if m}
{evalLabel(m.eval)} @@ -148,6 +148,10 @@ font-weight: 600; font-size: 14px; } + .pm { + font-size: 0.8em; + margin-left: 2px; + } .san.illegal { text-decoration: line-through wavy var(--danger); } diff --git a/apps/web/src/lib/game.svelte.ts b/apps/web/src/lib/game.svelte.ts index 9f457f4..a7c44cc 100644 --- a/apps/web/src/lib/game.svelte.ts +++ b/apps/web/src/lib/game.svelte.ts @@ -18,6 +18,9 @@ export class GameView { turn = $state(null); predictions = $state({ counts: {}, mine: null }); error = $state(null); + /** server dropped my premove (illegal after the opponent's reply) */ + stall = $state(null); + premoveDropped = $state<{ side: Side; uci: string; reason: string; at: number } | null>(null); private offs: (() => void)[] = []; constructor(id: string) { @@ -31,6 +34,7 @@ export class GameView { this.moves = r.moves; this.turn = r.live ? { ...r.live, tools: [...r.live.tools] } : null; this.predictions = r.predictions; + this.stall = r.stall ?? null; this.error = null; } catch (e) { this.error = (e as Error).message; @@ -51,6 +55,7 @@ export class GameView { const t = this.turn; switch (ev.type) { case 'turn_start': + this.stall = null; this.turn = { ply: ev.ply, side: ev.side, startedAt: ev.at, thinking: '', text: '', tools: [] }; break; case 'thinking_delta': @@ -68,6 +73,7 @@ export class GameView { break; } case 'move': + this.stall = null; if (!this.moves.some((m) => m.ply === ev.move.ply)) this.moves.push(ev.move); if (this.game) { this.game.ply = ev.move.ply; @@ -87,6 +93,9 @@ export class GameView { } case 'turn_end': break; + case 'premove_dropped': + this.premoveDropped = { side: ev.side, uci: ev.uci, reason: ev.reason, at: Date.now() }; + break; case 'interview': if (this.game) this.game.interviews = { ...this.game.interviews, [ev.side]: ev.text }; break; diff --git a/apps/web/src/lib/types.ts b/apps/web/src/lib/types.ts index ea73b4d..30c703b 100644 --- a/apps/web/src/lib/types.ts +++ b/apps/web/src/lib/types.ts @@ -60,6 +60,8 @@ export interface GameDetail extends GameSummary { interviews: { white?: string | null; black?: string | null }; lastWords: { white?: string | null; black?: string | null }; pendingDrawBy: Side | null; + /** my own queued premove (only sent to the human who set it) */ + premove?: { uci: string; phrase: string | null } | null; createdBy: string | null; error: string | null; } @@ -77,6 +79,8 @@ export interface GameResponse { game: GameDetail; moves: MoveDTO[]; live: LiveTurn | null; + /** last attempt failed (provider outage) — game paused, retried automatically */ + stall?: { note: string; at: string; attempts: number } | null; predictions: { counts: Partial>; mine: 'white' | 'draw' | 'black' | null }; } diff --git a/apps/web/src/routes/match/[id]/+page.svelte b/apps/web/src/routes/match/[id]/+page.svelte index fe4dc7c..6ef5eec 100644 --- a/apps/web/src/routes/match/[id]/+page.svelte +++ b/apps/web/src/routes/match/[id]/+page.svelte @@ -74,13 +74,72 @@ // ---- human move input const myTurn = $derived(!!mySide && g?.status === 'running' && view.sideToMove === mySide && atLive); + // premoves: allowed while the AI opponent thinks (the server plays them the instant it replies) + const canPremove = $derived(!!mySide && g?.status === 'running' && atLive && !myTurn && view.player(otherSide(mySide)).kind === 'ai'); const dests = $derived.by(() => { + if (canPremove) return { color: mySide!, dests: new Map() }; if (!myTurn) return null; const c = new Chess(g!.fen); const m = new Map(); for (const mv of c.moves({ verbose: true })) m.set(mv.from, [...(m.get(mv.from) ?? []), mv.to]); return { color: mySide!, dests: m }; }); + /** my queued premove, pinned to the position (move count) it was made in */ + let pm = $state<{ at: number; from: string; to: string; phrase: string | null } | null>(null); + $effect(() => { + // adopt a premove the server still holds (after a reload) — once per REST snapshot + const sp = g?.premove; + if (!g || !sp) return; + pm = { at: g.ply, from: sp.uci.slice(0, 2), to: sp.uci.slice(2, 4), phrase: sp.phrase }; + g.premove = null; + }); + const premoveShown = $derived<[string, string] | null>(pm && pm.at === view.moves.length && canPremove ? [pm.from, pm.to] : null); + async function setPremove(from: string, to: string) { + moveErr = null; + const piece = new Chess(g!.fen).get(from as any); + const promo = piece?.type === 'p' && (to[1] === '8' || to[1] === '1') ? 'q' : ''; + const at = view.moves.length; + const ph = phrase.trim() || null; + pm = { at, from, to, phrase: ph }; + try { + const r = await api.put<{ played: boolean }>(`/api/games/${view.id}/premove`, { move: from + to + promo, phrase: ph ?? undefined }); + if (ph) phrase = ''; + if (r.played) pm = null; + } catch (e) { + pm = null; + moveErr = (e as Error).message; + } + } + async function unsetPremove() { + if (!pm) return; + pm = null; + await api.del(`/api/games/${view.id}/premove`).catch(() => {}); + } + // ping when the AI finally replies (title + a short beep) — the opponent may think for minutes + let wasMyTurn: boolean | null = null; + $effect(() => { + const now = myTurn; + if (wasMyTurn === false && now) beep(); + wasMyTurn = now; + }); + function beep() { + try { + const ctx = new AudioContext(); + const o = ctx.createOscillator(); + const gn = ctx.createGain(); + o.frequency.value = 660; + gn.gain.setValueAtTime(0.0001, ctx.currentTime); + gn.gain.exponentialRampToValueAtTime(0.15, ctx.currentTime + 0.02); + gn.gain.exponentialRampToValueAtTime(0.0001, ctx.currentTime + 0.35); + o.connect(gn).connect(ctx.destination); + o.start(); + o.stop(ctx.currentTime + 0.4); + o.onended = () => ctx.close(); + } catch { + /* autoplay policy — ignore */ + } + } + const dropped = $derived(view.premoveDropped && view.premoveDropped.side === mySide ? view.premoveDropped : null); let phrase = $state(''); let offerDraw = $state(false); let moveErr = $state(null); @@ -134,7 +193,7 @@ -{g ? `${g.status === 'running' ? 'LIVE · ' : ''}${playerTitle(g.white)} — ${playerTitle(g.black)} · AI·CHESS` : 'AI·CHESS'} +{g ? `${myTurn ? '● Твой ход · ' : g.status === 'running' ? 'LIVE · ' : ''}${playerTitle(g.white)} — ${playerTitle(g.black)} · AI·CHESS` : 'AI·CHESS'} {#if view.error}
{view.error}
@@ -199,6 +258,9 @@
+ {#if g.status === 'running' && view.stall} +
⏸ {view.stall.note} · попыток: {view.stall.attempts}
+ {/if} {#if g.status === 'running' && atLive}
агент видит: {ruleNotes.join(' · ')}
{:else if !atLive} @@ -215,7 +277,7 @@
- +
@@ -236,6 +298,15 @@
{myTurn ? 'Твой ход' : 'Ход соперника'} ты играешь {mySide === 'white' ? 'белыми' : 'чёрными'}
+ {#if premoveShown} +
+ ⚡ премув {premoveShown[0]}–{premoveShown[1]}{#if pm?.phrase} · с репликой{/if} — сыграется сразу после хода соперника, даже если закроешь вкладку + +
+ {:else if canPremove} +
Пока соперник думает, можно сделать премув: перетащи фигуру — ход сыграется мгновенно после его ответа (если будет легален).
+ {/if} + {#if dropped && myTurn}
Премув {dropped.uci.slice(0, 2)}–{dropped.uci.slice(2, 4)} не сработал: стал нелегальным после ответа соперника.
{/if}
@@ -458,6 +529,26 @@ .nav button:last-child { border-right: 0; } + .premove { + display: flex; + align-items: center; + gap: 10px; + flex-wrap: wrap; + font-size: 12px; + padding: 8px 10px; + border: 1px dashed var(--accent); + border-radius: var(--radius); + } + .premove .btn { + margin-left: auto; + } + .hint { + font-size: 12px; + line-height: 1.4; + } + .warn-text { + color: var(--accent-text, var(--accent)); + } .wrap-row { flex-wrap: wrap; font-size: 13px; diff --git a/packages/core/src/position.ts b/packages/core/src/position.ts index 77526a6..eb1e3a6 100644 --- a/packages/core/src/position.ts +++ b/packages/core/src/position.ts @@ -203,6 +203,13 @@ export class GameState { return { ok: true, record: rec }; } + /** piece standing on a square of the current position (null if empty / bad square) */ + pieceAt(square: string): { side: Side; type: PieceSymbol } | null { + if (!/^[a-h][1-8]$/.test(square)) return null; + const p = this.chess.get(square as Square); + return p ? { side: sideOf(p.color), type: p.type } : null; + } + /** * Cheating mode: relocate a piece from->to regardless of rules. Accepts UCI-ish input * ("e2e4", "e2-e4", "e7e8q"). Legal moves should go through tryMove first. diff --git a/packages/core/src/types.ts b/packages/core/src/types.ts index 0f03fd7..bf6ad14 100644 --- a/packages/core/src/types.ts +++ b/packages/core/src/types.ts @@ -94,6 +94,7 @@ export type GameEvent = | { type: "eval"; gameId: string; ply: number; eval: EngineEval; classification?: MoveClass | null; accuracy?: number | null } | { type: "turn_end"; gameId: string; ply: number; usage: Usage } | { type: "draw_offer"; gameId: string; by: Side } + | { type: "premove_dropped"; gameId: string; side: Side; uci: string; reason: string } | { type: "game_over"; gameId: string; result: Result; termination: Termination } | { type: "interview"; gameId: string; side: Side; text: string } | { type: "thumbnail"; gameId: string; url: string; caption: string } @@ -109,6 +110,8 @@ export interface MoveDTO { note: string | null; // note_to_self (only visible to spectators after the game? — shown live, it's fun) offeredDraw: boolean; illegal: boolean; + /** played automatically from the human's premove */ + premoved?: boolean; thinkMs: number; usage: Usage; eval?: EngineEval | null;