clichess-cli 0.9.0__3-py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
clichess.py ADDED
@@ -0,0 +1,1625 @@
1
+ #!/usr/bin/env python3
2
+ """clichess — play chess against any LLM, in your terminal.
3
+
4
+ First run walks you through creating an "AI opponent" (model, endpoint, key) and
5
+ stores it locally. Each game then starts with a brief: you say what kind of game
6
+ you want, the model agrees on a plan, and that plan goes into the system prompt
7
+ for the whole game.
8
+
9
+ Only dependency: python-chess. Stockfish is optional, used for the eval score.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import argparse
15
+ import colorsys
16
+ import getpass
17
+ import json
18
+ import os
19
+ import random
20
+ import platform
21
+ import re
22
+ import shutil
23
+ import subprocess
24
+ import sys
25
+ import tarfile
26
+ import tempfile
27
+ import textwrap
28
+ import time
29
+ import urllib.error
30
+ import urllib.request
31
+ import zipfile
32
+ from dataclasses import dataclass, replace
33
+ from pathlib import Path
34
+
35
+ import chess
36
+ import chess.pgn
37
+
38
+ # A terminal may hand us bytes in a locale that is not UTF-8; read them as UTF-8
39
+ # anyway instead of turning them into lone surrogates.
40
+ for _stream in (sys.stdin, sys.stdout):
41
+ try:
42
+ _stream.reconfigure(encoding="utf-8", errors="replace")
43
+ except Exception:
44
+ pass
45
+
46
+
47
+ # ─────────────────────────── paths and constants ───────────────────────────
48
+
49
+ try:
50
+ from importlib.metadata import version as _pkg_version
51
+ __version__ = _pkg_version("clichess-cli")
52
+ except Exception:
53
+ __version__ = "0.9.0"
54
+
55
+ STATE_DIR = Path(os.environ.get("CLICHESS_STATE_DIR", Path.home() / ".local/state/clichess"))
56
+ OPP_DIR = Path(os.environ.get("CLICHESS_OPPONENTS_DIR", Path.home() / ".config/clichess/opponents"))
57
+
58
+ DEPTH = 15 # eval depth
59
+ CANDIDATES = 5 # moves to ask the model for each turn
60
+ FLAIR = 0.8 # pawns a candidate may lose before it is dropped
61
+ EFFORT = None # "low" halves the wait on reasoning models
62
+
63
+ DEFAULT_BASE = "https://api.deepseek.com"
64
+ DEFAULT_MODEL = "deepseek-chat"
65
+ @dataclass
66
+ class Cfg:
67
+ base_url: str = DEFAULT_BASE
68
+ model: str = DEFAULT_MODEL
69
+ api_key: str = ""
70
+ timeout: float = 180.0
71
+ retries: int = 3
72
+ temperature: float = 0.4
73
+ color: bool = True
74
+ coords: bool = True # a-h / 1-8 around the board
75
+ show_say: bool = True # the opponent's commentary column
76
+ show_panel: bool = True # eval / last / move
77
+ debug: bool = False
78
+ max_tokens: int = 2000
79
+
80
+ def endpoint(self) -> str:
81
+ b = self.base_url.rstrip("/")
82
+ if b.endswith("/chat/completions"):
83
+ return b
84
+ if b.endswith("/v1"):
85
+ return b + "/chat/completions"
86
+ return b + "/v1/chat/completions"
87
+
88
+
89
+ @dataclass
90
+ class Opponent:
91
+ """A reusable AI opponent: connection details plus a persona."""
92
+
93
+ name: str
94
+ model: str = DEFAULT_MODEL
95
+ base_url: str = DEFAULT_BASE
96
+ api_key: str = ""
97
+ temperature: float = 0.4
98
+ created: str = ""
99
+
100
+ def to_dict(self) -> dict:
101
+ return {
102
+ "name": self.name,
103
+ "model": self.model,
104
+ "base_url": self.base_url,
105
+ "api_key": self.api_key,
106
+ "temperature": self.temperature,
107
+ "created": self.created,
108
+ }
109
+
110
+ @classmethod
111
+ def from_dict(cls, d: dict) -> "Opponent":
112
+ return cls(
113
+ name=str(d.get("name", "opponent")),
114
+ model=d.get("model", DEFAULT_MODEL),
115
+ base_url=d.get("base_url", DEFAULT_BASE),
116
+ api_key=d.get("api_key", "") or "",
117
+ temperature=float(d.get("temperature", 0.4)),
118
+ created=d.get("created", ""),
119
+ )
120
+
121
+
122
+ # ──────────────────────────────── opponents ────────────────────────────────
123
+
124
+ def _slug(name: str) -> str:
125
+ s = re.sub(r"[^\w\-]+", "-", name, flags=re.UNICODE).strip("-")
126
+ return s or "opponent"
127
+
128
+
129
+ def load_opponents() -> list[Opponent]:
130
+ out: list[Opponent] = []
131
+ if not OPP_DIR.is_dir():
132
+ return out
133
+ for p in sorted(OPP_DIR.glob("*.json")):
134
+ try:
135
+ out.append(Opponent.from_dict(json.loads(p.read_text())))
136
+ except Exception:
137
+ continue
138
+ return sorted(out, key=lambda o: o.name.lower())
139
+
140
+
141
+ def save_opponent(o: Opponent) -> Path:
142
+ OPP_DIR.mkdir(parents=True, exist_ok=True)
143
+ try:
144
+ os.chmod(OPP_DIR, 0o700)
145
+ except OSError:
146
+ pass
147
+ p = OPP_DIR / f"{_slug(o.name)}.json"
148
+ p.write_text(json.dumps(o.to_dict(), ensure_ascii=False, indent=2))
149
+ try:
150
+ os.chmod(p, 0o600) # it holds an API key
151
+ except OSError:
152
+ pass
153
+ return p
154
+
155
+
156
+ def delete_opponent(o: Opponent) -> None:
157
+ """Match by content, since the file name need not be the slug."""
158
+ if not OPP_DIR.is_dir():
159
+ return
160
+ for p in OPP_DIR.glob("*.json"):
161
+ try:
162
+ if json.loads(p.read_text()).get("name") == o.name:
163
+ p.unlink()
164
+ except (OSError, json.JSONDecodeError):
165
+ continue
166
+
167
+
168
+ # ───────────────────────────────── drawing ─────────────────────────────────
169
+
170
+ class C:
171
+ R = "\x1b[0m"
172
+ LABEL = "\x1b[38;5;45m" # rank / file labels
173
+ EMPTY = "\x1b[38;5;240m" # empty square
174
+ WHITE = "\x1b[1;38;5;231m" # white pieces
175
+ BLACK = "\x1b[38;5;203m" # opponent pieces (red)
176
+ MOVE = "\x1b[1;38;5;120m" # the opponent's last move
177
+ DIM = "\x1b[2m"
178
+ BOLD = "\x1b[1m"
179
+ RED = "\x1b[31m"
180
+ GREEN = "\x1b[32m"
181
+ CYAN = "\x1b[36m"
182
+
183
+
184
+ ANSI_RE = re.compile(r"\x1b\[[0-9;]*m")
185
+
186
+
187
+ def vis_len(s: str) -> int:
188
+ return len(ANSI_RE.sub("", s))
189
+
190
+
191
+ def render(board: chess.Board, cfg: Cfg, human: chess.Color, last: chess.Move | None = None) -> str:
192
+ """Letter board. Both sides uppercase, split by colour; the opponent's last
193
+ move (piece and the square it came from) turns green."""
194
+ flip = human == chess.BLACK
195
+ ranks = list(range(8, 0, -1)) if not flip else list(range(1, 9))
196
+ files = list(range(0, 8)) if not flip else list(range(7, -1, -1))
197
+ on = cfg.color
198
+
199
+ lines = []
200
+ for r in ranks:
201
+ cells = []
202
+ for f in files:
203
+ sq = chess.square(f, r - 1)
204
+ pc = board.piece_at(sq)
205
+ ch = "." if pc is None else pc.symbol().upper()
206
+ if on:
207
+ if last and sq in (last.from_square, last.to_square):
208
+ fg = C.MOVE
209
+ elif pc is None:
210
+ fg = C.EMPTY
211
+ else:
212
+ fg = C.WHITE if pc.color else C.BLACK
213
+ cells.append(f"{fg}{ch} {C.R}")
214
+ else:
215
+ cells.append(f"{ch} ")
216
+ row = "".join(cells)
217
+ if not cfg.coords:
218
+ lines.append(row)
219
+ elif on:
220
+ lines.append(f"{C.LABEL}{r}{C.R} {row}")
221
+ else:
222
+ lines.append(f"{r} {row}")
223
+
224
+ if cfg.coords:
225
+ foot = " " + " ".join(chess.FILE_NAMES[f] for f in files)
226
+ lines.append(f"{C.LABEL}{foot}{C.R}" if on else foot)
227
+ return "\n".join(lines)
228
+
229
+
230
+ def board_text(board: chess.Board) -> str:
231
+ """Plain board for the model: white uppercase, black lowercase."""
232
+ rows = []
233
+ for r in range(7, -1, -1):
234
+ cells = []
235
+ for f in range(8):
236
+ pc = board.piece_at(chess.square(f, r))
237
+ cells.append(pc.symbol() if pc else ".")
238
+ rows.append(f"{r + 1} " + " ".join(cells))
239
+ rows.append(" " + " ".join(chess.FILE_NAMES))
240
+ return "\n".join(rows)
241
+
242
+
243
+ # ──────────────────────────────── right panel ────────────────────────────────
244
+
245
+ def eval_label(cp: int) -> str:
246
+ if cp >= 150:
247
+ return "white winning"
248
+ if cp >= 50:
249
+ return "white better"
250
+ if cp <= -150:
251
+ return "black winning"
252
+ if cp <= -50:
253
+ return "black better"
254
+ return "equal"
255
+
256
+
257
+ def move_label(delta: float) -> str:
258
+ """delta is the eval change from the mover's point of view, in pawns."""
259
+ if delta >= 0.15:
260
+ return "great"
261
+ if delta >= -0.05:
262
+ return "good"
263
+ if delta >= -0.30:
264
+ return "inacc"
265
+ if delta >= -1.00:
266
+ return "mistake"
267
+ return "blunder"
268
+
269
+
270
+ def _move_score(evals: list[int | None], i: int) -> str:
271
+ """What move number i (1-based half-move) was worth to the player who made it."""
272
+ if i < 1 or i >= len(evals):
273
+ return ""
274
+ before, after = evals[i - 1], evals[i]
275
+ if before is None or after is None:
276
+ return ""
277
+ if abs(before) >= 29000 or abs(after) >= 29000:
278
+ return "mate"
279
+ delta = (after - before) if i % 2 == 1 else (before - after)
280
+ return f"{delta / 100:+.2f} {move_label(delta / 100)}"
281
+
282
+
283
+ def side_panel(board: chess.Board, evals: list[int | None], history: list[str],
284
+ on: bool = True) -> list[str]:
285
+ cp = evals[-1] if evals else None
286
+ if cp is None:
287
+ rows = ["eval n/a", " no engine"]
288
+ elif abs(cp) >= 29000:
289
+ rows = ["eval mate", f" {'white' if cp > 0 else 'black'} mates"]
290
+ else:
291
+ rows = [f"eval {cp / 100:+.2f}", f" {eval_label(cp)}"]
292
+ rows.append("")
293
+
294
+ n = len(history)
295
+ last_white = n if n % 2 == 1 else n - 1
296
+ last_black = n if n % 2 == 0 else n - 1
297
+ rows.append("last")
298
+ for idx, colour in ((last_white, C.WHITE), (last_black, C.BLACK)):
299
+ if idx < 1:
300
+ rows.append("")
301
+ continue
302
+ score = _move_score(evals, idx)
303
+ if not score:
304
+ rows.append("")
305
+ continue
306
+ text = f" {history[idx - 1]:<6}{score}".rstrip()
307
+ rows.append(f"{colour}{text}{C.R}" if on else text)
308
+ rows.append("")
309
+ rows.append(f"move {board.fullmove_number}")
310
+ return rows[:10]
311
+
312
+
313
+ def compose(board_str: str, panel: list[str], say: str, on: bool, who: str = "") -> str:
314
+ """board | eval/last panel DeepSeek: whatever it just said"""
315
+ rows = board_str.split(chr(10))
316
+ width = max((vis_len(r) for r in rows), default=19)
317
+ panel_w = max((vis_len(p) for p in panel), default=0) if panel else 0
318
+
319
+ label = f"{who}: " if who else ""
320
+ cols = shutil.get_terminal_size((80, 24)).columns
321
+ room = cols - width - panel_w - (3 if panel else 0) - 4 - len(label)
322
+ say_lines = textwrap.wrap(say, max(16, room)) if (say and room >= 16) else []
323
+
324
+ out = []
325
+ for i in range(max(len(rows), len(panel), len(say_lines))):
326
+ b = rows[i] if i < len(rows) else ""
327
+ p = panel[i] if i < len(panel) else ""
328
+ text = say_lines[i] if i < len(say_lines) else ""
329
+ line = b + " " * max(0, width - vis_len(b))
330
+ if panel:
331
+ line += " | " + p + " " * max(0, panel_w - vis_len(p))
332
+ if text:
333
+ prefix = label if i == 0 else " " * len(label)
334
+ line += " " + prefix + text
335
+ out.append(line.rstrip())
336
+ return chr(10).join(out)
337
+
338
+
339
+ # ─────────────────────────────────- engine ─────────────────────────────────
340
+
341
+ class Engine:
342
+ """Stockfish over the UCI protocol, via python-chess."""
343
+
344
+ def __init__(self, path: str, depth: int = 15):
345
+ from chess.engine import Limit, SimpleEngine
346
+ self._limit = Limit
347
+ self.impl = SimpleEngine.popen_uci(path)
348
+ self.depth = depth
349
+ self.name = self.impl.id.get("name", "stockfish")
350
+ self.cache: dict[str, int] = {}
351
+
352
+ def _remember(self, key: str, value: int) -> int:
353
+ if len(self.cache) > 400: # keep it bounded over long sessions
354
+ self.cache.clear()
355
+ self.cache[key] = value
356
+ return value
357
+
358
+ def eval(self, board: chess.Board, depth: int | None = None) -> int:
359
+ depth = depth or self.depth
360
+ key = f"{depth}|{board.fen()}"
361
+ if key not in self.cache:
362
+ info = self.impl.analyse(board, self._limit(depth=depth, time=3.0))
363
+ self._remember(key, info["score"].pov(chess.WHITE).score(mate_score=30000))
364
+ return self.cache[key]
365
+
366
+ def play(self, board: chess.Board, elo: int, depth: int = 12) -> chess.Move:
367
+ """Play a move with the strength limited to roughly `elo`."""
368
+ try:
369
+ full = elo >= 3190
370
+ self.impl.configure({"UCI_LimitStrength": not full,
371
+ "UCI_Elo": max(1320, min(3190, elo))})
372
+ except Exception:
373
+ pass
374
+ return self.impl.play(board, self._limit(depth=depth, time=2.5)).move
375
+
376
+ def best_move(self, board: chess.Board, depth: int | None = None):
377
+ """The engine's own first choice, used as a reference for the filter."""
378
+ try:
379
+ return self.impl.play(board, self._limit(depth=depth or 10, time=2.0)).move
380
+ except Exception:
381
+ return None
382
+
383
+ def line_eval(self, board: chess.Board, depth: int | None = None) -> int:
384
+ """Best available score for the side to move, from its own point of view."""
385
+ depth = depth or self.depth
386
+ key = f"line|{depth}|{board.fen()}"
387
+ if key not in self.cache:
388
+ info = self.impl.analyse(board, self._limit(depth=depth, time=3.0))
389
+ self._remember(key, info["score"].pov(board.turn).score(mate_score=30000))
390
+ return self.cache[key]
391
+
392
+ def close(self) -> None:
393
+ try:
394
+ self.impl.quit()
395
+ except Exception:
396
+ pass
397
+
398
+
399
+ ENGINE: Engine | None = None
400
+
401
+
402
+ ENGINE_ASSETS = {
403
+ ("linux", "x86_64"): "stockfish-linux-x86-64-universal.tar.gz",
404
+ ("linux", "aarch64"): "stockfish-linux-arm64-universal.tar.gz",
405
+ ("darwin", "x86_64"): "stockfish-macos-universal.tar.gz",
406
+ ("darwin", "arm64"): "stockfish-macos-universal.tar.gz",
407
+ ("win32", "amd64"): "stockfish-windows-x86-64-universal.zip",
408
+ ("win32", "arm64"): "stockfish-windows-arm64-universal.zip",
409
+ }
410
+ ENGINE_PREFERENCE = {
411
+ ("linux", "x86_64"): ["avx2", "bmi2", "sse41-popcnt", "x86-64"],
412
+ ("linux", "aarch64"): ["arm64"],
413
+ ("darwin", "arm64"): ["m1-apple-silicon"],
414
+ ("darwin", "x86_64"): ["x86-64-avx2", "x86-64"],
415
+ ("win32", "amd64"): ["x86-64-avx2", "x86-64"],
416
+ ("win32", "arm64"): ["arm64"],
417
+ }
418
+
419
+
420
+ def _platform() -> tuple[str, str]:
421
+ return sys.platform, platform.machine().lower()
422
+
423
+
424
+ def _candidates(root: Path) -> list[Path]:
425
+ """Executables inside the archive, best first."""
426
+ pref = ENGINE_PREFERENCE.get(_platform(), [])
427
+ files = [p for p in root.rglob("*") if p.is_file() and p.stat().st_size > 1_000_000]
428
+ files = [p for p in files if p.suffix.lower() not in (".nnue", ".txt", ".md", ".json")]
429
+
430
+ def rank(p: Path) -> int:
431
+ name = p.name.lower()
432
+ for i, want in enumerate(pref):
433
+ if want in name:
434
+ return i
435
+ return len(pref)
436
+
437
+ return sorted(files, key=rank)
438
+
439
+
440
+ def _runs(binary: Path) -> bool:
441
+ try:
442
+ out = subprocess.run([str(binary), "uci"], input="quit\n", capture_output=True,
443
+ text=True, timeout=15).stdout
444
+ return "Stockfish" in out
445
+ except Exception:
446
+ return False
447
+
448
+
449
+ def install_engine(target_dir: Path | None = None, quiet: bool = False) -> Path | None:
450
+ """Download the official Stockfish build for this platform into ~/.local/bin."""
451
+ plat = _platform()
452
+ asset = ENGINE_ASSETS.get(plat)
453
+ if asset is None:
454
+ print(f"no stockfish build known for {plat}", file=sys.stderr)
455
+ return None
456
+
457
+ bin_dir = target_dir or (Path.home() / ".local" / "bin")
458
+ bin_dir.mkdir(parents=True, exist_ok=True)
459
+ url = f"https://github.com/official-stockfish/Stockfish/releases/latest/download/{asset}"
460
+ if not quiet:
461
+ print(f"downloading {asset} (~80 MB) ...", file=sys.stderr)
462
+
463
+ with tempfile.TemporaryDirectory() as tmp:
464
+ tmp_path = Path(tmp)
465
+ archive = tmp_path / asset
466
+ try:
467
+ with urllib.request.urlopen(url, timeout=120) as resp, open(archive, "wb") as fh:
468
+ shutil.copyfileobj(resp, fh)
469
+ except Exception as e:
470
+ print(f"could not download stockfish: {e}", file=sys.stderr)
471
+ return None
472
+
473
+ try:
474
+ if asset.endswith(".zip"):
475
+ with zipfile.ZipFile(archive) as zf:
476
+ zf.extractall(tmp_path / "x")
477
+ else:
478
+ with tarfile.open(archive) as tf:
479
+ tf.extractall(tmp_path / "x")
480
+ except Exception as e:
481
+ print(f"could not unpack stockfish: {e}", file=sys.stderr)
482
+ return None
483
+
484
+ for cand in _candidates(tmp_path / "x"):
485
+ if not _runs(cand):
486
+ continue
487
+ dest = bin_dir / ("stockfish.exe" if sys.platform == "win32" else "stockfish")
488
+ shutil.copyfile(cand, dest)
489
+ dest.chmod(0o755)
490
+ if not quiet:
491
+ print(f"stockfish installed: {dest}", file=sys.stderr)
492
+ return dest
493
+
494
+ print("no runnable stockfish binary in the archive", file=sys.stderr)
495
+ return None
496
+
497
+
498
+ def find_engine(path: str | None) -> str | None:
499
+ bin_dir = Path.home() / ".local/bin"
500
+ cands = [path] if path else [
501
+ os.environ.get("CLICHESS_ENGINE") or "",
502
+ shutil.which("stockfish") or "",
503
+ "/usr/games/stockfish",
504
+ str(bin_dir / "stockfish"),
505
+ str(bin_dir / "stockfish.exe"),
506
+ "/usr/local/bin/stockfish",
507
+ "/opt/homebrew/bin/stockfish",
508
+ r"C:\Program Files\Stockfish\stockfish.exe",
509
+ ]
510
+ for c in cands:
511
+ if c and Path(c).exists():
512
+ return c
513
+ return None
514
+
515
+
516
+ def evaluate(board: chess.Board) -> int | None:
517
+ """Centipawns from white's point of view, or None when there is no engine."""
518
+ if ENGINE is None:
519
+ return None
520
+ try:
521
+ return ENGINE.eval(board)
522
+ except Exception:
523
+ return None
524
+
525
+
526
+ # ─────────────────────────────── configuration ───────────────────────────────
527
+
528
+ def settings_path() -> Path:
529
+ return STATE_DIR / "settings.json"
530
+
531
+
532
+ def load_settings() -> dict:
533
+ try:
534
+ data = json.loads(settings_path().read_text())
535
+ return data if isinstance(data, dict) else {}
536
+ except (OSError, json.JSONDecodeError):
537
+ return {}
538
+
539
+
540
+ def save_settings(cfg: Cfg) -> None:
541
+ try:
542
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
543
+ settings_path().write_text(json.dumps(
544
+ {"coords": cfg.coords, "say": cfg.show_say, "eval": cfg.show_panel}))
545
+ except OSError:
546
+ pass
547
+
548
+
549
+ def base_cfg() -> Cfg:
550
+ cfg = Cfg()
551
+ saved = load_settings()
552
+ cfg.coords = bool(saved.get("coords", cfg.coords))
553
+ cfg.show_say = bool(saved.get("say", cfg.show_say))
554
+ cfg.show_panel = bool(saved.get("eval", cfg.show_panel))
555
+ cfg.base_url = os.environ.get("CLICHESS_BASE_URL") or cfg.base_url
556
+ cfg.model = os.environ.get("CLICHESS_MODEL") or cfg.model
557
+ cfg.api_key = (
558
+ os.environ.get("CLICHESS_API_KEY")
559
+ or os.environ.get("DEEPSEEK_API_KEY")
560
+ or os.environ.get("OPENAI_API_KEY")
561
+ or cfg.api_key
562
+ )
563
+ cfg.color = cfg.color and not os.environ.get("NO_COLOR")
564
+ return cfg
565
+
566
+
567
+ def cfg_for(opp: Opponent | None, base: Cfg) -> Cfg:
568
+ """Apply an opponent profile on top of the base configuration."""
569
+ if opp is None:
570
+ return base
571
+ cfg = replace(base)
572
+ cfg.model = opp.model or base.model
573
+ cfg.base_url = opp.base_url or base.base_url
574
+ cfg.api_key = opp.api_key or base.api_key
575
+ if opp.temperature is not None:
576
+ cfg.temperature = opp.temperature
577
+ return cfg
578
+
579
+
580
+ # ──────────────────────────── creating an opponent ────────────────────────────
581
+
582
+ def ask(prompt: str, default: str | None = None, secret: bool = False) -> str | None:
583
+ """Read one line. EOF / Ctrl-C returns None."""
584
+ shown = "[keep]" if (secret and default) else (f"[{default}]" if default else "")
585
+ suffix = f" {C.DIM}{shown}{C.R}" if shown else ""
586
+ try:
587
+ if secret and sys.stdin.isatty():
588
+ try:
589
+ got = getpass.getpass(f"{C.BOLD}{prompt}{C.R}{suffix}: ").strip() or (default or "")
590
+ return clean(got)
591
+ except Exception:
592
+ pass # no usable tty for getpass: fall through and echo it
593
+ raw = input(f"{C.BOLD}{prompt}{C.R}{suffix}: ").strip()
594
+ return clean(raw or (default or ""))
595
+ except (EOFError, KeyboardInterrupt):
596
+ print()
597
+ return None
598
+
599
+
600
+ def ask_brief() -> str:
601
+ """One line from the human describing the game they want."""
602
+ if not sys.stdin.isatty():
603
+ return ""
604
+ try:
605
+ return clean(input(f"{C.BOLD}brief{C.R} > ").strip())
606
+ except (EOFError, KeyboardInterrupt):
607
+ print()
608
+ return ""
609
+
610
+
611
+ BANNER = r"""
612
+ __ __
613
+ _ _____ / /________ ____ ___ ___ _____/ /_ ___ __________
614
+ | | /| / / _ \/ / ___/ __ \/ __ `__ \/ _ \ / ___/ __ \/ _ \/ ___/ ___/
615
+ | |/ |/ / __/ / /__/ /_/ / / / / / / __/ / /__/ / / / __(__ |__ )
616
+ |__/|__/\___/_/\___/\____/_/ /_/ /_/\___/ \___/_/ /_/\___/____/____/
617
+ """
618
+
619
+
620
+ def rainbow(text: str, on: bool = True) -> str:
621
+ """Smooth diagonal hue sweep across the banner, one escape per colour change."""
622
+ if not on:
623
+ return text
624
+ out = []
625
+ for y, line in enumerate(text.split("\n")):
626
+ if not line:
627
+ out.append(line)
628
+ continue
629
+ row, last = [], None
630
+ for x, ch in enumerate(line):
631
+ if ch == " ":
632
+ row.append(ch)
633
+ continue
634
+ h = ((x * 4 + y * 26) % 360) / 360
635
+ r, g, b = colorsys.hsv_to_rgb(h, 0.85, 1.0)
636
+ rgb = (int(r * 255), int(g * 255), int(b * 255))
637
+ if rgb != last:
638
+ row.append(f"\x1b[38;2;{rgb[0]};{rgb[1]};{rgb[2]}m")
639
+ last = rgb
640
+ row.append(ch)
641
+ out.append("".join(row) + C.R)
642
+ return "\n".join(out)
643
+
644
+
645
+ def banner_block(on: bool) -> str:
646
+ lines = [line.rstrip() for line in BANNER.strip("\n").split("\n")]
647
+ while lines and not lines[0]:
648
+ lines.pop(0)
649
+ indent = " "
650
+ art = "\n".join(indent + line for line in lines)
651
+ width = max(len(line) for line in lines)
652
+ rule = indent + "=" * width
653
+ body = rainbow(art, on)
654
+ line = f"\x1b[38;5;244m{rule}{C.R}" if on else rule
655
+ return f"{line}\n{body}\n\n{line}"
656
+
657
+
658
+ PROVIDERS = [
659
+ ("openai", "ChatGPT (OpenAI)", "https://api.openai.com/v1",
660
+ ["gpt-4o", "gpt-4o-mini", "gpt-4.1", "gpt-4.1-mini", "o4-mini"]),
661
+ ("anthropic", "Claude (Anthropic)", "https://api.anthropic.com/v1",
662
+ ["claude-sonnet-4-20250514", "claude-opus-4-20250514", "claude-3-7-sonnet-latest"]),
663
+ ("deepseek", "DeepSeek", "https://api.deepseek.com",
664
+ ["deepseek-chat", "deepseek-reasoner"]),
665
+ ("gemini", "Gemini (Google)", "https://generativelanguage.googleapis.com/v1beta/openai",
666
+ ["gemini-2.5-pro", "gemini-2.5-flash"]),
667
+ ("dashscope", "Alibaba Qwen", "https://dashscope.aliyuncs.com/compatible-mode/v1",
668
+ ["qwen-plus", "qwen-max", "qwen-turbo"]),
669
+ ]
670
+
671
+ SKIP_MODELS = ("embed", "whisper", "tts", "dall-e", "moderation", "image", "audio", "rerank")
672
+
673
+
674
+ def fetch_models(kind: str, key: str, base: str) -> list[str]:
675
+ """Ask the provider what it can serve. Empty list means: we could not tell."""
676
+ def get(url: str, headers: dict) -> dict:
677
+ req = urllib.request.Request(url, headers=headers)
678
+ with urllib.request.urlopen(req, timeout=20) as r:
679
+ return json.loads(r.read().decode())
680
+
681
+ try:
682
+ if kind == "gemini":
683
+ data = get("https://generativelanguage.googleapis.com/v1beta/models?key=" + urllib.parse.quote(key),
684
+ {"User-Agent": "clichess"})
685
+ names = [m["name"].split("/")[-1] for m in data.get("models", [])]
686
+ elif kind == "anthropic":
687
+ data = get(base.rstrip("/") + "/models",
688
+ {"x-api-key": key, "anthropic-version": "2023-06-01"})
689
+ names = [m["id"] for m in data.get("data", [])]
690
+ else:
691
+ data = get(base.rstrip("/") + "/models", {"Authorization": f"Bearer {key}"})
692
+ names = [m["id"] for m in data.get("data", [])]
693
+ except Exception:
694
+ return []
695
+ return [n for n in names if not any(bad in n.lower() for bad in SKIP_MODELS)]
696
+
697
+
698
+ def add_opponent() -> Opponent | None:
699
+ """Provider, key, model - all chosen by number, nothing typed but the key."""
700
+
701
+ def choose(options: list[str], prompt: str, default: str = "1") -> int | None:
702
+ for i, label in enumerate(options, 1):
703
+ print(f" {i}) {label}")
704
+ c = ask(prompt, default)
705
+ if c is None:
706
+ return None
707
+ try:
708
+ idx = int(c) - 1
709
+ if 0 <= idx < len(options):
710
+ return idx
711
+ except ValueError:
712
+ pass
713
+ print(" no such number.")
714
+ return None
715
+
716
+ print(f"\n{C.BOLD}Add an opponent{C.R}")
717
+ entries = list(PROVIDERS) + [("custom", "Custom / local (Ollama, LM Studio, a gateway)", "", [])]
718
+ idx = choose([e[1] for e in entries], "which one")
719
+ if idx is None:
720
+ return None
721
+ kind, label, url, fallback = entries[idx]
722
+
723
+ if kind == "custom":
724
+ url = ask("API endpoint", "http://localhost:11434/v1")
725
+ if not url:
726
+ return None
727
+ label = "Custom"
728
+
729
+ key = ask(f"API key for {label}" + ("" if kind != "custom" else " (enter to skip)"), secret=True)
730
+ if key is None:
731
+ return None
732
+ if not key and kind != "custom":
733
+ print(" a key is required.")
734
+ return None
735
+
736
+ print(f"{C.DIM}asking {label} which models this key can use...{C.R}")
737
+ models = fetch_models(kind, key, url) or list(fallback)
738
+ if models:
739
+ idx = choose(models[:20], "model")
740
+ if idx is None:
741
+ return None
742
+ model = models[idx]
743
+ else:
744
+ model = ask("model name", "")
745
+ if not model:
746
+ return None
747
+
748
+ taken = {o.name for o in load_opponents()}
749
+ suggested = label.split(" (")[0]
750
+ if suggested in taken:
751
+ n = 2
752
+ while f"{suggested} {n}" in taken:
753
+ n += 1
754
+ suggested = f"{suggested} {n}"
755
+
756
+ while True:
757
+ name = ask("nickname", suggested)
758
+ if name is None:
759
+ return None
760
+ name = name.strip() or suggested
761
+ if name not in taken:
762
+ break
763
+ print(f" \"{name}\" is taken.")
764
+ suggested = f"{name} 2"
765
+
766
+ opp = Opponent(name=name, model=model, base_url=url, api_key=key or "",
767
+ created=time.strftime("%Y-%m-%d"))
768
+ save_opponent(opp)
769
+ print(f"\n{C.GREEN}saved \"{opp.name}\"{C.R}\t{C.DIM}{model}{C.R}")
770
+ return opp
771
+
772
+
773
+ LEVELS = [(1320, "beginner"), (1600, "casual"), (1900, "club"),
774
+ (2200, "strong"), (2500, "expert"), (3190, "maximum")]
775
+ STOCKFISH = Opponent(name="Stockfish", model="stockfish", base_url="", api_key="")
776
+ PLAY_ENGINE: "Engine | None" = None
777
+ ELO: int | None = None
778
+
779
+
780
+ def ask_level() -> int | None:
781
+ print()
782
+ for i, (elo, label) in enumerate(LEVELS, 1):
783
+ shown = "full strength" if elo >= 3190 else f"about {elo}"
784
+ print(f" {i}) {label:<9} {C.DIM}{shown}{C.R}")
785
+ c = ask("level", "3")
786
+ if c is None:
787
+ return None
788
+ try:
789
+ return LEVELS[int(c) - 1][0]
790
+ except (ValueError, IndexError):
791
+ return None
792
+
793
+
794
+ INTRO = """chess, in your terminal. Play Stockfish at any strength, or a language model
795
+ you brief before the first move: it agrees a plan, plays to it, and talks back
796
+ while it does. Every position is scored by Stockfish."""
797
+
798
+ AUTHOR_NAME = "Jude"
799
+ AUTHOR_URL = "https://github.com/Helios1919"
800
+ AUTHOR_LINES = [
801
+ "2026, undergraduate in Software Engineering at NKU.",
802
+ "clichess is a side project I built after hours.",
803
+ "Hope you enjoy it.",
804
+ ]
805
+
806
+
807
+ def author_block(on: bool) -> str:
808
+ lines = [f"hi, I'm {AUTHOR_NAME}.", ""] + AUTHOR_LINES + ["", AUTHOR_URL]
809
+ return rainbow("\n".join(f" {line}" if line else "" for line in lines), on)
810
+
811
+
812
+ def find_saved(arg: str) -> Opponent | None:
813
+ """Look an opponent up by 1-based number or by name."""
814
+ opps = load_opponents()
815
+ if arg.isdigit():
816
+ i = int(arg)
817
+ return opps[i - 1] if 1 <= i <= len(opps) else None
818
+ return next((o for o in opps if o.name == arg or _slug(o.name) == _slug(arg)), None)
819
+
820
+
821
+ def print_opponents() -> list[Opponent]:
822
+ print(f" {C.BOLD}0{C.R}\tStockfish\t{C.DIM}local engine{C.R}")
823
+ opps = load_opponents()
824
+ for i, o in enumerate(opps, 1):
825
+ print(f" {C.BOLD}{i}{C.R}\t{o.name}\t{C.DIM}{o.model}{C.R}")
826
+ return opps
827
+
828
+
829
+ def welcome_page(base: Cfg) -> tuple[str, Opponent | None]:
830
+ """Shown on every start. Accepts the same words as the flags, without dashes."""
831
+
832
+ def screen() -> None:
833
+ print()
834
+ print(banner_block(base.color))
835
+ print()
836
+ for line in INTRO.split("\n"):
837
+ print(f" {line}")
838
+ print()
839
+ print(f" {C.DIM}type help{C.R}")
840
+
841
+ def start_block() -> None:
842
+ print()
843
+ print_opponents()
844
+
845
+ screen()
846
+ while True:
847
+ try:
848
+ typed = clean(input(f"{C.BOLD}>{C.R} ").strip())
849
+ except (EOFError, KeyboardInterrupt):
850
+ print()
851
+ return "quit", None
852
+
853
+ parts = typed.split()
854
+ cmd = parts[0].lower() if parts else "start"
855
+ arg = " ".join(parts[1:])
856
+
857
+ if cmd in ("q", "quit", "exit"):
858
+ return "quit", None
859
+ if cmd in ("start", ""):
860
+ start_block()
861
+ continue
862
+ if cmd == "author":
863
+ print()
864
+ print(author_block(base.color))
865
+ print()
866
+ continue
867
+ if cmd in ("help", "h", "?"):
868
+ print()
869
+ print(help_text("the opponent"))
870
+ print()
871
+ continue
872
+ if cmd == "new":
873
+ opp = add_opponent()
874
+ if opp is not None:
875
+ return "play", opp
876
+ continue
877
+ if cmd == "delete":
878
+ if not arg:
879
+ print(f" {C.RED}usage: delete NAME or delete <number>{C.R}")
880
+ continue
881
+ if arg.lower() in ("0", "stockfish"):
882
+ print(f" {C.RED}Stockfish is built in - nothing to delete{C.R}")
883
+ continue
884
+ target = find_saved(arg)
885
+ if target is None:
886
+ print(f" {C.RED}no opponent \"{arg}\"{C.R}")
887
+ continue
888
+ delete_opponent(target)
889
+ print(f" deleted \"{target.name}\".")
890
+ continue
891
+ if cmd == "opponent":
892
+ target = find_saved(arg)
893
+ if target is None:
894
+ print(f" {C.RED}no opponent \"{arg}\"{C.R}")
895
+ continue
896
+ return "play", target
897
+ if cmd == "continue":
898
+ if load_state() is None:
899
+ print(f" {C.RED}no saved game{C.R}")
900
+ continue
901
+ return "resume", None
902
+ if cmd in ("0", "stockfish"):
903
+ return "engine", STOCKFISH
904
+ try:
905
+ return "play", load_opponents()[int(typed) - 1]
906
+ except (ValueError, IndexError):
907
+ print(f" {C.RED}no such opponent{C.R}")
908
+
909
+
910
+ def resolve_opponent(args: argparse.Namespace) -> tuple[Opponent | None, bool]:
911
+ """Returns (opponent, should_run). None means: play from the environment."""
912
+ opps = load_opponents()
913
+
914
+ if args.opponent and args.opponent.lower() in ("0", "stockfish"):
915
+ return STOCKFISH, True
916
+
917
+ if args.opponent:
918
+ for o in opps:
919
+ if o.name == args.opponent or _slug(o.name) == _slug(args.opponent):
920
+ return o, True
921
+ print(f"no opponent called \"{args.opponent}\".", file=sys.stderr)
922
+ return None, False
923
+
924
+ if not opps:
925
+ return None, True # nothing saved: fall back to env vars
926
+ return opps[0], True
927
+
928
+
929
+ # ──────────────────────────────── calling the model ────────────────────────────────
930
+
931
+ class ApiError(RuntimeError):
932
+ pass
933
+
934
+
935
+ def shorten(text: str, limit: int = 200) -> str:
936
+ """Keep replies short no matter what the model sends."""
937
+ text = " ".join(text.split())
938
+ if len(text) <= limit:
939
+ return text
940
+ cut = text[:limit].rstrip()
941
+ for end in (". ", "! ", "? ", "。", "!", "?"):
942
+ i = cut.rfind(end)
943
+ if i > limit * 0.4:
944
+ return cut[:i + 1].strip()
945
+ return cut.rsplit(" ", 1)[0] + " ..."
946
+
947
+
948
+ def clean(text: str) -> str:
949
+ """A terminal can hand us lone surrogates; JSON APIs refuse them."""
950
+ try:
951
+ return text.encode("utf-8", "replace").decode("utf-8", "replace")
952
+ except UnicodeError:
953
+ return "".join(ch for ch in text if not 0xD800 <= ord(ch) <= 0xDFFF)
954
+
955
+
956
+ def chat(cfg: Cfg, messages: list[dict], max_tokens: int | None = None) -> str:
957
+ messages = [{"role": m["role"], "content": clean(m["content"])} for m in messages]
958
+ body = {
959
+ "model": cfg.model,
960
+ "messages": messages,
961
+ "temperature": cfg.temperature,
962
+ "max_tokens": max_tokens or cfg.max_tokens,
963
+ }
964
+ if EFFORT:
965
+ body["reasoning_effort"] = EFFORT
966
+ req = urllib.request.Request(
967
+ cfg.endpoint(),
968
+ data=json.dumps(body).encode("utf-8"),
969
+ headers={"Content-Type": "application/json", "Authorization": f"Bearer {cfg.api_key}"},
970
+ method="POST",
971
+ )
972
+ last_err: Exception | None = None
973
+ for attempt in range(2):
974
+ try:
975
+ with urllib.request.urlopen(req, timeout=cfg.timeout) as resp:
976
+ data = json.loads(resp.read().decode("utf-8"))
977
+ choice = data["choices"][0]
978
+ msg = choice["message"]
979
+ if cfg.debug and msg.get("reasoning_content"):
980
+ print(f"{C.DIM}[reasoning] {msg['reasoning_content']}{C.R}")
981
+ content = (msg.get("content") or "").strip()
982
+ # A reasoning model may spend the whole budget thinking and return nothing.
983
+ if not content and choice.get("finish_reason") == "length" and attempt == 0:
984
+ body["max_tokens"] = int(body["max_tokens"]) * 4
985
+ req.data = json.dumps(body).encode("utf-8")
986
+ continue
987
+ return content
988
+ except urllib.error.HTTPError as e:
989
+ last_err = ApiError(f"HTTP {e.code}: {e.read().decode('utf-8', 'replace')[:300]}")
990
+ except (urllib.error.URLError, TimeoutError, OSError) as e:
991
+ last_err = ApiError(f"network error: {e}")
992
+ except (KeyError, json.JSONDecodeError) as e:
993
+ last_err = ApiError(f"unexpected response: {e}")
994
+ if attempt == 0:
995
+ time.sleep(1.5)
996
+ raise last_err # type: ignore[misc]
997
+
998
+
999
+ SYSTEM_CORE = """You are a chess player, playing a game against a human in a terminal. Rules:
1000
+ 1. You only ever receive the board, the move history, and a "legal moves" list. Every entry in that list is a legal move in this position.
1001
+ 2. You must copy every move from that list. Never invent or rewrite one.
1002
+ 3. Reply in exactly this shape, and nothing else:
1003
+ SAY: <one short line to your opponent, at most 12 words: a taunt, a joke, or a real thought>
1004
+ MOVE: <a move copied exactly from the legal list>
1005
+ MOVE: <another one>
1006
+ ... up to {n} moves. Offer genuinely different ideas, not variations of one. {flavour}
1007
+ No analysis, no preamble, never more than one SAY line."""
1008
+
1009
+ WILD = ("Include one steady move, one sharper move that fits your style, and at least one move a cautious player "
1010
+ "would never consider (as long as it is not simply losing).")
1011
+ ON_PLAN = "Every candidate must follow the agreed plan for this game."
1012
+
1013
+
1014
+ NEGOTIATE_SYSTEM = """You are about to play a chess game against a human. They describe the kind of game they want. Reply with at most two short lines: the concrete plan for both sides (opening, pawn structure, where the play happens). If their idea cannot happen - impossible move order, simply unsound - name the closest plan you will use instead. No greetings, no questions."""
1015
+
1016
+
1017
+ def negotiate(cfg: Cfg, opp: "Opponent | None", brief: str) -> str:
1018
+ """Agree on a plan with the model before the first move."""
1019
+ name = opp.name if opp else "the player"
1020
+ msgs = [
1021
+ {"role": "system", "content": NEGOTIATE_SYSTEM},
1022
+ {"role": "user", "content": f"The human says: {brief}\n\nYou are {name}. Reply with the plan."},
1023
+ ]
1024
+ return shorten(chat(cfg, msgs, max_tokens=400).strip(), 240)
1025
+
1026
+
1027
+ def build_system(opp: Opponent | None, n: int, plan: str = "") -> str:
1028
+ core = SYSTEM_CORE.format(n=n, flavour=ON_PLAN if plan else WILD)
1029
+ if plan:
1030
+ core += f"\n\nAgreed plan for this game:\n{plan}\nFollow it. If a move has to break it, say so in your one-liner."
1031
+ if not opp:
1032
+ return core + "\n\nWrite each sentence in the first person, like a player talking to themself."
1033
+ return (
1034
+ core
1035
+ + f"\n\nYour name is {opp.name}. Write each sentence in the first person, short."
1036
+ )
1037
+
1038
+
1039
+
1040
+
1041
+
1042
+ CHAT_SYSTEM = """You are playing chess against a human in a terminal. They can talk to you between moves. Reply with one or two very short sentences (at most 25 words), in character. Output only what you would say out loud: no moves, no labels, no analysis dump."""
1043
+
1044
+
1045
+ def talk(cfg: Cfg, board: chess.Board, history: list[str], opp: "Opponent | None",
1046
+ plan: str, message: str) -> str:
1047
+ system = CHAT_SYSTEM
1048
+ if opp:
1049
+ system += f"\n\nYour name is {opp.name}."
1050
+ if plan:
1051
+ system += f"\n\nThe agreed plan for this game:\n{plan}"
1052
+ msgs = [
1053
+ {"role": "system", "content": system},
1054
+ {"role": "user", "content": f"Board:\n{board_text(board)}\nFEN: {board.fen()}\n"
1055
+ f"History: {' '.join(history[-24:]) or '(start)'}\n\n"
1056
+ f"The human says: {message}"},
1057
+ ]
1058
+ return shorten(chat(cfg, msgs, max_tokens=300).strip(), 180)
1059
+
1060
+
1061
+ def legal_list(board: chess.Board) -> list[str]:
1062
+ return [board.san(m) for m in board.legal_moves]
1063
+
1064
+
1065
+ def move_messages(board: chess.Board, history: list[str], opp: "Opponent | None" = None,
1066
+ last_error: str | None = None, n: int = 5, plan: str = "") -> list[dict]:
1067
+ side = "White" if board.turn == chess.WHITE else "Black"
1068
+ legal = legal_list(board)
1069
+ hist = " ".join(history[-24:]) if history else "(start of the game)"
1070
+ user = (
1071
+ f"{side} to move.\n\n"
1072
+ f"Board (white uppercase, black lowercase, '.' is empty):\n{board_text(board)}\n\n"
1073
+ f"FEN: {board.fen()}\n"
1074
+ f"History: {hist}\n"
1075
+ f"Legal moves ({len(legal)}):\n" + "\n".join(f"- {m}" for m in legal)
1076
+ )
1077
+ if last_error:
1078
+ user += f"\n\nNote: your previous reply '{last_error}' was not usable. Reply with only lines of the form: MOVE: <legal move> | <sentence>"
1079
+ return [{"role": "system", "content": build_system(opp, n, plan)}, {"role": "user", "content": user}]
1080
+
1081
+
1082
+ def try_move(s: str, board: chess.Board) -> chess.Move | None:
1083
+ """One token from the model to a legal move, as forgivingly as possible."""
1084
+ s = s.strip().strip("`*_\"'()[]{}.,;:!?")
1085
+ if not s:
1086
+ return None
1087
+ s = s.replace("0-0-0", "O-O-O").replace("0-0", "O-O").replace("–", "-").replace("—", "-").strip()
1088
+ try:
1089
+ mv = board.parse_san(s)
1090
+ if mv in board.legal_moves:
1091
+ return mv
1092
+ except ValueError:
1093
+ pass
1094
+ compact = re.sub(r"[\s\-_]", "", s).lower()
1095
+ legal = {m.uci(): m for m in board.legal_moves}
1096
+ if compact in legal:
1097
+ return legal[compact]
1098
+ m = re.search(r"\b([a-h][1-8][a-h][1-8][qrbnQRBN]?)\b", s)
1099
+ if m and m.group(1).lower() in legal:
1100
+ return legal[m.group(1).lower()]
1101
+ return None
1102
+
1103
+
1104
+ def parse_say(reply: str) -> str:
1105
+ m = re.search(r"^\s*SAY\s*[::]\s*(.+)$", reply, re.M | re.I)
1106
+ return shorten(m.group(1).strip().strip('"'), 110) if m else ""
1107
+
1108
+
1109
+ def parse_candidates(reply: str, board: chess.Board, limit: int = 4) -> list[chess.Move]:
1110
+ """Every legal MOVE: line, first occurrence of each move, up to limit."""
1111
+ out: list[chess.Move] = []
1112
+ for line in reply.replace("\r", "").split("\n"):
1113
+ m = re.match(r"\s*(?:MOVE|move|Move)\s*[::]\s*(.+)", line)
1114
+ if not m:
1115
+ continue
1116
+ mv = try_move(m.group(1), board)
1117
+ if mv is None or mv in out:
1118
+ continue
1119
+ out.append(mv)
1120
+ if len(out) >= limit:
1121
+ break
1122
+ if not out: # a model that ignored the format: take any legal move in the text
1123
+ for tok in re.split(r"[\s,|]+", reply):
1124
+ mv = try_move(tok, board)
1125
+ if mv:
1126
+ out.append(mv)
1127
+ break
1128
+ if not out:
1129
+ for mv in board.legal_moves:
1130
+ if re.search(rf"(?<![\w-]){re.escape(board.san(mv))}(?![\w-])", reply):
1131
+ out.append(mv)
1132
+ break
1133
+ return out
1134
+
1135
+
1136
+ def ask_candidates(cfg: Cfg, board: chess.Board, history: list[str],
1137
+ opp: "Opponent | None", plan: str = "") -> tuple[str, list[chess.Move]]:
1138
+ err: str | None = None
1139
+ raw = ""
1140
+ for attempt in range(1, cfg.retries + 1):
1141
+ raw = chat(cfg, move_messages(board, history, opp, err, CANDIDATES, plan))
1142
+ cands = parse_candidates(raw, board, CANDIDATES)
1143
+ if cands:
1144
+ return parse_say(raw), cands
1145
+ err = raw.strip().split("\n")[0][:80] or "(empty reply)"
1146
+ print(f"{C.DIM} (reply {attempt}/{cfg.retries} unusable: {err}){C.R}")
1147
+ raise ApiError(f"no legal move after {cfg.retries} replies, last one: {raw[:200]}")
1148
+
1149
+
1150
+ def pick_candidate(cands: list[chess.Move], board: chess.Board, flair: float) -> chess.Move:
1151
+ """Drop candidates that give up more than `flair` pawns, then pick at random.
1152
+
1153
+ Without an engine the model's first choice is taken as is."""
1154
+ if ENGINE is None:
1155
+ return cands[0]
1156
+ mover_white = board.turn == chess.WHITE
1157
+ depth = max(8, ENGINE.depth - 6)
1158
+
1159
+ def score(mv: chess.Move) -> int:
1160
+ after = board.copy(stack=False)
1161
+ after.push(mv)
1162
+ cp = ENGINE.eval(after, depth)
1163
+ return cp if mover_white else -cp
1164
+
1165
+ scored = [(score(mv), mv) for mv in cands]
1166
+ # Reference: the best thing available, counting what the engine itself would
1167
+ # play, so a candidate set that is entirely bad still gets a target.
1168
+ ref = max(v for v, _ in scored)
1169
+ bm = ENGINE.best_move(board, depth)
1170
+ if bm is not None and bm not in board.legal_moves:
1171
+ bm = None
1172
+ if bm is not None:
1173
+ ref = max(ref, score(bm))
1174
+ keep = [mv for v, mv in scored if ref - v <= flair * 100]
1175
+ return random.choice(keep or [max(scored)[1]])
1176
+
1177
+
1178
+ # ─────────────────────────────────- input ─────────────────────────────────
1179
+
1180
+ def parse_human_move(board: chess.Board, s: str) -> chess.Move | None:
1181
+ s = s.strip()
1182
+ if not s:
1183
+ return None
1184
+ s2 = s.replace("0-0-0", "O-O-O").replace("0-0", "O-O").replace("–", "-").replace("—", "-")
1185
+ try:
1186
+ mv = board.parse_san(s2)
1187
+ return mv if mv in board.legal_moves else None
1188
+ except ValueError:
1189
+ pass
1190
+ compact = re.sub(r"[\s\-_]", "", s2).lower()
1191
+ try:
1192
+ mv = chess.Move.from_uci(compact)
1193
+ return mv if mv in board.legal_moves else None
1194
+ except ValueError:
1195
+ return None
1196
+
1197
+
1198
+ def help_text(opp_name: str) -> str:
1199
+ return f"""{C.BOLD}At the prompt{C.R}
1200
+ start show the opponents
1201
+ 0 play Stockfish, you pick the level each time
1202
+ <number> play that opponent
1203
+ new create an opponent
1204
+ delete NAME|N remove one
1205
+ opponent NAME play that one
1206
+ continue resume the last game
1207
+ author who made this
1208
+ q quit
1209
+
1210
+ {C.BOLD}In a game{C.R}
1211
+ e4 / Nf3 / O-O a move, SAN or UCI
1212
+ hint ask Stockfish for a suggestion
1213
+ chat [text] say something to {opp_name}; bare chat asks for the text
1214
+ undo take back your move and its reply
1215
+ fen show the position
1216
+ coords toggle the a-h / 1-8 labels
1217
+ say toggle the opponent's commentary column
1218
+ eval toggle eval / last / move
1219
+ new start a new game
1220
+ debug toggle raw model output
1221
+ help this text
1222
+ quit leave, the game is saved
1223
+
1224
+ {C.BOLD}From the shell{C.R}
1225
+ clichess the welcome page
1226
+ clichess --new create an opponent
1227
+ clichess --list list opponents
1228
+ clichess --delete NAME remove one
1229
+ clichess --opponent NAME play that one, or 0 for Stockfish
1230
+ clichess --continue resume the last game
1231
+ clichess --as black play black
1232
+ clichess --brief "..." skip the brief prompt
1233
+ clichess --engine PATH stockfish path"""
1234
+
1235
+
1236
+ # ─────────────────────────────────- saving ─────────────────────────────────
1237
+
1238
+ def state_path() -> Path:
1239
+ return STATE_DIR / "last.json"
1240
+
1241
+
1242
+ def save_state(board: chess.Board, history: list[str], human: chess.Color, opponent: str,
1243
+ plan: str = "", elo: int | None = None) -> None:
1244
+ try:
1245
+ STATE_DIR.mkdir(parents=True, exist_ok=True)
1246
+ state_path().write_text(json.dumps({
1247
+ "fen": board.fen(),
1248
+ "history": history,
1249
+ "human": "white" if human == chess.WHITE else "black",
1250
+ "opponent": opponent,
1251
+ "plan": plan,
1252
+ "elo": elo,
1253
+ }))
1254
+ except OSError:
1255
+ pass
1256
+
1257
+
1258
+ def load_state() -> dict | None:
1259
+ try:
1260
+ return json.loads(state_path().read_text())
1261
+ except (OSError, json.JSONDecodeError):
1262
+ return None
1263
+
1264
+
1265
+ def result_text(board: chess.Board) -> str:
1266
+ if board.is_checkmate():
1267
+ return f"Checkmate. {'Black' if board.turn == chess.WHITE else 'White'} wins."
1268
+ if board.is_stalemate():
1269
+ return "Stalemate. Draw."
1270
+ if board.is_insufficient_material():
1271
+ return "Insufficient material. Draw."
1272
+ if board.is_fivefold_repetition():
1273
+ return "Fivefold repetition. Draw."
1274
+ if board.is_seventyfive_moves():
1275
+ return "Seventy-five move rule. Draw."
1276
+ if board.is_fifty_moves():
1277
+ return "Fifty move rule. Draw."
1278
+ if board.is_repetition(3):
1279
+ return "Threefold repetition. Draw."
1280
+ return "Game over."
1281
+
1282
+
1283
+ def last_san(board: chess.Board) -> str:
1284
+ b = board.copy()
1285
+ return b.san(b.pop())
1286
+
1287
+
1288
+ # ─────────────────────────────────- main ─────────────────────────────────
1289
+
1290
+ def saved_opponent(name: str) -> Opponent | None:
1291
+ return next((o for o in load_opponents() if o.name == name), None)
1292
+
1293
+
1294
+ def play_game(cfg: Cfg, opp: Opponent | None, opp_name: str, plan: str,
1295
+ board: chess.Board, history: list[str], evals: list, human: chess.Color) -> None:
1296
+ last: chess.Move | None = None # only the opponent's move is highlighted
1297
+ say = "" # the opponent's last line of table talk
1298
+ shown = -1 # last drawn ply, avoids double drawing
1299
+
1300
+ def draw() -> int:
1301
+ print()
1302
+ panel = side_panel(board, evals, history, cfg.color) if cfg.show_panel else []
1303
+ print(compose(render(board, cfg, human, last), panel,
1304
+ say if cfg.show_say else "", cfg.color, opp_name))
1305
+ if board.is_check():
1306
+ print(f" {C.RED}check!{C.R}")
1307
+ return board.ply()
1308
+
1309
+ def save() -> None:
1310
+ save_state(board, history, human, opp_name, plan, ELO)
1311
+
1312
+ try:
1313
+ shown = draw()
1314
+ while not board.is_game_over(claim_draw=True):
1315
+ if board.turn == human:
1316
+ print()
1317
+ try:
1318
+ raw = clean(input("you > ").strip())
1319
+ except (EOFError, KeyboardInterrupt):
1320
+ print()
1321
+ break
1322
+ cmd, _, arg = raw.partition(" ")
1323
+ low = cmd.lower()
1324
+ arg = arg.strip()
1325
+ if low in ("quit", "exit", "q"):
1326
+ break
1327
+ if low in ("help", "h", "?"):
1328
+ print(help_text(opp_name))
1329
+ continue
1330
+ if low == "chat":
1331
+ if PLAY_ENGINE is not None:
1332
+ print(" the engine does not talk.")
1333
+ continue
1334
+ line = arg
1335
+ if not line:
1336
+ try:
1337
+ line = clean(input("say > ").strip())
1338
+ except (EOFError, KeyboardInterrupt):
1339
+ print()
1340
+ break
1341
+ if not line:
1342
+ continue
1343
+ print(f"{C.DIM}{opp_name} is thinking...{C.R}")
1344
+ try:
1345
+ reply = talk(cfg, board, history, opp, plan, line)
1346
+ print(f" {C.CYAN}{opp_name}{C.R}: {reply}")
1347
+ say = reply
1348
+ except ApiError as e:
1349
+ print(f" {C.RED}{e}{C.R}")
1350
+ continue
1351
+ if low == "hint":
1352
+ if ENGINE is not None:
1353
+ mv = ENGINE.best_move(board, DEPTH)
1354
+ print(f" suggests: {C.BOLD}{board.san(mv) if mv else '?'}{C.R}")
1355
+ continue
1356
+ try:
1357
+ print(f"{C.DIM}{opp_name} is thinking...{C.R}")
1358
+ hint_say, cands = ask_candidates(cfg, board, history, opp, plan)
1359
+ print(f" suggests: {C.BOLD}{board.san(cands[0])}{C.R} {C.DIM}{hint_say}{C.R}")
1360
+ except ApiError as e:
1361
+ print(f" {C.RED}{e}{C.R}")
1362
+ continue
1363
+ if low == "undo":
1364
+ if len(board.move_stack) >= 2:
1365
+ board.pop(), history.pop()
1366
+ board.pop(), history.pop()
1367
+ del evals[-2:]
1368
+ last, say = None, ""
1369
+ print(" taken back.")
1370
+ save()
1371
+ shown = draw()
1372
+ else:
1373
+ print(" nothing to take back yet.")
1374
+ continue
1375
+ if low == "fen":
1376
+ print(f" {board.fen()}")
1377
+ continue
1378
+ if low == "new":
1379
+ board, history, last, say = chess.Board(), [], None, ""
1380
+ evals = [evaluate(board)]
1381
+ print(" new game.")
1382
+ shown = draw()
1383
+ continue
1384
+ if low in ("coords", "say", "eval"):
1385
+ if low == "coords":
1386
+ cfg.coords = not cfg.coords
1387
+ elif low == "say":
1388
+ cfg.show_say = not cfg.show_say
1389
+ else:
1390
+ cfg.show_panel = not cfg.show_panel
1391
+ save_settings(cfg)
1392
+ print(f" {low} = {getattr(cfg, {'coords': 'coords', 'say': 'show_say', 'eval': 'show_panel'}[low])}")
1393
+ shown = draw()
1394
+ continue
1395
+ if low == "debug":
1396
+ cfg.debug = not cfg.debug
1397
+ print(f" debug = {cfg.debug}")
1398
+ continue
1399
+ mv = parse_human_move(board, raw)
1400
+ if mv is None:
1401
+ print(f" {C.RED}illegal move{C.R}")
1402
+ continue
1403
+ board.push(mv)
1404
+ history.append(last_san(board))
1405
+ evals.append(evaluate(board))
1406
+ save()
1407
+ last, say = None, "" # your own move is not highlighted
1408
+ continue
1409
+
1410
+ print(f"\n{C.DIM}{opp_name} is thinking...{C.R}", end="", flush=True)
1411
+ t0 = time.time()
1412
+ try:
1413
+ if PLAY_ENGINE is not None and ELO is not None:
1414
+ mv = PLAY_ENGINE.play(board, ELO)
1415
+ say = ""
1416
+ else:
1417
+ say, cands = ask_candidates(cfg, board, history, opp, plan)
1418
+ mv = pick_candidate(cands, board, FLAIR)
1419
+ except ApiError as e:
1420
+ # the model gave nothing usable: let the engine play that move
1421
+ mv = ENGINE.best_move(board, 12) if ENGINE is not None else None
1422
+ print(f"\n {C.RED}{e}{C.R}")
1423
+ if mv is None:
1424
+ break
1425
+ print(f" {C.DIM}engine plays instead{C.R}")
1426
+ say = ""
1427
+ dt = time.time() - t0
1428
+ board.push(mv)
1429
+ history.append(last_san(board))
1430
+ last = mv
1431
+ evals.append(evaluate(board))
1432
+ save()
1433
+ print("\r" + " " * 24 + "\r", end="")
1434
+ print(f"{C.CYAN}{opp_name}{C.R} > {C.BOLD}{history[-1]}{C.R} {C.DIM}({dt:.1f}s){C.R}")
1435
+ shown = draw()
1436
+ except KeyboardInterrupt:
1437
+ print(f"\n{C.DIM}interrupted{C.R}")
1438
+ finally:
1439
+ if PLAY_ENGINE is not None:
1440
+ PLAY_ENGINE.close()
1441
+ if ENGINE is not None:
1442
+ ENGINE.close()
1443
+ if board.is_game_over(claim_draw=True):
1444
+ if board.ply() != shown:
1445
+ draw()
1446
+ print(f"\n{C.BOLD}{result_text(board)}{C.R}")
1447
+ elif board.move_stack:
1448
+ print(f"\n{C.DIM}saved.{C.R}")
1449
+
1450
+
1451
+ def main() -> int:
1452
+ global ENGINE, PLAY_ENGINE, ELO
1453
+ ap = argparse.ArgumentParser(
1454
+ description="Play chess against an LLM or Stockfish in your terminal",
1455
+ formatter_class=argparse.RawDescriptionHelpFormatter,
1456
+ epilog="Run without arguments for the welcome page.",
1457
+ )
1458
+ ap.add_argument("--opponent", metavar="NAME", help="play a saved opponent, or 0 for Stockfish")
1459
+ ap.add_argument("--new", action="store_true", help="create an opponent, skipping the welcome page")
1460
+ ap.add_argument("--list", dest="list_opponents", action="store_true", help="list saved opponents")
1461
+ ap.add_argument("--delete", metavar="NAME", help="delete an opponent")
1462
+ ap.add_argument("--continue", dest="resume", action="store_true", help="resume the last game")
1463
+ ap.add_argument("--as", dest="human_color", choices=["white", "black"], default="white")
1464
+ ap.add_argument("--brief", help="what kind of game you want (skips the prompt)")
1465
+ ap.add_argument("--engine", help="path to stockfish (default: on PATH)")
1466
+ ap.add_argument("--install-engine", action="store_true", help="download stockfish for this platform and exit")
1467
+ ap.add_argument("--version", action="version", version=f"clichess {__version__}")
1468
+ args = ap.parse_args()
1469
+
1470
+ if args.install_engine:
1471
+ got = install_engine()
1472
+ return 0 if got else 2
1473
+
1474
+ base = base_cfg()
1475
+
1476
+ if args.list_opponents:
1477
+ opps = load_opponents()
1478
+ if not opps:
1479
+ print("no opponents yet.")
1480
+ for i, o in enumerate(opps, 1):
1481
+ print(f"{i}. {o.name:<12} {o.model:<22} {o.base_url}")
1482
+ return 0
1483
+
1484
+ if args.delete:
1485
+ if args.delete.strip().lower() in ("0", "stockfish"):
1486
+ print("Stockfish is built in - nothing to delete.", file=sys.stderr)
1487
+ return 2
1488
+ target = find_saved(args.delete.strip())
1489
+ if not target:
1490
+ print(f"no opponent called \"{args.delete}\".", file=sys.stderr)
1491
+ return 2
1492
+ delete_opponent(target)
1493
+ print(f"deleted \"{target.name}\".")
1494
+ return 0
1495
+
1496
+ state = load_state() if args.resume else None
1497
+ opp: Opponent | None = None
1498
+
1499
+ if args.new:
1500
+ opp = add_opponent()
1501
+ if opp is None:
1502
+ return 2
1503
+ state = None
1504
+ elif args.opponent:
1505
+ opp, ok = resolve_opponent(args)
1506
+ if not ok:
1507
+ return 2
1508
+ elif state is not None:
1509
+ opp = saved_opponent(state.get("opponent", ""))
1510
+ if opp is None:
1511
+ print(f'"{state.get("opponent")}" is gone.', file=sys.stderr)
1512
+ state = None
1513
+
1514
+ if opp is None and state is None and not sys.stdin.isatty():
1515
+ opp, ok = resolve_opponent(args)
1516
+ if not ok:
1517
+ return 2
1518
+ elif opp is None and state is None:
1519
+ action, opp = welcome_page(base)
1520
+ if action == "quit":
1521
+ return 0
1522
+ if action == "resume":
1523
+ st = load_state()
1524
+ cand = saved_opponent(st.get("opponent", "")) if st else None
1525
+ if st is None or cand is None:
1526
+ print(" no saved game to resume.")
1527
+ return 0
1528
+ state, opp = st, cand
1529
+
1530
+ cfg = cfg_for(opp, base)
1531
+ local = bool(opp and ("127.0.0.1" in opp.base_url or "localhost" in opp.base_url))
1532
+ if opp is STOCKFISH or local or opp is None:
1533
+ if opp is None and not base.api_key:
1534
+ print("No API key: add an opponent, or export DEEPSEEK_API_KEY.", file=sys.stderr)
1535
+ return 2
1536
+ elif not cfg.api_key:
1537
+ print(f"\"{opp.name}\" has no API key.", file=sys.stderr)
1538
+ return 2
1539
+
1540
+ # start the engine only now, so --list / --delete never spawn one
1541
+ epath = find_engine(args.engine)
1542
+ if epath:
1543
+ try:
1544
+ ENGINE = Engine(epath, DEPTH)
1545
+ except Exception as e:
1546
+ print(f"warning: cannot start stockfish ({e}); no eval", file=sys.stderr)
1547
+ else:
1548
+ print("warning: no stockfish found - no eval, and moves come straight from the model", file=sys.stderr)
1549
+ if sys.stdin.isatty():
1550
+ c = ask("download stockfish now (~80 MB)?", "Y")
1551
+ if c and c.lower() not in ("n", "no"):
1552
+ got = install_engine()
1553
+ if got is not None:
1554
+ epath = str(got)
1555
+ try:
1556
+ ENGINE = Engine(epath, DEPTH)
1557
+ except Exception as e:
1558
+ print(f"warning: cannot start stockfish ({e})", file=sys.stderr)
1559
+
1560
+ plan = (state or {}).get("plan", "") if state else ""
1561
+ if opp is STOCKFISH:
1562
+ if ENGINE is None:
1563
+ print("Stockfish is not available - run `clichess --install-engine` first.",
1564
+ file=sys.stderr)
1565
+ return 2
1566
+ if state and (state.get("elo") or state.get("skill")):
1567
+ ELO = int(state.get("elo") or state.get("skill") or 0) or None
1568
+ if ELO is None:
1569
+ ELO = ask_level()
1570
+ if ELO is None:
1571
+ return 0
1572
+ PLAY_ENGINE = Engine(epath, DEPTH)
1573
+ plan = ""
1574
+ else:
1575
+ if args.brief is not None:
1576
+ brief, plan = args.brief, ""
1577
+ elif state:
1578
+ brief = ""
1579
+ else:
1580
+ brief = ask_brief()
1581
+ if brief:
1582
+ print(f"{C.DIM}agreeing a plan...{C.R}")
1583
+ try:
1584
+ plan = negotiate(cfg, opp, brief)
1585
+ except ApiError as e:
1586
+ print(f"{C.DIM}could not agree ({e}), playing without a plan{C.R}")
1587
+ plan = ""
1588
+
1589
+ if state:
1590
+ board = chess.Board(state["fen"])
1591
+ history = list(state["history"])
1592
+ human = chess.WHITE if state.get("human") == "white" else chess.BLACK
1593
+ head = f"resuming, you play {'white' if human == chess.WHITE else 'black'}"
1594
+ else:
1595
+ board = chess.Board()
1596
+ history = []
1597
+ human = chess.WHITE if args.human_color == "white" else chess.BLACK
1598
+ head = f"new game, you play {'white' if human == chess.WHITE else 'black'}"
1599
+
1600
+ # eval history (white's perspective), evals[i] = position after i half-moves
1601
+ evals: list = [evaluate(board)]
1602
+ if history:
1603
+ b, ev = chess.Board(), [evaluate(chess.Board())]
1604
+ try:
1605
+ for san in history:
1606
+ b.push_san(san)
1607
+ ev.append(evaluate(b))
1608
+ if b.fen() == board.fen():
1609
+ evals = ev
1610
+ except Exception:
1611
+ pass
1612
+
1613
+ opp_name = opp.name if opp else cfg.model
1614
+ who = ("full strength" if (ELO or 0) >= 3190 else f"elo {ELO}") if opp is STOCKFISH else cfg.model
1615
+ print(f"{C.BOLD}clichess{C.R}\t{C.CYAN}{opp_name}{C.R}\t{who}\t{head}")
1616
+ if plan:
1617
+ print(f"{C.DIM}plan: {plan}{C.R}")
1618
+ print()
1619
+
1620
+ play_game(cfg, opp, opp_name, plan, board, history, evals, human)
1621
+ return 0
1622
+
1623
+
1624
+ if __name__ == "__main__":
1625
+ sys.exit(main())