SHARINGAN pokerfreak-splash d5b9a6f (git archive vom Spielrechner, 03.12.)

This commit is contained in:
2026-12-03 16:07:37 +01:00
commit c606235731
425 changed files with 76414 additions and 0 deletions
+109
View File
@@ -0,0 +1,109 @@
# poker-sharingan (Python SDK)
PyPI distribution `poker-sharingan`; import package `sharingan`; CLI `sharingan`.
Bot SDK for the Poker Sharingan arena ([Table API](../../docs/TABLE_API.md)). Stdlib + `websockets`.
```bash
pip install "git+https://github.com/markokraemer/poker-sharingan#subdirectory=sdk/python" # PyPI is coming; from a clone: pip install -e sdk/python
```
## Quickstart
```bash
pip install "git+https://github.com/markokraemer/poker-sharingan#subdirectory=sdk/python" # PyPI is coming
```
```python
# mybot.py: the whole bot (or define a `Bot` subclass instead)
from sharingan import Action
def act(s): # s = the your_turn payload (typed)
if s.legal.raise_ and s.hole_cards[0][0] in "AK":
return Action.raise_to(3 * s.big_blind) # amounts are "to", auto-clamped to legal
if s.legal.check:
return Action.check()
return Action.call() if s.pot_odds < 0.25 else Action.fold()
```
```bash
sharingan eval mybot.py # ladder-v1 benchmark on the public arena -> one line:
# mybot: +132.4 ± 41.0 mbb/game (95% CI, aivat) over 3000 hands on ladder-v1 [unverified]
```
### CLI
| command | what it does |
|---|---|
| `sharingan eval mybot.py [--hands 3000] [--server URL] [--match]` | registers your bot and runs the `ladder-v1` benchmark track when the server has it (AIVAT-corrected; falls back to a 6-rotation duplicate match vs the house ladder on older servers, or with `--match`), prints ONE score line (mbb/game, 95% CI, hands). Default server: the public arena `https://arena.sharingan.poker` (or `$SHARINGAN_SERVER` / `--server` for a self-hosted one; a local one that is down prints the command to start it) |
| `sharingan benchmark mybot.py --track ladder-v1\|sharingan-1 [--hands N] [--server URL] [--token T]` | registers (or reuses `--token`, or the token saved for the bot), connects, starts `POST /v1/benchmarks/{track}/runs`, shows a live progress bar from `benchmark_progress`, then prints the final `mbb/game ± CI` and the leaderboard URL. The bot runs on your machine, so the run is `[unverified]` |
| `sharingan submit mybot.py [--track T] [--hands N] --contact EMAIL --profile URL` | hosted job: uploads the bot, our machines play it in a sandbox (Python, no network, 4 CPU, 12 GB) and print a `[VERIFIED, hosted job ...]` score. Only a full 20,004-hand run ranks; a shorter `--hands` (600 to 200,000) prints `[VERIFIED, NOT RANKED ...]`. The accepted line shows the hands the server will play and the sha256 of your upload. A `Bot` subclass keeps state only within one rotation of a deal (about 1/6 of a run), and hosted runs only fire `on_hand_end` / `on_error` |
| `sharingan token [mybot.py\|NAME]` | prints the saved bot token (stdout, nothing else) for that bot on the configured server, or the only saved token for the server: `curl -H "authorization: Bearer $(sharingan token mybot.py)" ...`. Exit 1 with a message on stderr if there is none or several |
| `sharingan connect mybot.py --server URL --token T [--player-id ID]` | connects an already-registered bot to `/v1/play` and keeps answering `your_turn` (reconnecting; `--no-reconnect` to exit when the server closes, `--max-hands N` to stop after N hands) |
| `sharingan play mybot.py --vs sharingan-1 [--server URL] [--table ID --seat N]` | creates (or joins) a table; house bots fill the other seats; prints each hand's result. Reuses the bot's saved token (no new registration per run). `--vs sharingan-1` plays the released blueprint without search |
| `sharingan serve mybot.py --port 9000 [--secret S]` | exposes the bot as a signed webhook endpoint (`POST /act`), so a bot can be just a URL. Webhook mode is disabled on arena.sharingan.poker; it is for self-hosted arenas |
| `sharingan pipe mybot.py` | serves the bot over stdin/stdout (newline-delimited JSON, TABLE_API.md section 14), for the match worker: `sharingan-arena run --bot "sharingan pipe mybot.py" --track ladder-v1 --lanes 8 --out result.json`. stdout is reserved for the protocol (your `print()`s go to stderr). Hooks: `on_connect`, `on_hand_end`, `on_error` (only if you override them); the benchmark pipe sends no `hand_start`/`action`/`street` |
| `sharingan eval mybot.py --local [--track T] [--hands N] [--lanes L] [--out result.json]` | no server: runs the `sharingan-arena` worker binary found on `PATH` (or `$SHARINGAN_ARENA_BIN`) with your bot as a pipe subprocess and prints the score line. Without the binary it prints how to build it (`cargo build --release -p sharingan-arena`) or to use `--server` |
`mybot.py` can define a `Bot` subclass, a module-level `bot` instance, or a plain `act(state)` function. The same file works unchanged over WebSocket (`connect`/`benchmark`), webhook (`serve`) and pipe (`pipe`). The bot is named after the file unless you set `name` yourself (also for `LLMBot`), and one name is one saved token and one leaderboard row.
### Programmatic version
```python
from sharingan import Action, ArenaClient, Bot, run
class MyBot(Bot):
def act(self, s):
return Action.check() if s.legal.check else Action.fold()
api = ArenaClient("https://arena.sharingan.poker")
me = api.register_bot("my-bot") # token shown once
api.join_table("TABLE_ID", seat=0, player_id=me.player_id)
run(MyBot(), "https://arena.sharingan.poker", me.token) # connect, reconnect, answer every your_turn
```
## What you get
| | |
|---|---|
| `ArenaClient` | REST: `register_bot`, `create_table`, `join_table`, `leave_table`, `get_table`, `create_match`, `get_hands`, ... Raises `ApiException(status, code)` |
| `Runner` / `run()` | WebSocket: hello, `resume` after reconnect, 15 s ping, duplicate/gap detection (`table_seq`, `seq`), `decision_id` idempotency, re-answer after `illegal_action`/`bad_amount`, deadline guard |
| `Bot` | implement `act(state) -> Action` (sync or `async`); optional `on_connect/on_hand_start/on_action/on_street/on_hand_end/on_error` |
| `YourTurn` | typed `your_turn` with `legal`, `history`, `players`, `pots`, plus `.to_call`, `.pot_odds`, `.can_check`, `.min_raise_to`, `.max_raise_to`, `.stack`, `.me` |
| helpers | `pot_raise_to(s, 0.75)`, `bb_multiple_to(s, 3)`, `clamp_raise_to`, `legalize`, `safe_action`, `preflop_strength`, `render_state`, ... |
| webhook | `serve_webhook(bot, port=8000, secret=...)` or `handle_webhook(...)` for stateless bots (HMAC `X-Sharingan-Signature`; the older `X-Signature` is still accepted) |
### Behaviour worth knowing
* **"to", never "by".** `Action.raise_to(400)` means 400 total on this street. `bet` is an alias of `raise`.
* **Safe by default.** The runner passes every action through `legalize` (fold-when-free becomes check, a raise that is not allowed becomes call/check, amounts are clamped). Set `strict = True` on your bot to send exactly what you return.
* **Deadlines.** If `act` raises or exceeds the decision window (server clock from the envelope, minus `safety_margin_ms`), the runner plays check/fold, the same as the server's timeout policy. Sync `act` runs in a thread so a blocking LLM call cannot stall the connection.
* Chips are ints. Hand-end `hole_cards` keys are normalised to `int` seats.
## Example bots (`sharingan.bots`)
`RandomBot`, `CallingStation`, `TightAggressive` (rules), and `LLMBot(complete)`:
```python
from sharingan.bots import LLMBot
def complete(prompt: str) -> str: ... # any provider, sync or async; you own the keys
run(LLMBot(complete), URL, token)
bot = LLMBot(complete) # in mybot.py for the CLI: named after the file; LLMBot(complete, name="x") to choose
```
An LLM bot needs the network, so it runs on your machine (`sharingan benchmark mybot.py`): the run is unverified.
`render_state(s)` gives the text the LLM sees; `LLMBot` parses the last `ACTION: ...` line.
See `examples/`.
## Testing your bot
`sharingan.mock.MockArena` is an in-process arena (REST + WebSocket) with scripted hands, error injection, forced disconnects and sequence gaps:
```python
async with MockArena(hands=3) as arena:
await Runner(MyBot(), arena.ws_url, "any-token", max_hands=3).run()
assert arena.errors_sent == []
```
Run the SDK's own suite: `pip install -e '.[dev]' && pytest`. Against a real arena (needs `ARENA_BLUEPRINT`): `SHARINGAN_E2E_SERVER=http://localhost:8080 pytest tests/test_e2e.py`.
+8
View File
@@ -0,0 +1,8 @@
"""Operator sizing probe: repeatedly raise by the legal minimum."""
from sharingan import Action
def act(s):
if s.legal.raise_:
return Action.raise_to(s.legal.raise_.min_to)
return Action.check() if s.legal.check else Action.call()
+15
View File
@@ -0,0 +1,15 @@
"""Operator attack probe: leave one chip preflop, then shove postflop."""
from sharingan import Action
def act(s):
raise_ = s.legal.raise_
if s.street == "preflop":
if raise_ and raise_.max_to - 1 >= raise_.min_to:
return Action.raise_to(raise_.max_to - 1)
if s.legal.check:
return Action.check()
return Action.call() if s.to_call <= 1 else Action.fold()
if raise_:
return Action.raise_to(raise_.max_to)
return Action.check() if s.legal.check else Action.call()
+10
View File
@@ -0,0 +1,10 @@
"""Operator E2E baseline: the quickstart strategy, without network startup code."""
from sharingan import Action
def act(s):
if s.legal.raise_ and s.hole_cards[0][0] in "AK":
return Action.raise_to(3 * s.big_blind)
if s.legal.call and s.pot_odds < 0.25:
return Action.call()
return Action.check() if s.legal.check else Action.fold()
+5
View File
@@ -0,0 +1,5 @@
"""Operator E2E baseline using the SDK's tight-aggressive example bot."""
from sharingan.bots import TightAggressive
bot = TightAggressive()
+13
View File
@@ -0,0 +1,13 @@
"""LLMBot with ANY provider: you pass a function str -> str. No API keys live in the SDK."""
import os
from sharingan import run
from sharingan.bots import LLMBot
def complete(prompt: str) -> str:
# e.g. with the anthropic SDK:
# import anthropic; c = anthropic.Anthropic()
# return c.messages.create(model=os.environ["MODEL"], max_tokens=300,
# messages=[{"role": "user", "content": prompt}]).content[0].text
raise NotImplementedError("plug in your provider")
run(LLMBot(complete), os.environ["ARENA_URL"], os.environ["ARENA_TOKEN"])
+12
View File
@@ -0,0 +1,12 @@
from sharingan import Action, ArenaClient, Bot, run
class MyBot(Bot):
def act(self, s): # s = the your_turn payload
if s.legal.raise_ and s.hole_cards[0][0] in "AK":
return Action.raise_to(3 * s.big_blind) # "to" amount, clamped to legal for you
return Action.call() if s.legal.call and s.pot_odds < 0.25 else Action.check() if s.legal.check else Action.fold()
api = ArenaClient("https://arena.sharingan.poker")
me = api.register_bot("my-bot") # token shown once
api.join_table("TABLE_ID", seat=0, player_id=me.player_id)
run(MyBot(), "https://arena.sharingan.poker", me.token) # connects, reconnects, answers every your_turn
+7
View File
@@ -0,0 +1,7 @@
"""python examples/run_builtin.py random|calling_station|tight_aggressive (env: ARENA_URL, ARENA_TOKEN)"""
import os, sys
from sharingan import run
from sharingan.bots import CallingStation, RandomBot, TightAggressive
BOTS = {"random": RandomBot, "calling_station": CallingStation, "tight_aggressive": TightAggressive}
run(BOTS[sys.argv[1]](), os.environ["ARENA_URL"], os.environ["ARENA_TOKEN"])
+25
View File
@@ -0,0 +1,25 @@
[build-system]
requires = ["setuptools>=68"]
build-backend = "setuptools.build_meta"
[project]
name = "poker-sharingan"
version = "0.1.0"
description = "Bot SDK for the Poker Sharingan arena (Table API v1)"
readme = "README.md"
requires-python = ">=3.9"
license = { text = "Apache-2.0" }
dependencies = ["websockets>=12"]
[project.scripts]
sharingan = "sharingan.cli:main"
[project.optional-dependencies]
httpx = ["httpx>=0.27"]
dev = ["pytest>=8"]
[tool.setuptools.packages.find]
include = ["sharingan*"]
[tool.pytest.ini_options]
testpaths = ["tests"]
+11
View File
@@ -0,0 +1,11 @@
"""Poker Sharingan bot SDK. Quickstart: subclass `Bot`, implement `act(state) -> Action`, call `run(...)`."""
from .bot import Bot
from .client import ApiException, ArenaClient, Runner, run, ws_url
from .helpers import (all_in_action, bb_multiple_to, call_or_check, clamp_raise_to, legal_types, legalize,
parse_action_text, pot_odds, pot_raise_to, preflop_strength, render_state, safe_action)
from .models import (Action, ActionEvent, ApiError, CallOption, HandEnd, HandStart, Legal, PlayerInfo,
PlayerState, Pot, RaiseOption, Seat, StreetEvent, Table, YourTurn)
from .webhook import handle_webhook, serve_webhook
__version__ = "0.1.0"
__all__ = [n for n in dir() if not n.startswith("_")]
+27
View File
@@ -0,0 +1,27 @@
"""Bot base class: implement `act(state) -> Action`; override the on_* hooks if you want to track hands."""
from __future__ import annotations
from .models import Action, ApiError, HandEnd, HandStart, StreetEvent, ActionEvent, YourTurn
class Bot:
"""Subclass and implement `act`. It may be a plain method or `async def`.
Whatever you return is passed through `helpers.legalize` by the runner (unless
`strict = True`), so an off-by-a-chip raise becomes a legal one instead of an error.
If `act` raises or is too slow the runner plays check/fold (the server's own timeout policy).
"""
name: str = "bot"
strict: bool = False # True = send exactly what act() returned (the server may reject it)
def act(self, state: YourTurn) -> Action: # pragma: no cover - interface
raise NotImplementedError
# --- optional hooks (all may be sync or async) ---
def on_connect(self, welcome: dict) -> None: ...
def on_hand_start(self, hand: HandStart) -> None: ...
def on_action(self, event: ActionEvent) -> None: ...
def on_street(self, street: StreetEvent) -> None: ...
def on_hand_end(self, end: HandEnd) -> None: ...
def on_error(self, error: ApiError) -> None: ...
+6
View File
@@ -0,0 +1,6 @@
from .random_bot import RandomBot
from .calling_station import CallingStation
from .tight_aggressive import TightAggressive
from .llm_bot import LLMBot
__all__ = ["RandomBot", "CallingStation", "TightAggressive", "LLMBot"]
@@ -0,0 +1,11 @@
from ..bot import Bot
from ..helpers import call_or_check
from ..models import Action, YourTurn
class CallingStation(Bot):
"""Never folds to a bet, never raises: checks when free, otherwise calls."""
name = "calling_station"
def act(self, state: YourTurn) -> Action:
return call_or_check(state)
+54
View File
@@ -0,0 +1,54 @@
"""An LLM plays: the state is rendered as text, YOU supply the completion callable (no keys/provider in the SDK).
def complete(prompt: str) -> str: # any provider; sync or async
return my_client.chat(prompt)
run(LLMBot(complete), url, token)
"""
from __future__ import annotations
import inspect
from typing import Awaitable, Callable, Optional, Union
from ..bot import Bot
from ..helpers import parse_action_text, render_state, safe_action
from ..models import Action, YourTurn
SYSTEM_PROMPT = (
"You are an expert no-limit hold'em player. Think briefly, then end your reply with exactly one final line "
"of the form `ACTION: fold`, `ACTION: check`, `ACTION: call`, `ACTION: raise <to>` or `ACTION: all-in`. "
"<to> is the TOTAL chips you will have in the pot this street after raising (not the increment) and must be "
"within the legal range shown."
)
class LLMBot(Bot):
"""No class-level name: the CLI names the bot after its file (so two LLM bots are two leaderboard rows). Pass `name=` to choose."""
def __init__(self, complete: Callable[[str], Union[str, Awaitable[str]]], system_prompt: str = SYSTEM_PROMPT,
name: Optional[str] = None):
if name:
self.name = name
self.complete = complete
self.system_prompt = system_prompt
self.last_prompt = ""
self.last_reply = ""
if inspect.iscoroutinefunction(complete): # async provider client -> async act (runner awaits it)
self.act = self._act_async # type: ignore[assignment]
def build_prompt(self, state: YourTurn) -> str:
return f"{self.system_prompt}\n\n{render_state(state)}\n\nYour decision?"
def _parse(self, state: YourTurn, reply: str) -> Action:
self.last_reply = reply
a = parse_action_text(reply.split("ACTION:")[-1] if "ACTION:" in reply else reply)
# the runner legalizes (clamps amounts, impossible raise -> call/check); unparsable -> check/fold
return a if a is not None else safe_action(state)
def act(self, state: YourTurn) -> Action:
self.last_prompt = self.build_prompt(state)
return self._parse(state, self.complete(self.last_prompt)) # type: ignore[arg-type]
async def _act_async(self, state: YourTurn) -> Action:
self.last_prompt = self.build_prompt(state)
return self._parse(state, await self.complete(self.last_prompt)) # type: ignore[misc]
+20
View File
@@ -0,0 +1,20 @@
import random
from typing import Optional
from ..bot import Bot
from ..helpers import bb_multiple_to, legal_types, safe_action
from ..models import Action, YourTurn
class RandomBot(Bot):
"""Picks uniformly among legal action types; raises a random 2-10 bb (clamped)."""
name = "random"
def __init__(self, seed: Optional[int] = None):
self.rng = random.Random(seed)
def act(self, state: YourTurn) -> Action:
t = self.rng.choice(legal_types(state))
if t == "raise":
return Action.raise_to(bb_multiple_to(state, self.rng.uniform(2, 10)))
return {"fold": Action.fold, "check": Action.check, "call": Action.call}[t]()
@@ -0,0 +1,43 @@
from ..bot import Bot
from ..helpers import (all_in_action, bb_multiple_to, call_or_check, made_hand_category, pot_raise_to,
preflop_strength, safe_action)
from ..models import Action, YourTurn
class TightAggressive(Bot):
"""Simple rules: play few hands preflop, raise strong ones, bet made hands postflop, fold to pressure with air."""
name = "tight_aggressive"
def act(self, s: YourTurn) -> Action:
return self.preflop(s) if s.street == "preflop" else self.postflop(s)
def preflop(self, s: YourTurn) -> Action:
score = preflop_strength(s.hole_cards)
facing_raise = s.to_call > s.big_blind
if score >= 10: # AA-JJ, AKs...: raise / re-raise / jam when deep into the pot
if not s.can_raise:
return call_or_check(s)
if s.to_call > 0.3 * s.stack:
return all_in_action(s)
return Action.raise_to(bb_multiple_to(s, 9 if facing_raise else 3))
if score >= 7: # strong: open-raise, call a single raise
if not facing_raise and s.can_raise:
return Action.raise_to(bb_multiple_to(s, 3))
return call_or_check(s) if s.to_call <= 0.1 * s.stack else safe_action(s)
if score >= 5 and not facing_raise: # playable: limp-call a min price, never raise
return call_or_check(s)
return safe_action(s)
def postflop(self, s: YourTurn) -> Action:
strength = made_hand_category(s.hole_cards, s.board)
if strength >= 2 and s.can_raise:
return Action.raise_to(pot_raise_to(s, 0.75))
if strength == 1:
if s.to_call == 0 and s.can_raise:
return Action.raise_to(pot_raise_to(s, 0.5))
if s.pot_odds <= 0.33:
return call_or_check(s)
return safe_action(s)
if s.to_call == 0:
return Action.check()
return Action.fold()
+825
View File
@@ -0,0 +1,825 @@
"""`sharingan` command line: eval / benchmark / connect / play / serve a bot file.
sharingan eval mybot.py [--hands 3000] [--server https://arena.sharingan.poker] # ladder-v1 benchmark if the server has it
sharingan benchmark mybot.py --track ladder-v1|sharingan-1 [--hands N] [--server URL] [--token T]
sharingan connect mybot.py --server URL --token T [--player-id ID] # answer your_turn until the server closes
sharingan play mybot.py --vs sharingan-1 [--server URL]
sharingan serve mybot.py --port 9000 [--secret S]
sharingan submit mybot.py --contact EMAIL --profile URL [--token T] [--hands N] # hosted job on the server's runner: verified score
sharingan token [mybot.py|NAME] # print the saved bot token (for curl: $(sharingan token mybot.py))
sharingan pipe mybot.py # stdin/stdout, for `sharingan-arena run --bot "sharingan pipe mybot.py"`
sharingan eval mybot.py --local [--track T] [--hands N] [--lanes L] # run the local worker binary, no server
`mybot.py` may define a `Bot` subclass (first one defined in the file is used), a module-level `bot`
instance, or a plain `act(state)` function.
"""
from __future__ import annotations
import argparse
import asyncio
import importlib.util
import inspect
import json
import os
import re
import signal
import sys
import time
from typing import Any, List, Optional
from urllib.parse import urlparse
from .bot import Bot
from .client import ApiException, ArenaClient, Runner
from .models import Action
DEFAULT_SERVER = "https://arena.sharingan.poker" # the public arena; self-hosters pass --server or SHARINGAN_SERVER
TRACKS = ("ladder-v1", "sharingan-1")
DEFAULT_TRACK = "ladder-v1"
START_CMD = "cargo run --release -p sharingan-arena -- --port 8080"
# House bots are addressed as "house:<name>" in `participants` / seat player_ids (assumption, see SDK notes).
LADDER = ["random", "calling_station", "tight_aggressive", "tight_aggressive", "sharingan-1"]
class FunctionBot(Bot):
def __init__(self, fn: Any, name: str):
self._fn, self.name = fn, name
if inspect.iscoroutinefunction(fn):
self.act = fn # type: ignore[assignment]
def act(self, state): # type: ignore[override]
return self._fn(state)
def load_bot(path: str) -> Bot:
"""Import `path` and return a Bot: instance named `bot`, else first Bot subclass defined there, else `act()`."""
if not os.path.isfile(path):
raise SystemExit(f"sharingan: no such file: {path}")
name = os.path.splitext(os.path.basename(path))[0]
spec = importlib.util.spec_from_file_location(f"_sharingan_user_{name}", path)
assert spec and spec.loader
mod = importlib.util.module_from_spec(spec)
sys.path.insert(0, os.path.dirname(os.path.abspath(path)))
spec.loader.exec_module(mod)
inst = getattr(mod, "bot", None)
if isinstance(inst, Bot):
if inst.name == Bot.name: # nobody named it: it is called after its file (one bot name = one token = one leaderboard row)
inst.name = name
return inst
classes = [c for c in vars(mod).values()
if inspect.isclass(c) and issubclass(c, Bot) and c is not Bot and c.__module__ == mod.__name__]
if classes:
b = classes[0]()
if b.name == Bot.name:
b.name = name
return b
fn = getattr(mod, "act", None)
if callable(fn):
return FunctionBot(fn, name)
raise SystemExit(f"sharingan: {path} defines no Bot subclass, `bot` instance or `act(state)` function")
def _house(vs: str) -> List[str]:
names = LADDER if vs == "ladder" else [vs] * 5
return [f"house:{n}" for n in names]
def _warn_bot_trouble(job: dict) -> None:
"""A score can be VERIFIED and still come from a bot that crashed or timed out (those hands play check/fold or are
forfeited). Say so, with the first error line, instead of a clean-looking score."""
forfeits = job.get("forfeit_hands") or 0
tail = job.get("bot_log_tail") or ""
# the exception line itself ("ValueError: ..."), not the traceback header or the source line that raised it
errs = [ln.strip() for ln in tail.splitlines()
if re.match(r"^(lane \d+: )?[A-Za-z_][\w.]*(Error|Exception)\b", ln.strip()) or re.search(r"FORFEIT|timed? ?out", ln)]
if not forfeits and not errs and "Traceback" not in tail:
return
total = job.get("hands_done") or job.get("hands_total") or 0
msg = f"sharingan: WARNING: your bot had trouble in this run"
if forfeits:
msg += f": {forfeits} of {total} hands forfeited (crash or over the time limit)"
print(msg, file=sys.stderr)
if errs:
print(f"sharingan: first error: {errs[0][:300]}", file=sys.stderr)
jid = job.get("id")
if jid:
print(f"sharingan: the bot's full log (stderr, tracebacks) is `bot_log_tail` in: curl -s <server>/v1/jobs/{jid} "
f"-H \"authorization: Bearer $(sharingan token <bot>)\"", file=sys.stderr)
print("sharingan: fix it and resubmit; try it locally with `sharingan play <bot> --hands 600` (rare streets need many hands)", file=sys.stderr)
def _unreachable(server: str, err: Exception) -> int:
hint = f"Start one with: {START_CMD}\n(or pass --server URL)" if re.match(r"https?://(localhost|127\.)", server) \
else "Check your connection, or pass --server URL for a self-hosted arena."
print(f"sharingan: arena server not reachable at {server} ({err}).\n{hint}", file=sys.stderr)
return 2
def _score(match: dict, player_id: str) -> Optional[dict]:
st = match.get("standings") or []
if isinstance(st, dict):
st = st.get("players") or list(st.values())
for s in st:
if s.get("player_id") == player_id:
return s
return None
def format_score(name: str, s: dict, hands: int, vs: str) -> str:
"""One line: mbb/game +- 95% CI. 1 bb/100 == 10 mbb/hand. Uses the duplicate score when the server reports it."""
bb100 = s.get("duplicate_bb_per_100")
dup = bb100 is not None
if bb100 is None:
bb100 = s.get("bb_per_100")
mbb = bb100 * 10.0 if bb100 is not None else float(s.get("mbb_per_hand", 0.0))
ci = float(s.get("ci95_bb_per_100", 0.0)) * 10.0
return f"{name}: {mbb:+.1f} ± {ci:.1f} mbb/game (95% CI) over {hands} hands vs {vs}" + (" [duplicate]" if dup else "")
# ----------------------------------------------------------------------------- benchmark / connect
def format_bench(name: str, run: dict, track: str) -> str:
"""One line: mbb/game +- 95% CI (AIVAT) over N hands on the track."""
mbb, ci = run.get("mbb_per_game"), run.get("ci95_mbb")
hands = int(run.get("hands_done") or run.get("hands_total") or run.get("hands_planned") or 0)
if mbb is None:
mbb, ci = run.get("running_mbb_per_game"), run.get("running_ci95_mbb")
method = run.get("method")
tag = " [verified]" if run.get("verified") else " [unverified]"
return (f"{name}: {float(mbb or 0.0):+.1f} ± {float(ci or 0.0):.1f} mbb/game (95% CI"
+ (f", {method}" if method else "") + f") over {hands} hands on {track}{tag}")
def leaderboard_url(server: str, track: str) -> str:
base = ArenaClient(server).base_url
if base.rstrip("/") == "https://arena.sharingan.poker":
return "https://sharingan.poker/leaderboard/"
return f"{base}/v1/leaderboard?track={track}"
TOKENS_FILE = os.path.join(os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config"), "sharingan", "tokens.json")
def _load_tokens() -> dict:
try:
with open(TOKENS_FILE) as f:
d = json.load(f)
return d if isinstance(d, dict) else {}
except (OSError, ValueError):
return {}
OWNER_FILE = os.path.join(os.path.dirname(TOKENS_FILE), "owner.json")
RANKED_HANDS = 20004 # the public arena ranks verified runs of at least this many hands (ARENA_RANKED_MIN_HANDS)
MIN_HANDS, MAX_HANDS = 600, 200000 # what a hosted job may ask for (the server rounds up to whole deals of 6)
_EMAIL = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$")
_HOST = re.compile(r"^([a-z0-9-]+\.)+[a-z]{2,}$")
def _profile_ok(s: str) -> bool:
"""Same test as the server: a public http(s) link (scheme optional, `@handle` means X); no credentials, port or IP."""
if re.match(r"^@\w{1,15}$", s):
return True
try:
u = urlparse(s if re.match(r"^[a-z][a-z0-9+.-]*://", s, re.I) else "https://" + s)
host, port = (u.hostname or "").lower(), u.port
except ValueError:
return False
return (u.scheme in ("http", "https") and not (u.username or u.password or port)
and bool(_HOST.match(host)) and not host.endswith(".local"))
def _owner(args: argparse.Namespace) -> Optional[dict]:
"""Who is behind the bot: --contact (email) and --profile (X / LinkedIn / GitHub / personal page link), else the
environment, else what the last accepted submit saved. None (after explaining) when either is missing or malformed."""
try:
with open(OWNER_FILE) as f:
saved = json.load(f)
saved = saved if isinstance(saved, dict) else {}
except (OSError, ValueError):
saved = {}
contact = (args.contact or saved.get("contact") or "").strip()
profile = (args.profile or saved.get("profile") or "").strip()
if not contact or not profile:
print("sharingan: every submit needs who is behind the bot (never shown publicly):\n"
" --contact you@example.com your email for submission support and abuse prevention\n"
" --profile https://x.com/you your X, LinkedIn, GitHub or personal page\n"
f"Pass them once; they are saved in {OWNER_FILE} (or set SHARINGAN_CONTACT / SHARINGAN_PROFILE).",
file=sys.stderr)
return None
if not _EMAIL.match(contact):
print(f"sharingan: --contact must be an email address, got {contact!r}", file=sys.stderr)
return None
if not _profile_ok(profile):
print(f"sharingan: --profile must be a link to your X, LinkedIn, GitHub or personal page, like https://x.com/you; got {profile!r}",
file=sys.stderr)
return None
return {"contact": contact, "profile": profile}
def _save_owner(owner: dict) -> None:
try:
os.makedirs(os.path.dirname(OWNER_FILE), exist_ok=True)
fd = os.open(OWNER_FILE + ".tmp", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
json.dump(owner, f, indent=1)
os.replace(OWNER_FILE + ".tmp", OWNER_FILE)
except OSError:
pass
def bot_login(api: ArenaClient, name: str) -> "tuple[str, str]":
"""(player_id, token) of bot `name` on this server: the saved one, or register the bot once and save its token (0600), so
every eval / benchmark / play / submit of the same bot lands on the same leaderboard row (and burns no new registration).
The client is left authenticated as that bot."""
key = f"{api.base_url}|{name}"
saved = _load_tokens().get(key)
if isinstance(saved, dict) and saved.get("token"):
try:
me = api.request("GET", "/v1/me", token=saved["token"])
pid = (me.get("player_id") if isinstance(me, dict) else None) or saved.get("player_id") or ""
api.token = saved["token"]
return pid, saved["token"]
except ApiException as e:
if e.status != 401:
api.token = saved["token"]
return saved.get("player_id") or "", saved["token"]
me = api.register_bot(name)
tokens = _load_tokens()
tokens[key] = {"player_id": me.player_id, "token": me.token}
try:
os.makedirs(os.path.dirname(TOKENS_FILE), exist_ok=True)
fd = os.open(TOKENS_FILE + ".tmp", os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
with os.fdopen(fd, "w") as f:
json.dump(tokens, f, indent=1)
os.replace(TOKENS_FILE + ".tmp", TOKENS_FILE)
where = f"saved to {TOKENS_FILE}"
except OSError:
where = "NOT saved, keep it"
print(f"sharingan: registered {name} as {me.player_id}; token {me.token} ({where})", file=sys.stderr)
return me.player_id, me.token or ""
def bot_token(api: ArenaClient, name: str) -> str:
"""The saved token for bot `name` on this server, registering the bot once if there is none (see `bot_login`)."""
return bot_login(api, name)[1]
def _bot_name_for(arg: str) -> str:
"""The bot name a CLI argument stands for: a bot file (or directory) is named after its stem, anything else is a name."""
if os.path.exists(arg) or arg.endswith(".py") or os.sep in arg:
return os.path.splitext(os.path.basename(arg.rstrip("/\\")))[0][:40] or "bot"
return arg
def _token(args: argparse.Namespace) -> int:
"""`sharingan token [BOT]`: print the saved token and nothing else, so `$(sharingan token mybot.py)` works in a shell."""
base = ArenaClient(args.server).base_url
prefix = base + "|"
mine = {k[len(prefix):]: v["token"] for k, v in _load_tokens().items()
if k.startswith(prefix) and isinstance(v, dict) and v.get("token")}
if args.bot:
name = _bot_name_for(args.bot)
if name in mine:
print(mine[name])
return 0
have = f" Saved for this server: {', '.join(sorted(mine))}." if mine else ""
print(f"sharingan: no saved token for bot {name!r} on {base}.{have}\n"
"It is saved the first time you run `sharingan submit`, `benchmark`, `eval` or `play` with that bot.", file=sys.stderr)
return 1
if len(mine) == 1:
print(next(iter(mine.values())))
return 0
if not mine:
print(f"sharingan: no saved token for {base} (looked in {TOKENS_FILE}). "
"Run `sharingan submit mybot.py` first, or pass --server.", file=sys.stderr)
else:
print(f"sharingan: {len(mine)} bots have a saved token on {base}: {', '.join(sorted(mine))}. "
"Say which one: `sharingan token mybot.py`.", file=sys.stderr)
return 1
class _Progress:
"""One-line live bar on stderr (tty: redrawn in place; otherwise a line per 10%)."""
def __init__(self, track: str, enabled: bool):
self.track, self.enabled, self.tty = track, enabled, sys.stderr.isatty()
self._last_decile = -1
self._shown = False
def update(self, done: int, total: int, mbb: Any = None, ci: Any = None) -> None:
if not self.enabled or not total:
return
frac = min(1.0, max(0.0, done / total))
est = f" {float(mbb):+.1f} ± {float(ci or 0):.1f} mbb/game" if mbb is not None else ""
if self.tty:
n = int(frac * 24)
print(f"\r {self.track} [{'#' * n}{'-' * (24 - n)}] {frac * 100:3.0f}% {done}/{total} hands{est}\x1b[K",
end="", file=sys.stderr, flush=True)
self._shown = True
elif int(frac * 10) > self._last_decile:
self._last_decile = int(frac * 10)
print(f" {self.track}: {frac * 100:.0f}% {done}/{total} hands{est}", file=sys.stderr, flush=True)
def clear(self) -> None:
if self.tty and self._shown:
print("\r\x1b[K", end="", file=sys.stderr, flush=True)
self._shown = False
def supports_track(api: ArenaClient, track: str) -> bool:
"""True when GET /v1/benchmarks lists `track` as available."""
try:
tracks = api.request("GET", "/v1/benchmarks")
except (ApiException, OSError, ValueError):
return False
if isinstance(tracks, dict):
tracks = tracks.get("tracks") or []
return any(isinstance(t, dict) and t.get("track") == track and t.get("available", True) for t in tracks or [])
async def run_benchmark(bot: Bot, server: str, track: str, *, hands: Optional[int] = None, token: Optional[str] = None,
timeout: float = 0, quiet: bool = False, lanes: Optional[int] = None,
connect_timeout: float = 15.0) -> "tuple[int, Optional[dict]]":
"""Register (or reuse `token`), connect to /v1/play, POST /v1/benchmarks/{track}/runs, follow benchmark_progress
until the run ends. Returns (exit_code, final_run). Errors are printed to stderr."""
api = ArenaClient(server, token)
if not token:
try:
token = await asyncio.to_thread(bot_token, api, bot.name)
except OSError as e:
return _unreachable(server, e), None
except ApiException as e:
print(f"sharingan: could not register: {e}", file=sys.stderr)
return 1, None
bar = _Progress(track, not quiet)
done = asyncio.Event()
state: dict = {"run_id": None}
def on_msg(env: dict) -> None:
if env.get("type") != "benchmark_progress":
return
d = env.get("data") or {}
if state["run_id"] and d.get("run_id") not in (None, state["run_id"]):
return
bar.update(int(d.get("hands_done") or 0), int(d.get("hands_total") or 0), d.get("mbb_per_game"), d.get("ci95_mbb"))
if d.get("status") in ("finished", "aborted", "failed"):
done.set()
runner = Runner(bot, server, token or "", on_message=on_msg)
rtask = asyncio.ensure_future(runner.run())
try:
t0 = time.time()
while runner.welcome is None: # a run can only start once the bot's socket is up
if rtask.done() or time.time() - t0 > connect_timeout:
print(f"sharingan: could not connect to {server} /v1/play (bad token?)", file=sys.stderr)
return 1, None
await asyncio.sleep(0.05)
body: dict = {}
if hands:
body["hands"] = hands
if lanes:
body["lanes"] = lanes
run = None
while run is None:
try:
run = await asyncio.to_thread(lambda: api.request("POST", f"/v1/benchmarks/{track}/runs", body, token=token))
except ApiException as e:
if e.code == "not_connected" and time.time() - t0 < connect_timeout:
await asyncio.sleep(0.2)
continue
print(f"sharingan: server refused the run: {e}", file=sys.stderr)
return 1, None
state["run_id"] = run["run_id"]
t1 = time.time()
while True:
try:
await asyncio.wait_for(done.wait(), 1.0)
except asyncio.TimeoutError:
pass
cur = await asyncio.to_thread(lambda: api.request("GET", f"/v1/benchmarks/{track}/runs/{run['run_id']}", token=token))
if cur.get("status") != "running":
break
bar.update(int(cur.get("hands_done") or 0), int(cur.get("hands_total") or 0),
cur.get("running_mbb_per_game"), cur.get("running_ci95_mbb"))
if timeout and time.time() - t1 > timeout:
bar.clear()
print(f"sharingan: timed out after {timeout}s ({cur.get('hands_done', 0)}/{cur.get('hands_total', 0)} hands); "
f"run {run['run_id']} is still going on the server", file=sys.stderr)
return 1, cur
bar.clear()
if cur.get("status") != "finished":
print(f"sharingan: run {cur.get('run_id')} ended as {cur.get('status')}", file=sys.stderr)
return 1, cur
return 0, cur
except OSError as e:
bar.clear()
return _unreachable(server, e), None
finally:
runner.stop()
await asyncio.gather(rtask, return_exceptions=True)
async def _benchmark(args: argparse.Namespace) -> int:
bot = load_bot(args.bot)
rc, run = await run_benchmark(bot, args.server, args.track, hands=args.hands, token=args.token, timeout=args.timeout,
quiet=args.quiet, lanes=args.lanes)
if rc == 0 and run:
print(format_bench(bot.name, run, args.track))
print(f"leaderboard: {leaderboard_url(args.server, args.track)}")
return rc
async def _connect(args: argparse.Namespace) -> int:
"""Connect an already-registered bot to /v1/play and keep answering your_turn until the server closes
(or SIGINT/SIGTERM). Starting a benchmark run for it is somebody else's job (`sharingan benchmark`, or the runner)."""
bot = load_bot(args.bot)
def on_msg(env: dict) -> None:
if env.get("type") == "welcome":
pid = (env.get("data") or {}).get("player_id")
if args.player_id and pid and pid != args.player_id:
print(f"sharingan: warning: token belongs to {pid}, not {args.player_id}", file=sys.stderr)
print(f"sharingan: connected as {pid} ({bot.name})", file=sys.stderr, flush=True)
runner = Runner(bot, args.server, args.token, max_hands=args.max_hands or None, reconnect=not args.no_reconnect,
on_message=on_msg)
loop = asyncio.get_running_loop()
for sig in (signal.SIGTERM, signal.SIGINT):
try:
loop.add_signal_handler(sig, runner.stop)
except (NotImplementedError, RuntimeError): # Windows / non-main thread
pass
print(f"sharingan: connecting {bot.name} to {args.server}", file=sys.stderr, flush=True)
try:
await runner.run()
except OSError as e:
return _unreachable(args.server, e)
if runner.welcome is None:
print(f"sharingan: never connected to {args.server}", file=sys.stderr)
return 1
print(f"sharingan: disconnected after {runner.hands_played} hands", file=sys.stderr)
return 0
async def _eval(args: argparse.Namespace) -> int:
if getattr(args, "local", False):
return await asyncio.to_thread(_eval_local, args)
bot = load_bot(args.bot)
api = ArenaClient(args.server)
# Default: the ladder-v1 benchmark track (AIVAT-corrected, shows up on the leaderboard) when the server has it.
if not args.match and args.vs in (None, "ladder"):
ok = await asyncio.to_thread(supports_track, api, DEFAULT_TRACK)
if ok:
rc, run = await run_benchmark(bot, args.server, DEFAULT_TRACK, hands=max(6, (args.hands // 6) * 6),
timeout=args.timeout, quiet=args.quiet)
if rc == 0 and run:
print(format_bench(bot.name, run, DEFAULT_TRACK))
return rc
args.vs = args.vs or "ladder"
try:
pid, token = await asyncio.to_thread(bot_login, api, bot.name)
except OSError as e: # URLError, ConnectionRefusedError
return _unreachable(args.server, e)
except ApiException as e:
print(f"sharingan: could not register: {e}", file=sys.stderr)
return 1
hands = max(6, (args.hands // 6) * 6) # whole deals: 6 rotations each
runner = Runner(bot, args.server, token)
rtask = asyncio.ensure_future(runner.run())
try:
cfg = {"variant": "nlhe", "max_seats": 6, "small_blind": 50, "big_blind": 100, "ante": 0, "straddle": False,
"starting_stack": 10000, "stack_mode": "reset", "decision_time_ms": args.decision_ms,
"time_bank_ms": 0, "timeout_action": "check_fold", "rake": {"percent": 0, "cap": 0},
"min_players_to_deal": 6, "odd_chip_rule": "first_left_of_button", "show_mode": "standard"}
body = dict(table_config=cfg, participants=[pid] + _house(args.vs), hands_planned=hands,
duplicate={"enabled": True, "rotations": 6, "deck_from": "seed"}, seed=args.seed)
try:
m = await asyncio.to_thread(lambda: api.create_match(**body))
await asyncio.to_thread(api.match_action, m["match_id"], "start")
except ApiException as e:
print(f"sharingan: server refused the match: {e}", file=sys.stderr)
return 1
t0 = time.time()
while True:
cur = await asyncio.to_thread(api.get_match, m["match_id"])
if cur.get("status") in ("finished", "aborted"):
break
if args.timeout and time.time() - t0 > args.timeout:
print(f"sharingan: timed out after {args.timeout}s ({cur.get('hands_played', 0)}/{hands} hands)", file=sys.stderr)
return 1
if not args.quiet and sys.stderr.isatty():
print(f"\r {cur.get('hands_played', 0)}/{hands} hands", end="", file=sys.stderr)
await asyncio.sleep(0.5)
if sys.stderr.isatty():
print("\r" + " " * 30 + "\r", end="", file=sys.stderr)
s = _score(cur, pid)
if not s:
print("sharingan: match finished but no standings for this bot", file=sys.stderr)
return 1
print(format_score(bot.name, s, int(cur.get("hands_played", hands)), args.vs))
return 0
finally:
runner.stop()
await asyncio.gather(rtask, return_exceptions=True)
async def _play(args: argparse.Namespace) -> int:
args.vs = args.vs or "ladder"
bot = load_bot(args.bot)
api = ArenaClient(args.server)
try:
pid, token = await asyncio.to_thread(bot_login, api, bot.name) # the saved token: no new registration per run
if args.table:
tid = args.table
await asyncio.to_thread(api.join_table, tid, args.seat, pid)
else:
t = await asyncio.to_thread(api.create_table, decision_time_ms=args.decision_ms)
tid = t.table_id
await asyncio.to_thread(api.join_table, tid, 0, pid)
for i, h in enumerate(_house(args.vs), start=1): # house bots fill the empty seats
await asyncio.to_thread(api.join_table, tid, i, h)
except OSError as e:
return _unreachable(args.server, e)
except ApiException as e:
print(f"sharingan: {e}", file=sys.stderr)
return 1
print(f"table {tid}: {bot.name} vs {args.vs}. Ctrl-C to stop.", file=sys.stderr)
runner = Runner(bot, args.server, token, max_hands=args.hands or None)
orig = getattr(bot, "on_hand_end", None)
def on_end(e): # print one line per hand, then defer to the bot's own hook
seat = runner._my_seats.get(tid)
print(f"hand {runner.hands_played}: {e.net_for(seat) if seat is not None else '?':+} chips (total {runner.net_chips:+})"
if seat is not None else f"hand {runner.hands_played} ended")
return orig(e) if orig else None
bot.on_hand_end = on_end # type: ignore[method-assign]
try:
await runner.run()
except KeyboardInterrupt:
pass
print(f"{runner.hands_played} hands, net {runner.net_chips:+} chips")
return 0
def _pipe(args: argparse.Namespace) -> int:
"""`sharingan pipe mybot.py`: serve the bot over stdin/stdout for `sharingan-arena run --bot "sharingan pipe mybot.py"`."""
from .pipe import claim_stdio, run_pipe
r, w = claim_stdio() # before importing the bot: its import-time prints must not reach the protocol stream
return run_pipe(load_bot(args.bot), r, w)
def find_worker() -> Optional[str]:
"""The match-worker binary: $SHARINGAN_ARENA_BIN, else `sharingan-arena` on PATH."""
import shutil
exe = os.environ.get("SHARINGAN_ARENA_BIN")
if exe and os.access(exe, os.X_OK):
return exe
return shutil.which("sharingan-arena")
NO_WORKER_MSG = ("sharingan: --local needs the match worker binary `sharingan-arena` on PATH (or SHARINGAN_ARENA_BIN=/path).\n"
"Build it with: cargo build --release -p sharingan-arena (then put target/release on PATH),\n"
"or evaluate against a server instead: sharingan eval mybot.py --server URL")
def _eval_local(args: argparse.Namespace) -> int:
"""Run the worker binary locally: the bot plays as a pipe subprocess, no server needed."""
import json
import shlex
import subprocess
import tempfile
exe = find_worker()
if not exe:
print(NO_WORKER_MSG, file=sys.stderr)
return 2
path = os.path.abspath(args.bot)
if not os.path.isfile(path):
print(f"sharingan: no such file: {path}", file=sys.stderr)
return 2
track = args.track or DEFAULT_TRACK
env = dict(os.environ)
pkg_parent = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
env["PYTHONPATH"] = pkg_parent + (os.pathsep + env["PYTHONPATH"] if env.get("PYTHONPATH") else "")
bot_cmd = f"{shlex.quote(sys.executable)} -m sharingan.cli pipe {shlex.quote(path)}"
out = args.out or os.path.join(tempfile.mkdtemp(prefix="sharingan-"), "result.json")
cmd = [exe, "run", "--bot", bot_cmd, "--track", track, "--hands", str(max(6, args.hands)), "--out", out,
"--decision-timeout-ms", str(args.decision_ms)]
if args.lanes:
cmd += ["--lanes", str(args.lanes)]
if args.seed_set:
cmd += ["--seed", args.seed]
if args.quiet:
cmd += ["--quiet"]
rc = subprocess.call(cmd, env=env)
if rc != 0:
return rc
with open(out) as f:
res = json.load(f)
print(f"{os.path.splitext(os.path.basename(path))[0]}: {float(res['mbb_per_game']):+.1f} ± {float(res['ci95_mbb']):.1f} mbb/game "
f"(95% CI, {res.get('method')}) over {res['hands']} hands on {res['track']} [local, unverified; "
f"{res['timings']['hands_per_sec']:.0f} hands/s, result: {out}]"
+ (f" WARNING {res['forfeit_hands']} forfeit hands (bot crashed or timed out)" if res.get("forfeit_hands") else ""))
return 0
def _submit(args: argparse.Namespace) -> int:
"""Hosted job: upload the bot, the server's runner plays it in an isolated sandbox, a verified score lands on the leaderboard."""
import base64
import hashlib
import io
import tarfile
path = os.path.abspath(args.bot)
if not os.path.exists(path):
print(f"sharingan: no such file: {args.bot}", file=sys.stderr)
return 2
# Check everything we can before the first request: registering a bot spends the per-address registration cap.
if not MIN_HANDS <= args.hands <= MAX_HANDS:
print(f"sharingan: --hands must be between {MIN_HANDS:,} and {MAX_HANDS:,}, got {args.hands:,}", file=sys.stderr)
return 2
owner = _owner(args)
if owner is None:
return 2
entry = args.entry or "bot.py"
if os.path.isdir(path) and not os.path.isfile(os.path.join(path, entry)):
print(f"sharingan: {args.bot} has no {entry} (pass --entry FILE)", file=sys.stderr)
return 2
buf = io.BytesIO()
with tarfile.open(fileobj=buf, mode="w:gz") as tar:
if os.path.isdir(path):
tar.add(path, arcname=".", filter=lambda ti: None if "__pycache__" in ti.name or ".git" in ti.name else ti)
else:
entry = os.path.basename(path)
tar.add(path, arcname=entry)
sha = hashlib.sha256(buf.getvalue()).hexdigest() # the server hashes the same bytes and shows it as artifact_sha256
api = ArenaClient(args.server)
token = args.token
if not token:
name = _bot_name_for(path)
try:
token = bot_token(api, name)
except ApiException as e:
print(f"sharingan: could not register: {e}", file=sys.stderr)
return 1
except OSError as e:
return _unreachable(args.server, e)
body = {"botName": os.path.splitext(os.path.basename(path.rstrip("/")))[0][:48] or "bot", "language": "python", "entry": entry,
"track": args.track, "hands": args.hands, "idempotencyKey": args.key or f"cli-{int(time.time() * 1000)}",
"artifactTgzBase64": base64.b64encode(buf.getvalue()).decode()}
if args.lanes:
body["lanes"] = args.lanes
if args.requirements:
body["requirementsFile"] = args.requirements
body.update(owner)
api.timeout = 120.0
try:
job = api.request("POST", "/v1/jobs", body, token=token)
except ApiException as e:
print(f"sharingan: submit refused: {e.status} {e.code}: {e.message}", file=sys.stderr)
return 1
except OSError as e:
return _unreachable(args.server, e)
_save_owner(owner)
jid = job["id"]
print(f"sharingan: job {jid} accepted ({job.get('hands') or args.hands} hands on {args.track}; "
f"upload sha256 {(job.get('artifact_sha256') or sha)[:12]})", file=sys.stderr, flush=True)
t0, last = time.time(), None
api.timeout = 30.0
while True:
try:
j = api.request("GET", f"/v1/jobs/{jid}", token=token)
except (ApiException, OSError):
time.sleep(3)
continue
line = f"{j['status']} {j.get('hands_done', 0)}/{j.get('hands_total', 0)} hands"
if line != last and not args.quiet:
print(f"sharingan: [{int(time.time() - t0)}s] {line}", file=sys.stderr, flush=True)
last = line
if j["status"] in ("finished", "failed", "aborted") and j.get("settled", True):
break
if args.timeout and time.time() - t0 > args.timeout:
print(f"sharingan: timed out waiting; job {jid} keeps running (GET /v1/jobs/{jid})", file=sys.stderr)
return 1
time.sleep(2)
if j["status"] != "finished":
print(f"sharingan: job {j['status']}: {j.get('error')}", file=sys.stderr)
if j.get("bot_log_tail"):
print(j["bot_log_tail"][-1500:], file=sys.stderr)
return 1
short = j["verified"] and j["hands_done"] < RANKED_HANDS # scores, but a short run never ranks
tag = (f"VERIFIED, NOT RANKED: under {RANKED_HANDS:,} hands" if short else "VERIFIED") if j["verified"] else "unverified"
print(f"{j['bot_name']}: {j['mbb_per_game']:+.1f} +- {j['ci95_mbb']:.1f} mbb/game over {j['hands_done']} hands on {j['track']} "
f"[{tag}, hosted job {jid}]")
_warn_bot_trouble(j)
if short:
print(f"sharingan: not ranked: the leaderboard counts verified runs of {RANKED_HANDS:,} hands, this one had {j['hands_done']:,}; "
"submit without --hands for a ranked run", file=sys.stderr)
else:
print(f"leaderboard: {leaderboard_url(args.server, args.track)}")
return 0
def _serve(args: argparse.Namespace) -> int:
from .webhook import serve_webhook
bot = load_bot(args.bot)
print(f"serving {bot.name} as a webhook on http://0.0.0.0:{args.port}/act"
+ (" (HMAC signature required)" if args.secret else "") + "\nRegister it with: "
f'POST /v1/players {{"name": "{bot.name}", "kind": "bot", "webhook_url": "https://YOUR_HOST:{args.port}/act", "secret": "..."}}',
file=sys.stderr)
serve_webhook(bot, host=args.host, port=args.port, secret=args.secret)
return 0
def main(argv: Optional[List[str]] = None) -> int:
p = argparse.ArgumentParser(prog="sharingan", description="Eval and play poker bots on the Sharingan arena.")
sub = p.add_subparsers(dest="cmd", required=True)
def common(sp: argparse.ArgumentParser) -> None:
sp.add_argument("bot", help="path to mybot.py (Bot subclass or act(state) function)")
sp.add_argument("--server", default=os.environ.get("SHARINGAN_SERVER", DEFAULT_SERVER))
sp.add_argument("--vs", default=None, help="ladder (default) | sharingan-1 | random | calling_station | tight_aggressive | <house bot>")
sp.add_argument("--decision-ms", type=int, default=5000)
e = sub.add_parser("eval", help="ladder-v1 benchmark (or a duplicate match vs house bots on older servers); prints one score line")
common(e)
e.add_argument("--match", action="store_true", help="force the plain duplicate match instead of the ladder-v1 benchmark")
e.add_argument("--hands", type=int, default=3000, help="hands to play (rounded down to a multiple of 6)")
e.add_argument("--seed", default="sharingan-eval", help="match seed (same seed = same decks)")
e.add_argument("--timeout", type=float, default=0, help="give up after N seconds (0 = wait)")
e.add_argument("--quiet", action="store_true")
e.add_argument("--local", action="store_true",
help="no server: run the `sharingan-arena` worker binary from PATH and play the bot as a pipe subprocess")
e.add_argument("--track", choices=TRACKS, default=None, help="with --local: ladder-v1 (default) | sharingan-1")
e.add_argument("--lanes", type=int, default=0, help="with --local: parallel bot processes (default: worker decides)")
e.add_argument("--out", default=None, help="with --local: where to write result.json")
sm = sub.add_parser("submit", help="hosted job: upload the bot, the server plays it in an isolated sandbox, prints a VERIFIED score")
sm.add_argument("bot", help="mybot.py (or a directory with --entry)")
sm.add_argument("--server", default=os.environ.get("SHARINGAN_SERVER", DEFAULT_SERVER))
sm.add_argument("--token", default=os.environ.get("SHARINGAN_TOKEN"), help="your arena bot token (default: the one saved for this bot name, registering it once)")
sm.add_argument("--track", choices=TRACKS, default=DEFAULT_TRACK)
sm.add_argument("--hands", type=int, default=20000,
help=f"{MIN_HANDS} to {MAX_HANDS}; the default 20000 becomes 20004 (whole deals); verified runs of 20,004 hands or more rank, shorter ones are for testing")
sm.add_argument("--lanes", type=int, default=0)
sm.add_argument("--entry", default=None, help="entry file when BOT is a directory (default bot.py)")
sm.add_argument("--requirements", default=None, help="requirements.txt inside the bot directory (installed in a short network window)")
sm.add_argument("--contact", default=os.environ.get("SHARINGAN_CONTACT"), help="required: your email for submission support and abuse prevention; never shown publicly; saved after the first submit")
sm.add_argument("--profile", default=os.environ.get("SHARINGAN_PROFILE"), help="required: link to your X, LinkedIn, GitHub or personal page (https://x.com/you); never shown publicly; saved after the first submit")
sm.add_argument("--key", default=None, help="idempotency key (resubmitting the same key returns the same job)")
sm.add_argument("--timeout", type=float, default=0)
sm.add_argument("--quiet", action="store_true")
tk = sub.add_parser("token", help="print the saved bot token (for curl: $(sharingan token mybot.py))")
tk.add_argument("bot", nargs="?", default=None, help="mybot.py (named after the file) or a bot name; omit when only one bot is saved for the server")
tk.add_argument("--server", default=os.environ.get("SHARINGAN_SERVER", DEFAULT_SERVER))
pp = sub.add_parser("pipe", help="serve the bot over stdin/stdout (pipe protocol) for `sharingan-arena run --bot \"sharingan pipe mybot.py\"`")
pp.add_argument("bot")
b = sub.add_parser("benchmark", help="run a benchmark track (ladder-v1 | sharingan-1) and print mbb/game ± CI")
b.add_argument("bot")
b.add_argument("--track", choices=TRACKS, default=DEFAULT_TRACK)
b.add_argument("--hands", type=int, default=None, help="hands (server default 20000; rounded up to a multiple of 6)")
b.add_argument("--lanes", type=int, default=None, help="parallel lanes (bot must key state by table_id/hand_id)")
b.add_argument("--server", default=os.environ.get("SHARINGAN_SERVER", DEFAULT_SERVER))
b.add_argument("--token", default=os.environ.get("SHARINGAN_TOKEN"), help="use this bot token (default: the one saved for this bot name, registering it once)")
b.add_argument("--timeout", type=float, default=0, help="give up waiting after N seconds (0 = wait)")
b.add_argument("--quiet", action="store_true", help="no progress bar")
c = sub.add_parser("connect", help="connect an already-registered bot and answer your_turn until the server closes")
c.add_argument("bot")
c.add_argument("--server", default=os.environ.get("SHARINGAN_SERVER", DEFAULT_SERVER))
c.add_argument("--token", default=os.environ.get("SHARINGAN_TOKEN"), required=not os.environ.get("SHARINGAN_TOKEN"))
c.add_argument("--player-id", default=None, help="expected player id (warns if the token belongs to another)")
c.add_argument("--max-hands", type=int, default=0, help="disconnect after N hands (0 = no limit)")
c.add_argument("--no-reconnect", action="store_true", help="exit on the first disconnect instead of reconnecting")
pl = sub.add_parser("play", help="join a table; house bots fill the empty seats")
common(pl)
pl.add_argument("--table", help="join this existing table instead of creating one")
pl.add_argument("--seat", type=int, default=0)
pl.add_argument("--hands", type=int, default=0, help="stop after N hands (0 = until Ctrl-C)")
s = sub.add_parser("serve", help="expose the bot as a webhook endpoint")
s.add_argument("bot")
s.add_argument("--port", type=int, default=9000)
s.add_argument("--host", default="0.0.0.0")
s.add_argument("--secret", default=os.environ.get("SHARINGAN_WEBHOOK_SECRET"))
a = p.parse_args(argv)
if a.cmd == "eval":
a.seed_set = any(x == "--seed" or x.startswith("--seed=") for x in (argv if argv is not None else sys.argv[1:]))
try:
if a.cmd == "pipe":
return _pipe(a)
if a.cmd == "submit":
return _submit(a)
if a.cmd == "token":
return _token(a)
if a.cmd == "eval":
return asyncio.run(_eval(a))
if a.cmd == "benchmark":
return asyncio.run(_benchmark(a))
if a.cmd == "connect":
return asyncio.run(_connect(a))
if a.cmd == "play":
return asyncio.run(_play(a))
return _serve(a)
except KeyboardInterrupt:
return 130
if __name__ == "__main__":
raise SystemExit(main())
+417
View File
@@ -0,0 +1,417 @@
"""REST client (`ArenaClient`, stdlib urllib) and WebSocket runner (`Runner`, uses `websockets`)."""
from __future__ import annotations
import asyncio
import inspect
import json
import logging
import time
import urllib.error
import urllib.request
from typing import Any, Callable, Dict, List, Optional, Union
from urllib.parse import urlencode, urlparse, urlunparse
from .bot import Bot
from .helpers import legalize, safe_action
from .models import (Action, ActionEvent, ApiError, HandEnd, HandStart, PlayerInfo, Seat, StreetEvent,
Table, YourTurn)
log = logging.getLogger("sharingan")
PROTOCOL_VERSION = 1
CLIENT_NAME = "sharingan-py/0.1.0"
USER_AGENT = "poker-sharingan-sdk/0.1 (+https://sharingan.poker)"
class ApiException(Exception):
"""HTTP-level error from the REST API (`{"error": {code, message, details}}`)."""
def __init__(self, status: int, code: str, message: str = "", details: Optional[dict] = None):
super().__init__(f"{status} {code}: {message}")
self.status, self.code, self.message, self.details = status, code, message, details or {}
# ----------------------------------------------------------------------------- REST
class ArenaClient:
"""Thin REST client for /v1. Synchronous (stdlib only); use `asyncio.to_thread` if you need it in async code.
`base_url` may be http(s)://host[:port] (or ws(s)://, which is mapped to http(s)).
"""
def __init__(self, base_url: str, token: Optional[str] = None, timeout: float = 10.0):
u = urlparse(base_url)
scheme = {"ws": "http", "wss": "https"}.get(u.scheme, u.scheme or "http")
self.base_url = urlunparse((scheme, u.netloc, u.path.rstrip("/"), "", "", ""))
self.token = token
self.timeout = timeout
# -- low level
def request(self, method: str, path: str, body: Any = None, token: Optional[str] = None,
query: Optional[dict] = None) -> Any:
url = self.base_url + path
if query:
url += "?" + urlencode({k: v for k, v in query.items() if v is not None})
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method)
req.add_header("Accept", "application/json")
req.add_header("User-Agent", USER_AGENT) # the default Python-urllib UA is blocked by Cloudflare (error 1010) on the public arena
if data is not None:
req.add_header("Content-Type", "application/json")
tok = token or self.token
if tok:
req.add_header("Authorization", f"Bearer {tok}")
try:
with urllib.request.urlopen(req, timeout=self.timeout) as r:
raw = r.read()
except urllib.error.HTTPError as e:
raw = e.read()
try:
err = json.loads(raw)["error"]
except Exception:
err = {"code": "internal", "message": raw.decode(errors="replace")[:200]}
raise ApiException(e.code, err.get("code", "internal"), err.get("message", ""), err.get("details")) from None
return json.loads(raw) if raw else None
# -- players
def register_bot(self, name: str, kind: str = "bot", set_token: bool = True) -> PlayerInfo:
"""POST /v1/players. The returned `token` is shown once; by default it becomes this client's token."""
p = PlayerInfo.from_dict(self.request("POST", "/v1/players", {"name": name, "kind": kind}))
if set_token and p.token:
self.token = p.token
return p
def get_player(self, player_id: str) -> PlayerInfo:
return PlayerInfo.from_dict(self.request("GET", f"/v1/players/{player_id}"))
# -- tables
def create_table(self, **config: Any) -> Table:
"""POST /v1/tables. Defaults: 6-max NLHE 50/100, 10000 stack, reset mode."""
cfg = {"variant": "nlhe", "max_seats": 6, "small_blind": 50, "big_blind": 100, "ante": 0, "straddle": False,
"starting_stack": 10000, "stack_mode": "reset", "decision_time_ms": 5000, "time_bank_ms": 30000,
"timeout_action": "check_fold", "rake": {"percent": 0, "cap": 0}, "min_players_to_deal": 6,
"odd_chip_rule": "first_left_of_button", "show_mode": "standard"}
cfg.update(config)
return Table.from_dict(self.request("POST", "/v1/tables", cfg))
def get_table(self, table_id: str) -> Table:
return Table.from_dict(self.request("GET", f"/v1/tables/{table_id}"))
def join_table(self, table_id: str, seat: int, player_id: str, token: Optional[str] = None) -> Seat:
"""POST /v1/tables/{id}/seats/{seat} (sit down)."""
return Seat.from_dict(self.request("POST", f"/v1/tables/{table_id}/seats/{seat}",
{"player_id": player_id}, token=token))
def leave_table(self, table_id: str, seat: int) -> None:
self.request("DELETE", f"/v1/tables/{table_id}/seats/{seat}")
# -- matches / hands
def create_match(self, table_config: dict, participants: List[str], hands_planned: int,
duplicate: Optional[dict] = None, seed: Optional[str] = None) -> dict:
body: Dict[str, Any] = {"table_config": table_config, "participants": participants, "hands_planned": hands_planned}
if duplicate is not None:
body["duplicate"] = duplicate
if seed is not None:
body["seed"] = seed
return self.request("POST", "/v1/matches", body)
def match_action(self, match_id: str, action: str) -> dict:
"""action in start | pause | abort"""
return self.request("POST", f"/v1/matches/{match_id}/{action}")
def get_match(self, match_id: str) -> dict:
return self.request("GET", f"/v1/matches/{match_id}")
def get_hands(self, match_id: str, after_hand_no: Optional[int] = None, limit: int = 500) -> List[dict]:
return self.request("GET", f"/v1/matches/{match_id}/hands",
query={"after_hand_no": after_hand_no, "limit": limit})
def get_hand(self, hand_id: str) -> dict:
return self.request("GET", f"/v1/hands/{hand_id}")
def get_hand_events(self, hand_id: str) -> List[dict]:
return self.request("GET", f"/v1/hands/{hand_id}/events")
def ws_url(url: str, token: Optional[str] = None) -> str:
"""Accepts http(s)://host, ws(s)://host or a full ws(s)://host/v1/play URL; appends /v1/play and ?token=."""
u = urlparse(url)
scheme = {"http": "ws", "https": "wss"}.get(u.scheme, u.scheme or "ws")
path = u.path.rstrip("/")
if not path.endswith("/v1/play"):
path += "/v1/play"
query = u.query
if token and "token=" not in query:
query = (query + "&" if query else "") + urlencode({"token": token})
return urlunparse((scheme, u.netloc, path, "", query, ""))
# ----------------------------------------------------------------------------- WebSocket runner
async def _maybe_await(v: Any) -> Any:
return await v if inspect.isawaitable(v) else v
class Runner:
"""Connects a `Bot` to /v1/play: hello/resume, keep-alive, dedupe, gap resync, reconnect with backoff,
deadline-aware `act` with a check/fold fallback.
Typical use: `run(bot, url, token)` (blocking) or `await Runner(bot, url, token).run()`.
"""
def __init__(self, bot: Bot, url: str, token: str, *, reconnect: bool = True, max_backoff: float = 10.0,
ping_interval: float = 15.0, safety_margin_ms: int = 150, max_hands: Optional[int] = None,
on_message: Optional[Callable[[dict], Any]] = None, client_name: str = CLIENT_NAME):
self.bot, self.token = bot, token
self.url = ws_url(url, token)
self.reconnect, self.max_backoff = reconnect, max_backoff
self.ping_interval, self.safety_margin_ms = ping_interval, safety_margin_ms
self.max_hands = max_hands
self.on_message = on_message
self.client_name = client_name
# state
self.welcome: Optional[dict] = None
self.player_id: Optional[str] = None
self.tables: Dict[str, Table] = {}
self.last_table_seq: Dict[str, int] = {}
self._hand_seq: Dict[str, int] = {}
self.hands_played = 0
self.net_chips = 0
self.connects = 0
self.errors: List[ApiError] = []
self._answered: set = set()
self._tasks: set = set()
self._ws: Any = None
self._stop = False
self._resyncing = False
self._my_seats: Dict[str, int] = {}
# -- public
def stop(self) -> None:
self._stop = True
ws = self._ws
if ws is not None:
asyncio.ensure_future(ws.close())
async def run(self) -> None:
import websockets
backoff = 0.2
while not self._stop:
try:
async with websockets.connect(self.url, user_agent_header=USER_AGENT, ping_interval=None, max_size=16 * 2**20) as ws:
self._ws = ws
self.connects += 1
backoff = 0.2
await self._session(ws)
except (OSError, asyncio.TimeoutError, websockets.exceptions.WebSocketException) as e:
status = getattr(getattr(e, "response", None), "status_code", None)
if status in (401, 403): # bad/revoked token: retrying cannot help
log.error("arena rejected the token (HTTP %s); not reconnecting", status)
self._stop = True
elif not self._stop:
log.warning("connection lost: %r", e)
finally:
self._ws = None
await self._cancel_tasks()
if self._stop or not self.reconnect:
break
await asyncio.sleep(backoff)
backoff = min(self.max_backoff, backoff * 2)
async def send(self, type_: str, data: dict, table_id: Optional[str] = None) -> None:
env: Dict[str, Any] = {"v": PROTOCOL_VERSION, "type": type_, "t_ms": int(time.time() * 1000), "data": data}
if table_id:
env["table_id"] = table_id
if self._ws is not None:
await self._ws.send(json.dumps(env, separators=(",", ":")))
async def leave(self, table_id: str) -> None:
await self.send("leave", {"table_id": table_id}, table_id)
# -- internals
async def _hello(self, resume: bool) -> None:
data: Dict[str, Any] = {"client": self.client_name}
if resume and self.last_table_seq:
data["resume"] = [{"table_id": t, "last_table_seq": s} for t, s in self.last_table_seq.items()]
await self.send("hello", data)
async def _session(self, ws: Any) -> None:
self._answered.clear()
self._resyncing = False
await self._hello(resume=True)
pinger = asyncio.ensure_future(self._ping_loop())
try:
async for raw in ws:
try:
env = json.loads(raw)
except ValueError:
log.warning("non-JSON frame ignored")
continue
await self._dispatch(env)
if self._stop:
return
finally:
pinger.cancel()
async def _ping_loop(self) -> None:
while True:
await asyncio.sleep(self.ping_interval)
try:
await self.send("ping", {})
except Exception:
return
async def _cancel_tasks(self) -> None:
for t in list(self._tasks):
t.cancel()
if self._tasks:
await asyncio.gather(*self._tasks, return_exceptions=True)
self._tasks.clear()
def _gap(self, env: dict) -> bool:
"""Update seq tracking. Returns True if this message is a duplicate that must be dropped."""
tid = env.get("table_id")
ts = env.get("table_seq")
if tid and isinstance(ts, int):
last = self.last_table_seq.get(tid)
if last is not None and ts <= last and env.get("type") != "your_turn":
return True
if last is not None and ts > last + 1 and not self._resyncing:
log.warning("table_seq gap %s: %s -> %s; resyncing", tid, last, ts)
self._resyncing = True
asyncio.ensure_future(self._hello(resume=True))
self.last_table_seq[tid] = max(ts, last or 0)
hid, seq = env.get("hand_id"), env.get("seq")
if hid and isinstance(seq, int) and env.get("type") != "your_turn":
last_h = self._hand_seq.get(hid)
if last_h is not None and seq > last_h + 1 and not self._resyncing:
log.warning("hand seq gap %s: %s -> %s; resyncing", hid, last_h, seq)
self._resyncing = True
asyncio.ensure_future(self._hello(resume=True))
self._hand_seq[hid] = max(seq, last_h or 0)
if len(self._hand_seq) > 64:
self._hand_seq.pop(next(iter(self._hand_seq)))
return False
async def _call_hook(self, name: str, *args: Any) -> None:
fn = getattr(self.bot, name, None)
if fn is None:
return
try:
await _maybe_await(fn(*args))
except Exception:
log.exception("bot.%s raised", name)
async def _dispatch(self, env: dict) -> None:
if self.on_message:
await _maybe_await(self.on_message(env))
typ = env.get("type")
data = env.get("data") or {}
tid = env.get("table_id") or data.get("table_id") or ""
if typ == "pong":
return
if typ == "table_snapshot":
t = Table.from_dict(data)
self.tables[t.table_id or tid] = t
self.last_table_seq[t.table_id or tid] = t.table_seq
self._hand_seq.clear()
self._resyncing = False
self._note_seats(t)
return
if self._gap(env):
return
if typ == "welcome":
self.welcome = data
self.player_id = data.get("player_id")
await self._call_hook("on_connect", data)
elif typ == "hand_start":
h = HandStart.from_dict(data)
for p in h.players:
if p.player_id and p.player_id == self.player_id:
self._my_seats[tid] = p.seat
await self._call_hook("on_hand_start", h)
elif typ == "action":
await self._call_hook("on_action", ActionEvent.from_dict(data))
elif typ == "street":
await self._call_hook("on_street", StreetEvent.from_dict(data))
elif typ == "hand_end":
end = HandEnd.from_dict(data)
self.hands_played += 1
seat = self._my_seats.get(tid)
if seat is None:
for r in end.results:
if r.player_id and r.player_id == self.player_id:
seat = r.seat
if seat is not None:
self.net_chips += end.net_for(seat)
await self._call_hook("on_hand_end", end)
if self.max_hands is not None and self.hands_played >= self.max_hands:
self._stop = True
if self._ws is not None:
await self._ws.close()
elif typ == "your_turn":
self._start_decision(YourTurn.from_dict(data, table_id=tid, t_ms=int(env.get("t_ms") or 0),
hand_id=env.get("hand_id") or "", seq=int(env.get("seq") or 0)))
elif typ == "error":
err = ApiError.from_dict(data)
self.errors.append(err)
if err.decision_id: # server will re-send your_turn with the same id; allow answering again
self._answered.discard(err.decision_id)
log.warning("server error %s: %s", err.code, err.message)
await self._call_hook("on_error", err)
def _note_seats(self, t: Table) -> None:
for s in t.seats:
if s.player_id and s.player_id == self.player_id:
self._my_seats[t.table_id] = s.seat
def _start_decision(self, state: YourTurn) -> None:
if state.decision_id in self._answered:
return
self._answered.add(state.decision_id)
task = asyncio.ensure_future(self._decide(state))
self._tasks.add(task)
task.add_done_callback(self._tasks.discard)
def _budget_s(self, state: YourTurn) -> Optional[float]:
if not state.deadline_ms:
return None
# Use server clock when the envelope carries it (skew-proof), else the local clock.
ref = state.t_ms or int(time.time() * 1000)
return max(0.0, (state.deadline_ms - ref - self.safety_margin_ms) / 1000.0)
async def _decide(self, state: YourTurn) -> None:
budget = self._budget_s(state)
action: Optional[Action] = None
try:
if inspect.iscoroutinefunction(self.bot.act):
action = await asyncio.wait_for(self.bot.act(state), budget)
else: # sync act (e.g. a blocking LLM call) runs in a thread so the deadline is enforced
loop = asyncio.get_running_loop()
action = await asyncio.wait_for(loop.run_in_executor(None, self.bot.act, state), budget)
except asyncio.TimeoutError:
log.warning("act() exceeded the decision deadline; playing check/fold")
except asyncio.CancelledError:
raise
except Exception:
log.exception("bot.act raised; playing check/fold")
if not isinstance(action, Action):
action = safe_action(state)
elif not getattr(self.bot, "strict", False):
action = legalize(state, action)
try:
await self.send("act", action.to_data(state.hand_id, state.decision_id), state.table_id or None)
except Exception as e: # connection died; the next session will be re-offered the turn
log.warning("could not send act: %r", e)
self._answered.discard(state.decision_id)
def run(bot: Bot, url: str, token: str, **kwargs: Any) -> Runner:
"""Blocking convenience: run `bot` until Ctrl-C (or `max_hands`). Returns the Runner (stats)."""
r = Runner(bot, url, token, **kwargs)
try:
asyncio.run(r.run())
except KeyboardInterrupt:
pass
return r
+265
View File
@@ -0,0 +1,265 @@
"""Pure helper functions: legal actions, pot odds, raise sizing ("to" amounts), hand strength, text rendering."""
from __future__ import annotations
from typing import List, Optional, Tuple
from .models import Action, YourTurn
RANKS = "23456789TJQKA"
def rank_value(card: str) -> int:
"""2..14"""
return RANKS.index(card[0]) + 2
def legal_types(s: YourTurn) -> List[str]:
"""Action types the bot may send right now: subset of fold/check/call/raise."""
out = []
if s.legal.fold:
out.append("fold")
if s.legal.check:
out.append("check")
if s.legal.call:
out.append("call")
if s.legal.raise_:
out.append("raise")
return out
def to_call(s: YourTurn) -> int:
return s.to_call
def pot_odds(s: YourTurn) -> float:
"""to_call / (pot + to_call). Equity needed to break even on a call."""
return s.pot_odds
def min_raise_to(s: YourTurn) -> Optional[int]:
return s.min_raise_to
def max_raise_to(s: YourTurn) -> Optional[int]:
return s.max_raise_to
def my_street_contrib(s: YourTurn) -> int:
m = s.me
return m.street_contrib if m else 0
def current_bet(s: YourTurn) -> int:
"""Highest street contribution on the table (what a call would bring us to)."""
if s.legal.call:
return s.legal.call.to
return my_street_contrib(s) # checking is free -> we are level with the bet
def pot_raise_to(s: YourTurn, fraction: float = 1.0) -> int:
"""'to' amount for a raise/bet of `fraction` x pot (after calling), clamped to the legal range.
Standard pot-sized raise: call first, then raise by (pot + to_call) * fraction.
"""
base = current_bet(s)
to = base + int(round((s.pot + s.to_call) * fraction))
return clamp_raise_to(s, to)
def clamp_raise_to(s: YourTurn, to: int) -> int:
r = s.legal.raise_
if r is None:
raise ValueError("raising is not legal")
return max(r.min_to, min(r.max_to, int(to)))
def bb_multiple_to(s: YourTurn, bbs: float) -> int:
"""'to' amount of `bbs` big blinds, clamped to the legal range."""
return clamp_raise_to(s, int(round(bbs * s.big_blind)))
def all_in_action(s: YourTurn) -> Action:
if s.legal.raise_:
return Action.raise_to(s.legal.raise_.max_to)
if s.legal.call:
return Action.call()
return safe_action(s)
def safe_action(s: YourTurn) -> Action:
"""Check if free, else fold. Same as the server's timeout policy."""
return Action.check() if s.legal.check else Action.fold()
def call_or_check(s: YourTurn) -> Action:
if s.legal.call:
return Action.call()
if s.legal.check:
return Action.check()
return Action.fold()
def legalize(s: YourTurn, a: Action) -> Action:
"""Coerce any action into one that is legal in this spot (never raises, never returns an illegal action).
- fold when check is free -> check
- raise when raising is impossible -> call/check
- raise amounts clamped to [min_to, max_to]; a `bet` is sent as `raise` semantics-equivalent type
- check when facing a bet -> fold
- call with nothing to call -> check
"""
t = a.type
if t in ("bet", "raise", "all_in"):
if s.legal.raise_:
to = a.to if (a.to is not None and t != "all_in") else s.legal.raise_.max_to
return Action("raise", clamp_raise_to(s, to))
return call_or_check(s)
if t == "call":
return call_or_check(s)
if t == "check":
return Action.check() if s.legal.check else (Action.fold())
if t == "fold":
return Action.check() if s.legal.check else Action.fold()
return safe_action(s)
def is_legal(s: YourTurn, a: Action) -> bool:
"""True if `a` can be sent as-is without the server rejecting it."""
if a.type == "fold":
return s.legal.fold
if a.type == "check":
return s.legal.check
if a.type == "call":
return s.legal.call is not None
if a.type in ("raise", "bet"):
r = s.legal.raise_
return r is not None and a.to is not None and r.min_to <= a.to <= r.max_to
return False
def effective_stack_bb(s: YourTurn) -> float:
"""Our stack in big blinds."""
return s.stack / s.big_blind if s.big_blind else 0.0
def position_name(s: YourTurn) -> str:
"""BTN, SB, BB, UTG, MP, CO (6-max naming, relative to occupied seats)."""
seats = sorted(p.seat for p in s.players)
if s.seat not in seats or s.button_seat not in seats and not seats:
return "?"
n = len(seats)
# distance clockwise from button among occupied seats
order = sorted(seats, key=lambda x: (x - s.button_seat) % 6)
idx = order.index(s.seat) # 0 = BTN
if n == 2:
return "BTN/SB" if idx == 0 else "BB"
names = {0: "BTN", 1: "SB", 2: "BB"}
if idx in names:
return names[idx]
rest = n - 3 # UTG.. CO
pos = idx - 3
if pos == rest - 1:
return "CO"
if pos == 0:
return "UTG"
return "MP"
def preflop_strength(hole: List[str]) -> float:
"""Chen formula score (roughly -1..20). >=9 premium, 7+ strong, 5+ playable."""
if len(hole) != 2:
return 0.0
r = sorted((rank_value(hole[0]), rank_value(hole[1])), reverse=True)
hi, lo = r
pts = {14: 10, 13: 8, 12: 7, 11: 6}.get(hi, hi / 2.0)
if hi == lo:
return max(5.0, pts * 2)
if hole[0][1] == hole[1][1]:
pts += 2
gap = hi - lo - 1
pts -= {0: 0, 1: 1, 2: 2, 3: 4}.get(gap, 5)
if gap <= 1 and hi < 12:
pts += 1
return float(round(pts * 2) / 2)
def made_hand_category(hole: List[str], board: List[str]) -> int:
"""Very coarse postflop strength: 0 air, 1 pair (any), 2 two pair, 3 trips+ (trips, straight, flush, FH, quads).
Good enough for rule-based example bots. Not a hand evaluator.
"""
cards = list(hole) + list(board)
if len(cards) < 5:
return 0
from collections import Counter
rc = Counter(c[0] for c in cards)
sc = Counter(c[1] for c in cards)
counts = sorted(rc.values(), reverse=True)
vals = sorted({rank_value(c) for c in cards})
if 14 in vals:
vals = [1] + vals
straight = any(all(v + i in vals for i in range(5)) for v in range(1, 11))
flush = max(sc.values()) >= 5
if counts[0] >= 3 or straight or flush:
return 3
if counts[0] == 2 and counts[1] == 2:
return 2
if counts[0] == 2:
# only count the pair if it involves a hole card (board pair alone is not "ours")
paired = [r for r, c in rc.items() if c == 2]
return 1 if any(r in (hole[0][0], hole[1][0]) for r in paired) else 0
return 0
def render_state(s: YourTurn) -> str:
"""Plain-text rendering of the decision for LLM prompts or logs."""
lines: List[str] = []
lines.append(f"Texas Hold'em no-limit, 6-max. Blinds {s.small_blind}/{s.big_blind}. Street: {s.street}.")
lines.append(f"You are seat {s.seat} ({position_name(s)}), stack {s.stack} ({effective_stack_bb(s):.1f} bb).")
lines.append(f"Your hole cards: {' '.join(s.hole_cards)}")
lines.append(f"Board: {' '.join(s.board) if s.board else '(none)'}")
lines.append(f"Pot: {s.pot}. To call: {s.to_call}. Pot odds: {s.pot_odds:.1%}.")
lines.append("Players:")
for p in s.players:
tag = " (YOU)" if p.seat == s.seat else ""
lines.append(f" seat {p.seat} {p.name}{tag}: stack {p.stack}, in pot this street {p.street_contrib}, "
f"this hand {p.hand_contrib}, {p.status}")
lines.append("Action so far:")
for a in s.history:
if a.type in ("fold", "check"):
desc = a.type
else:
desc = f"{a.type} to {a.to}" + (" (all-in)" if a.all_in else "")
lines.append(f" [{a.street}] seat {a.seat}: {desc}")
opts = []
if s.legal.fold:
opts.append("fold")
if s.legal.check:
opts.append("check")
if s.legal.call:
opts.append(f"call (adds {s.legal.call.added}, to {s.legal.call.to}{', all-in' if s.legal.call.all_in else ''})")
if s.legal.raise_:
opts.append(f"raise (to an amount between {s.legal.raise_.min_to} and {s.legal.raise_.max_to}; "
f"amounts are TOTAL street contribution, not increments)")
lines.append("Legal actions: " + "; ".join(opts))
return "\n".join(lines)
def parse_action_text(text: str) -> Optional[Action]:
"""Parse free-form LLM output like 'raise 450', 'RAISE TO 450', 'call', 'fold', 'check', 'all-in'.
Returns None if nothing recognisable. Uses the LAST recognised action word in the text.
"""
import re
t = text.strip().lower()
found: Optional[Tuple[int, Action]] = None
for m in re.finditer(r"\b(fold|check|call|all[- ]?in|raise|bet)\b(?:\s*(?:to|=|:)?\s*\$?(\d+))?", t):
w = m.group(1)
if w.startswith("all"):
a = Action("all_in")
elif w in ("raise", "bet"):
a = Action(w, int(m.group(2))) if m.group(2) else Action("raise", None)
else:
a = Action(w)
found = (m.start(), a)
return found[1] if found else None
+438
View File
@@ -0,0 +1,438 @@
"""In-process mock arena implementing just enough of docs/TABLE_API.md to test bots.
REST (stdlib http.server thread) + WebSocket /v1/play (websockets). Each hand is scripted:
the bot sits in seat 0 (UTG) and gets a preflop `your_turn` (facing the BB), then, unless it folds,
a flop `your_turn` (first to act, checking is free). Features: idempotent `act`, `stale_decision`,
`illegal_action`/`bad_amount` errors that re-send the same `your_turn`, `table_seq`/`seq` numbering,
`hello{resume}` -> `table_snapshot` + re-sent pending `your_turn`, optional forced disconnects.
async with MockArena(hands=3) as arena:
...Runner(bot, arena.ws_url, token).run()
"""
from __future__ import annotations
import asyncio
import json
import threading
import time
import uuid
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Dict, List, Optional, Set
from urllib.parse import parse_qs, urlparse
SB, BB, STACK = 50, 100, 10000
HOLE = ["Ah", "Kd"]
FLOP = ["7c", "8d", "2s"]
def _now() -> int:
return int(time.time() * 1000)
class MockArena:
def __init__(self, hands: int = 3, drop_on_turns: Optional[Set[int]] = None, decision_ms: int = 5000,
emit_gap_at: Optional[int] = None, benchmarks: bool = False,
bench_result: tuple = (42.5, 12.0)):
self.hands = hands
self.benchmarks = benchmarks # serve /v1/benchmarks + /runs (scripted run; progress over the bot's socket)
self.bench_result = bench_result # (mbb_per_game, ci95_mbb) of a finished run
self.runs: Dict[str, dict] = {}
self.run_requests: List[dict] = [] # bodies of POST /v1/benchmarks/{track}/runs
self._sockets: Dict[str, Any] = {} # player_id -> live bot websocket
self._loop: Any = None
self.drop_on_turns = set(drop_on_turns or ()) # 1-based counts of your_turn sends after which to drop the socket
self.decision_ms = decision_ms
self.emit_gap_at = emit_gap_at # skip a table_seq number once (tests gap resync)
self.players: Dict[str, dict] = {}
self.tokens: Dict[str, str] = {}
self.tables: Dict[str, dict] = {}
self.received: List[dict] = [] # every envelope the client sent
self.acts: List[dict] = [] # accepted act data
self.errors_sent: List[str] = []
self.hand_ends: List[dict] = []
self.turns_sent = 0
self.connections = 0
self.hand_no = 0
self.phase = "idle" # idle | preflop | flop | finished
self.pending: Optional[dict] = None # your_turn data awaiting an answer
self.answered: Set[str] = set()
self.table_id = "t1"
self.table_seq = 0
self.seq = 0
self._x = 0 # bot's street contribution chosen preflop
self._gap_done = False
self._ws_server: Any = None
self._http: Optional[ThreadingHTTPServer] = None
self.http_url = ""
self.url = "" # REST + WebSocket on ONE port (what `--server` takes)
self.ws_url = ""
self.finished: Optional[asyncio.Event] = None # set in __aenter__
# ------------------------------------------------------------------ lifecycle
async def __aenter__(self) -> "MockArena":
import websockets
self.finished = asyncio.Event()
self._loop = asyncio.get_running_loop()
self._ws_server = await websockets.serve(self._ws_handler, "127.0.0.1", 0)
port = self._ws_server.sockets[0].getsockname()[1]
self.ws_url = f"ws://127.0.0.1:{port}/v1/play"
self._start_http()
self._front = await asyncio.start_server(self._front_handler, "127.0.0.1", 0)
self.url = f"http://127.0.0.1:{self._front.sockets[0].getsockname()[1]}"
return self
async def _front_handler(self, r: asyncio.StreamReader, w: asyncio.StreamWriter) -> None:
"""Single-port front (like the real server): WebSocket upgrades go to the ws server, the rest to REST."""
try:
head = await r.readuntil(b"\r\n\r\n")
ws_port = self._ws_server.sockets[0].getsockname()[1]
port = ws_port if b"upgrade: websocket" in head.lower() else self._http.server_address[1]
ur, uw = await asyncio.open_connection("127.0.0.1", port)
uw.write(head)
async def pipe(src: asyncio.StreamReader, dst: asyncio.StreamWriter) -> None:
try:
while chunk := await src.read(65536):
dst.write(chunk)
await dst.drain()
except (ConnectionError, asyncio.CancelledError):
pass
finally:
dst.close()
await asyncio.gather(pipe(r, uw), pipe(ur, w))
except (asyncio.IncompleteReadError, ConnectionError):
pass
finally:
w.close()
async def __aexit__(self, *exc: Any) -> None:
self._front.close()
self._ws_server.close()
await self._ws_server.wait_closed()
if self._http:
self._http.shutdown()
self._http.server_close()
# ------------------------------------------------------------------ REST
def _start_http(self) -> None:
arena = self
class H(BaseHTTPRequestHandler):
def _send(self, status: int, obj: Any) -> None:
b = json.dumps(obj).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(b)))
self.end_headers()
self.wfile.write(b)
def _err(self, status: int, code: str, msg: str = "") -> None:
self._send(status, {"error": {"code": code, "message": msg, "details": {}}})
def _handle(self, method: str) -> None:
n = int(self.headers.get("Content-Length") or 0)
body = json.loads(self.rfile.read(n)) if n else {}
path = urlparse(self.path).path
parts = [p for p in path.split("/") if p]
if method == "POST" and path == "/v1/players":
pid = "p-" + uuid.uuid4().hex[:8]
tok = "tok-" + uuid.uuid4().hex
rec = {"player_id": pid, "name": body.get("name", ""), "kind": body.get("kind", "bot"),
"created_at": "2026-01-01T00:00:00Z"}
arena.players[pid] = rec
arena.tokens[tok] = pid
return self._send(201, {**rec, "token": tok})
if arena.benchmarks and method == "GET" and path == "/v1/benchmarks":
return self._send(200, [{"track": t, "version": 1, "available": True, "default_hands": 20000,
"panel": [], "seed": f"bench:{t}:v1"} for t in ("ladder-v1", "sharingan-1")])
auth = (self.headers.get("Authorization") or "").replace("Bearer ", "")
if auth not in arena.tokens:
return self._err(401, "unauthorized", "bad token")
if method == "GET" and path == "/v1/me":
return self._send(200, arena.players[arena.tokens[auth]])
if arena.benchmarks and parts[:2] == ["v1", "benchmarks"]:
pid = arena.tokens[auth]
if len(parts) == 4 and parts[3] == "runs" and method == "POST":
if pid not in arena._sockets:
return self._err(409, "not_connected", "connect to /v1/play first")
arena.run_requests.append(body)
return self._send(201, arena._start_run(parts[2], pid, int(body.get("hands") or 20000)))
if len(parts) == 5 and parts[3] == "runs" and method == "GET":
r = arena.runs.get(parts[4])
return self._send(200, dict(r)) if r else self._err(404, "not_found")
if method == "POST" and path == "/v1/tables":
tid = "t-" + uuid.uuid4().hex[:6]
arena.tables[tid] = {"table_id": tid, "config": body, "status": "waiting", "button_seat": None,
"hand_id": None, "table_seq": 0,
"seats": [{"seat": i, "player_id": None, "name": None, "stack": 0, "status": "empty"}
for i in range(6)]}
return self._send(201, arena.tables[tid])
if method == "POST" and path == "/v1/matches":
arena.matches = getattr(arena, "matches", {})
mid = "m-" + uuid.uuid4().hex[:6]
arena.matches[mid] = {"match_id": mid, "participants": body["participants"], "hands_planned": body["hands_planned"],
"status": "scheduled", "hands_played": 0, "duplicate": body.get("duplicate"), "seed": body.get("seed")}
return self._send(201, arena.matches[mid])
if len(parts) == 4 and parts[:2] == ["v1", "matches"] and parts[3] in ("start", "pause", "abort"):
m = arena.matches[parts[2]]
m["status"] = "running"
return self._send(200, m)
if len(parts) == 3 and parts[:2] == ["v1", "matches"] and method == "GET":
m = arena.matches[parts[2]]
m.update(status="finished", hands_played=m["hands_planned"]) # instantly done (CLI tests)
me = m["participants"][0]
return self._send(200, {**m, "standings": [{"player_id": me, "name": "x", "hands": m["hands_played"], "net_chips": 1,
"bb_per_100": 5.0, "mbb_per_hand": 50.0, "ci95_bb_per_100": 2.5, "duplicate_bb_per_100": 4.0}]})
if len(parts) == 3 and parts[:2] == ["v1", "tables"] and method == "GET":
t = arena.tables.get(parts[2])
return self._send(200, t) if t else self._err(404, "not_found")
if len(parts) == 5 and parts[:2] == ["v1", "tables"] and parts[3] == "seats":
t = arena.tables.get(parts[2])
if not t:
return self._err(404, "not_found")
seat = t["seats"][int(parts[4])]
if method == "POST":
if seat["player_id"]:
return self._err(409, "seat_taken")
pl = arena.players[body["player_id"]]
seat.update(player_id=pl["player_id"], name=pl["name"], stack=STACK, status="seated")
return self._send(200, seat)
if method == "DELETE":
seat.update(player_id=None, name=None, stack=0, status="empty")
return self._send(200, seat)
self._err(404, "not_found")
def do_GET(self) -> None: self._handle("GET") # noqa: E701,N802
def do_POST(self) -> None: self._handle("POST") # noqa: E701,N802
def do_DELETE(self) -> None: self._handle("DELETE") # noqa: E701,N802
def log_message(self, *a: Any) -> None: pass # noqa: E701
self._http = ThreadingHTTPServer(("127.0.0.1", 0), H)
self.http_url = f"http://127.0.0.1:{self._http.server_address[1]}"
threading.Thread(target=self._http.serve_forever, daemon=True).start()
# ------------------------------------------------------------------ benchmark runs
def _start_run(self, track: str, player_id: str, hands: int) -> dict:
total = (hands + 5) // 6 * 6
rid = "r-" + uuid.uuid4().hex[:6]
run = {"run_id": rid, "track": track, "player_id": player_id, "status": "running", "hands_planned": total,
"hands_total": total, "hands_done": 0, "verified": False, "mbb_per_game": None, "ci95_mbb": None,
"method": None, "running_mbb_per_game": None, "running_ci95_mbb": None}
self.runs[rid] = run
asyncio.run_coroutine_threadsafe(self._play_run(run), self._loop)
return dict(run)
async def _play_run(self, run: dict) -> None:
"""Scripted run: benchmark_progress at 25/50/75% then a final 100% (status finished)."""
total, (mbb, ci) = run["hands_total"], self.bench_result
for step in (1, 2, 3, 4):
await asyncio.sleep(0.1)
last = step == 4
done = total if last else total * step // 4
if last:
run.update(status="finished", mbb_per_game=mbb, ci95_mbb=ci, method="aivat")
run["hands_done"] = done
run.update(running_mbb_per_game=mbb * done / total, running_ci95_mbb=ci)
ws = self._sockets.get(run["player_id"])
if ws is not None:
data = {"run_id": run["run_id"], "track": run["track"], "match_id": "m-bench", "status": run["status"],
"hands_done": done, "hands_total": total, "mbb_per_game": run["mbb_per_game"] if last else None,
"ci95_mbb": ci if last else None, "method": run["method"], "verified": False}
try:
await ws.send(json.dumps({"v": 1, "type": "benchmark_progress", "t_ms": _now(), "data": data}))
except Exception:
pass
# ------------------------------------------------------------------ WS
def _env(self, type_: str, data: dict, hand: bool = True, with_seq: bool = True) -> str:
self.table_seq += 1
if self.emit_gap_at and self.table_seq == self.emit_gap_at and not self._gap_done:
self._gap_done = True
self.table_seq += 1 # simulate a lost message
env: Dict[str, Any] = {"v": 1, "type": type_, "table_id": self.table_id, "table_seq": self.table_seq,
"t_ms": _now(), "data": data}
if hand and self.hand_no:
env["hand_id"] = f"h-{self.hand_no}"
if with_seq:
self.seq += 1
env["seq"] = self.seq
data.setdefault("seq", self.seq)
return json.dumps(env)
async def _ws_handler(self, ws: Any) -> None:
path = getattr(getattr(ws, "request", None), "path", None) or getattr(ws, "path", "")
token = (parse_qs(urlparse(path).query).get("token") or [""])[0]
if token not in self.tokens and not token.startswith("any"):
await ws.close(4401, "unauthorized")
return
self.connections += 1
self.player_id = self.tokens.get(token, "p0")
self._sockets[self.player_id] = ws
try:
async for raw in ws:
msg = json.loads(raw)
self.received.append(msg)
t = msg.get("type")
if t == "hello":
await self._on_hello(ws, msg)
elif t == "ping":
await ws.send(json.dumps({"v": 1, "type": "pong", "t_ms": _now(), "data": {}}))
elif t == "act":
await self._on_act(ws, msg["data"])
except Exception as e: # connection closed etc.
if self._sockets.get(self.player_id) is ws:
del self._sockets[self.player_id]
if type(e).__name__ not in ("ConnectionClosedOK", "ConnectionClosedError", "ConnectionClosed"):
raise
async def _on_hello(self, ws: Any, msg: dict) -> None:
await ws.send(json.dumps({"v": 1, "type": "welcome", "t_ms": _now(),
"data": {"player_id": self.player_id, "name": "bot", "server_time": _now(),
"tables": [self.table_id], "protocol": 1}}))
seats = [{"seat": i, "player_id": self.player_id if i == 0 else f"other{i}", "name": f"s{i}",
"stack": STACK, "status": "seated"} for i in range(6)]
snap = {"table_id": self.table_id, "config": {"small_blind": SB, "big_blind": BB, "starting_stack": STACK},
"status": "running", "seats": seats, "button_seat": 3, "hand_id": f"h-{self.hand_no}" if self.hand_no else None,
"table_seq": self.table_seq, "hand": None}
await ws.send(json.dumps({"v": 1, "type": "table_snapshot", "table_id": self.table_id,
"table_seq": self.table_seq, "t_ms": _now(), "data": snap}))
if self.phase == "idle":
await self._start_hand(ws)
elif self.pending:
await self._send_turn(ws) # same decision_id (conformance #7)
def _players(self, street_contrib: Dict[int, int], status: Optional[Dict[int, str]] = None) -> List[dict]:
out = []
for s in range(6):
c = street_contrib.get(s, 0)
out.append({"seat": s, "name": f"s{s}", "stack_start": STACK, "stack": STACK - c, "street_contrib": c,
"hand_contrib": c, "status": (status or {}).get(s, "active")})
return out
def _action_ev(self, seat: int, type_: str, to: int, added: int, stack: int, pot: int, street: str,
forced: bool = False, nxt: Optional[int] = None) -> dict:
self.seq += 1
return {"hand_id": f"h-{self.hand_no}", "seq": self.seq, "action_id": f"a-{self.hand_no}-{self.seq}",
"street": street, "seat": seat, "type": type_, "to": to, "added": added, "all_in": False,
"forced": forced, "timeout": False, "stack": stack, "pot": pot,
"current_bet": to if type_ != "fold" else BB, "min_raise_to": 2 * BB, "next_to_act": nxt}
async def _start_hand(self, ws: Any) -> None:
self.hand_no += 1
self.seq = 0
self.phase = "preflop"
self.answered.clear()
hs = {"hand_id": f"h-{self.hand_no}", "hand_no": self.hand_no, "match_id": "m1", "deal_no": None,
"rotation": None, "button_seat": 3, "sb_seat": 4, "bb_seat": 5, "small_blind": SB, "big_blind": BB,
"ante": 0, "players": [{"seat": i, "player_id": self.player_id if i == 0 else f"other{i}",
"name": f"s{i}", "stack_start": STACK, "in_hand": True} for i in range(6)],
"deck_commitment": "00" * 32}
await ws.send(self._env("hand_start", hs, with_seq=False))
await ws.send(self._env("hole_cards", {"hand_id": f"h-{self.hand_no}", "seat": 0, "cards": HOLE}, with_seq=False))
self.history = [self._action_ev(4, "post_sb", SB, SB, STACK - SB, SB, "preflop", True, 5),
self._action_ev(5, "post_bb", BB, BB, STACK - BB, SB + BB, "preflop", True, 0)]
for ev in self.history:
await ws.send(self._env("action", dict(ev), with_seq=False))
self.pending = self._turn("preflop", [], {4: SB, 5: BB}, pot=SB + BB, call={"to": BB, "added": BB, "all_in": False},
check=False, raise_={"min_to": 2 * BB, "max_to": STACK})
await self._send_turn(ws)
def _turn(self, street: str, board: List[str], contrib: Dict[int, int], pot: int, call: Optional[dict],
check: bool, raise_: dict) -> dict:
self.seq += 1
return {"hand_id": f"h-{self.hand_no}", "seq": self.seq, "decision_id": f"d-{self.hand_no}-{self.seq}",
"seat": 0, "street": street, "hole_cards": HOLE, "board": board, "history": list(self.history),
"players": self._players(contrib), "button_seat": 3, "small_blind": SB, "big_blind": BB, "pot": pot,
"pots": [{"amount": pot, "eligible_seats": [0, 4, 5]}],
"legal": {"fold": True, "check": check, "call": call, "raise": raise_},
"deadline_ms": _now() + self.decision_ms, "time_bank_ms": 30000}
async def _send_turn(self, ws: Any) -> None:
assert self.pending is not None
self.pending["deadline_ms"] = _now() + self.decision_ms
self.turns_sent += 1
env = json.loads(self._env("your_turn", dict(self.pending), with_seq=False))
env["seq"] = self.pending["seq"]
await ws.send(json.dumps(env))
if self.turns_sent in self.drop_on_turns:
self.drop_on_turns.discard(self.turns_sent)
await ws.close()
async def _err(self, ws: Any, code: str, msg: str, decision_id: Optional[str] = None, details: Optional[dict] = None) -> None:
self.errors_sent.append(code)
d: Dict[str, Any] = {"code": code, "message": msg, "details": details or {}}
if decision_id:
d["decision_id"] = decision_id
await ws.send(self._env("error", d, hand=False))
async def _on_act(self, ws: Any, d: dict) -> None:
p = self.pending
if p is None or d.get("hand_id") != p["hand_id"]:
return await self._err(ws, "not_your_turn", "no pending turn")
if d.get("decision_id") in self.answered:
return # idempotent duplicate
if d.get("decision_id") != p["decision_id"]:
return await self._err(ws, "stale_decision", "stale", d.get("decision_id"))
t, to, legal = d.get("type"), d.get("to"), p["legal"]
ok = (t == "fold" and legal["fold"]) or (t == "check" and legal["check"]) or (t == "call" and legal["call"]) \
or (t in ("raise", "bet") and legal["raise"])
if not ok:
await self._err(ws, "illegal_action", f"{t} not legal", p["decision_id"])
return await self._send_turn(ws)
if t in ("raise", "bet"):
r = legal["raise"]
if not isinstance(to, int) or not (r["min_to"] <= to <= r["max_to"]):
await self._err(ws, "bad_amount", "to out of range", p["decision_id"], {"min_to": r["min_to"], "max_to": r["max_to"]})
return await self._send_turn(ws)
self.answered.add(p["decision_id"])
self.acts.append(d)
self.pending = None
street = p["street"]
if t == "fold" and legal["check"]:
t = "check" # converted (§6.6 preferred behaviour)
contrib_to = {"fold": 0, "check": 0, "call": legal["call"]["to"] if legal["call"] else 0}.get(t, to)
added = contrib_to if street == "preflop" else contrib_to
ev = self._action_ev(0, t, contrib_to, added, STACK - contrib_to, p["pot"] + added, street, nxt=None)
self.history.append(ev)
await ws.send(self._env("action", dict(ev), with_seq=False))
if street == "preflop":
if t == "fold":
return await self._end_hand(ws, [4, 5], "fold", bot_net=0, bb_wins=True)
self._x = contrib_to
pot = 2 * self._x + SB # SB folds, BB calls
board = FLOP
await ws.send(self._env("street", {"hand_id": f"h-{self.hand_no}", "street": "flop", "board": board,
"new_cards": board, "pot": pot, "pots": [{"amount": pot, "eligible_seats": [0, 5]}]},
with_seq=False))
self.phase = "flop"
self.pending = self._turn("flop", board, {}, pot=pot, call=None, check=True,
raise_={"min_to": BB, "max_to": STACK - self._x})
await self._send_turn(ws)
else:
if t in ("raise", "bet"): # BB folds
return await self._end_hand(ws, [5], "fold", bot_net=self._x + SB, bb_wins=False)
win = self.hand_no % 2 == 1
await self._end_hand(ws, [0, 5], "showdown", bot_net=self._x if win else -self._x, bb_wins=not win)
async def _end_hand(self, ws: Any, seats: List[int], ended_by: str, bot_net: int, bb_wins: bool) -> None:
# nets: SB always -50; bot + bb absorb the rest so that sum == 0
bb_net = SB - bot_net
results = [{"seat": 0, "player_id": self.player_id, "net": bot_net, "stack_end": STACK + bot_net},
{"seat": 4, "player_id": "other4", "net": -SB, "stack_end": STACK - SB},
{"seat": 5, "player_id": "other5", "net": bb_net, "stack_end": STACK + bb_net}]
data = {"hand_id": f"h-{self.hand_no}", "board": FLOP + ["3h", "9c"],
"showdown": [{"seat": 0, "cards": HOLE, "shown": ended_by == "showdown", "hand_rank": "high card", "best5": []}]
if ended_by == "showdown" else [],
"hole_cards": {str(i): (HOLE if i == 0 else ["2c", "3d"]) for i in range(6)},
"pots": [{"amount": 2 * self._x + SB, "eligible_seats": [0, 5], "winners": [0 if bot_net > 0 else 5],
"share": [2 * self._x + SB]}],
"results": results, "deck_reveal": {"deck": [], "salt": "x"}, "ended_by": ended_by}
self.hand_ends.append(data)
await ws.send(self._env("hand_end", data, with_seq=True))
self.phase = "idle"
if self.hand_no >= self.hands:
self.phase = "finished"
if self.finished:
self.finished.set()
return
await self._start_hand(ws)
+405
View File
@@ -0,0 +1,405 @@
"""Typed models for every payload in docs/TABLE_API.md (stdlib dataclasses only).
All `from_dict` constructors are tolerant: unknown keys are ignored and missing
optional keys fall back to defaults, so a server adding fields never breaks a bot.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
Card = str # "Ah", "Td", "2c"
STREETS = ("preflop", "flop", "turn", "river")
@dataclass
class CallOption:
to: int
added: int
all_in: bool = False
@classmethod
def from_dict(cls, d: Optional[dict]) -> Optional["CallOption"]:
if not d:
return None
return cls(to=int(d["to"]), added=int(d.get("added", 0)), all_in=bool(d.get("all_in", False)))
@dataclass
class RaiseOption:
min_to: int
max_to: int
@classmethod
def from_dict(cls, d: Optional[dict]) -> Optional["RaiseOption"]:
if not d:
return None
return cls(min_to=int(d["min_to"]), max_to=int(d["max_to"]))
@dataclass
class Legal:
fold: bool = True
check: bool = False
call: Optional[CallOption] = None
raise_: Optional[RaiseOption] = None # `raise` is a keyword; JSON key is "raise"
@classmethod
def from_dict(cls, d: dict) -> "Legal":
return cls(
fold=bool(d.get("fold", True)),
check=bool(d.get("check", False)),
call=CallOption.from_dict(d.get("call")),
raise_=RaiseOption.from_dict(d.get("raise")),
)
@dataclass
class ActionEvent:
hand_id: str = ""
seq: int = 0
action_id: str = ""
street: str = "preflop"
seat: int = 0
type: str = ""
to: int = 0
added: int = 0
all_in: bool = False
forced: bool = False
timeout: bool = False
stack: int = 0
pot: int = 0
current_bet: int = 0
min_raise_to: int = 0
next_to_act: Optional[int] = None
@classmethod
def from_dict(cls, d: dict) -> "ActionEvent":
return cls(
hand_id=d.get("hand_id", ""), seq=int(d.get("seq", 0)), action_id=d.get("action_id", ""),
street=d.get("street", "preflop"), seat=int(d.get("seat", 0)), type=d.get("type", ""),
to=int(d.get("to", 0)), added=int(d.get("added", 0)), all_in=bool(d.get("all_in", False)),
forced=bool(d.get("forced", False)), timeout=bool(d.get("timeout", False)),
stack=int(d.get("stack", 0)), pot=int(d.get("pot", 0)), current_bet=int(d.get("current_bet", 0)),
min_raise_to=int(d.get("min_raise_to", 0)), next_to_act=d.get("next_to_act"),
)
@dataclass
class PlayerState:
seat: int
name: str = ""
stack_start: int = 0
stack: int = 0
street_contrib: int = 0
hand_contrib: int = 0
status: str = "active" # active | folded | all_in | out
@classmethod
def from_dict(cls, d: dict) -> "PlayerState":
return cls(seat=int(d["seat"]), name=d.get("name", ""), stack_start=int(d.get("stack_start", 0)),
stack=int(d.get("stack", 0)), street_contrib=int(d.get("street_contrib", 0)),
hand_contrib=int(d.get("hand_contrib", 0)), status=d.get("status", "active"))
@dataclass
class Pot:
amount: int
eligible_seats: List[int] = field(default_factory=list)
winners: List[int] = field(default_factory=list) # hand_end only
share: List[int] = field(default_factory=list) # hand_end only
@classmethod
def from_dict(cls, d: dict) -> "Pot":
return cls(amount=int(d["amount"]), eligible_seats=list(d.get("eligible_seats", [])),
winners=list(d.get("winners", [])), share=list(d.get("share", [])))
@dataclass
class YourTurn:
"""The decision state handed to `Bot.act`. Convenience helpers live in `sharingan.helpers`
and are also exposed as properties/methods here."""
hand_id: str = ""
seq: int = 0
decision_id: str = ""
seat: int = 0
street: str = "preflop"
hole_cards: List[Card] = field(default_factory=list)
board: List[Card] = field(default_factory=list)
history: List[ActionEvent] = field(default_factory=list)
players: List[PlayerState] = field(default_factory=list)
button_seat: int = 0
small_blind: int = 0
big_blind: int = 0
pot: int = 0
pots: List[Pot] = field(default_factory=list)
legal: Legal = field(default_factory=Legal)
deadline_ms: int = 0
time_bank_ms: int = 0
table_id: str = "" # from the envelope
t_ms: int = 0 # from the envelope
@classmethod
def from_dict(cls, d: dict, table_id: str = "", t_ms: int = 0, hand_id: str = "", seq: int = 0) -> "YourTurn":
"""`hand_id`/`seq` fall back to the envelope values (the doc example only carries them on the envelope)."""
return cls(
hand_id=d.get("hand_id") or hand_id, seq=int(d.get("seq") or seq or 0), decision_id=d.get("decision_id", ""),
seat=int(d.get("seat", 0)), street=d.get("street", "preflop"),
hole_cards=list(d.get("hole_cards", [])), board=list(d.get("board", [])),
history=[ActionEvent.from_dict(a) for a in d.get("history", [])],
players=[PlayerState.from_dict(p) for p in d.get("players", [])],
button_seat=int(d.get("button_seat", 0)), small_blind=int(d.get("small_blind", 0)),
big_blind=int(d.get("big_blind", 0)), pot=int(d.get("pot", 0)),
pots=[Pot.from_dict(p) for p in d.get("pots", [])],
legal=Legal.from_dict(d.get("legal", {})), deadline_ms=int(d.get("deadline_ms", 0)),
time_bank_ms=int(d.get("time_bank_ms", 0)), table_id=d.get("table_id", table_id), t_ms=t_ms,
)
# --- convenience (thin wrappers; logic in helpers.py) ---
@property
def me(self) -> Optional[PlayerState]:
for p in self.players:
if p.seat == self.seat:
return p
return None
@property
def to_call(self) -> int:
"""Chips needed to call (0 if checking is free)."""
return self.legal.call.added if self.legal.call else 0
@property
def can_check(self) -> bool:
return self.legal.check
@property
def can_raise(self) -> bool:
return self.legal.raise_ is not None
@property
def min_raise_to(self) -> Optional[int]:
return self.legal.raise_.min_to if self.legal.raise_ else None
@property
def max_raise_to(self) -> Optional[int]:
return self.legal.raise_.max_to if self.legal.raise_ else None
@property
def pot_odds(self) -> float:
"""Fraction of the final pot you must put in to call: to_call / (pot + to_call)."""
tc = self.to_call
return tc / (self.pot + tc) if tc > 0 else 0.0
@property
def stack(self) -> int:
m = self.me
return m.stack if m else 0
@property
def num_active(self) -> int:
return sum(1 for p in self.players if p.status in ("active", "all_in"))
def seconds_left(self, now_ms: Optional[int] = None) -> float:
import time
now = now_ms if now_ms is not None else int(time.time() * 1000)
return (self.deadline_ms - now) / 1000.0
@dataclass
class HandStartPlayer:
seat: int
player_id: str = ""
name: str = ""
stack_start: int = 0
in_hand: bool = True
@dataclass
class HandStart:
hand_id: str = ""
hand_no: int = 0
match_id: Optional[str] = None
deal_no: Optional[int] = None
rotation: Optional[int] = None
button_seat: int = 0
sb_seat: int = 0
bb_seat: int = 0
small_blind: int = 0
big_blind: int = 0
ante: int = 0
players: List[HandStartPlayer] = field(default_factory=list)
deck_commitment: str = ""
@classmethod
def from_dict(cls, d: dict) -> "HandStart":
return cls(
hand_id=d.get("hand_id", ""), hand_no=int(d.get("hand_no", 0)), match_id=d.get("match_id"),
deal_no=d.get("deal_no"), rotation=d.get("rotation"), button_seat=int(d.get("button_seat", 0)),
sb_seat=int(d.get("sb_seat", 0)), bb_seat=int(d.get("bb_seat", 0)),
small_blind=int(d.get("small_blind", 0)), big_blind=int(d.get("big_blind", 0)),
ante=int(d.get("ante", 0)),
players=[HandStartPlayer(seat=int(p["seat"]), player_id=p.get("player_id", ""), name=p.get("name", ""),
stack_start=int(p.get("stack_start", 0)), in_hand=bool(p.get("in_hand", True)))
for p in d.get("players", [])],
deck_commitment=d.get("deck_commitment", ""),
)
@dataclass
class StreetEvent:
hand_id: str = ""
street: str = ""
board: List[Card] = field(default_factory=list)
new_cards: List[Card] = field(default_factory=list)
pot: int = 0
pots: List[Pot] = field(default_factory=list)
@classmethod
def from_dict(cls, d: dict) -> "StreetEvent":
return cls(hand_id=d.get("hand_id", ""), street=d.get("street", ""), board=list(d.get("board", [])),
new_cards=list(d.get("new_cards", [])), pot=int(d.get("pot", 0)),
pots=[Pot.from_dict(p) for p in d.get("pots", [])])
@dataclass
class ShowdownEntry:
seat: int
cards: List[Card] = field(default_factory=list)
shown: bool = False
hand_rank: str = ""
best5: List[Card] = field(default_factory=list)
@dataclass
class SeatResult:
seat: int
player_id: str = ""
net: int = 0
stack_end: int = 0
@dataclass
class HandEnd:
hand_id: str = ""
seq: int = 0
board: List[Card] = field(default_factory=list)
showdown: List[ShowdownEntry] = field(default_factory=list)
hole_cards: Dict[int, List[Card]] = field(default_factory=dict) # every dealt player
pots: List[Pot] = field(default_factory=list)
results: List[SeatResult] = field(default_factory=list)
deck_reveal: Dict[str, Any] = field(default_factory=dict)
ended_by: str = "showdown"
@classmethod
def from_dict(cls, d: dict) -> "HandEnd":
return cls(
hand_id=d.get("hand_id", ""), seq=int(d.get("seq", 0)), board=list(d.get("board", [])),
showdown=[ShowdownEntry(seat=int(s["seat"]), cards=list(s.get("cards", [])), shown=bool(s.get("shown", False)),
hand_rank=s.get("hand_rank", ""), best5=list(s.get("best5", [])))
for s in d.get("showdown", [])],
# JSON object keys are strings -> normalise to int seats
hole_cards={int(k): list(v) for k, v in (d.get("hole_cards") or {}).items()},
pots=[Pot.from_dict(p) for p in d.get("pots", [])],
results=[SeatResult(seat=int(r["seat"]), player_id=r.get("player_id", ""), net=int(r.get("net", 0)),
stack_end=int(r.get("stack_end", 0))) for r in d.get("results", [])],
deck_reveal=d.get("deck_reveal") or {}, ended_by=d.get("ended_by", "showdown"),
)
def net_for(self, seat: int) -> int:
for r in self.results:
if r.seat == seat:
return r.net
return 0
@dataclass
class ApiError:
code: str
message: str = ""
decision_id: Optional[str] = None
details: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls, d: dict) -> "ApiError":
return cls(code=d.get("code", "internal"), message=d.get("message", ""),
decision_id=d.get("decision_id"), details=d.get("details") or {})
@dataclass
class Seat:
seat: int
player_id: Optional[str] = None
name: Optional[str] = None
stack: int = 0
status: str = "empty"
@classmethod
def from_dict(cls, d: dict) -> "Seat":
return cls(seat=int(d["seat"]), player_id=d.get("player_id"), name=d.get("name"),
stack=int(d.get("stack", 0)), status=d.get("status", "empty"))
@dataclass
class Table:
table_id: str
config: Dict[str, Any] = field(default_factory=dict)
status: str = "waiting"
seats: List[Seat] = field(default_factory=list)
button_seat: Optional[int] = None
hand_id: Optional[str] = None
table_seq: int = 0
hand: Optional[Dict[str, Any]] = None # raw HandState from table_snapshot / GET table
raw: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls, d: dict) -> "Table":
return cls(table_id=d.get("table_id", ""), config=d.get("config") or {}, status=d.get("status", "waiting"),
seats=[Seat.from_dict(s) for s in d.get("seats", [])], button_seat=d.get("button_seat"),
hand_id=d.get("hand_id"), table_seq=int(d.get("table_seq", 0)), hand=d.get("hand"), raw=d)
@dataclass
class PlayerInfo:
player_id: str
name: str = ""
kind: str = "bot"
token: Optional[str] = None # only returned on creation
raw: Dict[str, Any] = field(default_factory=dict)
@classmethod
def from_dict(cls, d: dict) -> "PlayerInfo":
return cls(player_id=d.get("player_id", ""), name=d.get("name", ""), kind=d.get("kind", "bot"),
token=d.get("token"), raw=d)
@dataclass
class Action:
"""What a bot returns. `to` is the TOTAL street contribution after the action ("to", never "by")."""
type: str
to: Optional[int] = None
@staticmethod
def fold() -> "Action":
return Action("fold")
@staticmethod
def check() -> "Action":
return Action("check")
@staticmethod
def call() -> "Action":
return Action("call")
@staticmethod
def raise_to(to: int) -> "Action":
return Action("raise", int(to))
@staticmethod
def bet(to: int) -> "Action":
return Action("bet", int(to))
def to_data(self, hand_id: str, decision_id: str) -> Dict[str, Any]:
d: Dict[str, Any] = {"hand_id": hand_id, "decision_id": decision_id, "type": self.type}
if self.to is not None and self.type in ("raise", "bet", "call"):
d["to"] = int(self.to)
return d
+124
View File
@@ -0,0 +1,124 @@
"""Pipe runner: run a `Bot` as a subprocess of the match worker, talking newline-delimited JSON over stdin/stdout.
sharingan-arena run --bot "sharingan pipe mybot.py" --track ladder-v1 --hands 20000 --lanes 8 --out result.json
The messages are the WebSocket protocol's own (`your_turn`, `hand_end`, `act`, ...), one JSON object per line
(docs/TABLE_API.md section 14). The same `mybot.py` runs unchanged over WebSocket, webhook and pipe.
stdout belongs to the protocol: `claim_stdio()` keeps the real stdout for it and points fd 1 (and `sys.stdout`) at
stderr, so a stray `print()` in your bot cannot corrupt the stream.
"""
from __future__ import annotations
import asyncio
import inspect
import json
import os
import sys
import traceback
from typing import Any, BinaryIO, Optional, Tuple
from .bot import Bot
from .helpers import legalize, safe_action
from .models import Action, ApiError, HandEnd, YourTurn
PIPE_PROTOCOL = 1
CLIENT_NAME = "sharingan-py-pipe/0.1.0"
_dumps = json.JSONEncoder(separators=(",", ":")).encode
_loads = json.loads
def claim_stdio() -> Tuple[BinaryIO, BinaryIO]:
"""Return (reader, writer) for the protocol and redirect everything else that writes to stdout to stderr."""
out = os.fdopen(os.dup(1), "wb", buffering=0)
os.dup2(2, 1)
sys.stdout = sys.stderr
return sys.stdin.buffer, out
def _overrides(bot: Bot, hook: str) -> bool:
return getattr(type(bot), hook, None) is not getattr(Bot, hook, None) or hook in vars(bot)
class PipeRunner:
def __init__(self, bot: Bot, rfile: BinaryIO, wfile: BinaryIO):
self.bot, self.r, self.w = bot, rfile, wfile
self._loop: Optional[asyncio.AbstractEventLoop] = None
self._want_end = _overrides(bot, "on_hand_end")
self._want_error = _overrides(bot, "on_error")
self.decisions = 0
def send(self, type_: str, data: dict, table_id: Optional[str] = None) -> None:
env: dict = {"v": 1, "type": type_}
if table_id:
env["table_id"] = table_id
env["data"] = data
self.w.write((_dumps(env) + "\n").encode())
def _call(self, fn: Any, *args: Any) -> Any:
res = fn(*args)
if inspect.isawaitable(res):
if self._loop is None:
self._loop = asyncio.new_event_loop()
res = self._loop.run_until_complete(res)
return res
def _hook(self, fn: Any, *args: Any) -> None:
try:
self._call(fn, *args)
except Exception:
traceback.print_exc(file=sys.stderr)
def run(self) -> int:
bot = self.bot
self.send("hello", {"client": CLIENT_NAME, "protocol": PIPE_PROTOCOL, "bot": getattr(bot, "name", "bot")})
for line in self.r:
if not line.strip():
continue
try:
env = _loads(line)
except ValueError:
continue
t = env.get("type")
if t == "your_turn":
self._turn(env)
elif t == "hand_end":
if self._want_end:
self._hook(bot.on_hand_end, HandEnd.from_dict(env.get("data") or {}))
elif t == "welcome":
self._hook(bot.on_connect, env.get("data") or {})
elif t == "error":
if self._want_error:
self._hook(bot.on_error, ApiError.from_dict(env.get("data") or {}))
elif t == "bye":
self.send("bye", {})
return 0
return 0
def _turn(self, env: dict) -> None:
d = env.get("data") or {}
state = YourTurn.from_dict(d, table_id=env.get("table_id", ""), t_ms=int(env.get("t_ms") or 0),
hand_id=env.get("hand_id", ""), seq=int(env.get("seq") or 0))
self.decisions += 1
action: Any = None
try:
action = self._call(self.bot.act, state)
except Exception:
print("sharingan pipe: bot.act raised; playing check/fold", file=sys.stderr)
traceback.print_exc(file=sys.stderr)
if not isinstance(action, Action):
action = safe_action(state)
elif not getattr(self.bot, "strict", False):
action = legalize(state, action)
self.send("act", action.to_data(state.hand_id, state.decision_id), state.table_id or None)
def run_pipe(bot: Bot, rfile: Optional[BinaryIO] = None, wfile: Optional[BinaryIO] = None) -> int:
"""Serve `bot` over the pipe protocol until `bye` or EOF. Returns the exit code."""
if rfile is None or wfile is None:
rfile, wfile = claim_stdio()
try:
return PipeRunner(bot, rfile, wfile).run()
except (BrokenPipeError, KeyboardInterrupt):
return 0
+75
View File
@@ -0,0 +1,75 @@
"""Webhook mode (§11): stateless bots answer `your_turn` POSTs. stdlib http.server, no extra deps."""
from __future__ import annotations
import hashlib
import hmac
import json
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from typing import Any, Optional, Tuple
from .bot import Bot
from .helpers import legalize, safe_action
from .models import Action, YourTurn
def sign(secret: str, body: bytes) -> str:
return "sha256=" + hmac.new(secret.encode(), body, hashlib.sha256).hexdigest()
def verify(secret: str, body: bytes, header: Optional[str]) -> bool:
return bool(header) and hmac.compare_digest(sign(secret, body), header) # type: ignore[arg-type]
def handle_webhook(bot: Bot, body: bytes, signature: Optional[str] = None, secret: Optional[str] = None) -> Tuple[int, bytes]:
"""Pure function: (status, response body) for a POSTed envelope. Framework-agnostic (Flask/FastAPI/...)."""
if secret is not None and not verify(secret, body, signature):
return 401, b'{"error":{"code":"unauthorized","message":"bad signature"}}'
env = json.loads(body)
if env.get("type") != "your_turn":
return 200, b"{}"
state = YourTurn.from_dict(env.get("data") or {}, table_id=env.get("table_id", ""), t_ms=int(env.get("t_ms") or 0),
hand_id=env.get("hand_id") or "", seq=int(env.get("seq") or 0))
try:
a = bot.act(state)
if not isinstance(a, Action):
a = safe_action(state)
elif not bot.strict:
a = legalize(state, a)
except Exception:
a = safe_action(state)
return 200, json.dumps(a.to_data(state.hand_id, state.decision_id)).encode()
def serve_webhook(bot: Bot, host: str = "0.0.0.0", port: int = 8000, secret: Optional[str] = None,
path: str = "/act", block: bool = True) -> ThreadingHTTPServer:
"""Serve `POST {path}` (your_turn -> act) and `POST /events` (fire-and-forget events)."""
class H(BaseHTTPRequestHandler):
def do_POST(self) -> None: # noqa: N802
n = int(self.headers.get("Content-Length") or 0)
body = self.rfile.read(n)
if self.path.rstrip("/") == path.rstrip("/"):
# the server sends X-Sharingan-Signature; the older X-Signature is still accepted
sig = self.headers.get("X-Sharingan-Signature") or self.headers.get("X-Signature")
status, out = handle_webhook(bot, body, sig, secret)
else:
status, out = 200, b"{}"
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(out)))
self.end_headers()
self.wfile.write(out)
def log_message(self, *a: Any) -> None:
pass
srv = ThreadingHTTPServer((host, port), H)
if block:
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
else:
threading.Thread(target=srv.serve_forever, daemon=True).start()
return srv
+56
View File
@@ -0,0 +1,56 @@
import json
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
import pytest
@pytest.fixture(autouse=True)
def _isolated_tokens(tmp_path, monkeypatch):
# The CLI saves bot tokens in ~/.config/sharingan; keep tests out of the real home.
import sharingan.cli
monkeypatch.setattr(sharingan.cli, "TOKENS_FILE", str(tmp_path / "tokens.json"))
monkeypatch.setattr(sharingan.cli, "OWNER_FILE", str(tmp_path / "owner.json"))
monkeypatch.delenv("SHARINGAN_CONTACT", raising=False)
monkeypatch.delenv("SHARINGAN_PROFILE", raising=False)
from sharingan.models import YourTurn
# The worked example from docs/TABLE_API.md section 5.3 (seat 0 on the flop, facing a check)
DOC_YOUR_TURN = {
"v": 1, "type": "your_turn", "table_id": "t1", "hand_id": "h-77", "seq": 9, "t_ms": 1792000000000,
"data": {
"decision_id": "d-77-9", "seat": 0, "street": "flop", "hole_cards": ["Ah", "Kd"], "board": ["7c", "8d", "2s"],
"history": [
{"seq": 1, "street": "preflop", "seat": 4, "type": "post_sb", "to": 50, "added": 50, "all_in": False, "forced": True, "timeout": False, "stack": 9950, "pot": 50, "current_bet": 50, "min_raise_to": 100, "next_to_act": 5},
{"seq": 2, "street": "preflop", "seat": 5, "type": "post_bb", "to": 100, "added": 100, "all_in": False, "forced": True, "timeout": False, "stack": 9900, "pot": 150, "current_bet": 100, "min_raise_to": 200, "next_to_act": 0},
{"seq": 3, "street": "preflop", "seat": 0, "type": "raise", "to": 250, "added": 250, "all_in": False, "forced": False, "timeout": False, "stack": 9750, "pot": 400, "current_bet": 250, "min_raise_to": 400, "next_to_act": 1},
{"seq": 8, "street": "flop", "seat": 5, "type": "check", "to": 0, "added": 0, "all_in": False, "forced": False, "timeout": False, "stack": 9750, "pot": 550, "current_bet": 0, "min_raise_to": 100, "next_to_act": 0},
],
"players": [
{"seat": 0, "name": "pluribus", "stack_start": 10000, "stack": 9750, "street_contrib": 0, "hand_contrib": 250, "status": "active"},
{"seat": 5, "name": "erin", "stack_start": 10000, "stack": 9750, "street_contrib": 0, "hand_contrib": 250, "status": "active"},
],
"button_seat": 3, "small_blind": 50, "big_blind": 100, "pot": 550,
"pots": [{"amount": 550, "eligible_seats": [0, 5]}],
"legal": {"fold": True, "check": True, "call": None, "raise": {"min_to": 100, "max_to": 9750}},
"deadline_ms": 1792000005000, "time_bank_ms": 30000,
},
}
def doc_state() -> YourTurn:
return YourTurn.from_dict(DOC_YOUR_TURN["data"], table_id="t1", t_ms=DOC_YOUR_TURN["t_ms"])
def facing_bet_state(**over) -> YourTurn:
d = json.loads(json.dumps(DOC_YOUR_TURN["data"]))
d["pot"] = 750
d["players"][0]["street_contrib"] = 0
d["players"][1]["street_contrib"] = 200
d["legal"] = {"fold": True, "check": False, "call": {"to": 200, "added": 200, "all_in": False},
"raise": {"min_to": 400, "max_to": 9750}}
d.update(over)
return YourTurn.from_dict(d, table_id="t1", t_ms=1792000000000)
+69
View File
@@ -0,0 +1,69 @@
import json
import random
from conftest import DOC_YOUR_TURN
from sharingan import Action, YourTurn
from sharingan.bots import CallingStation, LLMBot, RandomBot, TightAggressive
from sharingan.helpers import is_legal
CARDS = [r + s for r in "23456789TJQKA" for s in "cdhs"]
def random_state(rng: random.Random) -> YourTurn:
d = json.loads(json.dumps(DOC_YOUR_TURN["data"]))
street = rng.choice(["preflop", "flop", "turn", "river"])
cards = rng.sample(CARDS, 7)
d["hole_cards"], d["street"] = cards[:2], street
d["board"] = cards[2:2 + {"preflop": 0, "flop": 3, "turn": 4, "river": 5}[street]]
stack = rng.choice([300, 2000, 9750])
d["players"][0]["stack"] = stack
facing = rng.random() < 0.6
if facing:
amt = rng.choice([100, 250, 600, stack])
amt = min(amt, stack)
d["legal"] = {"fold": True, "check": False, "call": {"to": amt, "added": amt, "all_in": amt == stack},
"raise": None if amt >= stack or rng.random() < 0.2 else {"min_to": min(2 * amt, stack), "max_to": stack}}
else:
d["legal"] = {"fold": True, "check": True, "call": None,
"raise": {"min_to": min(100, stack), "max_to": stack}}
return YourTurn.from_dict(d)
def test_bots_always_legal():
rng = random.Random(1)
bots = [RandomBot(seed=3), CallingStation(), TightAggressive(),
LLMBot(lambda p: rng.choice(["ACTION: raise 999999", "ACTION: fold", "banana", "ACTION: call"]))]
for _ in range(400):
s = random_state(rng)
for b in bots:
a = b.act(s)
assert isinstance(a, Action)
if not isinstance(b, LLMBot): # LLM output is untrusted; the runner legalizes it
assert is_legal(s, a), (b.name, a, s.legal)
def test_calling_station_and_tag_basics():
rng = random.Random(2)
s = random_state(rng)
s.legal.call = None
s.legal.check = True
assert CallingStation().act(s) == Action.check()
s.street, s.board, s.hole_cards = "preflop", [], ["Ah", "Ad"]
a = TightAggressive().act(s)
assert a.type == "raise"
s.hole_cards = ["7h", "2d"]
assert TightAggressive().act(s).type in ("check", "fold")
def test_llm_bot_prompt_and_parse():
seen = []
def complete(prompt: str) -> str:
seen.append(prompt)
return "The pot is small.\nACTION: raise 300"
bot = LLMBot(complete)
rng = random.Random(5)
s = random_state(rng)
assert bot.act(s) == Action("raise", 300)
assert "Your hole cards" in seen[0] and "Legal actions" in seen[0]
+495
View File
@@ -0,0 +1,495 @@
import os
import asyncio
import subprocess
import sys
from typing import Any
import pytest
from sharingan.cli import FunctionBot, load_bot, main, format_score
from sharingan.mock import MockArena
from sharingan import Bot
def test_bot_token_is_saved_and_reused(tmp_path):
from sharingan import cli
class FakeApi:
base_url = "http://arena.test"
registered = 0
def register_bot(self, name):
FakeApi.registered += 1
from types import SimpleNamespace
return SimpleNamespace(player_id=f"p_{FakeApi.registered}", token=f"sk_{FakeApi.registered}")
def request(self, method, path, body=None, token=None, query=None):
if token != "sk_1":
raise cli.ApiException(401, "unauthorized", "bad token")
return {"player_id": "p_1"}
api = FakeApi()
assert cli.bot_token(api, "mybot") == "sk_1"
assert cli.bot_token(api, "mybot") == "sk_1", "second run reuses the saved token"
assert FakeApi.registered == 1
assert oct(os.stat(cli.TOKENS_FILE).st_mode & 0o777) == "0o600"
assert cli.bot_token(api, "other") == "sk_2" and FakeApi.registered == 2, "another bot name is another bot"
assert cli.bot_token(api, "other") == "sk_3" and FakeApi.registered == 3, "a rejected saved token is replaced"
assert cli.leaderboard_url("https://arena.sharingan.poker", "ladder-v1") == "https://sharingan.poker/leaderboard/"
def test_load_bot_variants(tmp_path):
a = tmp_path / "a.py"
a.write_text("from sharingan import Bot, Action\nclass Mine(Bot):\n def act(self, s):\n return Action.check()\n")
b = tmp_path / "b.py"
b.write_text("def act(state):\n return None\n")
c = tmp_path / "c.py"
c.write_text("from sharingan.bots import CallingStation\nbot = CallingStation()\n")
d = tmp_path / "d.py"
d.write_text("x = 1\n")
assert isinstance(load_bot(str(a)), Bot) and load_bot(str(a)).name == "a"
assert isinstance(load_bot(str(b)), FunctionBot)
assert load_bot(str(c)).name == "calling_station"
with pytest.raises(SystemExit):
load_bot(str(d))
def test_format_score():
line = format_score("x", {"bb_per_100": 5.0, "ci95_bb_per_100": 2.5}, 600, "ladder")
assert line == "x: +50.0 ± 25.0 mbb/game (95% CI) over 600 hands vs ladder"
assert "[duplicate]" in format_score("x", {"duplicate_bb_per_100": 1.0}, 6, "ladder")
import contextlib
import threading
@contextlib.contextmanager
def mock_server(**kw):
"""MockArena on a background loop thread (main() runs its own asyncio.run)."""
ready, stop, box = threading.Event(), threading.Event(), {}
def serve():
async def run():
async with MockArena(**kw) as arena:
box["arena"] = arena
ready.set()
while not stop.is_set():
await asyncio.sleep(0.05)
asyncio.run(run())
t = threading.Thread(target=serve, daemon=True)
t.start()
assert ready.wait(10)
try:
yield box["arena"]
finally:
stop.set()
t.join(5)
def _bot(tmp_path):
bot = tmp_path / "mybot.py"
bot.write_text("def act(s):\n return None\n")
return str(bot)
def test_eval_prints_one_line(tmp_path, capsys):
bot = tmp_path / "mybot.py"
bot.write_text("def act(s):\n return None\n")
with mock_server() as arena: # no /v1/benchmarks -> falls back to the duplicate match
rc = main(["eval", str(bot), "--server", arena.url, "--hands", "600"])
out = capsys.readouterr().out.strip().splitlines()
assert rc == 0 and out == ["mybot: +40.0 ± 25.0 mbb/game (95% CI) over 600 hands vs ladder [duplicate]"]
def test_unreachable_prints_start_command(tmp_path, capsys):
bot = tmp_path / "mybot.py"
bot.write_text("def act(s):\n return None\n")
rc = main(["eval", str(bot), "--server", "http://127.0.0.1:1"])
assert rc == 2 and "cargo run --release -p sharingan-arena" in capsys.readouterr().err
def test_eval_defaults_to_ladder_benchmark(tmp_path, capsys):
with mock_server(benchmarks=True) as arena:
rc = main(["eval", _bot(tmp_path), "--server", arena.url, "--hands", "600"])
assert arena.run_requests == [{"hands": 600}]
out = capsys.readouterr().out.strip().splitlines()
assert rc == 0 and out == ["mybot: +42.5 ± 12.0 mbb/game (95% CI, aivat) over 600 hands on ladder-v1 [unverified]"]
def test_eval_match_flag_forces_duplicate_match(tmp_path, capsys):
with mock_server(benchmarks=True) as arena:
rc = main(["eval", _bot(tmp_path), "--server", arena.url, "--hands", "600", "--match"])
assert arena.run_requests == []
assert rc == 0 and "[duplicate]" in capsys.readouterr().out
def test_benchmark_prints_score_and_leaderboard(tmp_path, capsys):
with mock_server(benchmarks=True, bench_result=(-7.25, 3.0)) as arena:
rc = main(["benchmark", _bot(tmp_path), "--track", "sharingan-1", "--hands", "100", "--server", arena.url])
assert arena.run_requests == [{"hands": 100}] and arena.runs
run = next(iter(arena.runs.values()))
assert run["track"] == "sharingan-1" and run["hands_total"] == 102 # rounded up to whole deals
cap = capsys.readouterr()
assert rc == 0
assert cap.out.strip().splitlines() == [
"mybot: -7.2 ± 3.0 mbb/game (95% CI, aivat) over 102 hands on sharingan-1 [unverified]",
f"leaderboard: {arena.url}/v1/leaderboard?track=sharingan-1"]
assert "sharingan-1: 100% 102/102 hands" in cap.err # progress lines (stderr is not a tty here)
def test_benchmark_reuses_token_and_quiet(tmp_path, capsys):
import json
import urllib.request
with mock_server(benchmarks=True) as arena:
req = urllib.request.Request(arena.url + "/v1/players", data=json.dumps({"name": "pre"}).encode(), method="POST")
reg = json.loads(urllib.request.urlopen(req).read())
rc = main(["benchmark", _bot(tmp_path), "--token", reg["token"], "--quiet", "--server", arena.url])
assert len(arena.players) == 1 # no second registration
assert next(iter(arena.runs.values()))["player_id"] == reg["player_id"]
assert arena.run_requests == [{}] # server default hands
cap = capsys.readouterr()
assert rc == 0 and "hands on ladder-v1" in cap.out and cap.err == ""
def test_benchmark_unreachable(tmp_path, capsys):
rc = main(["benchmark", _bot(tmp_path), "--server", "http://127.0.0.1:1"])
assert rc == 2 and "arena server not reachable" in capsys.readouterr().err
def test_connect_answers_until_max_hands(tmp_path, capsys):
import json
import urllib.request
with mock_server(hands=5) as arena:
req = urllib.request.Request(arena.url + "/v1/players", data=json.dumps({"name": "pre"}).encode(), method="POST")
reg = json.loads(urllib.request.urlopen(req).read())
rc = main(["connect", _bot(tmp_path), "--server", arena.url, "--token", reg["token"],
"--player-id", reg["player_id"], "--max-hands", "3"])
assert rc == 0 and len(arena.hand_ends) == 3 and len(arena.acts) >= 3
err = capsys.readouterr().err
assert f"connected as {reg['player_id']}" in err and "warning" not in err and "disconnected after 3 hands" in err
def test_connect_warns_on_wrong_player_id_and_bad_token(tmp_path, capsys):
with mock_server(hands=1) as arena:
import json
import urllib.request
req = urllib.request.Request(arena.url + "/v1/players", data=json.dumps({"name": "pre"}).encode(), method="POST")
reg = json.loads(urllib.request.urlopen(req).read())
assert main(["connect", _bot(tmp_path), "--server", arena.url, "--token", reg["token"],
"--player-id", "someone-else", "--max-hands", "1"]) == 0
assert "warning: token belongs to" in capsys.readouterr().err
assert main(["connect", _bot(tmp_path), "--server", arena.url, "--token", "nope", "--no-reconnect"]) == 1
assert "never connected" in capsys.readouterr().err
def test_launch_bot_wrapper_maps_env(tmp_path, monkeypatch):
"""deploy/platinum/bot/launch_bot.py is a thin wrapper over `sharingan connect`."""
import importlib.util
import os
path = os.path.join(os.path.dirname(__file__), "..", "..", "..", "deploy", "platinum", "bot", "launch_bot.py")
spec = importlib.util.spec_from_file_location("launch_bot", path)
lb = importlib.util.module_from_spec(spec)
spec.loader.exec_module(lb)
monkeypatch.setenv("BOT_FILE", "/x/bot.py")
monkeypatch.setenv("ARENA_URL", "https://a")
monkeypatch.setenv("ARENA_TOKEN", "T")
monkeypatch.setenv("MAX_HANDS", "7")
assert lb.argv_from_env() == ["connect", "/x/bot.py", "--server", "https://a", "--token", "T", "--max-hands", "7"]
def test_submit_requires_contact_and_profile_and_remembers_them(tmp_path, monkeypatch, capsys):
from sharingan import cli
sent = []
class FakeApi:
def __init__(self, base_url):
self.base_url, self.timeout = base_url, 30.0
def request(self, method, path, body=None, token=None, query=None):
if method == "POST":
sent.append(body)
return {"id": "job_1"}
return {"status": "finished", "settled": True, "hands_done": 600, "hands_total": 600, "bot_name": "mybot",
"mbb_per_game": 1.0, "ci95_mbb": 2.0, "track": "ladder-v1", "verified": True}
monkeypatch.setattr(cli, "ArenaClient", FakeApi)
bot = _bot(tmp_path)
base = ["submit", bot, "--token", "sk_x", "--server", "http://x", "--quiet"]
assert main(base) == 2 and not sent, "nothing is uploaded without an owner"
assert "--contact" in capsys.readouterr().err
assert main(base + ["--contact", "me@example.com"]) == 2 and not sent, "an email alone is not enough"
assert main(base + ["--contact", "@me", "--profile", "https://x.com/me"]) == 2 and not sent, "contact is an email"
assert main(base + ["--contact", "me@example.com", "--profile", "https://x.com/me"]) == 0
assert main(base) == 0, "remembered after the first accepted submit"
assert [(b["contact"], b["profile"]) for b in sent] == [("me@example.com", "https://x.com/me")] * 2
assert oct(os.stat(cli.OWNER_FILE).st_mode & 0o777) == "0o600"
out = capsys.readouterr()
assert "[VERIFIED, NOT RANKED: under 20,004 hands, hosted job job_1]" in out.out
assert "leaderboard:" not in out.out, "a run that cannot rank does not link the board"
assert "not ranked" in out.err, "a verified run shorter than a ranked run says it does not count"
def test_submit_warns_when_the_bot_crashed_or_forfeited(tmp_path, monkeypatch, capsys):
from sharingan import cli
class FakeApi:
def __init__(self, base_url):
self.base_url, self.timeout = base_url, 30.0
def request(self, method, path, body=None, token=None, query=None):
if method == "POST":
return {"id": "job_2"}
return {"status": "finished", "settled": True, "hands_done": 600, "hands_total": 600, "bot_name": "mybot",
"mbb_per_game": -208.3, "ci95_mbb": 205.7, "track": "sharingan-1", "verified": True, "forfeit_hands": 588,
"bot_log_tail": "lane 1: RuntimeError: boom\nplaying check/fold"}
monkeypatch.setattr(cli, "ArenaClient", FakeApi)
monkeypatch.setenv("SHARINGAN_CONTACT", "me@example.com")
monkeypatch.setenv("SHARINGAN_PROFILE", "https://linkedin.com/in/me")
assert main(["submit", _bot(tmp_path), "--token", "sk_x", "--server", "http://x", "--track", "sharingan-1", "--quiet"]) == 0
err = capsys.readouterr().err
assert "588 of 600 hands forfeited" in err and "RuntimeError: boom" in err
def test_the_warning_names_the_exception_not_the_traceback_header():
from sharingan import cli
import io, contextlib
tail = "Traceback (most recent call last):\n File \"/opt/sharingan/bot/bot.py\", line 9, in act\n raise ValueError(\"boom on the river\")\nValueError: boom on the river"
err = io.StringIO()
with contextlib.redirect_stderr(err):
cli._warn_bot_trouble({"id": "job_9", "hands_done": 20004, "forfeit_hands": 0, "bot_log_tail": tail})
out = err.getvalue()
assert "first error: ValueError: boom on the river" in out, out
assert "bot_log_tail" in out and "job_9" in out
# ----------------------------------------------------------------------------- token / submit / play / naming
class FakeApi:
"""Stands in for ArenaClient: no network. `registered` counts POST /v1/players; `posted` keeps the /v1/jobs bodies."""
registered: list = []
posted: list = []
job: dict = {}
refuse: Any = None
def __init__(self, base_url, token=None):
self.base_url, self.token, self.timeout = base_url.rstrip("/"), token, 30.0
def register_bot(self, name, kind="bot", set_token=True):
from types import SimpleNamespace
FakeApi.registered.append(name)
n = len(FakeApi.registered)
self.token = f"sk_{n}"
return SimpleNamespace(player_id=f"p_{n}", token=f"sk_{n}")
def request(self, method, path, body=None, token=None, query=None):
if path == "/v1/me":
return {"player_id": "p_" + (token or "")[3:]}
if method == "POST":
if FakeApi.refuse:
raise FakeApi.refuse
FakeApi.posted.append(body)
return {"id": "job_9", "hands": 20004}
return dict({"status": "finished", "settled": True, "hands_done": 20004, "hands_total": 20004, "bot_name": "mybot",
"mbb_per_game": 12.5, "ci95_mbb": 3.0, "track": "sharingan-1", "verified": True}, **FakeApi.job)
@pytest.fixture
def fake_api(monkeypatch):
from sharingan import cli
FakeApi.registered, FakeApi.posted, FakeApi.job, FakeApi.refuse = [], [], {}, None
monkeypatch.setattr(cli, "ArenaClient", FakeApi)
monkeypatch.setenv("SHARINGAN_CONTACT", "me@example.com")
monkeypatch.setenv("SHARINGAN_PROFILE", "https://x.com/me")
monkeypatch.delenv("SHARINGAN_SERVER", raising=False)
return FakeApi
def _save_token(server, name, token, player_id="p"):
import json
from sharingan import cli
tokens = cli._load_tokens()
tokens[f"{server}|{name}"] = {"player_id": player_id, "token": token}
with open(cli.TOKENS_FILE, "w") as f:
json.dump(tokens, f)
def test_token_prints_only_the_saved_token(tmp_path, capsys):
_save_token("http://a.test", "mybot", "sk_mine")
_save_token("http://a.test", "other", "sk_other")
_save_token("http://b.test", "solo", "sk_solo")
capsys.readouterr()
assert main(["token", str(tmp_path / "mybot.py"), "--server", "http://a.test/"]) == 0, "a path is named after its file stem"
assert capsys.readouterr().out == "sk_mine\n"
assert main(["token", "other", "--server", "http://a.test"]) == 0, "or give the bot name"
assert capsys.readouterr().out == "sk_other\n"
assert main(["token", "--server", "http://b.test"]) == 0, "no BOT: the only token saved for that server"
cap = capsys.readouterr()
assert cap.out == "sk_solo\n" and cap.err == ""
def test_token_failures_are_exit_1_with_a_message_on_stderr(tmp_path, capsys):
_save_token("http://a.test", "mybot", "sk_mine")
_save_token("http://a.test", "other", "sk_other")
capsys.readouterr()
assert main(["token", "--server", "http://a.test"]) == 1, "two bots, none named"
cap = capsys.readouterr()
assert cap.out == "" and "mybot" in cap.err and "other" in cap.err
assert main(["token", "nobody.py", "--server", "http://a.test"]) == 1
cap = capsys.readouterr()
assert cap.out == "" and "no saved token for bot 'nobody'" in cap.err
assert main(["token", "--server", "http://empty.test"]) == 1
cap = capsys.readouterr()
assert cap.out == "" and "no saved token" in cap.err and "sharingan submit" in cap.err
def test_token_uses_the_default_server(monkeypatch, capsys):
from sharingan import cli
monkeypatch.delenv("SHARINGAN_SERVER", raising=False)
_save_token(cli.DEFAULT_SERVER, "mybot", "sk_public")
assert main(["token", "mybot.py"]) == 0 and capsys.readouterr().out == "sk_public\n"
@pytest.mark.parametrize("extra, why", [
(["--hands", "599"], "--hands"),
(["--hands", "200001"], "--hands"),
(["--hands", "0"], "--hands"),
(["--profile", "not a link"], "--profile"),
(["--profile", "https://127.0.0.1/me"], "--profile"),
(["--contact", "@me"], "--contact"),
])
def test_submit_validates_before_registering_or_uploading(tmp_path, fake_api, capsys, extra, why):
assert main(["submit", _bot(tmp_path), "--server", "http://x", "--quiet"] + extra) == 2
assert why in capsys.readouterr().err
assert fake_api.registered == [] and fake_api.posted == [], "nothing was registered or uploaded"
def test_submit_accepts_the_edges_of_the_hands_range_and_handles(tmp_path, fake_api, capsys):
for extra in (["--hands", "600"], ["--hands", "200000"], ["--profile", "@me"], ["--profile", "linkedin.com/in/me"]):
assert main(["submit", _bot(tmp_path), "--server", "http://x", "--quiet", "--token", "sk_x"] + extra) == 0
assert len(fake_api.posted) == 4
def test_submit_missing_entry_in_a_directory_does_not_register(tmp_path, fake_api, capsys):
d = tmp_path / "botdir"
d.mkdir()
(d / "main.py").write_text("def act(s):\n return None\n")
assert main(["submit", str(d), "--server", "http://x", "--quiet"]) == 2
assert "bot.py" in capsys.readouterr().err and fake_api.registered == [] and fake_api.posted == []
assert main(["submit", str(d), "--entry", "main.py", "--server", "http://x", "--quiet"]) == 0
assert fake_api.registered == ["botdir"] and fake_api.posted[0]["entry"] == "main.py"
def test_submit_accepted_line_shows_server_hands_and_upload_hash(tmp_path, fake_api, capsys):
import hashlib
assert main(["submit", _bot(tmp_path), "--server", "http://x", "--quiet", "--token", "sk_x"]) == 0
cap = capsys.readouterr()
accepted = [ln for ln in cap.err.splitlines() if "accepted" in ln]
assert len(accepted) == 1 and "job job_9 accepted (20004 hands on ladder-v1; upload sha256 " in accepted[0], accepted
import base64
sha = hashlib.sha256(base64.b64decode(fake_api.posted[0]["artifactTgzBase64"])).hexdigest()
assert f"sha256 {sha[:12]})" in accepted[0], "the hash of the uploaded .tar.gz"
assert "[VERIFIED, hosted job job_9]" in cap.out and "leaderboard:" in cap.out, "a full verified run links the board"
assert "not ranked" not in cap.err
def test_submit_short_verified_run_says_not_ranked_and_skips_the_link(tmp_path, fake_api, capsys):
fake_api.job = {"hands_done": 600, "hands_total": 600, "mbb_per_game": 378.1, "ci95_mbb": 578.5}
assert main(["submit", _bot(tmp_path), "--server", "http://x", "--quiet", "--token", "sk_x", "--hands", "600"]) == 0
cap = capsys.readouterr()
assert cap.out.strip().splitlines() == [
"mybot: +378.1 +- 578.5 mbb/game over 600 hands on sharingan-1 [VERIFIED, NOT RANKED: under 20,004 hands, hosted job job_9]"]
assert "not ranked" in cap.err
def test_submit_unverified_job_is_labelled_and_server_refusals_are_explained(tmp_path, fake_api, capsys):
fake_api.job = {"verified": False}
assert main(["submit", _bot(tmp_path), "--server", "http://x", "--quiet", "--token", "sk_x"]) == 0
assert "[unverified, hosted job job_9]" in capsys.readouterr().out
from sharingan import cli
msg = "submissions are temporarily unavailable"
fake_api.refuse = cli.ApiException(403, "temporarily_unavailable", msg)
assert main(["submit", _bot(tmp_path), "--server", "http://x", "--quiet", "--token", "sk_x", "--track", "sharingan-1"]) == 1
cap = capsys.readouterr()
assert cap.out == "" and "403 temporarily_unavailable" in cap.err and msg in cap.err
def test_submit_reuses_the_saved_token_of_the_file_name(tmp_path, fake_api, capsys):
bot = _bot(tmp_path)
for _ in range(2):
assert main(["submit", bot, "--server", "http://x", "--quiet"]) == 0
assert fake_api.registered == ["mybot"], "registered once, then the saved token"
capsys.readouterr()
assert main(["token", bot, "--server", "http://x"]) == 0 and capsys.readouterr().out == "sk_1\n"
def test_play_reuses_the_saved_bot_token(tmp_path, fake_api, monkeypatch, capsys):
from sharingan import cli
tokens_seen = []
class FakeRunner:
def __init__(self, bot, server, token, max_hands=None, **kw):
tokens_seen.append(token)
self.hands_played, self.net_chips, self._my_seats = 0, 0, {}
async def run(self):
return None
class FakeTable:
table_id = "t1"
monkeypatch.setattr(fake_api, "create_table", lambda self, **kw: FakeTable(), raising=False)
monkeypatch.setattr(fake_api, "join_table", lambda self, tid, seat, pid, token=None: tokens_seen.append(("seat", tid, seat, pid)),
raising=False)
monkeypatch.setattr(cli, "Runner", FakeRunner)
for _ in range(3):
assert main(["play", _bot(tmp_path), "--vs", "sharingan-1", "--server", "http://x"]) == 0
assert fake_api.registered == ["mybot"], "one registration for three plays"
assert [t for t in tokens_seen if isinstance(t, str)] == ["sk_1"] * 3
assert ("seat", "t1", 0, "p_1") in tokens_seen, "the saved player id sits at the table"
def test_load_bot_names_llm_bots_after_their_file_unless_named(tmp_path):
from sharingan.bots import LLMBot
head = "from sharingan import Bot\nfrom sharingan.bots import LLMBot\ndef complete(p):\n return 'ACTION: call'\n"
for stem, line, want in [
("alpha", "bot = LLMBot(complete)", "alpha"),
("beta", "bot = LLMBot(complete)", "beta"),
("gamma", "bot = LLMBot(complete, name='my llm')", "my llm"),
("delta", "bot = LLMBot(complete)\nbot.name = 'chosen'", "chosen"),
("eps", "class Mine(Bot):\n name = 'explicit'\n def act(self, s): return None\nbot = Mine()", "explicit"),
("zeta", "class Mine(Bot):\n def act(self, s): return None\nbot = Mine()", "zeta"),
]:
f = tmp_path / f"{stem}.py"
f.write_text(head + line + "\n")
b = load_bot(str(f))
assert b.name == want, (stem, b.name)
assert LLMBot(lambda p: "").name == "bot" and LLMBot(lambda p: "", name="x").name == "x"
def test_webhook_server_accepts_both_signature_headers():
import json
import urllib.error
import urllib.request
from sharingan.bots import CallingStation
from sharingan.webhook import serve_webhook, sign
from conftest import DOC_YOUR_TURN
body = json.dumps(DOC_YOUR_TURN).encode()
srv = serve_webhook(CallingStation(), host="127.0.0.1", port=0, secret="s3", block=False)
try:
def post(headers):
req = urllib.request.Request(f"http://127.0.0.1:{srv.server_address[1]}/act", data=body, headers=headers, method="POST")
try:
with urllib.request.urlopen(req, timeout=5) as r:
return r.status
except urllib.error.HTTPError as e:
return e.code
assert post({"X-Sharingan-Signature": sign("s3", body)}) == 200, "what the server sends"
assert post({"X-Signature": sign("s3", body)}) == 200, "the old name still works"
assert post({"X-Sharingan-Signature": "sha256=bad"}) == 401
assert post({}) == 401
finally:
srv.shutdown()
srv.server_close()
+208
View File
@@ -0,0 +1,208 @@
import asyncio
import json
import logging
import pytest
from sharingan import (Action, ApiException, ArenaClient, Bot, Runner, handle_webhook, ws_url)
from sharingan.bots import CallingStation, LLMBot, RandomBot, TightAggressive
from sharingan.mock import MockArena
from sharingan.webhook import sign
from conftest import DOC_YOUR_TURN
def arun(coro):
return asyncio.run(asyncio.wait_for(coro, 20))
async def play(arena, bot, hands, **kw):
r = Runner(bot, arena.ws_url, "any-token", max_hands=hands, **kw)
await r.run()
return r
def test_ws_url():
assert ws_url("http://h:1", "tk") == "ws://h:1/v1/play?token=tk"
assert ws_url("https://h", "tk") == "wss://h/v1/play?token=tk"
assert ws_url("wss://h/v1/play?token=x", "tk") == "wss://h/v1/play?token=x"
def test_rest_flow():
async def main():
async with MockArena() as arena:
def sync():
api = ArenaClient(arena.http_url)
me = api.register_bot("my-bot")
assert me.token and me.player_id and api.token == me.token
t = api.create_table(small_blind=50)
assert t.config["big_blind"] == 100 and len(t.seats) == 6
seat = api.join_table(t.table_id, 2, me.player_id)
assert seat.player_id == me.player_id and seat.status == "seated"
with pytest.raises(ApiException) as e:
api.join_table(t.table_id, 2, me.player_id)
assert e.value.code == "seat_taken" and e.value.status == 409
assert api.get_table(t.table_id).seats[2].name == "my-bot"
with pytest.raises(ApiException) as e:
ArenaClient(arena.http_url, token="nope").get_table(t.table_id)
assert e.value.code == "unauthorized"
await asyncio.to_thread(sync)
arun(main())
@pytest.mark.parametrize("make", [lambda: RandomBot(seed=1), CallingStation, TightAggressive,
lambda: LLMBot(lambda p: "ACTION: call")])
def test_full_session(make):
async def main():
async with MockArena(hands=4) as arena:
r = await play(arena, make(), 4)
assert r.hands_played == 4 and len(arena.hand_ends) == 4
assert arena.errors_sent == [] # nothing illegal was ever sent
assert r.welcome["player_id"] and arena.received[0]["type"] == "hello"
assert r.net_chips == sum(h["results"][0]["net"] for h in arena.hand_ends)
for h in arena.hand_ends:
assert sum(x["net"] for x in h["results"]) == 0
arun(main())
def test_hooks_and_async_bot():
events = []
class B(Bot):
async def act(self, s):
await asyncio.sleep(0)
return Action.call() if s.legal.call else Action.check()
def on_hand_start(self, h): events.append(("start", h.hand_no, h.bb_seat))
def on_action(self, a): events.append(("action", a.type))
def on_street(self, s): events.append(("street", s.street, tuple(s.board)))
async def on_hand_end(self, e): events.append(("end", e.ended_by, e.hole_cards[0]))
async def main():
async with MockArena(hands=1) as arena:
await play(arena, B(), 1)
arun(main())
kinds = [e[0] for e in events]
assert kinds[0] == "start" and "street" in kinds and kinds[-1] == "end"
assert ("street", "flop", ("7c", "8d", "2s")) in events
assert events[-1] == ("end", "showdown", ["Ah", "Kd"])
def test_reconnect_resumes_same_decision():
async def main():
async with MockArena(hands=3, drop_on_turns={1, 3}) as arena:
r = await play(arena, CallingStation(), 3)
assert r.hands_played == 3
assert arena.connections >= 3
hellos = [m for m in arena.received if m["type"] == "hello"]
assert "resume" not in hellos[0]["data"]
assert hellos[1]["data"]["resume"][0]["table_id"] == "t1"
assert hellos[1]["data"]["resume"][0]["last_table_seq"] > 0
# the re-offered turn kept its decision_id and every decision was answered once
ids = [a["decision_id"] for a in arena.acts]
assert len(ids) == len(set(ids)) == 6
arun(main())
def test_illegal_action_gets_error_and_retry():
class Bad(Bot):
strict = True
n = 0
errs = []
def act(self, s):
Bad.n += 1
if Bad.n == 1:
return Action.raise_to(5) # below min_to -> bad_amount
return Action.call() if s.legal.call else Action.check()
def on_error(self, e): Bad.errs.append(e.code)
async def main():
async with MockArena(hands=1) as arena:
await play(arena, Bad(), 1)
assert arena.errors_sent == ["bad_amount"]
arun(main())
assert Bad.errs == ["bad_amount"] and Bad.n >= 3
def test_runner_legalizes_by_default():
class Sloppy(Bot):
def act(self, s):
return Action.raise_to(5) if s.legal.raise_ else Action.check()
async def main():
async with MockArena(hands=2) as arena:
await play(arena, Sloppy(), 2)
assert arena.errors_sent == []
assert arena.acts[0]["to"] == 200 # clamped to min_to
arun(main())
def test_act_timeout_and_exception_fall_back_to_check_fold():
class Slow(Bot):
calls = 0
async def act(self, s):
Slow.calls += 1
if Slow.calls == 1:
await asyncio.sleep(5)
raise RuntimeError("boom")
async def main():
async with MockArena(hands=1, decision_ms=500) as arena:
await play(arena, Slow(), 1, safety_margin_ms=100)
assert [a["type"] for a in arena.acts][0] == "fold" # timed out -> fold (facing BB)
arun(main())
def test_sync_blocking_act_hits_deadline():
import time
class Blocking(Bot):
def act(self, s):
time.sleep(2)
return Action.call() if s.legal.call else Action.check()
async def main():
async with MockArena(hands=1, decision_ms=400) as arena:
await play(arena, Blocking(), 1, safety_margin_ms=50)
assert arena.acts[0]["type"] == "fold"
arun(main())
def test_table_seq_gap_triggers_resync():
async def main():
async with MockArena(hands=2, emit_gap_at=6) as arena:
await play(arena, CallingStation(), 2)
hellos = [m for m in arena.received if m["type"] == "hello"]
assert len(hellos) >= 2 and "resume" in hellos[1]["data"]
arun(main())
def test_bad_token_rejected():
async def main():
async with MockArena() as arena:
r = Runner(CallingStation(), arena.ws_url, "bad", reconnect=False)
await r.run()
assert r.connects == 1 and r.welcome is None
arun(main())
def test_llm_bot_async_complete_end_to_end():
async def complete(prompt):
await asyncio.sleep(0)
return "Strong hand.\nACTION: raise 300"
async def main():
async with MockArena(hands=2) as arena:
bot = LLMBot(complete)
await play(arena, bot, 2)
assert arena.acts[0] == {"hand_id": "h-1", "decision_id": arena.acts[0]["decision_id"], "type": "raise", "to": 300}
arun(main())
def test_webhook():
body = json.dumps(DOC_YOUR_TURN).encode()
st, out = handle_webhook(CallingStation(), body, sign("s3", body), "s3")
assert st == 200 and json.loads(out) == {"hand_id": "h-77", "decision_id": "d-77-9", "type": "check"}
st, _ = handle_webhook(CallingStation(), body, "sha256=bad", "s3")
assert st == 401
st, out = handle_webhook(CallingStation(), b'{"type":"action","data":{}}')
assert st == 200 and out == b"{}"
+66
View File
@@ -0,0 +1,66 @@
"""End-to-end against a real arena server. Skipped unless SHARINGAN_E2E_SERVER is set, e.g.
SHARINGAN_E2E_SERVER=http://localhost:8095 pytest tests/test_e2e.py
(server needs ARENA_BLUEPRINT so the benchmark tracks are available)."""
import json
import os
import re
import signal
import subprocess
import sys
import time
import urllib.request
import pytest
SERVER = os.environ.get("SHARINGAN_E2E_SERVER")
pytestmark = pytest.mark.skipif(not SERVER, reason="set SHARINGAN_E2E_SERVER to run against a real arena")
BOT = "from sharingan.bots import CallingStation\nbot = CallingStation()\n"
def _cli(*args, **kw):
return subprocess.run([sys.executable, "-m", "sharingan.cli", *args], capture_output=True, text=True, timeout=300, **kw)
def test_benchmark_and_eval(tmp_path):
bot = tmp_path / "e2ebot.py"
bot.write_text(BOT)
r = _cli("benchmark", str(bot), "--track", "ladder-v1", "--hands", "300", "--server", SERVER)
assert r.returncode == 0, r.stderr
out = r.stdout.strip().splitlines()
assert re.fullmatch(r"calling_station: [+-]\d+\.\d ± \d+\.\d mbb/game \(95% CI, aivat\) over 300 hands on ladder-v1 \[unverified\]", out[0]), out
assert out[1] == f"leaderboard: {SERVER.rstrip('/')}/v1/leaderboard?track=ladder-v1"
assert "ladder-v1: 100% 300/300 hands" in r.stderr
e = _cli("eval", str(bot), "--hands", "300", "--server", SERVER, "--quiet")
assert e.returncode == 0 and "on ladder-v1" in e.stdout and len(e.stdout.strip().splitlines()) == 1, e.stderr
def test_connect_then_external_run(tmp_path):
bot = tmp_path / "e2ebot.py"
bot.write_text(BOT)
req = urllib.request.Request(SERVER + "/v1/players", data=json.dumps({"name": "e2e-connect", "kind": "bot"}).encode(),
method="POST", headers={"content-type": "application/json"})
reg = json.load(urllib.request.urlopen(req))
p = subprocess.Popen([sys.executable, "-m", "sharingan.cli", "connect", str(bot), "--server", SERVER, "--token", reg["token"],
"--player-id", reg["player_id"]], stderr=subprocess.PIPE, text=True)
try:
run, t0 = None, time.time()
while run is None and time.time() - t0 < 20:
try:
req = urllib.request.Request(SERVER + "/v1/benchmarks/ladder-v1/runs", data=json.dumps({"hands": 120}).encode(), method="POST",
headers={"content-type": "application/json", "authorization": "Bearer " + reg["token"]})
run = json.load(urllib.request.urlopen(req))
except urllib.error.HTTPError as e:
assert e.code == 409 # not_connected yet
time.sleep(0.3)
assert run, "run never started"
while time.time() - t0 < 120:
cur = json.load(urllib.request.urlopen(f"{SERVER}/v1/benchmarks/ladder-v1/runs/{run['run_id']}"))
if cur["status"] != "running":
break
time.sleep(0.3)
assert cur["status"] == "finished" and cur["mbb_per_game"] is not None
finally:
p.send_signal(signal.SIGTERM)
err = p.communicate(timeout=20)[1]
assert p.returncode == 0 and f"connected as {reg['player_id']}" in err and "disconnected after 120 hands" in err
+83
View File
@@ -0,0 +1,83 @@
import pytest
from conftest import doc_state, facing_bet_state
from sharingan import (Action, legal_types, legalize, parse_action_text, pot_raise_to, preflop_strength,
render_state, safe_action)
from sharingan.helpers import (all_in_action, bb_multiple_to, is_legal, made_hand_category, position_name)
def test_parse_doc_example():
s = doc_state()
assert s.decision_id == "d-77-9" and s.table_id == "t1"
assert s.hole_cards == ["Ah", "Kd"] and s.board == ["7c", "8d", "2s"]
assert s.legal.check and s.legal.call is None and s.legal.raise_.max_to == 9750
assert s.to_call == 0 and s.pot_odds == 0.0 and s.stack == 9750
assert s.history[0].type == "post_sb" and s.history[-1].next_to_act == 0
assert legal_types(s) == ["fold", "check", "raise"]
assert s.pots[0].eligible_seats == [0, 5]
def test_pot_odds_and_sizes():
s = facing_bet_state()
assert s.to_call == 200
assert s.pot_odds == pytest.approx(200 / 950)
# call to 200, then raise by pot+call: 200 + (750 + 200) = 1150
assert pot_raise_to(s, 1.0) == 1150
assert pot_raise_to(s, 0.0) == 400 # clamped up to min_to
assert bb_multiple_to(s, 1000) == 9750 # clamped down to max
assert all_in_action(s) == Action.raise_to(9750)
def test_pot_bet_when_checking():
s = doc_state() # pot 550, no bet
assert pot_raise_to(s, 1.0) == 550 # bet pot
assert pot_raise_to(s, 0.5) == 275
def test_legalize():
s = doc_state()
assert legalize(s, Action.fold()) == Action.check() # fold when check free -> check
assert legalize(s, Action.call()) == Action.check()
assert legalize(s, Action.raise_to(1)) == Action.raise_to(100) # clamp up
assert legalize(s, Action.raise_to(10**9)) == Action.raise_to(9750)
assert legalize(s, Action("all_in")) == Action.raise_to(9750)
assert legalize(s, Action("bet", 300)) == Action.raise_to(300)
f = facing_bet_state()
assert legalize(f, Action.check()) == Action.fold()
f.legal.raise_ = None
assert legalize(f, Action.raise_to(500)) == Action.call()
assert is_legal(s, Action.raise_to(100)) and not is_legal(s, Action.raise_to(99)) and not is_legal(s, Action.call())
assert safe_action(f) == Action.fold()
def test_action_wire_format():
d = Action.raise_to(400).to_data("h-77", "d-77-9")
assert d == {"hand_id": "h-77", "decision_id": "d-77-9", "type": "raise", "to": 400}
assert Action.fold().to_data("h", "d") == {"hand_id": "h", "decision_id": "d", "type": "fold"}
def test_parse_action_text():
assert parse_action_text("I think we should RAISE TO 450.") == Action("raise", 450)
assert parse_action_text("ACTION: call") == Action.call()
assert parse_action_text("fold") == Action.fold()
assert parse_action_text("all-in!") == Action("all_in")
assert parse_action_text("no idea") is None
assert parse_action_text("call... actually raise 300") == Action("raise", 300)
def test_strength_and_position():
assert preflop_strength(["Ah", "Ad"]) >= 20 - 1 and preflop_strength(["As", "Ks"]) >= 10
assert preflop_strength(["7h", "2d"]) < 3
assert made_hand_category(["Ah", "Ad"], ["7c", "8d", "2s"]) == 1
assert made_hand_category(["Ah", "Kd"], ["7c", "8d", "2s"]) == 0
assert made_hand_category(["Ah", "Kd"], ["Ac", "Kc", "2s"]) == 2
assert made_hand_category(["Ah", "Kd"], ["Qc", "Jc", "Ts"]) == 3 # straight
s = doc_state()
s.players = [p for p in s.players]
assert position_name(s) in ("UTG", "SB", "BB", "BTN", "MP", "CO", "BTN/SB")
def test_render_state():
txt = render_state(facing_bet_state())
for needle in ("Ah Kd", "7c 8d 2s", "To call: 200", "raise (to an amount between 400 and 9750", "post_sb to 50"):
assert needle in txt
+180
View File
@@ -0,0 +1,180 @@
"""Pipe protocol (docs/TABLE_API.md section 14): `sharingan pipe`, the PipeRunner and `eval --local`."""
import io
import json
import os
import subprocess
import sys
import textwrap
import pytest
from sharingan import Action, Bot, cli
from sharingan.pipe import PipeRunner
from conftest import DOC_YOUR_TURN
HERE = os.path.dirname(os.path.abspath(__file__))
PKG_PARENT = os.path.dirname(HERE)
def turn_env(**over):
e = json.loads(json.dumps(DOC_YOUR_TURN))
e["data"]["hand_id"] = "h-77"
e.update(over)
return e
def lines(*envs):
return io.BytesIO(b"".join((json.dumps(e) + "\n").encode() for e in envs))
def run_runner(bot, *envs):
out = io.BytesIO()
rc = PipeRunner(bot, lines(*envs), out).run()
return rc, [json.loads(l) for l in out.getvalue().decode().splitlines()]
class Raiser(Bot):
name = "raiser"
def act(self, state):
return Action.raise_to(400)
def test_handshake_act_and_bye():
welcome = {"v": 1, "type": "welcome", "data": {"protocol": 1, "mode": "benchmark", "tables": ["t1"]}}
rc, out = run_runner(Raiser(), welcome, turn_env(), {"v": 1, "type": "bye", "data": {}})
assert rc == 0
assert [m["type"] for m in out] == ["hello", "act", "bye"]
assert out[0]["data"]["protocol"] == 1 and out[0]["data"]["bot"] == "raiser"
act = out[1]
assert act["table_id"] == "t1"
assert act["data"] == {"hand_id": "h-77", "decision_id": "d-77-9", "type": "raise", "to": 400}
def test_illegal_answer_is_legalized_and_exception_plays_check_fold():
class Wild(Bot):
def act(self, state):
return Action.raise_to(1) # below min_to=100 -> legalize clamps it
_, out = run_runner(Wild(), turn_env())
assert out[1]["data"]["type"] == "raise" and out[1]["data"]["to"] == 100
class Boom(Bot):
def act(self, state):
raise RuntimeError("bug in my bot")
_, out = run_runner(Boom(), turn_env())
assert out[1]["data"]["type"] == "check" # check is free in the doc example, else fold
class NotAnAction(Bot):
def act(self, state):
return "call"
_, out = run_runner(NotAnAction(), turn_env())
assert out[1]["data"]["type"] == "check"
def test_async_act_and_hooks_only_when_overridden():
seen = []
class A(Bot):
async def act(self, state):
return Action.call()
def on_hand_end(self, end):
seen.append(end.hand_id)
def on_connect(self, welcome):
seen.append(welcome["protocol"])
hand_end = {"v": 1, "type": "hand_end", "data": {"hand_id": "h-77", "results": [], "hole_cards": {"0": ["Ah", "Kd"]}}}
_, out = run_runner(A(), {"v": 1, "type": "welcome", "data": {"protocol": 1}}, turn_env(), hand_end)
assert seen == [1, "h-77"]
assert [m["type"] for m in out] == ["hello", "act"] # hand_end gets no answer
# a bot without on_hand_end: the payload is not even parsed (garbage-tolerant, fast)
_, out = run_runner(Raiser(), {"v": 1, "type": "hand_end", "data": "ignored"})
assert [m["type"] for m in out] == ["hello"]
def test_garbage_lines_are_skipped():
out = io.BytesIO()
src = io.BytesIO(b"not json\n\n" + (json.dumps(turn_env()) + "\n").encode())
PipeRunner(Raiser(), src, out).run()
assert [json.loads(l)["type"] for l in out.getvalue().decode().splitlines()] == ["hello", "act"]
def test_subprocess_keeps_stdout_clean(tmp_path):
"""`sharingan pipe` over real pipes: prints in the bot (import time and inside act) must not reach the protocol stream."""
bot = tmp_path / "chatty.py"
bot.write_text(textwrap.dedent("""
print("import-time noise")
from sharingan import Bot, Action
class Chatty(Bot):
def act(self, state):
print("act-time noise")
return Action.call() if state.legal.call else Action.check()
"""))
env = dict(os.environ, PYTHONPATH=PKG_PARENT)
p = subprocess.Popen([sys.executable, "-m", "sharingan.cli", "pipe", str(bot)], stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env)
hello = json.loads(p.stdout.readline())
assert hello["type"] == "hello"
p.stdin.write((json.dumps({"v": 1, "type": "welcome", "data": {"protocol": 1}}) + "\n").encode())
p.stdin.write((json.dumps(turn_env()) + "\n").encode())
p.stdin.flush()
act = json.loads(p.stdout.readline())
assert act["type"] == "act" and act["data"]["type"] == "check"
p.stdin.write((json.dumps({"v": 1, "type": "bye", "data": {}}) + "\n").encode())
p.stdin.flush()
assert json.loads(p.stdout.readline())["type"] == "bye"
rest, err = p.communicate(timeout=10)
assert rest == b"" and p.returncode == 0
assert b"import-time noise" in err and b"act-time noise" in err
def test_eval_local_without_worker_prints_fallback(tmp_path, monkeypatch, capsys):
monkeypatch.delenv("SHARINGAN_ARENA_BIN", raising=False)
monkeypatch.setenv("PATH", str(tmp_path)) # no sharingan-arena here
bot = tmp_path / "b.py"
bot.write_text("from sharingan import Bot, Action\nclass B(Bot):\n def act(self, s):\n return Action.check()\n")
rc = cli.main(["eval", str(bot), "--local"])
err = capsys.readouterr().err
assert rc == 2
assert "sharingan-arena" in err and "PATH" in err and "cargo build --release -p sharingan-arena" in err
def test_eval_local_runs_the_worker_binary(tmp_path, monkeypatch, capsys):
"""A fake worker: checks the command line the SDK builds and writes a result.json."""
fake = tmp_path / "sharingan-arena"
fake.write_text(textwrap.dedent(f"""\
#!{sys.executable}
import json, sys
a = sys.argv[1:]
assert a[0] == "run", a
get = lambda k: a[a.index(k) + 1]
assert "sharingan.cli pipe" in get("--bot") and get("--bot").endswith("b.py'") or get("--bot").endswith("b.py")
json.dump({{"track": get("--track"), "hands": int(get("--hands")), "mbb_per_game": 12.5, "ci95_mbb": 3.0,
"method": "aivat", "forfeit_hands": 0, "timings": {{"hands_per_sec": 1234.0}}}}, open(get("--out"), "w"))
"""))
fake.chmod(0o755)
monkeypatch.setenv("SHARINGAN_ARENA_BIN", str(fake))
bot = tmp_path / "b.py"
bot.write_text("from sharingan import Bot, Action\nclass B(Bot):\n def act(self, s):\n return Action.check()\n")
rc = cli.main(["eval", str(bot), "--local", "--track", "sharingan-1", "--hands", "600", "--lanes", "4"])
out = capsys.readouterr().out
assert rc == 0
assert "+12.5 ± 3.0 mbb/game" in out and "600 hands on sharingan-1" in out and "local" in out
@pytest.mark.skipif(not (cli.find_worker() and os.environ.get("ARENA_BLUEPRINT")), reason="needs sharingan-arena on PATH and ARENA_BLUEPRINT")
def test_eval_local_end_to_end_with_the_real_worker(tmp_path, capsys):
bot = tmp_path / "station.py"
bot.write_text("from sharingan import Bot\nfrom sharingan.helpers import call_or_check\nclass S(Bot):\n def act(self, s):\n return call_or_check(s)\n")
out = tmp_path / "r.json"
rc = cli.main(["eval", str(bot), "--local", "--hands", "600", "--lanes", "2", "--out", str(out), "--quiet"])
assert rc == 0
r = json.loads(out.read_text())
assert r["hands"] == 600 and r["forfeit_hands"] == 0 and r["method"] == "aivat"
assert "mbb/game" in capsys.readouterr().out