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
+335
View File
@@ -0,0 +1,335 @@
const $ = (id) => document.getElementById(id);
const STATE = {
options: null,
mode: null, // "ai_vs_ai" | "human_vs_ai" | null
inProgress: false,
game: null, // current game payload (only set when in progress)
bindings: null,
};
const SIDES = ["white", "black"];
function elSelect(side, name) {
return document.querySelector(`fieldset[data-side="${side}"] select[name="${name}"]`);
}
function elField(side, when) {
return document.querySelectorAll(`fieldset[data-side="${side}"] [data-when="${when}"]`);
}
// ---------- option loaders ----------
function fillAgentSelect(sel, agents) {
sel.innerHTML = "";
for (const a of agents) {
const o = document.createElement("option");
o.value = a;
o.textContent = a === "human" ? "you (human)" : a;
sel.appendChild(o);
}
}
function fillModelSelect(side) {
const agent = elSelect(side, "agent").value;
const sel = elSelect(side, "model");
sel.innerHTML = "";
if (agent === "human") return;
for (const m of (STATE.options.models[agent] || [])) {
const o = document.createElement("option");
o.value = m; o.textContent = m;
sel.appendChild(o);
}
}
function fillPromptSelect(side) {
const sel = elSelect(side, "prompt");
sel.innerHTML = "";
for (const p of STATE.options.prompts) {
const o = document.createElement("option");
o.value = p.id; o.textContent = p.label; o.dataset.desc = p.description;
sel.appendChild(o);
}
if (STATE.options.defaults?.prompt) sel.value = STATE.options.defaults.prompt;
updatePersonaDesc(side);
}
function updatePersonaDesc(side) {
const sel = elSelect(side, "prompt");
const target = document.querySelector(`fieldset[data-side="${side}"] .persona-desc`);
if (!sel || !target) return;
target.textContent = sel.options[sel.selectedIndex]?.dataset?.desc || "";
}
function refreshSide(side) {
const agent = elSelect(side, "agent").value;
fillModelSelect(side);
fillPromptSelect(side);
for (const el of elField(side, "ai")) el.hidden = (agent === "human");
for (const el of elField(side, "human")) el.hidden = (agent !== "human");
}
// ---------- mode selection ----------
function setMode(mode) {
STATE.mode = mode;
document.querySelectorAll(".mode").forEach((m) => {
m.setAttribute("aria-pressed", m.dataset.mode === mode ? "true" : "false");
});
const setup = $("setup");
setup.hidden = false;
setup.dataset.mode = mode;
$("setup-title").textContent =
mode === "ai_vs_ai" ? "configure the fight" : "you vs the silicon hustler";
// Set defaults per mode
const whiteAgentSel = elSelect("white", "agent");
const blackAgentSel = elSelect("black", "agent");
if (mode === "ai_vs_ai") {
fillAgentSelect(whiteAgentSel, STATE.options.agents);
fillAgentSelect(blackAgentSel, STATE.options.agents);
whiteAgentSel.value = STATE.options.agents[0];
blackAgentSel.value = STATE.options.agents[1] || STATE.options.agents[0];
} else if (mode === "human_vs_ai") {
// Default: human plays white, an AI plays black.
fillAgentSelect(whiteAgentSel, STATE.options.all_agents);
fillAgentSelect(blackAgentSel, STATE.options.all_agents);
whiteAgentSel.value = "human";
blackAgentSel.value = STATE.options.agents[0];
}
refreshSide("white");
refreshSide("black");
// scroll to setup
setTimeout(() => setup.scrollIntoView({ behavior: "smooth", block: "start" }), 60);
refreshGate();
}
// ---------- gating ----------
async function loadInProgress() {
try {
const s = await (await fetch("/api/state")).json();
STATE.inProgress = !!(s.game && !s.game.status?.result);
STATE.game = STATE.inProgress ? s.game : null;
STATE.bindings = STATE.inProgress ? s.bindings : null;
} catch (e) {
STATE.inProgress = false;
STATE.game = null;
STATE.bindings = null;
}
}
function refreshGate() {
$("setup-warning").hidden = !STATE.inProgress;
$("start-btn").disabled = STATE.inProgress;
}
// ---------- active game card ----------
function renderActiveCard() {
const card = $("active-card");
const modes = $("modes");
const setup = $("setup");
if (!STATE.inProgress) {
card.hidden = true;
modes.hidden = false;
return;
}
// Hide picker + setup, show the live card.
card.hidden = false;
modes.hidden = true;
setup.hidden = true;
const g = STATE.game || {};
const b = STATE.bindings || {};
const promptLabel = (id) => {
if (!id) return "";
const p = (STATE.options?.prompts || []).find(x => x.id === id);
return p ? p.label : id;
};
// Pull prompt out of game.agents (the dict committed by start_new_game) —
// bindings may not carry it.
const wA = g.agents?.white || {};
const bA = g.agents?.black || {};
$("active-white-agent").textContent = (wA.agent || "?");
$("active-white-model").textContent = wA.agent === "human" ? "controlled by you" : (wA.model || "?");
$("active-white-persona").textContent = wA.agent === "human" ? "" : promptLabel(wA.prompt);
$("active-black-agent").textContent = (bA.agent || "?");
$("active-black-model").textContent = bA.agent === "human" ? "controlled by you" : (bA.model || "?");
$("active-black-persona").textContent = bA.agent === "human" ? "" : promptLabel(bA.prompt);
// current state strip
const moves = (g.history || []).filter(h => h.san).length;
$("active-meta").textContent = `move ${Math.ceil(moves/2) + (g.side_to_move === "white" ? 0 : 0)} · ${moves} half-moves · ${g.id ? g.id.slice(0,10) : ""}…`;
const sideRu = g.side_to_move === "white" ? "белые" : "чёрные";
const moverAgent = (g.side_to_move === "white" ? wA.agent : bA.agent) || "?";
$("active-turn").textContent = `${moverAgent} (${sideRu}) thinks…`;
// Pick the right destination for watch
const watchHref = (wA.agent === "human" || bA.agent === "human") ? "/play" : "/ai-vs-ai";
$("watch-btn").setAttribute("href", watchHref);
}
// ---------- HUD ----------
async function refreshHud() {
try {
const s = await (await fetch("/api/state")).json();
$("hud-sf").textContent = `depth ${s.settings?.stockfish_depth ?? "?"}`;
if (s.game && !s.game.status?.result) {
$("hud-tmux").textContent = "session ‘chess’ running";
} else {
$("hud-tmux").textContent = "idle";
}
} catch (e) { /* ignore */ }
try {
// games count is allowed only when no active game.
const r = await fetch("/api/stats");
if (r.ok) {
const j = await r.json();
$("hud-games").textContent = String(j.total_games);
} else {
$("hud-games").textContent = "—";
}
} catch (e) {
$("hud-games").textContent = "—";
}
}
// ---------- start ----------
function readOverrides() {
const overrides = { white: {}, black: {} };
for (const side of SIDES) {
const agent = elSelect(side, "agent").value;
overrides[side].agent = agent;
if (agent !== "human") {
overrides[side].model = elSelect(side, "model").value;
overrides[side].prompt = elSelect(side, "prompt").value;
}
}
return overrides;
}
async function start() {
const overrides = readOverrides();
const r = await fetch("/api/new-game", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ overrides }),
});
if (r.status === 409) {
STATE.inProgress = true;
refreshGate();
return;
}
if (!r.ok) {
const detail = await r.text();
alert("Failed to start: " + detail);
return;
}
// Kick off the first prompt for AI side(s)
fetch("/api/dispatch-first", { method: "POST" }).catch(() => {});
// Route to the right gameplay page
const isHumanGame = (
overrides.white.agent === "human" || overrides.black.agent === "human"
);
location.href = isHumanGame ? "/play" : "/ai-vs-ai";
}
// ---------- wiring ----------
async function init() {
STATE.options = await (await fetch("/api/options")).json();
await loadInProgress();
renderActiveCard();
refreshHud();
setInterval(refreshHud, 5000);
// Poll the active-card payload so the meta strip ('move N · whose turn')
// updates without a page reload. Skipped while no game is live.
setInterval(async () => {
const before = STATE.inProgress;
await loadInProgress();
renderActiveCard();
// Game just ended? Unblock the picker.
if (before && !STATE.inProgress) {
$("modes").hidden = false;
}
}, 3000);
// Mode picker
document.querySelectorAll(".mode[data-mode]").forEach((el) => {
el.addEventListener("click", () => setMode(el.dataset.mode));
});
// Side change handlers
for (const side of SIDES) {
elSelect(side, "agent").addEventListener("change", () => refreshSide(side));
elSelect(side, "prompt").addEventListener("change", () => updatePersonaDesc(side));
}
// Swap & randomize
$("btn-swap").addEventListener("click", () => {
for (const name of ["agent", "model", "prompt"]) {
const w = elSelect("white", name);
const b = elSelect("black", name);
if (!w || !b) continue;
const tmp = w.value; w.value = b.value; b.value = tmp;
}
refreshSide("white"); refreshSide("black");
});
$("btn-random").addEventListener("click", () => {
const pool = (STATE.mode === "human_vs_ai")
? [...STATE.options.agents] // randomize only the AI agent (keep human side)
: [...STATE.options.agents];
pool.sort(() => Math.random() - 0.5);
if (STATE.mode === "ai_vs_ai") {
elSelect("white", "agent").value = pool[0];
elSelect("black", "agent").value = pool[1] || pool[0];
} else {
// Find which side is currently AI and randomize that one
for (const side of SIDES) {
if (elSelect(side, "agent").value !== "human") {
elSelect(side, "agent").value = pool[Math.floor(Math.random() * pool.length)];
}
}
}
refreshSide("white"); refreshSide("black");
// Random model + prompt for AI sides
for (const side of SIDES) {
const agent = elSelect(side, "agent").value;
if (agent === "human") continue;
const models = STATE.options.models[agent];
elSelect(side, "model").value = models[Math.floor(Math.random() * models.length)];
const prompts = STATE.options.prompts.map(p => p.id);
elSelect(side, "prompt").value = prompts[Math.floor(Math.random() * prompts.length)];
updatePersonaDesc(side);
}
});
// Back link → close setup
$("back-link").addEventListener("click", (e) => {
e.preventDefault();
$("setup").hidden = true;
STATE.mode = null;
document.querySelectorAll(".mode").forEach((m) => m.setAttribute("aria-pressed", "false"));
});
// Abort current (inside the setup dialog warning)
$("abort-current").addEventListener("click", async () => {
await fetch("/api/abort-game", { method: "POST" });
setTimeout(async () => {
await loadInProgress(); refreshGate(); refreshHud(); renderActiveCard();
}, 200);
});
// Abort current from the active-card (visible only when a game is live)
$("active-abort").addEventListener("click", async () => {
if (!confirm("Прервать текущую партию?")) return;
await fetch("/api/abort-game", { method: "POST" });
setTimeout(async () => { await loadInProgress(); renderActiveCard(); refreshHud(); }, 200);
});
// Start
$("start-btn").addEventListener("click", start);
// Enter starts the game when setup is open and not blocked
window.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !$("setup").hidden && !$("start-btn").disabled) {
e.preventDefault(); start();
}
});
}
init();