#!/usr/bin/env python3 """Schickt Anfragen an den Entscheidungskern (Rust, src/) und liest Antworten. from decide import entscheide """ import os as _os, sys as _sys _w = _os.path.dirname(_os.path.abspath(__file__)) while _w != "/" and not _os.path.isdir(_os.path.join(_w, "lesen")): _w = _os.path.dirname(_w) WURZEL = _w for _u in ("lesen", "entscheiden", "hand", "client", "lobby", "korpus", "betrieb"): _q = _os.path.join(_w, _u) if _os.path.isdir(_q) and _q not in _sys.path: _sys.path.insert(0, _q) import json import os import sys import subprocess import time BASE = os.path.dirname(os.path.abspath(__file__)) BINARY = os.environ.get("COINPOKER_KERN", os.path.join(BASE, "..", "target", "release", "rechner")) QUELLE = os.environ.get("COINPOKER_KERN_QUELLE", os.path.join(BASE, "..")) def bereit(): return os.path.exists(BINARY) def baue(): """Baut den Kern, falls nötig.""" r = subprocess.run(["cargo", "build", "--release"], cwd=QUELLE, capture_output=True, text=True, timeout=600) return r.returncode == 0, (r.stdout + r.stderr)[-400:] def frisch(): """Ist das Release-Binary nicht aelter als der Kern-Quelltext? Alles hier entscheidet ueber dieses Binary. Wird der Kern geaendert und nicht mit `cargo build --release` gebaut, prueft die Kette stillschweigend die alte Fassung - deshalb tests/kern_frisch_spec.py. """ if not os.path.exists(BINARY): return False quelle = os.path.join(QUELLE, "src") if not os.path.isdir(quelle): return True # fremder Kern: nur das Binary da juengste = max((os.path.getmtime(os.path.join(w, f)) for w, _, fs in os.walk(quelle) for f in fs if f.endswith(".rs")), default=0.0) return os.path.getmtime(BINARY) >= juengste _zuletzt_geprueft = 0.0 def _sicher_frisch(): """Haelt das Kern-Binary aktuell, ohne dass jemand von Hand `cargo build` tippt: ist der Quelltext neuer als das Binary, wird einmal neu gebaut. Hoechstens alle 10 s geprueft (ein mtime-Blick ueber src/), damit kein Takt leidet. So wirkt eine Engine-Aenderung ab der naechsten Hand - ohne Neustart und ohne Handbau.""" global _zuletzt_geprueft jetzt = time.time() if jetzt - _zuletzt_geprueft < 10.0: return _zuletzt_geprueft = jetzt if not frisch(): baue() def entscheide(anfragen, timeout=30): """Liste von Anfrage-Zeilen -> Liste von Entscheidungen (dict).""" if not anfragen: return [] _sicher_frisch() # Was die Übersetzung absichtlich leer lässt (`_unklar`), geht nicht zum Kern: ohne # eigenen Platz wäre es für ihn eine ungültige Anfrage statt eines Aussetzens. aussetzen = {} for i, zeile in enumerate(anfragen): try: a = json.loads(zeile) except ValueError: continue if isinstance(a, dict) and a.get("legalActions") == [] and a.get("_unklar"): aussetzen[i] = {"action": "ABSTAIN", "reason": f"Übersetzung setzt aus: {a['_unklar']}"} if aussetzen: rest = iter(entscheide([z for i, z in enumerate(anfragen) if i not in aussetzen], timeout)) return [aussetzen[i] if i in aussetzen else next(rest) for i in range(len(anfragen))] r = subprocess.run([BINARY], input="\n".join(anfragen) + "\n", capture_output=True, text=True, timeout=timeout) if r.returncode != 0: raise RuntimeError(f"der Kern scheiterte: {r.stderr.strip()[:300]}") antworten = [] for zeile in r.stdout.strip().split("\n"): if not zeile.strip(): continue try: antworten.append(json.loads(zeile)) except Exception: antworten.append({"action": "ABSTAIN", "reason": "Antwort unlesbar"}) return antworten if __name__ == "__main__": import sys if not bereit(): ok, ausgabe = baue() print("gebaut:", ok) if not ok: print(ausgabe) sys.exit(1) probe = json.dumps({ "variant": "NLHE", "bigBlind": 0.1, "seats": 6, "heroSeat": 5, "heroCards": [{"rank": "ACE", "suit": "SPADES"}, {"rank": "ACE", "suit": "HEARTS"}], "board": {}, "street": "PREFLOP", "pot": 0.15, "toCall": 0.1, "heroStack": 10.0, "legalActions": ["FOLD", "CALL", "RAISE"], "allowedSizes": [0.3, 0.5], "villains": [{"seat": 2, "stack": 10.0, "folded": False}]}) print(entscheide([probe])[0])