From ab38cda1bd7f92cf4536678777dcac109057dbeb Mon Sep 17 00:00:00 2001 From: ai-chess Date: Fri, 15 May 2026 01:10:47 +0300 Subject: [PATCH] feat(menu): unified home screen + ai-vs-ai/play split + human mode MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Routes: - GET / → menu.html (new home/menu). - GET /ai-vs-ai → old index.html (AI-vs-AI live game). - GET /play → same index.html; app.js detects the human side from bindings and enables chessground move input on that side only. - GET /games → unchanged. Backend: - coordinator: 'human' is now an allowed agent type alongside claude/codex. start_new_game accepts overrides[side].agent = 'human'. _send_first / _send_turn / watchdog skip human sides. - POST /api/human-move: humans submit moves from the browser (UCI/SAN + optional comment); rejected if it's not their turn or side isn't human. - /api/options now also returns 'all_agents' = AI agents + 'human' for the human-vs-AI configurator. - pane-agent.sh: when binding agent is 'human', the pane just prints a note and sleeps — no claude/codex is launched for that side. Frontend menu (new public/menu.{html,css,js}): - 'underground tournament' aesthetic: Major Mono Display title, JetBrains Mono body (Google Fonts), warm gold (#c0a060) / crimson (#c04040) accents, subtle film-grain overlay. - Three big mode cards: 01 AI×AI, 02 HUMAN×AI, 03 GAMES·STATS. - Inline configurator below the cards: WHITE / VS / BLACK columns with agent / model / persona selects, persona description preview, swap + randomize tools, abort-current warning that links to /api/abort-game. - Start button routes to /ai-vs-ai or /play depending on whether a human side was picked. Enter submits. - HUD strip with tmux / stockfish / games-played counters. app.js changes: - Chessground constructed with viewOnly toggling; renderBoard rebuilds movable.color + dests = legal moves at the live FEN from chess.js for the human's turn only; board is read-only when scrubbing history, during the AI's turn, or in AI-vs-AI. - humanSide() helper reads bindings; orientation auto-flips when the human plays black. --- public/app.js | 71 ++++++- public/menu.css | 365 ++++++++++++++++++++++++++++++++++++ public/menu.html | 132 +++++++++++++ public/menu.js | 260 +++++++++++++++++++++++++ scripts/pane-agent.sh | 8 + src/ai_chess/app.py | 36 +++- src/ai_chess/coordinator.py | 30 ++- 7 files changed, 889 insertions(+), 13 deletions(-) create mode 100644 public/menu.css create mode 100644 public/menu.html create mode 100644 public/menu.js diff --git a/public/app.js b/public/app.js index 77ce9c1..e4024d7 100644 --- a/public/app.js +++ b/public/app.js @@ -23,12 +23,34 @@ function fenKey(fen) { return parts.slice(0, 3).join(" "); } +async function submitHumanMove(orig, dest, prom) { + const uci = orig + dest + (prom ? prom : ""); + try { + await fetch("/api/human-move", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ move: uci }), + }); + } catch (e) { + console.warn("human-move failed", e); + } +} + const cg = Chessground($("board"), { - viewOnly: true, + viewOnly: false, fen: "start", orientation: "white", - movable: { free: false }, + movable: { free: false, color: undefined, dests: new Map(), showDests: true }, + draggable: { enabled: true, showGhost: true }, + selectable: { enabled: true }, drawable: { enabled: true, visible: true }, + events: { + move: (orig, dest) => { + // Only used in human-vs-AI mode; AI-vs-AI sets movable.color to undefined, + // making this unreachable. + submitHumanMove(orig, dest); + }, + }, }); // ---------- responsive board sizing ---------- @@ -72,6 +94,25 @@ function currentFen() { return c.fen(); } +function humanSide() { + const b = STATE.bindings || {}; + if (b.white?.agent === "human") return "white"; + if (b.black?.agent === "human") return "black"; + return null; +} + +function legalDestsForFen(fen) { + // Build a Map of legal moves at this position. Used to let + // chessground accept only legal squares for the human side. + const c = new Chess(fen); + const dests = new Map(); + for (const m of c.moves({ verbose: true })) { + if (!dests.has(m.from)) dests.set(m.from, []); + dests.get(m.from).push(m.to); + } + return dests; +} + function renderBoard() { if (!STATE.game) return; const moves = (STATE.game.history || []).filter(h => h.san); @@ -82,13 +123,33 @@ function renderBoard() { const uci = moves[idx].uci || ""; if (uci.length >= 4) lastMove = [uci.slice(0, 2), uci.slice(2, 4)]; } - // Pass shapes via set() to atomically replace last move + arrow. - // Arrow comes from stored eval for this FEN, if any. const e = STATE.evalByFen.get(fenKey(fen)); const shapes = (e && e.best_uci && e.best_uci.length >= 4) ? [{ orig: e.best_uci.slice(0, 2), dest: e.best_uci.slice(2, 4), brush: "green" }] : []; - cg.set({ fen, lastMove, drawable: { autoShapes: shapes } }); + + // Human-vs-AI: enable board moves only on the human's turn at the live FEN. + const hSide = humanSide(); + const sideToMove = STATE.game.side_to_move; + const isHumanTurn = ( + hSide && hSide === sideToMove + && STATE.viewPly === null + && !STATE.game.status?.result + ); + + const movable = isHumanTurn + ? { free: false, color: hSide, dests: legalDestsForFen(fen), showDests: true, events: {} } + : { free: false, color: undefined, dests: new Map(), showDests: false }; + + cg.set({ + fen, lastMove, + orientation: hSide === "black" ? "black" : "white", + movable, + draggable: { enabled: !!isHumanTurn, showGhost: true }, + selectable: { enabled: !!isHumanTurn }, + drawable: { enabled: true, visible: true, autoShapes: shapes }, + viewOnly: !isHumanTurn, + }); $("live-btn").hidden = STATE.viewPly === null; applyEvalForFen(fen); } diff --git a/public/menu.css b/public/menu.css new file mode 100644 index 0000000..7e62354 --- /dev/null +++ b/public/menu.css @@ -0,0 +1,365 @@ +/* ==================================================================== + ai-chess MENU — fight-club / tournament bulletin aesthetic + palette + ink #0a0a0c (background bottom) + paper #15151a (panels) + bone #e7e4d8 (primary text) + ash #6a6a72 (muted text) + gold #c0a060 (rule / decisions / accept) + crimson #c04040 (fight / abort) + gold-dim #6b5a35 + crimson-dim #6b2222 + ==================================================================== */ + +:root { + --ink: #0a0a0c; + --paper: #15151a; + --paper-2: #1d1d23; + --bone: #e7e4d8; + --bone-dim: #b8b4a3; + --ash: #6a6a72; + --rule: #2a2a30; + --gold: #c0a060; + --gold-dim: #6b5a35; + --crimson: #c04040; + --crimson-dim:#6b2222; +} + +* { box-sizing: border-box; } +html, body { + margin: 0; + background: radial-gradient(ellipse at 50% -10%, #1e1e24 0%, var(--ink) 60%) fixed; + color: var(--bone); + font-family: "JetBrains Mono", ui-monospace, SFMono-Regular, Menlo, monospace; + font-weight: 400; + line-height: 1.4; + min-height: 100vh; +} + +/* fine grain / film texture */ +.grain { + position: fixed; inset: 0; pointer-events: none; z-index: 100; + opacity: 0.06; + background-image: + repeating-linear-gradient(0deg, transparent 0 2px, rgba(255,255,255,0.05) 2px 3px), + repeating-linear-gradient(90deg, transparent 0 2px, rgba(255,255,255,0.04) 2px 3px); + mix-blend-mode: overlay; +} + +/* ---------- TOPBAR ---------- */ +.topbar { + display: flex; justify-content: space-between; align-items: baseline; + padding: 22px 36px; + font-size: 11px; letter-spacing: 0.16em; text-transform: uppercase; + color: var(--ash); + border-bottom: 1px solid var(--rule); +} +.brand { + color: var(--gold); + font-weight: 800; + letter-spacing: 0.22em; + font-size: 12px; +} +.topbar-meta { display: flex; gap: 10px; align-items: baseline; } +.topbar-meta .sep { opacity: 0.4; } +.topbar-meta .ver { color: var(--gold); } + +/* ---------- HERO ---------- */ +.hero { + max-width: 1180px; + margin: 0 auto; + padding: 36px 36px 80px; +} + +.badge-row { + display: flex; align-items: center; gap: 14px; + font-size: 10px; letter-spacing: 0.32em; color: var(--gold); + text-transform: uppercase; + margin-bottom: 16px; +} +.badge-line { flex: 1; height: 1px; background: linear-gradient(90deg, transparent, var(--gold-dim), transparent); } +.badge { white-space: nowrap; } + +.title { + font-family: "Major Mono Display", "JetBrains Mono", monospace; + font-size: clamp(56px, 9vw, 132px); + line-height: 0.9; + letter-spacing: 0.04em; + margin: 0 0 18px; + text-align: center; + color: var(--bone); + text-shadow: 0 0 60px rgba(192,160,96,0.18); + font-weight: 400; + display: flex; + justify-content: center; + align-items: baseline; + gap: 0.18em; + flex-wrap: nowrap; + white-space: nowrap; +} +.title .t1, .title .t2 { color: var(--bone); white-space: nowrap; } +.title .t-dot { + color: var(--crimson); + display: inline-block; + transform: translateY(-0.08em); + animation: pulse-dot 2s ease-in-out infinite; +} +@keyframes pulse-dot { + 0%,100% { opacity: 0.7; text-shadow: 0 0 18px var(--crimson-dim); } + 50% { opacity: 1; text-shadow: 0 0 36px var(--crimson); } +} + +.tagline { + text-align: center; + color: var(--bone-dim); + font-size: 14px; + letter-spacing: 0.02em; + margin: 0 auto 56px; + max-width: 620px; + font-style: italic; +} + +/* ---------- MODE CARDS ---------- */ +.modes { + display: grid; + grid-template-columns: repeat(3, 1fr); + gap: 14px; + margin-bottom: 32px; +} +.mode { + position: relative; + background: var(--paper); + border: 1px solid var(--rule); + border-radius: 4px; + padding: 26px 22px 22px; + cursor: pointer; + text-align: left; + color: var(--bone); + font-family: inherit; + font-size: 13px; + display: flex; flex-direction: column; gap: 8px; + min-height: 168px; + transition: transform 0.18s ease, border-color 0.18s, background 0.18s, box-shadow 0.18s; + text-decoration: none; + overflow: hidden; +} +.mode::before { + content: ""; + position: absolute; inset: 0; + background: + repeating-linear-gradient(45deg, transparent 0 6px, rgba(255,255,255,0.012) 6px 12px); + pointer-events: none; +} +.mode:hover { + transform: translateY(-2px); + border-color: var(--bone-dim); + background: var(--paper-2); +} +.mode-num { + font-size: 10px; + color: var(--ash); + letter-spacing: 0.3em; +} +.mode-name { + font-size: 22px; + font-weight: 800; + letter-spacing: 0.04em; + margin-top: 2px; +} +.mode-name .x { color: var(--crimson); margin: 0 4px; font-weight: 400; } +.mode-desc { + color: var(--bone-dim); + font-size: 12px; + line-height: 1.5; + flex: 1; +} +.mode-tag { + align-self: flex-start; + padding: 2px 8px; + font-size: 9px; + letter-spacing: 0.25em; + border: 1px solid currentColor; + border-radius: 2px; + text-transform: uppercase; +} +.tag-gold { color: var(--gold); } +.tag-crimson { color: var(--crimson); } +.tag-neutral { color: var(--ash); } + +/* Selected card */ +.mode[aria-pressed="true"] { + border-color: var(--gold); + box-shadow: 0 0 0 1px var(--gold), 0 20px 60px -30px rgba(192,160,96,0.4); + background: var(--paper-2); +} +.mode[aria-pressed="true"][data-mode="human_vs_ai"] { + border-color: var(--crimson); + box-shadow: 0 0 0 1px var(--crimson), 0 20px 60px -30px rgba(192,64,64,0.4); +} + +/* ---------- SETUP ---------- */ +.setup { + background: var(--paper); + border: 1px solid var(--rule); + border-radius: 4px; + padding: 24px 24px 18px; + margin-bottom: 28px; + animation: setup-in 0.3s ease both; +} +@keyframes setup-in { + from { opacity: 0; transform: translateY(8px); } + to { opacity: 1; transform: none; } +} +.setup-head { + display: flex; align-items: center; gap: 14px; + border-bottom: 1px dashed var(--rule); + padding-bottom: 12px; margin-bottom: 18px; +} +.setup-step { + font-size: 10px; letter-spacing: 0.3em; color: var(--gold); + text-transform: uppercase; +} +.setup-title { + font-size: 12px; letter-spacing: 0.06em; color: var(--bone-dim); +} +.setup-tools { margin-left: auto; display: flex; gap: 6px; } +.tool { + background: transparent; color: var(--bone-dim); border: 1px solid var(--rule); + padding: 3px 10px; font-size: 11px; font-family: inherit; cursor: pointer; + border-radius: 3px; letter-spacing: 0.05em; +} +.tool:hover { border-color: var(--bone-dim); color: var(--bone); } + +.sides { + display: grid; + grid-template-columns: 1fr 56px 1fr; + gap: 14px; + align-items: stretch; +} +.side { + border: 1px solid var(--rule); + border-radius: 4px; + padding: 18px 16px 16px; + background: rgba(0,0,0,0.18); + margin: 0; + display: flex; flex-direction: column; gap: 12px; + position: relative; +} +.side legend { + display: flex; align-items: center; gap: 8px; + padding: 0 8px; + font-size: 11px; letter-spacing: 0.3em; font-weight: 800; +} +.legend-pip { + display: inline-block; width: 8px; height: 8px; + background: var(--bone); border-radius: 50%; +} +.side-white legend { color: var(--bone); } +.side-white .legend-pip { background: var(--bone); } +.side-black legend { color: var(--bone-dim); } +.side-black .legend-pip { background: #1a1a1a; box-shadow: inset 0 0 0 1px var(--bone-dim); } + +.field { + display: flex; flex-direction: column; gap: 4px; + font-size: 10px; letter-spacing: 0.18em; text-transform: uppercase; + color: var(--ash); +} +.field select { + background: var(--paper-2); color: var(--bone); + border: 1px solid var(--rule); border-radius: 3px; + padding: 6px 8px; + font-family: inherit; font-size: 13px; letter-spacing: 0; + text-transform: none; + appearance: none; + background-image: + linear-gradient(45deg, transparent 50%, var(--bone-dim) 50%), + linear-gradient(-45deg, transparent 50%, var(--bone-dim) 50%); + background-position: calc(100% - 12px) 12px, calc(100% - 7px) 12px; + background-size: 5px 5px, 5px 5px; + background-repeat: no-repeat; +} +.field select:focus { outline: 1px solid var(--gold); border-color: var(--gold); } + +.persona-desc { + font-size: 11px; line-height: 1.5; color: var(--bone-dim); + margin: 4px 0 0; min-height: 2.4em; font-style: italic; +} +.human-note { + font-size: 11px; color: var(--crimson); margin: 0; + border: 1px dashed var(--crimson-dim); padding: 8px 10px; border-radius: 3px; +} + +.vs { + display: flex; align-items: center; justify-content: center; + font-size: 28px; font-weight: 800; color: var(--crimson); + letter-spacing: 0.1em; + position: relative; +} +.vs::before, .vs::after { + content: ""; position: absolute; left: 50%; transform: translateX(-50%); + width: 1px; height: 28%; background: var(--rule); +} +.vs::before { top: 0; } +.vs::after { bottom: 0; } + +/* warning + footer */ +#setup-warning { + margin-top: 16px; + background: rgba(192,64,64,0.08); + border: 1px solid var(--crimson-dim); + color: #e0a0a0; + padding: 10px 14px; + font-size: 12px; letter-spacing: 0.04em; + border-radius: 3px; +} +.link-abort { + background: transparent; border: none; color: var(--crimson); + text-decoration: underline; cursor: pointer; font: inherit; padding: 0; +} + +.setup-foot { + display: flex; align-items: center; justify-content: space-between; + margin-top: 18px; padding-top: 16px; border-top: 1px dashed var(--rule); +} +.back { + color: var(--ash); text-decoration: none; font-size: 12px; +} +.back:hover { color: var(--bone); } + +.start { + display: inline-flex; align-items: center; gap: 12px; + background: var(--gold); color: #1a1410; + border: none; padding: 10px 26px; + font-family: inherit; font-size: 14px; font-weight: 800; letter-spacing: 0.16em; + cursor: pointer; + border-radius: 3px; + transition: filter 0.15s, transform 0.1s; + box-shadow: 0 6px 24px -10px var(--gold); +} +.start:hover:not(:disabled) { filter: brightness(1.08); transform: translateY(-1px); } +.start:active:not(:disabled) { transform: translateY(0); } +.start:disabled { background: var(--rule); color: var(--ash); cursor: not-allowed; box-shadow: none; } +.start .kbd { + font-size: 11px; opacity: 0.7; + border: 1px solid rgba(0,0,0,0.3); padding: 1px 6px; border-radius: 2px; +} +.setup[data-mode="human_vs_ai"] .start { background: var(--crimson); color: #fff; box-shadow: 0 6px 24px -10px var(--crimson); } + +/* ---------- HUD footer ---------- */ +.hud { + display: flex; gap: 26px; justify-content: center; + margin-top: 32px; + font-size: 10px; letter-spacing: 0.2em; color: var(--ash); + text-transform: uppercase; + border-top: 1px solid var(--rule); padding-top: 16px; +} +.hud code { + font-family: inherit; color: var(--gold); letter-spacing: 0.02em; text-transform: none; +} + +/* ---------- responsive ---------- */ +@media (max-width: 880px) { + .modes { grid-template-columns: 1fr; } + .sides { grid-template-columns: 1fr; } + .vs { padding: 8px 0; } +} diff --git a/public/menu.html b/public/menu.html new file mode 100644 index 0000000..f94fa76 --- /dev/null +++ b/public/menu.html @@ -0,0 +1,132 @@ + + + + + ai-chess + + + + + + +
+ +
+
AI·CHESS
+
+ two llm. one crown. + · + stockfish-judged + · + v0.1 +
+
+ +
+
+ + UNDERGROUND TOURNAMENT + +
+ +

+ AI·CHESS +

+

две LLM выходят на доску. одна возвращается. без подсказок, без коучей, всё — на трэш-токе.

+ +
+ + + +
03
+
GAMES · STATS
+
Архив прошлых драк, лидерборд персонажей, реплеи с эвалами.
+
ARCHIVE
+
+
+ + + +
+ tmux: … + stockfish: … + games played: … +
+
+ + + + diff --git a/public/menu.js b/public/menu.js new file mode 100644 index 0000000..258361b --- /dev/null +++ b/public/menu.js @@ -0,0 +1,260 @@ +const $ = (id) => document.getElementById(id); + +const STATE = { + options: null, + mode: null, // "ai_vs_ai" | "human_vs_ai" | null + inProgress: false, +}; + +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); + } catch (e) { + STATE.inProgress = false; + } +} +function refreshGate() { + $("setup-warning").hidden = !STATE.inProgress; + $("start-btn").disabled = STATE.inProgress; +} + +// ---------- 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(); + refreshHud(); + setInterval(refreshHud, 5000); + + // 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 + $("abort-current").addEventListener("click", async () => { + await fetch("/api/abort-game", { method: "POST" }); + setTimeout(async () => { await loadInProgress(); refreshGate(); 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(); diff --git a/scripts/pane-agent.sh b/scripts/pane-agent.sh index d214509..25c5274 100755 --- a/scripts/pane-agent.sh +++ b/scripts/pane-agent.sh @@ -40,6 +40,14 @@ esac echo "[pane-agent] side=$side agent=$agent claude_theme=$claude_theme codex_theme=\"$codex_theme\"" +if [ "$agent" = "human" ]; then + cat < FastAPI: await start_new_game(state, overrides=overrides) return state.game.get_state() # type: ignore[union-attr] + @app.post("/api/human-move") + async def human_move(body: dict[str, Any]) -> dict[str, Any]: + """The human side submits a move from the browser. Accepts UCI/SAN + plus an optional comment. Only succeeds if the side-to-move is bound + to agent='human'.""" + if state.game is None or state.game.is_game_over(): + return {"ok": False, "reason": "no_active_game"} + side_to_move = state.game.side_to_move + binding = state.bindings.get(side_to_move) + if not binding or binding.agent != "human": + return {"ok": False, "reason": "not_your_turn_or_not_human"} + move_str = str(body.get("move") or "").strip() + if not move_str: + return {"ok": False, "reason": "missing_move"} + comment = body.get("comment") + if comment is not None: + comment = str(comment) + from ai_chess.mcp_server import build_tools_for_side + tools = build_tools_for_side(side_to_move, state) + return await tools["move"]({"move": move_str, "comment": comment}) + @app.post("/api/abort-game") async def abort_game() -> dict[str, Any]: if state.game is None: @@ -226,7 +247,8 @@ def build_app(state: state_mod.AppState) -> FastAPI: from ai_chess.coordinator import AGENTS, MODEL_OPTIONS from ai_chess.prompts import list_prompt_presets, DEFAULT_PROMPT return { - "agents": AGENTS, + "agents": AGENTS, # only AI agent ids — used for AI-vs-AI screen + "all_agents": AGENTS + ["human"], "models": MODEL_OPTIONS, "prompts": list_prompt_presets(), "defaults": {"prompt": DEFAULT_PROMPT}, @@ -419,7 +441,17 @@ def build_app(state: state_mod.AppState) -> FastAPI: app.mount("/static", StaticFiles(directory=state_mod.PUBLIC_DIR), name="static") @app.get("/") - async def index() -> FileResponse: + async def menu_page() -> FileResponse: + return FileResponse(state_mod.PUBLIC_DIR / "menu.html") + + @app.get("/ai-vs-ai") + async def ai_vs_ai_page() -> FileResponse: + return FileResponse(state_mod.PUBLIC_DIR / "index.html") + + @app.get("/play") + async def play_page() -> FileResponse: + # Same UI as /ai-vs-ai — app.js detects the human binding and + # enables board interactivity for that side. return FileResponse(state_mod.PUBLIC_DIR / "index.html") @app.get("/games") diff --git a/src/ai_chess/coordinator.py b/src/ai_chess/coordinator.py index 03c4a60..9f715e9 100644 --- a/src/ai_chess/coordinator.py +++ b/src/ai_chess/coordinator.py @@ -26,6 +26,8 @@ MODEL_OPTIONS: dict[str, list[str]] = { "codex": ["gpt-5.5", "gpt-5.4", "gpt-5"], } AGENTS: list[str] = ["claude", "codex"] +HUMAN: str = "human" +ALL_AGENT_TYPES: list[str] = AGENTS + [HUMAN] def _default_model(agent: str) -> str: @@ -38,6 +40,8 @@ def _default_effort(agent: str) -> str: def _make_binding(side: Side, agent: str, model: str | None = None, effort: str | None = None) -> AgentBinding: + if agent == HUMAN: + return AgentBinding(side=side, agent=HUMAN, model="human", effort="") if agent not in AGENTS: raise ValueError(f"unknown agent: {agent!r}") mdl = model or _default_model(agent) @@ -68,21 +72,20 @@ async def start_new_game( None — in that case the full assignment is random. """ overrides = overrides or {} - # 1) decide agent per side + # 1) decide agent per side (HUMAN is allowed) side_to_agent: dict[Side, str] = {} chosen = set() for side in (Side.WHITE, Side.BLACK): ov = overrides.get(side.value, {}) or {} a = ov.get("agent") - if a in AGENTS: + if a in ALL_AGENT_TYPES: side_to_agent[side] = a - chosen.add(a) - # fill remaining sides randomly from agents not yet placed + if a in AGENTS: + chosen.add(a) + # fill remaining sides randomly from AI agents not yet placed remaining_sides = [s for s in (Side.WHITE, Side.BLACK) if s not in side_to_agent] remaining_agents = [a for a in AGENTS if a not in chosen] random.shuffle(remaining_agents) - # if user specified the same agent on both sides, keep both — useful for - # claude-vs-claude games when more model variants exist. while len(remaining_agents) < len(remaining_sides): remaining_agents.append(random.choice(AGENTS)) for side, agent in zip(remaining_sides, remaining_agents): @@ -148,8 +151,16 @@ class Coordinator: except Exception as e: print(f"[coordinator] tmux submit to {side.value} failed: {e}", flush=True) + def _is_human(self, side: Side) -> bool: + b = self.state.bindings.get(side) + return bool(b and b.agent == "human") + async def _send_first(self, side: Side, *, opponent_san: str | None, opponent_comment: str | None) -> None: + if self._is_human(side): + # Humans drive their turn via /api/human-move — no prompt to inject. + self.state.first_move_sent[side] = True + return if self.state.first_move_sent[side]: return opp_name, opp_model = self._opponent(side) @@ -171,6 +182,9 @@ class Coordinator: async def _send_turn(self, side: Side, *, opponent_san: str, opponent_comment: str | None, pending_draw: bool) -> None: + if self._is_human(side): + # Human turn — UI waits and submits via /api/human-move. + return if not self.state.first_move_sent[side]: await self._send_first(side, opponent_san=opponent_san, opponent_comment=opponent_comment) return @@ -185,6 +199,10 @@ class Coordinator: self._mark_waiting(side) def _mark_waiting(self, side: Side) -> None: + # Don't watchdog a human — they take however long they take. + if self._is_human(side): + self._waiting_side = None + return self._waiting_side = side self._waiting_started_at = asyncio.get_event_loop().time() self.state.nudge_count[side] = 0