# Bot WebSocket protocol 0.7

Connect to `wss://arena.natural20.com/bot` from a client that can set the HTTP upgrade header `Authorization: Bearer <bot token>`. Use one socket per token. The service accepts JSON text messages. A fresh connection begins with the client sending its queue request. Match-specific messages identify the match in `hello` and `end`. Turns echo the observation tick.

## A complete exchange

Each line below is a separate WebSocket message. Send a queue request, acknowledge each hello with ready, and answer each observation with a turn. Leave is optional and cancels a waiting ticket.

```json
{"type":"queue","version":"v1","ladder_id":"public"}
```

Wait for `queued` and then `hello`. Save `hello.match_id`, your `bot_id`, the map, rules, opponent and deadlines. Acknowledge the assignment with this message.

```json
{"type":"ready"}
```

When `observation.tick` is 0, the following turn idles legally.

```json
{"type":"turn","tick":0}
```

Send exactly one turn for every new observation. Choose actions from that observation and its offered directions. After `end`, send another `queue` to play again. While waiting in the matchmaking queue, send this message to cancel.

```json
{"type":"leave"}
```

## Bot versions and limits

A bot token authenticates `GET /api/me`. To register a version, send `POST /api/me/versions` with an optional `alias` and `notes` and use the numbered `label` returned with HTTP 201. A newly queued number must be the next one for that bot. Retired labels cannot queue. Version aliases and notes are only published in the competitions where that version appeared.

Read effective start, ownership and concurrency quotas from `GET /api`. The default wire limits are five client messages in a tick, 50 per second outside a match and 4,096 bytes per frame. Reference codes are sent in an error message before the socket closes for a message-rate violation.

## Client message fields

- `queue` requires a version string and accepts an optional `ladder_id` (default `public`). This local registry begins at `v1`. An active existing version can queue. The next sequential label, such as `v2` after `v1`, can be registered on queue. Retired versions and gaps are rejected. [Queue schema](/docs/schema/bot-queue.json)
- `ready` accepts only its type. Send it promptly for every new or resumed hello. [Ready schema](/docs/schema/bot-ready.json)
- `turn` requires the exact integer `tick`. Its type may be omitted. Optional fields are `move` or `dash`, `attack`, and `shout`. Movement values are `N NE E SE S SW W NW`. An attack is an object with `name` and an optional integer coordinate pair `target`. Use either a move or a dash in one turn. A turn with just its tick idles. [Turn schema](/docs/schema/bot-turn.json)
- `leave` cancels a waiting ticket. During a running match the server answers `in_match`. To finish the current match and stop, stop queuing after `end`. [Leave schema](/docs/schema/bot-leave.json)

```json
{"type":"turn","tick":17,"move":"NE","attack":{"name":"ranged","target":[12,7]}}
```

The server rejects unknown inbound fields. When reading server objects, tolerate fields added in later versions. Native Arena clients use a different envelope on `/bot/native` with `enqueue`, `match_start`, `request` and `act`. Archived Beacon clients use that endpoint. [Native client schema](/docs/schema/client.json)

## Server message fields

- `queued` confirms `version`, `ladder_id` and `estimated_wait_s`. The estimate can change as opponents arrive. [Queued schema](/docs/schema/server-queued.json)
- `hello` carries `protocol_version`, `match_id`, your fighter `bot_id` (1 or 2), `opponent`, `rules`, `map` (rows of tiles), `map_name`, `pickups`, `seed_public` and `deadlines`. Reset per-match state on a different match ID. [Hello schema](/docs/schema/server-hello.json)
- `observation` carries the current tick, `self`, visible enemies and effects, movement offers, the zone, predicted danger and events. A missing enemy is out of sight. See the [combat guide](/docs/combat) and [observation schema](/docs/schema/server-observation.json).
- `end` carries `match_id`, `ladder_id`, `win`, `loss` or `draw` in `result`, plus `reason`, `final_tick`, `opponent_version`, `rating_change`, `replay_url` and optional `watch_url`, `stats` and `voided`. A void reports a draw and `voided:true`. Its rating change is null. A match that never began has no replay. [End schema](/docs/schema/server-end.json)
- `server_draining` gives an absolute `drain_deadline`. Finish the current requests and pause new queue attempts while the server restarts. [Drain schema](/docs/schema/server-draining.json)
- `error` carries a stable `code` and human-readable `message`. [Error schema](/docs/schema/server-error.json)

## Deadlines and reconnects

The hello gives `startup_ms` to send ready, `tick_ms` per turn and `match_budget_ms` across the match. Defaults are 10,000 ms, 1,000 ms and 300,000 ms. A turn must reach the server strictly before its deadline. Send early. A missing or invalid response yields an idle and a strike. A valid response resets the consecutive count. With the default settings, 10 consecutive failures forfeit the match. Old ticks are ignored. A future tick is rejected. A syntactically valid turn can also have a specific action refused by the game with a `rejected` event in the next visible observation.

After socket loss, reconnect promptly with the same token and exponential backoff with jitter. The default grace is 10 seconds and existing deadlines keep running. A resumed seat receives `hello` and its outstanding observation if one is due. Answer its current tick. An initial queue request racing a resumed hello may return `already_queued`; continue the live match. Missing a completed `end` is recoverable by reading `GET /api/matches/<saved-match-id>` or the bot's public match history. WebSocket ping frames need pong responses. Both starters' transports handle them.

## Error and close handling

- `missing_authorization` or `invalid_token` means check the upgrade header and token. `suspended` or `banned` requires an operator. Stop retries with those credentials.
- `replaced` means another socket connected as the same bot. Stop the older client to prevent two clients taking turns replacing each other.
- `already_queued`, `in_match`, `not_in_match` or `not_ready` indicate a phase mismatch. Reconcile the current ticket or hello before sending another control message.
- `invalid_message` indicates malformed JSON or an unsupported control frame. During play, malformed answers can yield `rejected` with part `(message)` and reasons such as `malformed_json`, `schema`, `wrong_tick` or `timeout`. Read your latest observation before retrying on the next tick.
- `version_unknown`, `version_retired`, `bot_or_ladder_unavailable`, `ladder_unavailable` and `account_queue_limit` concern version, access, no-show cooldown, drain or capacity. Confirm your registration and ladder. Three consecutive no-shows can impose a 60-second cooldown.
- Close codes are 4001 (replaced), 4002 (invalid credentials), 4003 (suspended), 4004 (protocol violation) and 4005 (rate limited). Status 1012 signals restart. Status 1009 signals a frame over the configured size. An upgrade may instead return HTTP 429 at the account connection limit or HTTP 503 during drain. Reconnect with backoff for transient failures.
- The combat frame limit defaults to 4,096 bytes. Send one requested answer, serialize once, avoid repeated queue attempts and avoid extra nesting. The default unsolicited frame limit is 200 per second. Credentials belong only in headers.

Public reads use cursor pagination with `items` and `next_cursor`. Continue with `?cursor=<encoded cursor>` when present. See the [HTTP route description](/openapi.json) and [full wire schema collection](/docs/schema/).
