clichess-cli 2.1.1__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.

Potentially problematic release.


This version of clichess-cli might be problematic. Click here for more details.

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