From 070366d87415aabcaa2f3676200d087eb1e0c6f1 Mon Sep 17 00:00:00 2001 From: Marc Mintel Date: Wed, 28 Oct 2026 15:52:41 +0100 Subject: [PATCH] Sonden und MCP-Harnesse nach werkzeuge/ einsortiert --- betrieb/runner.py | 2 +- korpus/korpus.py | 2 +- lesen/formats.py | 2 +- lesen/observe.py | 2 +- lesen/spot_from_log.py | 2 +- lobby/cdp.mjs | 13 ++- mcp/debug.py | 2 +- mcp/diagnose.py | 2 +- mcp/lobby_adapter.py | 20 +++- mcp/server.py | 2 +- werkzeuge/README.md | 15 +++ werkzeuge/axpress.py | 95 +++++++++++++++++++ werkzeuge/hover.py | 172 ++++++++++++++++++++++++++++++++++ werkzeuge/keytest.py | 148 +++++++++++++++++++++++++++++ werkzeuge/mcp_aufraeumen.py | 36 +++++++ werkzeuge/mcp_calls.py | 35 +++++++ werkzeuge/mcp_probe.py | 44 +++++++++ werkzeuge/mcp_tisch.py | 35 +++++++ werkzeuge/probe.py | 182 ++++++++++++++++++++++++++++++++++++ werkzeuge/shot.py | 84 +++++++++++++++++ 20 files changed, 885 insertions(+), 10 deletions(-) create mode 100644 werkzeuge/README.md create mode 100644 werkzeuge/axpress.py create mode 100644 werkzeuge/hover.py create mode 100644 werkzeuge/keytest.py create mode 100644 werkzeuge/mcp_aufraeumen.py create mode 100644 werkzeuge/mcp_calls.py create mode 100644 werkzeuge/mcp_probe.py create mode 100644 werkzeuge/mcp_tisch.py create mode 100644 werkzeuge/probe.py create mode 100644 werkzeuge/shot.py diff --git a/betrieb/runner.py b/betrieb/runner.py index 670bc70..b44a1c0 100644 --- a/betrieb/runner.py +++ b/betrieb/runner.py @@ -36,7 +36,7 @@ import nachsehen import spot_from_log BASE = os.path.dirname(os.path.abspath(__file__)) -LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") +LOG = os.environ.get("COINPOKER_LOG", os.path.expanduser("~/Library/Logs/CoinPoker/main.log")) SHADOW = os.path.join(BASE, "scratch", "shadow.jsonl") TAIL = 400_000 FRISCH = 3.0 # Sekunden: so alt darf der Zug beim Klicken sein diff --git a/korpus/korpus.py b/korpus/korpus.py index 3e89d3d..7daffcb 100644 --- a/korpus/korpus.py +++ b/korpus/korpus.py @@ -22,7 +22,7 @@ import sys import sys import time -LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") +LOG = os.environ.get("COINPOKER_LOG", os.path.expanduser("~/Library/Logs/CoinPoker/main.log")) BASE = os.path.dirname(os.path.abspath(__file__)) DIR = os.path.join(WURZEL, "archiv") STAND = os.path.join(DIR, "stand.txt") diff --git a/lesen/formats.py b/lesen/formats.py index f711d00..fe28726 100644 --- a/lesen/formats.py +++ b/lesen/formats.py @@ -22,7 +22,7 @@ import sys import re import sys -LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") +LOG = os.environ.get("COINPOKER_LOG", os.path.expanduser("~/Library/Logs/CoinPoker/main.log")) OUT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "scratch", "korpus-index.txt") diff --git a/lesen/observe.py b/lesen/observe.py index d32fc17..a4bb409 100644 --- a/lesen/observe.py +++ b/lesen/observe.py @@ -22,7 +22,7 @@ import re import sys import time -LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") +LOG = os.environ.get("COINPOKER_LOG", os.path.expanduser("~/Library/Logs/CoinPoker/main.log")) EVENT = re.compile( r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"([a-zA-Z_.]+)","RoomName":"((?:[^"\\]|\\.)*)"' diff --git a/lesen/spot_from_log.py b/lesen/spot_from_log.py index 6a07728..a172d4d 100644 --- a/lesen/spot_from_log.py +++ b/lesen/spot_from_log.py @@ -24,7 +24,7 @@ import re import profil -LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") +LOG = os.environ.get("COINPOKER_LOG", os.path.expanduser("~/Library/Logs/CoinPoker/main.log")) BEAN = re.compile( r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"(game\.[a-z_]+)","RoomName":"((?:[^"\\]|\\.)*)"') BLINDS = re.compile(r"NL ([\d.]+)-([\d.]+)") diff --git a/lobby/cdp.mjs b/lobby/cdp.mjs index 0409eb6..da188f4 100644 --- a/lobby/cdp.mjs +++ b/lobby/cdp.mjs @@ -30,11 +30,17 @@ const KLICK = (text) => `(() => { .filter((n) => ${SICHTBAR}); const genau = alle.filter((n) => (n.innerText || "").trim().toLowerCase() === wollen) .sort((a, b) => { + const istKnopf = (n) => (n.tagName === 'BUTTON' || + n.getAttribute('role') === 'button') ? 0 : 1; + if (istKnopf(a) !== istKnopf(b)) return istKnopf(a) - istKnopf(b); const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); return ra.width * ra.height - rb.width * rb.height; }); const teil = alle.filter((n) => (n.innerText || "").trim().toLowerCase().startsWith(wollen)) .sort((a, b) => { + const istKnopf = (n) => (n.tagName === 'BUTTON' || + n.getAttribute('role') === 'button') ? 0 : 1; + if (istKnopf(a) !== istKnopf(b)) return istKnopf(a) - istKnopf(b); const ra = a.getBoundingClientRect(), rb = b.getBoundingClientRect(); return ra.width * ra.height - rb.width * rb.height; }); @@ -95,7 +101,12 @@ const KLICK_IN = (zeilenText, knopfText) => `(() => { for (const z of treffer) { const knoepfe = [...z.querySelectorAll('button, a, [role="button"], span, div')] .filter((n) => sichtbar(n) && (n.innerText || "").trim().toLowerCase() === knopf) - .sort((a, b) => flaeche(a) - flaeche(b)); + .sort((a, b) => { + const istKnopf = (n) => (n.tagName === 'BUTTON' || + n.getAttribute('role') === 'button') ? 0 : 1; + if (istKnopf(a) !== istKnopf(b)) return istKnopf(a) - istKnopf(b); + return flaeche(a) - flaeche(b); + }); if (!knoepfe.length) continue; const ziel = knoepfe[0]; const r = ziel.getBoundingClientRect(); diff --git a/mcp/debug.py b/mcp/debug.py index eac0ab7..a4fd64b 100644 --- a/mcp/debug.py +++ b/mcp/debug.py @@ -10,7 +10,7 @@ while _w != "/" and not os.path.isdir(os.path.join(_w, "hand")): _w = os.path.dirname(_w) WURZEL = _w -LOG_PATH = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") +LOG_PATH = os.environ.get("COINPOKER_LOG", os.path.expanduser("~/Library/Logs/CoinPoker/main.log")) SHADOW_PATH = os.path.join(WURZEL, "betrieb", "scratch", "shadow.jsonl") diff --git a/mcp/diagnose.py b/mcp/diagnose.py index 3dcf166..587a558 100644 --- a/mcp/diagnose.py +++ b/mcp/diagnose.py @@ -24,7 +24,7 @@ import fenster as fenster_modul import korpus as korpus_modul import spot_from_log as spot_modul -LOG_PATH = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") +LOG_PATH = os.environ.get("COINPOKER_LOG", os.path.expanduser("~/Library/Logs/CoinPoker/main.log")) _fenster_cache = (0.0, []) diff --git a/mcp/lobby_adapter.py b/mcp/lobby_adapter.py index 77259d5..1bff7f7 100644 --- a/mcp/lobby_adapter.py +++ b/mcp/lobby_adapter.py @@ -16,6 +16,24 @@ WURZEL = _w CDP_SCRIPT = os.path.join(WURZEL, "lobby", "cdp.mjs") +def _geoeffnet(vorher, kennung): + """Belege dafür, dass der Beitritt gewirkt hat: neues Fenster, Fenstertitel, + oder der Raum taucht im Log auf. Ein einzelner Beleg genügt.""" + import os as _o + if len(fenster.tischfenster()) > vorher: + return True + if any(kennung in f["titel"] for f in fenster.tischfenster()): + return True + pfad = _o.environ.get("COINPOKER_LOG", + _o.path.expanduser("~/Library/Logs/CoinPoker/main.log")) + try: + with open(pfad, errors="replace") as h: + h.seek(max(0, _o.path.getsize(pfad) - 40_000)) + return kennung in h.read() + except OSError: + return False + + KLICK_ZEILE = """(() => { const zeile = document.querySelector('[data-table-id="__ID__"]'); if (!zeile) return "Zeile nicht gefunden"; @@ -94,7 +112,7 @@ def tisch_oeffnen(reiter, name=None): for kandidat in kandidaten[:3]: res = cdp_ausfuehren(["--eval", KLICK_ZEILE.replace("__ID__", kandidat["id"])]) time.sleep(2.0) - if len(fenster.tischfenster()) > vorher: + if _geoeffnet(vorher, kandidat["id"]): return (f"{reiter}-Tisch geöffnet: {kandidat['id']} [{kandidat['players']}] " f"-> {res}") return f"{reiter}: nach {min(3, len(kandidaten))} Versuchen ging kein Tisch auf" diff --git a/mcp/server.py b/mcp/server.py index f57c7ab..f5a6d29 100644 --- a/mcp/server.py +++ b/mcp/server.py @@ -50,7 +50,7 @@ from diagnose import ( from lobby_adapter import cdp_ausfuehren, tisch_oeffnen from stopp import ist_gestoppt, stopp_aufheben, stopp_setzen -LOG_PATH = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") +LOG_PATH = os.environ.get("COINPOKER_LOG", os.path.expanduser("~/Library/Logs/CoinPoker/main.log")) SHADOW_PATH = os.path.join(WURZEL, "betrieb", "scratch", "shadow.jsonl") TAIL_BYTES = 400_000 FRISCH_SEKUNDEN = 3.0 diff --git a/werkzeuge/README.md b/werkzeuge/README.md new file mode 100644 index 0000000..5d956d7 --- /dev/null +++ b/werkzeuge/README.md @@ -0,0 +1,15 @@ +# Sonden und Harnesse + +Werkzeuge, die **nicht** zum laufenden Betrieb gehören, aber festhalten, wie wir +etwas herausgefunden haben. Keine Spezifikationen – Stand-Sonden. + +| Datei | wofür | +|---|---| +| `probe.py` | Schreibt Testnachrichten in die Pipe des Clients und liest Reaktionen | +| `keytest.py` | Sucht Tastenkürzel des Tischfensters | +| `hover.py` | Fährt mit der Maus über die Knopfleiste und liest Meldungen | +| `axpress.py` | Drückt Knöpfe über die Bedienungshilfen | +| `shot.py` | Früher Bilder vom Tisch (heute `hand/foto.py`) | +| `mcp_*.py` | Harnesse, die MCP-Werkzeuge ohne Client aufrufen | + +Sie sind **nicht** Teil der Kette und werden von den Tests nicht abgedeckt. diff --git a/werkzeuge/axpress.py b/werkzeuge/axpress.py new file mode 100644 index 0000000..5141307 --- /dev/null +++ b/werkzeuge/axpress.py @@ -0,0 +1,95 @@ +#!/usr/bin/env python3 +"""Spricht die Knoepfe des Tischfensters direkt an (macOS-Bedienungshilfen). + +Kein Tastenraten, keine blinden Koordinaten: das System nennt uns die Knoepfe +samt Position, wir druecken den gewaehlten. + + python3 axpress.py --list # Knoepfe des Tisches auflisten + python3 axpress.py --press 3 # Knopf 3 druecken (AXPress) + python3 axpress.py --click 3 # stattdessen in die Mitte klicken +""" +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, "hand")): + _w = _os.path.dirname(_w) +WURZEL = _w +for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb", "mock"): + _q = _os.path.join(_w, _u) + if _os.path.isdir(_q) and _q not in _sys.path: + _sys.path.insert(0, _q) +import subprocess +import sys + + +def osa(script): + res = subprocess.run(["osascript", "-e", script], capture_output=True, text=True) + return (res.stdout or res.stderr).strip() + + +def game_pid(): + out = subprocess.run(["pgrep", "-f", "CoinPoker Game"], capture_output=True, text=True) + pids = [int(p) for p in out.stdout.split()] + return pids[0] if pids else None + + +def main(): + pid = game_pid() + if not pid: + print("kein Tischfenster (CoinPoker Game laeuft nicht)") + return 1 + proc = f'(first process whose unix id is {pid})' + title = osa(f'tell application "System Events" to tell {proc} to get value of ' + f'every static text of window 1') + win = osa(f'tell application "System Events" to tell {proc} to get position of window 1') + size = osa(f'tell application "System Events" to tell {proc} to get size of window 1') + print(f"Prozess {pid}") + print(f"Fenster-Titel: {title}") + print(f"Fenster: {win} Groesse: {size}") + + if "--list" in sys.argv or len(sys.argv) == 1: + def nums(text): + return [float(x) for x in text.replace(" ", "").split(",") if x.strip(" ,")] + + pos = nums(osa(f'tell application "System Events" to tell {proc} to get position ' + f'of every button of window 1')) + dim = nums(osa(f'tell application "System Events" to tell {proc} to get size ' + f'of every button of window 1')) + places = list(zip(pos[0::2], pos[1::2])) + sizes = list(zip(dim[0::2], dim[1::2])) + print(f"\nKnöpfe: {len(places)}") + for i, (x, y) in enumerate(places): + w, h = sizes[i] if i < len(sizes) else (0.0, 0.0) + print(f" [{i}] x={x:.0f} y={y:.0f} {w:.0f}x{h:.0f} " + f"Mitte=({x + w / 2:.0f}, {y + h / 2:.0f})") + return 0 + + index = None + for flag in ("--press", "--click"): + if flag in sys.argv: + index = int(sys.argv[sys.argv.index(flag) + 1]) + action = flag + if index is None: + print("bitte --press N oder --click N angeben") + return 1 + + if action == "--press": + out = osa(f'tell application "System Events" to tell {proc} to perform action ' + f'"AXPress" of button {index + 1} of window 1') + print(f"AXPress Knopf {index}: {out or 'gesendet'}") + else: + pos = osa(f'tell application "System Events" to tell {proc} to get position of ' + f'button {index + 1} of window 1').split(",") + dim = osa(f'tell application "System Events" to tell {proc} to get size of ' + f'button {index + 1} of window 1').split(",") + if len(pos) < 2 or len(dim) < 2: + print(f"Knopf {index} nicht gefunden") + return 1 + x = int(float(pos[0])) + int(float(dim[0])) // 2 + y = int(float(pos[1])) + int(float(dim[1])) // 2 + out = osa(f'tell application "System Events" to click at {{{x}, {y}}}') + print(f"Klick auf Knopf {index} bei {x},{y}: {out or 'gesendet'}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/werkzeuge/hover.py b/werkzeuge/hover.py new file mode 100644 index 0000000..e6fa976 --- /dev/null +++ b/werkzeuge/hover.py @@ -0,0 +1,172 @@ +#!/usr/bin/env python3 +"""Lernt die Aktionsknöpfe, indem es mit der Maus darüber fährt. + +Der Client meldet beim Überfahren selbst, was unter dem Zeiger liegt +(TABLE_PLAYER_ACTION_SHOW). Wir klicken dabei nichts - reines Überfahren. + + python3 hover.py [--minutes 30] +""" +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, "hand")): + _w = _os.path.dirname(_w) +WURZEL = _w +for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb", "mock"): + _q = _os.path.join(_w, _u) + if _os.path.isdir(_q) and _q not in _sys.path: + _sys.path.insert(0, _q) +import ctypes +import json +import os +import re +import subprocess +import sys +import time + +BASE = os.path.dirname(os.path.abspath(__file__)) +LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") +OUT = os.path.join(BASE, "scratch", "hover-log.txt") + +FW = "/System/Library/Frameworks/ApplicationServices.framework/ApplicationServices" +AS = ctypes.cdll.LoadLibrary(FW) + + +class CGPoint(ctypes.Structure): + _fields_ = [("x", ctypes.c_double), ("y", ctypes.c_double)] + + +AS.CGEventCreateMouseEvent.restype = ctypes.c_void_p +AS.CGEventCreateMouseEvent.argtypes = [ctypes.c_void_p, ctypes.c_uint32, CGPoint, + ctypes.c_uint32] +AS.CGEventPost.argtypes = [ctypes.c_uint32, ctypes.c_void_p] +MOUSE_MOVED = 5 + +EVENT = re.compile( + r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"([a-zA-Z_.]+)","RoomName":"((?:[^"\\]|\\.)*)"' +) +USER = re.compile(r"username=([A-Za-z0-9_]+)") +SHOW = "TABLE_PLAYER_ACTION" + + +class LogTail: + def __init__(self, path): + self.path, self.handle, self.inode = path, None, None + self._open(True) + + def _open(self, from_end): + if self.handle: + self.handle.close() + self.handle = open(self.path, errors="replace") + if from_end: + self.handle.seek(0, 2) + self.inode = os.fstat(self.handle.fileno()).st_ino + + def line(self): + found = self.handle.readline() + if found: + return found + try: + if os.stat(self.path).st_ino != self.inode: + self._open(False) + except FileNotFoundError: + pass + return "" + + +def osa(script): + r = subprocess.run(["osascript", "-e", script], capture_output=True, text=True) + return (r.stdout or r.stderr).strip() + + +def window_rect(): + pid = subprocess.run(["pgrep", "-f", "CoinPoker Game"], capture_output=True, + text=True).stdout.split() + if not pid: + return None + proc = f'(first process whose unix id is {pid[0]})' + pos = osa(f'tell application "System Events" to tell {proc} to get position of window 1') + size = osa(f'tell application "System Events" to tell {proc} to get size of window 1') + try: + x, y = [float(v) for v in pos.replace(" ", "").split(",")[:2]] + w, h = [float(v) for v in size.replace(" ", "").split(",")[:2]] + except Exception: + return None + return x, y, w, h + + +def move_to(x, y): + ev = AS.CGEventCreateMouseEvent(None, MOUSE_MOVED, CGPoint(x, y), 0) + AS.CGEventPost(0, ev) + + +def sweep(tail): + rect = window_rect() + if not rect: + return [] + x, y, w, h = rect + hits = [] + lane = y + h - 45 + step = 14 + for px in range(int(x) + 30, int(x + w) - 20, step): + move_to(px, lane) + time.sleep(0.10) + while True: + line = tail.line() + if not line: + break + if SHOW in line: + hits.append((px, line.strip()[:170])) + return hits + + +def main(): + minutes = 30.0 + if "--minutes" in sys.argv: + minutes = float(sys.argv[sys.argv.index("--minutes") + 1]) + out = open(OUT, "w") + def note(t): + out.write(t + "\n") + out.flush() + + tail = LogTail(LOG) + note(f"# Überfahren gestartet {time.strftime('%H:%M:%S')} | " + f"Fenster {window_rect()}") + me, armed, end = None, True, time.time() + minutes * 60 + while time.time() < end: + line = tail.line() + if not line: + time.sleep(0.1) + continue + who = USER.search(line) + if who: + me = who.group(1) + if "advance_player_action" in line: + armed = True + hit = EVENT.search(line) + if not hit or hit.group(2) != "game.user_turn": + continue + try: + data = json.loads(json.loads('"' + hit.group(1) + '"')) + except Exception: + continue + opts = {s: v for s, v in (data.get("userTurnOptions") or {}).items() if v} + if opts: + me = data.get("whoseTurn") or me + elif me is None or data.get("whoseTurn") != me: + continue + if not armed: + continue + armed = False + note(f"\n=== Zug {time.strftime('%H:%M:%S')} Hand {data.get('gameHandId')} " + f"Call {data.get('callAmount')} - fahre über die Knopfleiste") + hits = sweep(tail) + note(f" Meldungen des Clients: {len(hits)}") + for px, text in hits: + note(f" bei x={px}: {text}") + + note("\n# Ende") + out.close() + + +if __name__ == "__main__": + main() diff --git a/werkzeuge/keytest.py b/werkzeuge/keytest.py new file mode 100644 index 0000000..4d81eb3 --- /dev/null +++ b/werkzeuge/keytest.py @@ -0,0 +1,148 @@ +#!/usr/bin/env python3 +"""Testet Tastenkürzel des Tischfensters - sauber, eine Taste pro Zug. + +Erfolg heisst: der Zug ist danach vorbei (der Client meldet den naechsten Spieler +oder game.advance_player_action). Das ist der verlaesslichste Beweis, dass der +Tastendruck angekommen und gewirkt hat. + + python3 keytest.py [--minutes 30] +""" +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, "hand")): + _w = _os.path.dirname(_w) +WURZEL = _w +for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb", "mock"): + _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 re +import subprocess +import sys +import time + +BASE = os.path.dirname(os.path.abspath(__file__)) +LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") +OUT = os.path.join(BASE, "scratch", "keytest-log.txt") + +EVENT = re.compile( + r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"([a-zA-Z_.]+)","RoomName":"((?:[^"\\]|\\.)*)"' +) +USER = re.compile(r"username=([A-Za-z0-9_]+)") +KEYS = ["f", "c", "r", "space", "a", "b"] +TURN_OVER = ("advance_player_action", "ACTION_TYPE") + + +class LogTail: + def __init__(self, path): + self.path, self.handle, self.inode = path, None, None + self._open(True) + + def _open(self, from_end): + if self.handle: + self.handle.close() + self.handle = open(self.path, errors="replace") + if from_end: + self.handle.seek(0, 2) + self.inode = os.fstat(self.handle.fileno()).st_ino + + def line(self): + found = self.handle.readline() + if found: + return found + try: + if os.stat(self.path).st_ino != self.inode: + self._open(False) + except FileNotFoundError: + pass + return "" + + +def press(key): + cmd = [sys.executable, os.path.join(BASE, "press.py"), key] + return subprocess.run(cmd, capture_output=True, text=True).stdout.strip() + + +def main(): + minutes = 30.0 + if "--minutes" in sys.argv: + minutes = float(sys.argv[sys.argv.index("--minutes") + 1]) + + out = open(OUT, "w") + def note(text): + out.write(text + "\n") + out.flush() + + tail = LogTail(LOG) + note(f"# Sauberer Tastentest {time.strftime('%H:%M:%S')} | Tasten {KEYS} | " + f"eine Taste pro Zug | Erfolg = Zug danach vorbei") + + me = None + index = 0 + armed = True # darf gedrueckt werden? + results = [] + end = time.time() + minutes * 60 + while time.time() < end and index < len(KEYS): + line = tail.line() + if not line: + time.sleep(0.1) + continue + who = USER.search(line) + if who: + me = who.group(1) + if any(t in line for t in TURN_OVER): + armed = True + hit = EVENT.search(line) + if not hit or hit.group(2) != "game.user_turn": + continue + try: + data = json.loads(json.loads('"' + hit.group(1) + '"')) + except Exception: + continue + options = {s: v for s, v in (data.get("userTurnOptions") or {}).items() if v} + if options: + me = data.get("whoseTurn") or me + elif me is None or data.get("whoseTurn") != me: + continue + if not armed: + continue + + key = KEYS[index] + note(f"\n=== Zug | {time.strftime('%H:%M:%S')} | Taste '{key}' | Hand " + f"{data.get('gameHandId')} | Call {data.get('callAmount')} " + f"Pot {data.get('totalPot')} | ich={me}") + note(" " + press(key)) + armed = False + started = time.time() + + proof = [] + while time.time() - started < 2.5: + more = tail.line() + if not more: + time.sleep(0.04) + continue + if any(t in more for t in TURN_OVER): + proof.append(f"+{int((time.time()-started)*1000)}ms {more.strip()[:170]}") + if proof: + results.append((key, proof[0])) + note(f" WIRKT - der Zug war danach vorbei:") + for p in proof[:3]: + note(f" {p}") + index += 1 + else: + note(" ohne Wirkung") + + note("\n# Ergebnis") + if results: + for key, p in results: + note(f" Taste '{key}' wirkt -> {p[:130]}") + else: + note(" keine Taste hat gewirkt") + note(f"# beendet nach {index} bestaetigten Tasten") + out.close() + + +if __name__ == "__main__": + main() diff --git a/werkzeuge/mcp_aufraeumen.py b/werkzeuge/mcp_aufraeumen.py new file mode 100644 index 0000000..6b9fb2a --- /dev/null +++ b/werkzeuge/mcp_aufraeumen.py @@ -0,0 +1,36 @@ +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, "hand")): + _w = _os.path.dirname(_w) +WURZEL = _w +for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb", "mock"): + _q = _os.path.join(_w, _u) + if _os.path.isdir(_q) and _q not in _sys.path: + _sys.path.insert(0, _q) +import json, os, select, subprocess, sys, time +S = os.path.expanduser("~/Projects/pokerfreak-shell") +p = subprocess.Popen(["bash", os.path.join(S, "run.sh")], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, bufsize=1, cwd=S) +def send(o): p.stdin.write(json.dumps(o) + "\n"); p.stdin.flush() +def read(sek=60): + ende = time.time() + sek + while time.time() < ende: + if select.select([p.stdout], [], [], 0.3)[0]: + z = p.stdout.readline() + if z.strip(): + try: return json.loads(z) + except Exception: return {"raw": z[:200]} + return None +def call(nr, name, args=None): + send({"jsonrpc":"2.0","id":nr,"method":"tools/call","params":{"name":name,"arguments":args or {}}}) + a = read() or {} + t = ((a.get("result") or {}).get("content") or [{}])[0].get("text", "") + print(f"### {name} -> {t[:300]}") +send({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"p","version":"1"}}}) +read(15); send({"jsonrpc":"2.0","method":"notifications/initialized","params":{}}) +call(2, "close_all_tables") +time.sleep(3) +call(3, "open_practice_table") +time.sleep(8) +call(4, "status") +p.terminate() diff --git a/werkzeuge/mcp_calls.py b/werkzeuge/mcp_calls.py new file mode 100644 index 0000000..359da3f --- /dev/null +++ b/werkzeuge/mcp_calls.py @@ -0,0 +1,35 @@ +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, "hand")): + _w = _os.path.dirname(_w) +WURZEL = _w +for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb", "mock"): + _q = _os.path.join(_w, _u) + if _os.path.isdir(_q) and _q not in _sys.path: + _sys.path.insert(0, _q) +import json, os, select, subprocess, sys, time +S = os.path.expanduser("~/Projects/pokerfreak-shell") +p = subprocess.Popen(["bash", os.path.join(S, "run.sh")], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, bufsize=1, cwd=S) +def send(o): p.stdin.write(json.dumps(o) + "\n"); p.stdin.flush() +def read(sek=30): + ende = time.time() + sek + while time.time() < ende: + if select.select([p.stdout], [], [], 0.3)[0]: + z = p.stdout.readline() + if z.strip(): + try: return json.loads(z) + except Exception: return {"raw": z[:200]} + return None +def call(nr, name, args=None): + send({"jsonrpc":"2.0","id":nr,"method":"tools/call","params":{"name":name,"arguments":args or {}}}) + a = read() or {} + inhalt = ((a.get("result") or {}).get("content") or [{}]) + text = inhalt[0].get("text", "") + if not text and a.get("error"): text = "FEHLER: " + json.dumps(a["error"])[:200] + print(f"\n### {name} -> {text[:420]}") +send({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"p","version":"1"}}}) +read(15); send({"jsonrpc":"2.0","method":"notifications/initialized","params":{}}) +for nr, name in enumerate(["tables","korpus","close_all_tables","status"], start=2): + call(nr, name) +p.terminate() diff --git a/werkzeuge/mcp_probe.py b/werkzeuge/mcp_probe.py new file mode 100644 index 0000000..d63e563 --- /dev/null +++ b/werkzeuge/mcp_probe.py @@ -0,0 +1,44 @@ +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, "hand")): + _w = _os.path.dirname(_w) +WURZEL = _w +for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb", "mock"): + _q = _os.path.join(_w, _u) + if _os.path.isdir(_q) and _q not in _sys.path: + _sys.path.insert(0, _q) +import json, os, select, subprocess, sys, time +S = os.path.expanduser("~/Projects/pokerfreak-shell") +p = subprocess.Popen(["bash", os.path.join(S, "run.sh")], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1, cwd=S) +def send(o): + p.stdin.write(json.dumps(o) + "\n"); p.stdin.flush() +def read(sek=12): + ende = time.time() + sek + while time.time() < ende: + if select.select([p.stdout], [], [], 0.3)[0]: + zeile = p.stdout.readline() + if zeile.strip(): + try: return json.loads(zeile) + except Exception: return {"raw": zeile[:300]} + return None +send({"jsonrpc":"2.0","id":1,"method":"initialize","params":{ + "protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"probe","version":"1"}}}) +init = read(15) or {} +print("initialize:", json.dumps(init.get("result", init), ensure_ascii=False)[:260]) +send({"jsonrpc":"2.0","method":"notifications/initialized","params":{}}) +send({"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}) +r = read() or {} +tools = (r.get("result") or {}).get("tools", []) +print(f"\nWerkzeuge: {len(tools)}") +for t in tools: + print(" -", t["name"], "|", (t.get("description") or "").split("\n")[0][:66]) +send({"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"status","arguments":{}}}) +a = read(25) or {} +erg = (a.get("result") or {}) +inhalt = erg.get("content") or [] +print("\nstatus ->", json.dumps(inhalt, ensure_ascii=False)[:800] if inhalt else json.dumps(a, ensure_ascii=False)[:500]) +p.terminate() +time.sleep(0.4) +fehler = (p.stderr.read() or "")[:400] +if fehler.strip(): print("\nstderr:", fehler) diff --git a/werkzeuge/mcp_tisch.py b/werkzeuge/mcp_tisch.py new file mode 100644 index 0000000..6ad3f0a --- /dev/null +++ b/werkzeuge/mcp_tisch.py @@ -0,0 +1,35 @@ +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, "hand")): + _w = _os.path.dirname(_w) +WURZEL = _w +for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb", "mock"): + _q = _os.path.join(_w, _u) + if _os.path.isdir(_q) and _q not in _sys.path: + _sys.path.insert(0, _q) +import json, os, select, subprocess, sys, time +S = os.path.expanduser("~/Projects/pokerfreak-shell") +p = subprocess.Popen(["bash", os.path.join(S, "run.sh")], stdin=subprocess.PIPE, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True, bufsize=1, cwd=S) +def send(o): p.stdin.write(json.dumps(o) + "\n"); p.stdin.flush() +def read(sek=40): + ende = time.time() + sek + while time.time() < ende: + if select.select([p.stdout], [], [], 0.3)[0]: + z = p.stdout.readline() + if z.strip(): + try: return json.loads(z) + except Exception: return {"raw": z[:200]} + return None +def call(nr, name, args=None): + send({"jsonrpc":"2.0","id":nr,"method":"tools/call","params":{"name":name,"arguments":args or {}}}) + a = read() or {} + t = ((a.get("result") or {}).get("content") or [{}])[0].get("text", "") + if not t and a.get("error"): t = "FEHLER: " + json.dumps(a["error"])[:200] + print(f"\n### {name} -> {t[:500]}") +send({"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"p","version":"1"}}}) +read(15); send({"jsonrpc":"2.0","method":"notifications/initialized","params":{}}) +call(2, "open_practice_table") +time.sleep(6) +call(3, "status") +p.terminate() diff --git a/werkzeuge/probe.py b/werkzeuge/probe.py new file mode 100644 index 0000000..fdc60e0 --- /dev/null +++ b/werkzeuge/probe.py @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +"""Feuert bei deinem Zug je eine Testnachricht in die Client-Pipe. + +Eine einzige, dauerhafte Verbindung - damit eine Reaktion eindeutig von unserem +Schuss kommt und nicht von der Verbindung selbst. Ziel: messen, welche Nachricht +der Client wirklich verarbeitet. + + python3 probe.py [--minutes 40] +""" +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, "hand")): + _w = _os.path.dirname(_w) +WURZEL = _w +for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb", "mock"): + _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 re +import socket +import struct +import sys +import time + +LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") +PIPE = "/tmp/lobby-pipe" +BASE = os.path.dirname(os.path.abspath(__file__)) +OUT = os.path.join(BASE, "scratch", "probe-log.txt") + +EVENT = re.compile( + r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"([a-zA-Z_.]+)","RoomName":"((?:[^"\\]|\\.)*)"' +) +# Woran eine echte Reaktion erkennbar ist (nicht an der Verbindung selbst) +REACTION = ("token", "position", "settings", "user_action", "HUD", "hud", "action", + "extension", "IPC", "error", "Error") + + +def candidates(room, tag): + """Kandidaten mit unuebersehbarer Wirkung, aufsteigend nach Aufwand.""" + return [ + ("1 HUD-Fenster oeffnen", + {"EventName": "send_to_table", "RequestId": tag, + "Data": {"room_name": room, "event_type": "action", + "action": "open_hud_stats_window"}}), + ("2 Lobby in den Vordergrund", + {"EventName": "send_to_table", "RequestId": tag, + "Data": {"room_name": room, "event_type": "action", "action": "focus_lobby"}}), + ("3 Tischposition anfragen", + {"EventName": "send_to_table", "RequestId": tag, + "Data": {"room_name": room, "event_type": "action", "action": "table_layout", + "layout_request_type": "table_position_request"}}), + ("4 wie 2, aber an alle Tische", + {"EventName": "send_to_all_tables", "RequestId": tag, + "Data": {"event_type": "action", "action": "focus_lobby"}}), + ("5 als Bruxcke getarnt: receive_from_table", + {"EventName": "receive_from_table", "RequestId": tag, + "Data": {"room_name": room, "event_type": "action", "action": "focus_lobby"}}), + ] + + +def connect(): + sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) + sock.settimeout(0.2) + sock.connect(PIPE) + drain(sock, 1.2) + return sock + + +def drain(sock, seconds): + end = time.time() + seconds + while time.time() < end: + try: + if sock.recv(65536) == b"": + return + except socket.timeout: + time.sleep(0.05) + except Exception: + return + + +def send(sock, event): + payload = json.dumps(event).encode() + sock.sendall(struct.pack(">I", len(payload)) + payload) + + +def main(): + minutes = 40.0 + if "--minutes" in sys.argv: + minutes = float(sys.argv[sys.argv.index("--minutes") + 1]) + + out = open(OUT, "w") + def note(text): + out.write(text + "\n") + out.flush() + + try: + sock = connect() + except Exception as exc: + note(f"# keine Verbindung: {exc}") + return + note(f"# Probe gestartet {time.strftime('%H:%M:%S')}, eine Verbindung, {minutes} min " + f"(Verbindungsrauschen vor dem ersten Schuss ist geleert)") + + handle = open(LOG, errors="replace") + handle.seek(0, 2) + + shot = 0 + last_hand = None + end = time.time() + minutes * 60 + while time.time() < end: + line = handle.readline() + if not line: + time.sleep(0.15) + continue + hit = EVENT.search(line) + if not hit or hit.group(2) != "game.user_turn": + continue + try: + data = json.loads(json.loads('"' + hit.group(1) + '"')) + except Exception: + continue + if not {s: v for s, v in (data.get("userTurnOptions") or {}).items() if v}: + continue + hand = data.get("gameHandId") + if hand == last_hand: + continue + last_hand = hand + + room = hit.group(3) + label, event = candidates(room, f"zcode-{shot}")[shot % 5] + shot += 1 + note(f"\n=== Schuss {shot} | {time.strftime('%H:%M:%S')} | Hand {hand} | {room}") + note(f" Call {data.get('callAmount')} Pot-Raise {data.get('potRaiseValue')} " + f"Zeit {data.get('turnTime')}s") + note(f" Kandidat {label}") + note(f" gesendet: {json.dumps(event, ensure_ascii=False)[:170]}") + try: + drain(sock, 0.3) + started = time.time() + send(sock, event) + note(" gesendet OK") + except Exception as exc: + note(f" SENDEFEHLER: {exc} - neu verbinden") + try: + sock = connect() + except Exception: + pass + continue + + reactions = [] + while time.time() - started < 1.6: + try: + raw = sock.recv(65536) + except socket.timeout: + raw = b"" + except Exception: + break + if raw: + for m in re.finditer(rb'\{"trigger', raw): + pass + text = raw.decode("utf-8", "replace") + for part in re.findall(r'\{"EventName":"[^"]+"', text): + reactions.append(f"+{int((time.time()-started)*1000)}ms PIPE {part[14:60]}") + more = handle.readline() + if not more: + time.sleep(0.05) + continue + low = more.strip() + if any(w in low for w in REACTION): + reactions.append(f"+{int((time.time()-started)*1000)}ms LOG {low[:180]}") + note(f" Reaktionen: {len(reactions)}") + for r in reactions[:10]: + note(f" {r}") + + note(f"\n# Probe beendet {time.strftime('%H:%M:%S')}, {shot} Schuesse") + out.close() + + +if __name__ == "__main__": + main() diff --git a/werkzeuge/shot.py b/werkzeuge/shot.py new file mode 100644 index 0000000..15dca18 --- /dev/null +++ b/werkzeuge/shot.py @@ -0,0 +1,84 @@ +#!/usr/bin/env python3 +"""Macht Bilder vom Tisch - und markiert, bei welchem es dein Zug war. + + python3 shot.py [sekunden] +""" +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, "hand")): + _w = _os.path.dirname(_w) +WURZEL = _w +for _u in ("lesen", "entscheiden", "hand", "lobby", "korpus", "betrieb", "mock"): + _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 re +import subprocess +import sys +import time + +BASE = os.path.dirname(os.path.abspath(__file__)) +LOG = os.path.expanduser("~/Library/Logs/CoinPoker/main.log") +SHOTS = os.path.join(BASE, "scratch", "shots") +EVENT = re.compile(r'"BeanData":"((?:[^"\\]|\\.)*)","Cmd":"game\.user_turn"') +USER = re.compile(r"username=([A-Za-z0-9_]+)") + +os.makedirs(SHOTS, exist_ok=True) +duration = float(sys.argv[1]) if len(sys.argv) > 1 else 45.0 + + +def osa(script): + r = subprocess.run(["osascript", "-e", script], capture_output=True, text=True) + return (r.stdout or r.stderr).strip() + + +pid = subprocess.run(["pgrep", "-f", "CoinPoker Game"], capture_output=True, + text=True).stdout.split() +if not pid: + print("kein Tischfenster") + sys.exit(1) +proc = f'(first process whose unix id is {pid[0]})' +pos = osa(f'tell application "System Events" to tell {proc} to get position of window 1') +size = osa(f'tell application "System Events" to tell {proc} to get size of window 1') +x, y = [int(float(v)) for v in pos.replace(" ", "").split(",")[:2]] +w, h = [int(float(v)) for v in size.replace(" ", "").split(",")[:2]] +rect = f"{x},{y},{w},{h}" +print("Fenster:", rect) + +# Namen des Spielers einmal aus der ganzen Datei holen +_whole = open(LOG, errors="replace").read() +_names = re.findall(r"username=([A-Za-z0-9_]+)", _whole) +me = _names[-1] if _names else None +print("Spieler:", me, "| letzte eigene Züge:", len(_whole) - _whole.rfind('game.user_turn') if 'game.user_turn' in _whole else 0) +log = open(LOG, errors="replace") +log.seek(0, 2) +last_own = 0.0 +end = time.time() + duration +index = 0 +while time.time() < end: + index += 1 + out = os.path.join(SHOTS, f"s{index:02d}.png") + subprocess.run(["screencapture", "-x", f"-R{rect}", out], capture_output=True) + while True: + line = log.readline() + if not line: + break + who = USER.search(line) + if who: + me = who.group(1) + hit = EVENT.search(line) + if not hit: + continue + try: + d = json.loads(json.loads('"' + hit.group(1) + '"')) + except Exception: + continue + if {s: v for s, v in (d.get("userTurnOptions") or {}).items() if v}: + me = d.get("whoseTurn") or me + if me and d.get("whoseTurn") == me: + last_own = time.time() + tag = "DEIN ZUG" if time.time() - last_own < 8 else "" + print(f" {out} {tag}") + time.sleep(1.2)