lib
Poker core
Hand classes, the action, suit and grade palettes, and response types for the Poker Study AI strategy API.
Installation
$ npx shadcn@latest add https://www.pokerstudy.ai/r/poker-core.jsonSource
lib/pokerstudy/poker.ts
/**
* Poker Study AI registry core: hand classes, the action / suit / grade
* palettes, and the response types for the strategy API. Every other
* `@pokerstudy` registry item builds on this file, and the app's own strategy
* grid and cards read their colors from here too, so an installed component
* looks exactly like it does on pokerstudy.ai.
*
* No imports, no React: safe on the server and the client.
*/
/** Ranks high to low. The 13×13 hand matrix is indexed by these. */
export const RANKS = ["A", "K", "Q", "J", "T", "9", "8", "7", "6", "5", "4", "3", "2"] as const;
/**
* Every 169 hand class in matrix order, row-major: suited above the diagonal,
* offsuit below, pairs on it ("AA", "AKs", …, "32o"). Higher rank first.
*/
export const ALL_HANDS: string[] = (() => {
const hands: string[] = [];
for (let r = 0; r < 13; r++) {
for (let c = 0; c < 13; c++) {
const hi = RANKS[Math.min(r, c)];
const lo = RANKS[Math.max(r, c)];
if (r === c) hands.push(`${hi}${hi}`);
else hands.push(`${hi}${lo}${r < c ? "s" : "o"}`);
}
}
return hands;
})();
/** Concrete combos in a class, ignoring card removal: pair 6, suited 4, offsuit 12. */
export function comboCount(hand: string): number {
if (hand.length === 2) return 6;
return hand.endsWith("s") ? 4 : 12;
}
export type ActionKind = "fold" | "call" | "raise" | "allin" | "other";
/** One action at a preflop decision, as `GET /api/ranges/nl/v2/node` returns it. */
export interface NodeAction {
/** Raw action token: "Fold", "Call", "Limp", "Open", a size like "77%", or "AI". */
action: string;
kind: ActionKind;
/** Hand class → frequency of this action, in [0, 1]. */
weights: Record<string, number>;
/** Hand class → EV of this action in small blinds. */
evs?: Record<string, number>;
sizePct?: number;
combos?: number;
}
/** A whole preflop decision: who acts and every action they can take. */
export interface NodeResponse {
game: string;
stack: number;
history: string;
actor: string;
actions: NodeAction[];
continuingCombos?: number;
/** Present when the request named a `hand`. Action token → frequency. */
hand?: string;
strategy?: Record<string, number>;
}
export type Grade = "perfect" | "correct" | "inaccuracy" | "mistake" | "blunder";
/** `POST /api/play/evaluate`: the selected action scored against the agent's own. */
export interface EvaluateResponse {
equity: number;
model: string;
selected: { action: string; amount?: number; ev: number };
bot: { action: string; amount?: number; ev: number; source?: string; position?: string };
/** Big blinds given up versus the agent's action. Never negative. */
ev_loss_bb: number;
grade: Grade;
}
/** One action color scheme. `raises` darkens by size so several raise sizes stay distinct in one cell. */
export interface ActionPalette {
label: string;
Fold: string;
Check: string;
Call: string;
Bet: string;
Raise: string;
AllIn: string;
raises: readonly string[];
}
export type ActionPaletteId = "classic" | "midnight" | "frost" | "mint";
/**
* Action color schemes. Every one keeps the PioSolver rule a coach expects:
* fold, check-or-call and bet-or-raise read as three different colors, and
* check always matches call (check once shared fold's blue, which read as a
* fold when the hero was the aggressor). Ranges default to Mint.
*/
export const ACTION_PALETTES: Record<ActionPaletteId, ActionPalette> = {
classic: {
label: "Classic",
Fold: "#3b82f6",
Check: "#10b981",
Call: "#10b981",
Bet: "#ff4757",
Raise: "#c41e3a",
AllIn: "#8b1538",
raises: ["#ff4757", "#e0294f", "#c41f44", "#9c1838", "#8b1538"],
},
// Muted tones for a dark page: a steel-blue fold (black stays "not in
// range"), mint call, rose raises.
midnight: {
label: "Midnight",
Fold: "#4a6a94",
Check: "#55b888",
Call: "#55b888",
Bet: "#e8717f",
Raise: "#c9566a",
AllIn: "#8f3b52",
raises: ["#e8717f", "#d65f72", "#bf4d64", "#a64057", "#8f3b52"],
},
// Cool hues only: slate-blue fold, teal for the passive line, violet for aggression.
frost: {
label: "Frost",
Fold: "#5a7896",
Check: "#4fc4b4",
Call: "#4fc4b4",
Bet: "#9b8cfa",
Raise: "#7563e6",
AllIn: "#41308f",
raises: ["#9b8cfa", "#8573ef", "#6f5bdc", "#5945bf", "#41308f"],
},
// The GTO Wizard look: a solid blue fold (black stays "not in range"),
// check and call a soft green, raises a warm red darkening by size.
mint: {
label: "Mint",
Fold: "#4d7ab3",
Check: "#73b76f",
Call: "#73b76f",
Bet: "#dd4c45",
Raise: "#c94440",
AllIn: "#7f2b2a",
raises: ["#dd4c45", "#c94440", "#b23c39", "#993432", "#7f2b2a"],
},
};
export const ACTION_PALETTE_IDS = Object.keys(ACTION_PALETTES) as ActionPaletteId[];
/** The palette ranges, matrices and strategy bars use when none is picked. */
export const DEFAULT_ACTION_PALETTE: ActionPaletteId = "mint";
/** The palette for an id; Mint for none or an unknown one. */
export function actionPalette(id?: ActionPaletteId | null): ActionPalette {
return (id && ACTION_PALETTES[id]) || ACTION_PALETTES[DEFAULT_ACTION_PALETTE];
}
/** Range colors by action label in the default palette, for solver grids and their side panels. */
export const RANGE_COLORS = {
Fold: ACTION_PALETTES[DEFAULT_ACTION_PALETTE].Fold,
Check: ACTION_PALETTES[DEFAULT_ACTION_PALETTE].Check,
Call: ACTION_PALETTES[DEFAULT_ACTION_PALETTE].Call,
Bet: ACTION_PALETTES[DEFAULT_ACTION_PALETTE].Bet,
Raise: ACTION_PALETTES[DEFAULT_ACTION_PALETTE].Raise,
AllIn: ACTION_PALETTES[DEFAULT_ACTION_PALETTE].AllIn,
};
/** Classic action colors (fold blue, check and call green, bets and raises red), for action buttons. */
export const ACTION_COLORS = {
Fold: ACTION_PALETTES.classic.Fold,
Check: ACTION_PALETTES.classic.Check,
Call: ACTION_PALETTES.classic.Call,
Bet: ACTION_PALETTES.classic.Bet,
Raise: ACTION_PALETTES.classic.Raise,
AllIn: ACTION_PALETTES.classic.AllIn,
};
const KIND_ORDER: Record<ActionKind, number> = { fold: 0, call: 1, raise: 2, allin: 3, other: 4 };
/** Fold → call → raises (small to large) → all-in. */
export function sortActions<T extends Pick<NodeAction, "kind" | "sizePct">>(actions: T[]): T[] {
return [...actions].sort(
(a, b) => KIND_ORDER[a.kind] - KIND_ORDER[b.kind] || (a.sizePct ?? 0) - (b.sizePct ?? 0),
);
}
/** Display label for an action token. `stack` labels the all-in. */
export function actionLabel(action: Pick<NodeAction, "action" | "kind">, stack?: number): string {
if (action.kind === "fold") return "Fold";
if (action.action === "Limp") return "Limp";
if (action.kind === "call") return "Call";
if (action.kind === "allin" || action.action === "AI") return stack ? `All-in ${stack}` : "All-in";
if (action.action === "Open") return "Open";
if (action.kind === "raise") return `Raise ${action.action}`;
return action.action;
}
/** The node's actions in display order, each with a stable color and label. */
export function colorActions(
actions: NodeAction[],
stack?: number,
palette?: ActionPaletteId | null,
): { action: NodeAction; label: string; color: string }[] {
const p = actionPalette(palette);
let raise = 0;
return sortActions(actions).map((action) => {
let color: string;
if (action.kind === "fold") color = p.Fold;
else if (action.kind === "call") color = p.Call;
else if (action.kind === "allin") color = p.AllIn;
else color = p.raises[Math.min(raise++, p.raises.length - 1)];
return { action, label: actionLabel(action, stack), color };
});
}
/** Color for an action by kind; a label starting with "Bet" picks the bet red. */
export function actionColor(kind: ActionKind | "check", label?: string, palette?: ActionPaletteId | null): string {
const p = actionPalette(palette);
switch (kind) {
case "fold":
return p.Fold;
case "check":
return p.Check;
case "call":
return p.Call;
case "allin":
return p.AllIn;
case "raise":
return label?.toLowerCase().startsWith("bet") ? p.Bet : p.Raise;
default:
return "#52525b";
}
}
/**
* Four-color deck. Faces read CSS variables so the registry docs can restyle
* them; the fallbacks are the CoinPoker faces the train table uses, and they
* apply wherever those variables are unset.
*/
export const SUIT_FACES = {
h: { sym: "♥", token: "--ps-suit-heart", fallback: "#cf2b35" },
d: { sym: "♦", token: "--ps-suit-diamond", fallback: "#2360c8" },
c: { sym: "♣", token: "--ps-suit-club", fallback: "#2d9447" },
s: { sym: "♠", token: "--ps-suit-spade", fallback: "#23272d" },
} as const;
/** Card face color for one suit character ("h", "d", "c", "s"). */
export function suitTile(suit: string): { sym: string; bg: string } {
const face = SUIT_FACES[suit.toLowerCase() as keyof typeof SUIT_FACES];
if (!face) return { sym: suit, bg: `var(${SUIT_FACES.s.token}, ${SUIT_FACES.s.fallback})` };
return { sym: face.sym, bg: `var(${face.token}, ${face.fallback})` };
}
/** Grade ramp, Call green for perfect through Raise crimson for a blunder. */
export const GRADE_COLORS: Record<Grade, string> = {
perfect: "#10b981",
correct: "#84cc16",
inaccuracy: "#eab308",
mistake: "#f97316",
blunder: "#c41e3a",
};
export const GRADE_LABELS: Record<Grade, string> = {
perfect: "Perfect",
correct: "Correct",
inaccuracy: "Inaccuracy",
mistake: "Mistake",
blunder: "Blunder",
};
/** A counted frequency: `num` of `denom` opportunities, `pct` in [0, 1]. */
export interface StatValue {
num: number;
denom: number;
pct: number;
}
export const STAT_KEYS = [
"vpip",
"pfr",
"rfi",
"threeBet",
"foldToThreeBet",
"cbetFlop",
"cbetFlopIp",
"cbetFlopOop",
"foldToCbetFlop",
"checkRaiseFlop",
"cbetTurn",
"cbetRiver",
"wtsd",
"wonAtShowdown",
] as const;
export type StatKey = (typeof STAT_KEYS)[number];
/** HUD stats for one player, aggregated from their hands. */
export type PlayerStats = { hands: number; netChips: number } & Record<StatKey, StatValue>;
export const STAT_LABELS: Record<StatKey, string> = {
vpip: "VPIP",
pfr: "PFR",
rfi: "RFI",
threeBet: "3-bet",
foldToThreeBet: "Fold to 3-bet",
cbetFlop: "C-bet flop",
cbetFlopIp: "C-bet flop IP",
cbetFlopOop: "C-bet flop OOP",
foldToCbetFlop: "Fold to flop c-bet",
checkRaiseFlop: "Check-raise flop",
cbetTurn: "Double barrel",
cbetRiver: "Triple barrel",
wtsd: "Went to showdown",
wonAtShowdown: "Won at showdown",
};
/** `GET /api/sessions`: the key owner's uploaded sessions, newest first. */
export interface SessionListItem {
id: string;
hero: string;
createdAt: string;
firstHandAt: string | null;
lastHandAt: string | null;
totalHands: number;
heroHandsPlayed: number;
netMbb: number;
sourceName: string | null;
}
/** One session's summary and the hero's stats (trimmed by the proxy). */
export interface SessionSummary {
id: string;
hero: string;
createdAt: string;
heroStats: PlayerStats;
session: {
totalHands: number;
heroHandsPlayed: number;
firstTs: string | null;
lastTs: string | null;
gameType: string | null;
};
}
/** A note Poker Study AI wrote about an opponent once a pattern had enough hands. */
export interface OpponentNote {
id: string;
street: string;
spotLabel: string;
leakType: string;
sampleSize: number;
autoGenerated: boolean;
manualText: string | null;
}
export interface OpponentListItem {
id: string;
displayName: string;
handCount: number;
noteCount: number;
lastSeenAt: string | null;
gameTypes: string[];
}
/** `GET /api/opponents/{id}`. */
export interface OpponentDetail {
opponent: { id: string; displayName: string; handCount: number; firstSeenAt: string | null; lastSeenAt: string | null };
notes: OpponentNote[];
stats: PlayerStats;
}
/** `POST /api/analytics/opponent-limp-range`: hands opponents showed after limping first in. */
export interface LimpRange {
found: boolean;
shownLimps: number;
classes: { handClass: string; count: number; pct: number }[];
byPosition: Record<string, number>;
note?: string;
}
type Tally = Record<Grade, number>;
/** `GET /api/trainer/stats`: drill grades by stack depth and preflop scenario. */
export interface TrainerStats {
overall: { hands: number; correctPct: number; tally: Tally };
buckets: {
key: string;
label: string;
hands: number;
correctPct: number;
scenarios: { key: string; label: string; hands: number; correctPct: number; tally: Tally }[];
}[];
}
/** `POST /api/play/decide`: what the agent does at a table snapshot. */
export interface DecideResponse {
action: string;
amount?: number | null;
/** Which model answered, e.g. "ranges" (solver preflop) or "equity". */
source?: string;
[extra: string]: unknown;
}
/** A table snapshot in the Poker Study AI agent's wire format (cards like "Ah"). */
export interface TableSnapshot {
hole: string[];
board?: string[];
pot?: number;
big_blind?: number;
my_seat: number;
dealer_seat: number;
seats: number[];
valid_actions: (
| { action: "fold" | "check" }
| { action: "call"; amount: number }
| { action: "raise"; min: number; max: number }
)[];
[extra: string]: unknown;
}