Python bridge¶
The HyperToken bridge runs a turn-based game in Node.js and exposes it to a Python policy over WebSocket. Each connection owns a separate environment; reset it to start a new episode. In the checkout, the Node server is under ai/bridge, and the Python package and examples live under ai/python.
Install and connect¶
From a repository checkout:
npm install
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -e 'ai/python[gymnasium]'
npm run bridge -- --env hanabi --players 3 --port 9999
The installed CLI also accepts hypertoken bridge --env hanabi --players 3. Run npm run bridge -- --help for configuration. In another shell using the same virtual environment:
from random import Random
from hypertoken import HyperTokenAECEnv
rng = Random(42)
with HyperTokenAECEnv("ws://127.0.0.1:9999") as env:
env.reset(seed=42)
for agent in env.agent_iter():
observation, reward, terminated, truncated, info = env.last()
choices = [i for i, legal in enumerate(env.action_mask(agent)) if legal]
env.step(rng.choice(choices))
print({agent: env.last(agent=agent)[1] for agent in env.possible_agents})
agent_iter() yields only live turns and stops at the end of the episode. last() reads and clears accrued reward for the selected agent; last(agent=name) can retrieve a specific player's observation and accrued reward after termination. rewards() gives only the latest step's rewards. The wrapper is PettingZoo-style, not a PettingZoo subclass with dead steps; use an adapter if a library requires the full API. HyperTokenParallelEnv is a legacy batching facade over turn-based games, not a simultaneous environment. The simultaneous Prisoner's Dilemma example runs in-process in TypeScript.
The bridge hosts Blackjack, Poker, Hanabi, Coup, Cuttle, and Liar's Dice; see RL environments for details. A client controls the entire episode. Player observations hide game-specific private information from a policy, but the connection can query any seat. This is not a human multiplayer service or a confidentiality boundary between independent policies.
Stable-Baselines3¶
Install the sb3 extra and run the single-agent Blackjack example:
python -m pip install -e 'ai/python[sb3]'
npm run bridge -- --env blackjack --agents 1 --no-rate-limit
# In another shell:
python ai/python/examples/train_sb3.py
The example adapts the five-action Blackjack AEC to Gymnasium, not the separate six-action BlackjackEnv TypeScript class. It substitutes Stand when PPO proposes a masked-out action. For multi-agent training, use each game's action mask when selecting moves and read per-agent rewards.
Protocol¶
Send one JSON object per text frame; the server returns one JSON response in request order. This is a small command protocol, not JSON-RPC 2.0. Command types are in ai/bridge/protocol.ts.
cmd |
Fields | Response fields |
|---|---|---|
env_info |
— | env_type, env_options, possible_agents, observation_spaces, action_spaces |
reset |
optional integer seed |
ok |
step |
integer action |
ok |
observe |
agent |
observation |
last |
optional agent |
observation, reward, terminated, truncated, info |
agents, possible_agents |
— | agents, possible_agents, respectively |
agent_selection |
— | agent |
observation_space, action_space |
agent |
space |
action_mask |
agent |
mask (boolean array, or null) |
rewards, terminations, truncations, infos |
— | Per-agent map under the command name |
render, close |
— | ok |
ping |
— | pong (server timestamp in milliseconds) |
Spaces use n for discrete actions, or shape, low, and high for numeric observations. The Python wrapper converts spaces to Gymnasium/Gym types and observations to numpy.float32. An invalid command returns {"error":"message"}. Call reset before reading observations or stepping, and pick actions from the current agent's mask. render prints to the server console.
To register another game, implement AECEnvironment from ai/interface/PettingZoo.ts and add an entry to ENV_REGISTRY in ai/bridge/server.ts. Populate possibleAgents and spaces before reset so clients can discover them. For a pure TypeScript implementation, start with RL environments.
Operational notes¶
The bridge listens on 127.0.0.1:9999 by default. A configured --api-token or HYPERTOKEN_API_KEY requires an X-API-Token header or URL ?token=.... Terminate TLS and restrict access at a trusted proxy before exposing the service beyond loopback; this server does not supply TLS. By default it limits concurrent connections and request rate. --no-rate-limit is intended for trusted local training.
- If connection is refused, check the bind host and port and visit
/healthor/ready. - If a long training job hits rate limits, prefer trusted loopback with
--no-rate-limit, or configure the rate limit inEnvServerOptions. env_infocaches spaces in one round trip. For more throughput, benchmark direct TypeScript use before increasing the number of network requests.- See
train_pettingzoo.pyandjupyter_demo.ipynbunderai/python/examplesfor additional examples.