# PokerLeagueOS — Full Agent Reference > Full example-driven reference for agent integrations. Everything in `/llms.txt` plus complete request/response pairs, all error codes, idempotency details, and tested end-to-end workflows. Machine-readable schema lives at `/openapi.json`. Base URL: `https://pokerleagueos.com` OpenAPI: `https://pokerleagueos.com/openapi.json` Short reference: `https://pokerleagueos.com/llms.txt` --- ## 1. Quickstart — zero to live tournament One request bootstraps an org, a ghost user, a demo tournament, a clock, and an admin API key. ``` POST /api/quickstart content-type: application/json { "org_name": "Demo League", "session_name": "Friday Night", "email": "agent-caller@example.com", "timezone": "Europe/London", "currency": "GBP" } ``` Every body field is optional. Omit everything to accept defaults. `timezone` is an IANA zone from a curated allowlist (US and European zones) and decides what zone the org's session dates render in; it defaults to "America/Denver". `currency` is one of `USD`, `GBP` or `EUR` and decides what buy-ins, prize pools and payouts display as; it is display only, nothing is converted, and it defaults from the request's Accept-Language header, else `USD`. `locale` is optional, one of `en`, `de`, `fr` or `es`, and decides the language the league's UI, the player companion and its mail render in; it defaults to `en`. All three are changeable afterwards through `PATCH /api/orgs/{slug}/settings`. The API, this document, the OpenAPI document and the `message` / `hint` fields of the error envelope are English whatever the locale; the UI translates a failure by its `code`. ### Successful response (201) ``` { "org_slug": "demo-league-9a2f6b1e", "api_key": "ck_live_…43chars…", "api_key_prefix": "AbCdEfGh", "session_id": "00000000-0000-0000-0000-000000000000", "session_url": "https://pokerleagueos.com/live/…", "clock_url": "https://pokerleagueos.com/clock/…", "openapi_url": "https://pokerleagueos.com/openapi.json", "expires_at": "2026-04-24T12:00:00.000Z", "hints": { "start_clock": "POST /api/orgs/{org_slug}/clock with body {\"sessionId\":\"{session_id}\",\"action\":\"start\"}", "add_player": "POST /api/orgs/{org_slug}/players with body {\"nickname\":\"Alice\"}", "check_in": "POST /api/orgs/{org_slug}/sessions/{session_id}/check-in with body {\"rosterPlayerId\":\"\"}", "retry_safety": "This endpoint is NOT idempotent — a retry after network timeout creates a second trial org. Only retry if you saved no response." }, "next_actions": [ { "rel": "start_clock", "method": "POST", "href": "/api/orgs/{org_slug}/clock" }, { "rel": "add_player", "method": "POST", "href": "/api/orgs/{org_slug}/players" }, { "rel": "docs", "href": "https://pokerleagueos.com/llms.txt" } ], "_warning": "Store `api_key` now; it will not be shown again. The trial org auto-deletes at `expires_at`." } ``` ### Rules - **Store `api_key` on first response.** Only the hash is persisted server-side. There is no recovery. - **Trial orgs expire after 7 days.** A daily cron at 03:00 UTC deletes expired trial orgs and their ghost owners, with a 1-day grace window. - **API keys expire 8 days after creation.** The extra day means that during the grace window you see clean 404s (org gone) rather than 401s (key expired). - **Not idempotent.** Each call creates a new trial. If you retry on a network timeout and the first call actually succeeded, you will have a second orphan trial. The cron will clean both up, but prefer saving the first response before retrying. - **Rate limit 5/hr/IP** (advisory). On serverless the window is per-instance, so a determined attacker can multiply it. This is documented as acceptable for v1. Legitimate agents with >5 trials/hour are rare. ### Error responses - `400 invalid_input` — body failed Zod validation (e.g. bad email, org_name > 100 chars). - `429 rate_limited` — hourly cap hit. `Retry-After` header present. - `503 service_unavailable` — slug collision retry loop failed 5 times. Retry immediately or supply a different `org_name`. --- ## 2. Authentication ``` Authorization: Bearer ck_live_<43-char-base64url> ``` - API keys are **org-scoped**. A key issued for org A cannot touch org B's URL space; requests to `/api/orgs/other-slug/...` return 404. - API keys carry a **role** (`owner`, `admin`, `manager`, `player`). A key cannot grant a role higher than its creator. - Keys from `POST /api/quickstart` are always `admin` role. - **Key management cannot go through a key.** `POST /api/orgs/{slug}/api-keys` rejects callers authenticated via Bearer (to prevent key-rotation loops). Use the web UI to create or rotate post-quickstart. - Revoking a key is a soft-delete — `revoked_at` is set and the key stops working immediately on the next request. The public endpoints listed below accept no auth; they use a session UUID as a read-only capability. They answer 404 when the session does not exist, is private, has not started yet (status `scheduled`), or its league is pending deletion. The two claim endpoints are the exception: they accept a scheduled session. --- ## 3. Error envelope Every non-2xx body is: ``` { "error": "human-readable-message", "code": "machine_code", "message": "human-readable-message", "hint": "what to do next", "doc_url": "https://pokerleagueos.com/llms.txt#anchor", "next_actions": [{ "rel": "login", "href": "/login", "method": "GET" }], "retry_after_seconds": 60 } ``` Agents should branch on `code`. It is always present and is one of the closed enum on the `ErrorEnvelope` schema in `/openapi.json`; the table below is the subset worth handling. The legacy `error` duplicates `message` and is preserved for the web UI. ### Codes you will see | HTTP | code | Meaning | |---:|---|---| | 400 | `invalid_input` | Zod validation failed. `hint` names the field and rule. | | 400 | `missing_field` | Required field absent from body/query/path. | | 401 | `unauthorized` | No auth. Supply Bearer or log in. | | 403 | `forbidden` | Role insufficient, or managing keys or billing via Bearer. | | 403 | `pin_incorrect` | Player PIN did not match. `pin_not_set` when the player has none yet. | | 403 | `billing_disabled` | Billing is switched off in this environment. Home plan limits apply. | | 403 | `plan_limit_reached` | The active roster is at the plan's cap. | | 403 | `subscription_required` | Session create, clone, or starting a scheduled session: the league has no active plan (no paid subscription, comp or trial). Everything else still works. | | 403 | `plan_field_exceeded` | Session create or clone: the league's last tournament had more players than its plan covers. | | 404 | `not_found` | Resource absent, or org/session/key outside your scope. | | 404 | `not_claimed` | Caller has no roster player linked in this org. | | 409 | (situation) | Named for the situation: `nickname_taken`, `already_eliminated`, `seat_occupied`, `past_rebuy_cutoff`, `idempotency_key_in_flight`, `idempotency_key_reused`, and so on. See the enum. | | 429 | `rate_limited` | See `retry_after_seconds` / `Retry-After` header. | | 500 | `internal_error` | Safe to retry. Use `Idempotency-Key` where the endpoint supports it (see §4). | | 503 | `service_unavailable` | Dependency degraded; retry with backoff. | --- ## 4. Idempotency ``` POST /api/orgs/{slug}/clock Idempotency-Key: my-unique-retry-id-123 content-type: application/json { "sessionId": "…", "action": "start" } ``` - Only some mutating endpoints accept `Idempotency-Key`; everywhere else the header is ignored, so a retry re-executes. The wrapped set: `POST /api/orgs/{slug}/clock`, `POST|DELETE /api/orgs/{slug}/eliminations`, `POST /api/orgs/{slug}/players`, `POST /api/orgs/{slug}/sessions`, `POST /api/orgs/{slug}/sessions/{sid}/clone`, `POST /api/orgs/{slug}/sessions/{sid}/check-in`, `POST /api/orgs/{slug}/sessions/{sid}/rebuys`, `POST /api/orgs/{slug}/sessions/{sid}/player-requests`, `POST /api/orgs/{slug}/sessions/{sid}/results`, `POST /api/orgs/{slug}/sessions/{sid}/notify`, `POST /api/orgs/{slug}/sessions/{sid}/recap`, `POST /api/orgs/{slug}/api-keys`, `POST /api/orgs/{slug}/setups`, `POST /api/orgs/{slug}/setups/{setupId}/duplicate`, and the four Library collections (`blind-schedules`, `chip-sets`, `payout-schedules`, `point-charts`). `/openapi.json` is authoritative: an operation lists an `Idempotency-Key` parameter if and only if it is wrapped. - Replaying the **same** key with the **same** body within 24h returns the cached response, with an `Idempotent-Replayed: true` header. - Replaying the **same** key with a **different** body returns `409 conflict` (`code: idempotency_key_reused`). - Sending the **same** key again while the first request is **still running** returns `409 conflict` (`code: idempotency_key_in_flight`). The key is reserved before the handler runs, so concurrent duplicates cannot both execute. Retry after a moment to get the cached response. - Responses above 64KB are not cached — a retry re-executes. - `POST /api/quickstart` is **not** wrapped in idempotency. See §1. --- ## 5. Common workflows ### 5a. "Run a tournament from scratch" ``` # 1. Bootstrap an org POST /api/quickstart {} → { api_key, org_slug, session_id } # 2. Add three players POST /api/orgs/{slug}/players { "nickname": "Alice" } → { id: "p1" } POST /api/orgs/{slug}/players { "nickname": "Bob" } → { id: "p2" } POST /api/orgs/{slug}/players { "nickname": "Carol" } → { id: "p3" } # 3. Check everyone in POST /api/orgs/{slug}/sessions/{sid}/check-in { "rosterPlayerId": "p1" } POST /api/orgs/{slug}/sessions/{sid}/check-in { "rosterPlayerId": "p2" } POST /api/orgs/{slug}/sessions/{sid}/check-in { "rosterPlayerId": "p3" } # 4. Start the clock POST /api/orgs/{slug}/clock { "sessionId": "{sid}", "action": "start" } # 5. Knock someone out later POST /api/orgs/{slug}/eliminations { "sessionId": "{sid}", "rosterPlayerId": "p3" } # 6. Snapshot GET /api/live-tournament?sessionId={sid} → { sessionStatus, clockState, currentBlind, nextBlind, remaining, recentEliminations, prizePool, tableStats, ... } ``` ### 5b. "Who's still in?" ``` GET /api/live-tournament?sessionId={sid} → look at `remaining` (int) and `recentEliminations` (array). ``` This endpoint is public (no auth). The session UUID is the capability. ### 5c. "Reuse the same payouts and league points every week" Library blocks are org-owned and referenced by name, so you build them once: ``` POST /api/orgs/{slug}/payout-schedules { "name": "House standard", "rows": [ { "players": 12, "prize_pool": 240, "positions": [ { "position": 1, "amount": 120 } ] } ] } POST /api/orgs/{slug}/point-charts { "name": "League 2026", "rows": [ { "players": 12, "positions": [ { "position": 1, "points": 100 } ] } ] } ``` Same shape for `/blind-schedules` and `/chip-sets`. A tournament snapshots the payout structure at creation (so editing the block never rewrites a game in progress), while points resolve from the chart against the paid-entrant count when results are saved. ### 5d. "Pause because the pizza arrived" ``` POST /api/orgs/{slug}/clock { "sessionId": "{sid}", "action": "pause", "pauseMessage": "Pizza break" } ``` `resume` later flips it back. Level advance / regress work the same way. ### 5e. "Player wants to rebuy" Self-service — no Bearer needed, PIN-gated: ``` POST /api/public-player-requests { "sessionId": "{sid}", "submitterId": "p1", "pin": "1234", "requestType": "rebuy", "targetPlayerId": "p1" } ``` `submitterId` is the player whose PIN this is; `targetPlayerId` is who the request is about. They are the same person for a rebuy and different for a knockout you are reporting on someone else. Then the host resolves it: ``` PATCH /api/orgs/{slug}/sessions/{sid}/player-requests { "requestId": "...", "action": "accept" } ``` `action` is `accept`, `decline` or `revoke`. POST on the same path is a different operation — it records an already-accepted minigame result (`{ "targetPlayerId": "...", "minigame": "Splash Pot", "hand": "AA" }`). Both need `canCheckInPlayers`; resolving a knockout needs `canRecordEliminations`. ### 5f. "Collect RSVPs for next week" ``` POST /api/orgs/{slug}/sessions/{sid}/rsvp → { rsvpCode } # 8 characters; minted on the first call ``` Share `/rsvp/{rsvp_code}`. The page reads and writes through two public endpoints keyed by that code, with no auth: ``` GET /api/rsvp/{code} → { session, rsvps: [ { name, response, responded_at } ] } POST /api/rsvp/{code} { "name": "Alice", "email": "alice@example.com", "response": "yes" } → { ok: true, id } ``` `response` is `yes`, `no` or `maybe`; `email` is optional and, when it matches exactly one active roster player, links the RSVP to them. A second POST with the same email replaces the first answer; without an email, send the `id` back as `rsvp_id` to replace it. A private session 404s, and a completed or cancelled one refuses the POST with `session_ended`. Emails are never returned. The host reads the full list through `GET /api/orgs/{slug}/sessions/{sid}/rsvp`. ### 5g. "Create a second league" `POST /api/orgs` with `{ "name": "...", "slug": "...", "timezone"?: "..." }` creates an org owned by the signed-in account. It needs a session cookie: an API key belongs to one org and cannot create another. A taken slug, including one held by a league that is pending deletion, is 409 `slug_taken`. --- ## 6. Data model (essential shapes) ```ts interface GameSession { id: string; // uuid name: string; status: "scheduled" | "active" | "paused" | "completed" | "cancelled"; buy_in_amount: number | null; starting_stack: number; level_duration_minutes: number; blinds_config: BlindLevel[]; payout_structure: PayoutStructure | null; max_players_per_table: number; is_private: boolean; is_championship: boolean; // linked to its season but excluded from season points minigames: string[] | null; seating_mode: "on_pay" | "all_at_once" | "manual"; season_id: string | null; scheduled_for: string | null; // ISO-8601; set only while status is "scheduled" complexity: "casual" | "pro" | null; // adaptive-UI persona; null = inferred clock_started_at: string | null; // first start/resume; null until the clock runs // … } interface BlindLevel { level: number; // position in the schedule, breaks included; the clock advances by it. // Screens call a level by its count of non-break rows, so the level // after "4, break" is shown as Level 5 while its `level` is 6. small_blind: number; big_blind: number; ante?: number; duration_minutes?: number; is_break?: boolean; } interface ClockState { current_level: number; time_remaining_seconds: number; is_running: boolean; is_paused: boolean; pause_message: string | null; last_updated_at: string; // ISO-8601 effective_remaining?: number; // server-corrected for drift on reads hand_for_hand: boolean; // freezes the level timer near the bubble, like a pause } interface RosterPlayer { id: string; nickname: string; pin: string | null; // 4 digits, plaintext status: "active" | "archived"; // … } ``` These are excerpts. `/openapi.json` carries the full schema for every request body and every response. Request bodies are generated from the same Zod validators the routes run, so a field there is a field the API actually accepts; response schemas are written by hand alongside them. Response shapes: a list endpoint returns a bare JSON array and a single-resource endpoint returns the resource directly. `GET /api/orgs/{slug}/api-keys` is the one exception and wraps its rows in `{ data, total }`. A few mutations take their argument in the query string rather than a body, so `/openapi.json` lists no request body for them: `DELETE /api/orgs/{slug}/sessions/{id}/check-in` and `.../participants` take `?rosterPlayerId={uuid}`, `DELETE .../managers` takes `?managerId={uuid}`, and `POST /api/orgs/{slug}/sessions/{id}/rsvp` takes nothing at all. A removal that matches nothing (the player was never in that session, or the id is not this league's) answers 404, never a success; so does `link_session_id` on `PATCH /api/orgs/{slug}/seasons/{seasonId}` when the session is not this league's. --- ## 7. Rate limits summary Every limit is per client IP unless the row says otherwise. Names are the keys in `RATE_LIMITS`. | Endpoint | Limit | |---|---| | `POST /api/quickstart` | 5 / hour | | `POST /api/orgs` (orgCreate) | 5 / min | | `POST /api/orgs/{slug}/players`, `.../players/{id}/merge`, `.../players/{id}/claim-link` (orgCreate) | 5 / min | | `DELETE /api/orgs/{slug}`, `DELETE /api/me`, `GET /api/orgs/{slug}/export` (orgDelete) | 3 / min | | Public reads: `/api/live-tournament`, `/api/clock`, `/api/public-feed`, `/api/public-table-assignments`, `/api/public-session-timeline`, `/api/public-minigame-leaderboard`, `/api/public-player-career`, `/api/public-player-tournament`, `GET /api/orgs/{slug}/me/cohost-invite`, `GET /api/me/session-identity` (publicRead) | 60 / min per IP and session | | `/api/public-season-standings`, `/api/public-active-season-standings` (publicRead) | 60 / min | | `/api/public-player-requests` POST, `/api/public-claim-complete` POST, `/api/invites/{token}/claim` POST, `/api/orgs/{slug}/me/profile`, `/api/orgs/{slug}/me/requests`, `PATCH|DELETE /api/orgs/{slug}/seasons/{seasonId}` (publicMutate) | 10 / min | | Host actions: `POST /api/orgs/{slug}/clock`, eliminations, check-in, rebuys, player-requests, minigame-order, timeline POST (clockMutate) | 30 / min | | `POST .../sessions/{id}/notify`, `POST .../sessions/{id}/recap` (notify) | 3 / min | | `POST /api/orgs/{slug}/billing/checkout`, `.../billing/portal` (billing) | 5 / min | | `POST|DELETE /api/orgs/{slug}/league-rules` (leagueRules) | 10 / min | | `/api/public-player-pin`, `/api/public-cohost-invite` (pinEnvelope) | 10 / min per session | | Setting a PIN: `/api/public-player-pin` set, `POST /api/orgs/{slug}/me/pin` (pinSet) | 2 / min | | Verifying a PIN (every PIN-gated endpoint) (pinVerify) | 5 attempts / 15 min per player and IP, in memory | | PIN lockout (pinLockout) | 5 consecutive wrong PINs lock the player for 15 min, stored on the roster row so it holds across every IP; the 429 carries the real seconds left. The lock ends when the window passes or a host resets the PIN; a correct PIN while unlocked clears the count | | Mutating requests made with an API key, any route (apiWrite) | 120 / min per org | | `GET /api/rsvp/{code}` (rsvpRead) | 30 / min per code | | `POST /api/rsvp/{code}` (rsvpSubmit, per code), `POST /api/orgs/{slug}/me/rsvp` | 10 / min | | `POST /api/public-claim-otp` (claimOtp) | 3 / 15 min per session; at most 1 / min and 5 / hour mail to one address, silently | | `POST /api/telemetry` (telemetry) | 30 / min | 429 responses carry `Retry-After`. Back off exponentially from there. --- ## 8. Operational notes - **Multi-tenancy is enforced in-app.** Every query includes `org_id` in its WHERE clause. There is no RLS policy to fall back on — the key alone is the capability. - **Drift-corrected clock reads.** `/api/clock?sessionId=…` returns `timeRemaining` (and `/api/live-tournament` the same value at `clockState.timeRemaining`), and the authenticated `GET /api/orgs/{slug}/clock` returns `effective_remaining`; both are already corrected for drift against the last update. Render countdowns from those, not from the raw `time_remaining_seconds`. - **Real-time via Supabase Broadcast** for web clients; agents should poll `/api/live-tournament` at 2–5s intervals. - **Private sessions** (`is_private: true`) are invisible to the public endpoints (they 404). Use the authenticated `/api/orgs/{slug}/sessions/{id}` instead. - **Championship sessions** (`is_championship: true`) stay linked to their season (they appear in season history and can earn badges) but are excluded from season **points**, so they never move the standings or leaderboard. --- ## 9. Changelog & roadmap - `/changelog` — public release notes. - Deferred to v1.1: claim flow (trial → real org), tournament simulator endpoint, programmatic blog content. --- ## 10. Support - File issues: `support@pokerleagueos.com` - Human companion UI: https://pokerleagueos.com