# Standing Orders: rules and hosted agent API **Win by wiping out Red or by holding scoring districts long enough to outscore Red at the time limit.** A wipeout wins regardless of score; if both sides lose their last units in the same volley, the match is a draw. If time expires without a wipeout, the higher exact score wins and an exact tie is a draw. You and the player share Blue; the service controls Red. Create a private match to start the clock, connect to the state stream, load the map named in the first observation, and issue HOLD orders for Blue. Send heartbeats even when you have no orders. Movement, combat, recovery, and scoring run automatically once per second for up to **300 ticks (five minutes)** by default. Read `durationSeconds` for the actual limit and the final `result` for the outcome. ## Game rules ### Companies and the board Each company starts with two Soldiers, two Defenders, one Archer, and 10 coins. All units start at 100 strength. Both sides earn 1 coin every 4 seconds, independent of district control or army size. Send `RECRUIT` to recruit up to one unit per company per tick. It arrives after movement on the next tick and can fire immediately. It takes the free passable tile closest to your depot, with no distance limit. If every passable tile is occupied, the purchase fails without spending coins. Only one living unit can occupy a tile. Send a `REVEAL` order to spend 15 coins to lift your company's fog for 5 seconds. A 55-second cooldown starts when the reveal ends, so each company can reveal at most once every 60 seconds. Reveal shows enemy positions and strength, not their orders, and does not extend any unit's firing sight. | Role | Cost (coins) | Speed | Sight (tiles) | Attack range (tiles) | Base damage | |---|---:|---:|---:|---:|---:| | Soldier | 1 | 1× | 3 | 1 | 6 | | Archer | 2 | 1× | 4 | 3 | 4 | | Rider | 2 | 2× | 3 | 1 | 5 | | Defender | 1 | ⅔× | 3 | 1 | 3 | Adjacent hits deal 50% more damage to Archers and half damage to Defenders (round up). At longer distances both take full damage. Initially every unit holds its own spawn tile. Zero strength is permanent elimination. Deepwood Clearings v1 is the only live map: a 43×37 square grid with seven scoring districts. It uses zero-based integer coordinates `[column,row]` and Manhattan distance `abs(Δcolumn) + abs(Δrow)`. Only the four edge-sharing tiles are adjacent. | Glyph | Terrain | Seconds to enter (Soldier or Archer) | Blocks line of sight through it? | |---|---|---:|---| | `.` | Meadow | 1.5 | No | | `=` | Road | 1 | No | | `+` | Bridge | 1 | No | | `T` | Woods | 2 | Yes; also conceals occupants from nonadjacent observers | | `H` | Hill | Impassable | Yes | | `~` | Water | Impassable | No | Woods concealment is directional: a unit in woods can see out if the line to its target is clear, but a nonadjacent observer cannot see a unit in woods. Hills and intervening woods block sight and fire. When the sight line crosses exactly through a tile corner, either tile flanking that corner can block it. Cover does not reduce the damage of shots that hit. ### Movement and HOLD - HOLD is the only movement order. It sets a destination and optional ordered waypoints; the unit takes a least-time path through each leg in sequence, then stays on the destination until a new order replaces it. It can shoot along the way and while holding, but never leaves its route to chase a target. A HOLD on the current tile, with no waypoints, stops movement. Impassable or unreachable destinations/waypoints and orders for eliminated units are rejected. - Movement resolves in four quarter-second steps within the one-second order and combat tick. Riders take half as long as Soldiers to enter a tile; Defenders take 50% longer. The cost is for the tile entered. A new order preserves progress only if the next step is unchanged. The initial route considers terrain, not other units. Occupied destinations are not automatically illegal orders. - Only one living unit can occupy a tile. When moves are ready on the same substep, Blue has priority on odd ticks and Red on even ticks, then unit IDs are compared lexicographically within the company. Moves resolve in that order: a just-vacated tile can be entered, but units cannot swap directly. If the next tile is occupied, the unit tries to route around friendly units and known enemies while preserving the remaining waypoints. It may encounter an unseen blocker; if it cannot detour it stays `blocked` and retries on later substeps. Equal-cost paths are chosen deterministically in each side's orientation. ### Combat, fog, and recovery - Each tick applies queued orders, resolves movement and economy actions, then resolves a single automatic volley. Every surviving unit at the start of that volley can fire once at the nearest enemy in **its own** sight and range (lexicographically smallest enemy ID breaks distance ties). All shots are selected before damage is applied, so a unit can fire on the tick it dies. Damage from multiple shots adds up. There is no attack command. - Blue sees the whole map, district control and capture, both companies' scores and starting sizes, its own living units and orders, and living enemies within any living Blue unit's sight. Company sight is not permission for another unit to shoot. Enemies with no current sighting disappear; that does not mean they died. A direct movement encounter can reveal a contact for that tick, not a persistent track. Red orders and hidden units' telemetry are private; friendly damage may be reported without identifying the shooter. - To withdraw, HOLD on Blue's exact depot tile. A wounded unit must be holding there and have neither fired nor taken fire for at least six ticks. It then restores 12 HP every three eligible ticks, up to its initial HP. The sixth quiet tick can count as the first eligible tick. Breaking eligibility resets the recovery counter. Recovery is after combat and cannot revive units. ### Districts and scoring Districts start neutral. Count living occupants **after combat**: one or more units of a single team in the district for **15 consecutive ticks** captures it. An empty district, mixed occupancy, or a change of contender breaks that capture streak. An owner keeps control after leaving; mixed occupancy displays `contested` without removing ownership. The owner earns **1 district-second per tick (1 point per minute)** only while it alone has a unit in the district. Scoring starts the tick *after* capture. Empty, contested, and enemy-only districts don't score for the current owner; multiple qualifying districts score independently. Fractional points count. On a wipeout, even on the last tick, use the surviving side (or double-wipeout draw), not the district score. ## Hosted endpoints Use the base URL supplied for your service. For JSON requests send `Content-Type: application/json`. An HTTPS base URL uses `wss://` for the stream; an HTTP base URL uses `ws://`. Preserve the returned match ID exactly. **The match UUID is the only credential.** Anyone with it or the browser link can see Blue's view, submit orders, or end the match. Share the resolved `match_url` privately with the player, not in public logs or recordings. There are no accounts, API keys, spectator tokens, replay, or read-only links. | Method and path | Request and success response | |---|---| | `GET /llms.txt` | No credentials or body. **200** with this guide as plain-text Markdown. | | `GET /healthz` (also `GET /health`) | No body. **200** `{"status":"ok"}`; does not indicate spare capacity. | | `POST /matches` | Send `{}` to use the default Scripted opponent, or `{"opponent":"scripted"}`. **201** with `match_id` and `match_url`. Starts a new match immediately. | | `GET /matches/setup` | No body or query parameters. **200** with Blue's starting economy, including recruit costs and role stats, plus `manual` rule facts such as starting troops and match duration. | | `GET /matches/{id}` | No body. **200** live summary, or final Blue snapshot after termination. | | `WS /matches/{id}/state` | Receive Blue snapshots and send orders, heartbeats, or early end as JSON text frames. No auth frame. | | `GET /maps/{mapId}.json` | **200** map definition. Check `id` and `version` against the snapshot. | | `GET /client/terrain.json` | **200** terrain glyph names, passability, and sight blocking. Use snapshot `terrainMoveCosts` for live movement costs. | | `GET /live?match={id}` | **200** browser UI; use the returned `match_url`. | ### Create and keep a match alive The examples below are from a short private match; its expired UUID is only an example. Successful creation returns: ```json {"match_id":"325ac789c05044f081c674fc1bdb3d79","match_url":"/live?match=325ac789c05044f081c674fc1bdb3d79"} ``` Resolve `match_url` against the service URL: for `MATCH_ID`, open `https:///live?match=MATCH_ID`. A browser can watch live while the agent stays connected and plays. Both see Blue's fog-filtered view; the browser can also issue Blue orders, so agree on who controls which units. For a rematch, create a new match and share its new link. `scripted` is the only supported opponent and runs a rules-based policy as Red. `opponentMode` reports the mode. Creation does not wait for Red's first turn. Failure to initialize can return **503**; failure to produce Red's first turn in time ends the match with `endReason: "failed"`. The live status read is a summary, not a substitute for the state stream: ```json {"matchId":"325ac789c05044f081c674fc1bdb3d79","status":"live","opponentMode":"scripted","tick":0,"durationSeconds":12,"scores":{"blue":0.0,"red":0.0},"result":null} ``` Send `{"type":"heartbeat"}` on the socket about every **10 seconds**, even when not ordering. The reply is `{"type":"heartbeat","status":204}`. To end the match early without a winner, send `{"type":"end"}`. The successful reply is `{"type":"end","status":204}`, followed by the terminal snapshot and normal close. Neither message takes extra fields. A successful heartbeat or newly accepted Blue order renews the **30-second** idle timer; reads, a connected socket, replaying a command ID, and Red activity don't. Disconnects don't pause the match. Retry the stream with the same UUID and backoff, and treat its first frame as the latest state, not a replay of missed ticks. After a match ends, only its final snapshot is retained, by default for **600 seconds**. A service restart invalidates existing UUIDs. ### Load and interpret the map Percent-encode `mapId` as one URL path segment. Use the `mapId` and `mapVersion` from a state frame rather than assuming a default. This Deepwood Clearings response excerpt shows only the first row, one district, and the first camp tile for each team: ```json { "schema_version": 1, "id": "deepwood_clearings", "version": 1, "name": "Deepwood Clearings", "width": 43, "height": 37, "layout": "square", "rows": ["HHHHTT~~T........TTTT.TTTT........T~~TTHHHH"], "districts": { "westwood_glade": { "center": [4, 5], "cells": [[3, 4], [4, 4], [5, 4], [3, 5], [4, 5], [5, 5], [3, 6], [4, 6], [5, 6]] } }, "camps": {"blue": [[3, 18]], "red": [[39, 18]]}, "depots": {"blue": [4, 19], "red": [38, 19]} } ``` | Map field | Interpretation | |---|---| | `id`, `version` | Match these to the snapshot's `mapId` and `mapVersion`. | | `rows`, `width`, `height` | One glyph per tile. For the `square` layout, read `rows[row][column]`. | | `districts` | Keyed by district ID. Each `cells` list contains every tile in that district; `center` is one of them. | | `camps`, `depots` | Keyed by team. Camps list spawn tiles; depots are single tiles. | ### Submit an order The server queues accepted orders for the next simulation tick after it receives them. The caller does not choose a tick. For a HOLD, use a living Blue `unit_id` and a legal destination on the map. ```json {"type":"order","order":{ "match_id": "325ac789c05044f081c674fc1bdb3d79", "command_id": "guide-example-1", "unit_id": "blue-1", "type": "HOLD", "destination": [3, 18], "waypoints": [] }} ``` All three IDs are strings of 1–128 characters; `match_id` must match the path. `destination` and each of up to 32 optional `waypoints` are pairs of integers. Optional `message` is 1–240 characters of plain text or `null`; it appears in Blue's applied-order event. Unknown fields are rejected. ```json {"type":"order","status":200,"match_id":"325ac789c05044f081c674fc1bdb3d79","command_id":"guide-example-1","accepted_tick":1,"revision":2} ``` For a group HOLD, replace `unit_id` with `unit_ids`, a list of 1–128 distinct living Blue IDs. Use the same destination and optional waypoints. For multiple units the server assigns distinct reachable endpoints near the requested tile. It avoids friendly units outside the group and leaves room for the group to reach its endpoints. The order is queued only if every unit can be assigned an endpoint. For a recruit or reveal, omit the HOLD-specific fields. Include `match_id` and a fresh `command_id`: ```json {"type":"order","order":{"match_id":"325ac789c05044f081c674fc1bdb3d79","command_id":"recruit-1","type":"RECRUIT","role":"Rider"}} ``` ```json {"type":"order","order":{"match_id":"325ac789c05044f081c674fc1bdb3d79","command_id":"reveal-1","type":"REVEAL"}} ``` Each company can queue at most one `RECRUIT` and one `REVEAL` per tick. The company must already have enough coins when queueing. If recruiting fails because every passable tile is occupied when the order executes, use a new command ID to try again after freeing a tile. An acknowledgement confirms queueing, not execution. `accepted_tick` is the tick the server assigned. The last order accepted for a given unit and tick wins. The frame at the acknowledged `revision` can confirm application with `order_applied` and its `command_id`. If that frame was missed, use the latest authoritative unit state. Use a new `command_id` for each new decision, unique across all Blue clients. If the connection drops before the reply, reconnect and retry the **same order and ID**: while live, the server returns the cached acknowledgement or rejection for that ID without applying it again. Use a new ID for a correction. No IDs can be retried after termination. ### Read state and results **Read the latest snapshot.** JSON frames with a top-level `type` are replies; the other frames are snapshots. Replace your match state with each newer `revision` for the same `matchId`. Snapshots are complete, not patches. `tick` and `elapsedSeconds` count processed seconds; a revision can change without advancing the tick. | To find… | Read… | |---|---| | Units and their positions | `units` lists every living Blue unit and only currently visible living Red units. Each entry has `id`, `team`, `role`, `position`, `strength`, and `maxStrength`. A missing Red unit may have gone out of sight rather than died. | | What a Blue unit is doing | `movement.status` is `moving`, `holding`, or `blocked`. `route` is the remaining path, `progress` is the number of quarter-second steps accrued toward the next tile, and `holdDestination` is its assigned HOLD tile. `tactics.recoverySeconds` counts eligible ticks toward the next heal. Red entries omit `movement` and `tactics`. | | What Blue can see | `vision.visibleHexes` contains visible tiles, including the whole board during a reveal. `vision.contacts` lists encounter-only sightings for this tick rather than persistent enemy tracks. | | Where points come from | `scores` gives both point totals. `districts` is keyed by map district ID. Each entry has `control` (`blue`, `red`, `neutral`, or `contested`), `scoreRatePerMinute` (0 or 1), and `capture` (`null` or an object with `team`, `elapsedSeconds`, and `requiredSeconds`). | | What you can buy | `economy` gives Blue's `coins`, `incomeCoins`, `incomeEverySeconds`, `recruitCosts`, `roleStats`, and `reveal` timers. `reveal.cooldownSecondsRemaining` counts down until you can queue a reveal for the next tick if you can afford it. `terrainMoveCosts` gives live tile entry times for Soldiers and Archers. | | What just happened | `events` lists permitted events for this tick, not a history. Match applied HOLDs to `order_applied.command_id`. Economy events include `recruited`, `recruit_blocked`, and `fog_revealed`. `combatants` gives information about participants in combat events when Blue is allowed to know it. | **Read the outcome.** When `status` is `finished`, use `result`, not the score leader or the socket close, to determine the winner. | `endReason` | `result` | |---|---| | `completed` | `blue`, `red`, or `draw` by score at the time limit. | | `wipeout` | `blue` or `red` for the surviving company, or `draw` if both are eliminated. | | `abandoned` | `null`; Blue's idle timer expired. | | `ended` | `null`; Blue sent an early-end command or the server shut the match down. | | `failed` | `null`; the opponent or match failed. | The final snapshot includes `advantageHistory`, the signed Blue-minus-Red margin for each elapsed second starting at zero. Divide each value by 60 to convert it to points. If you miss the last frame, reconnect or use `GET /matches/{id}` during retention to get the final snapshot. While the match is live, the HTTP route returns only a summary, not units or events. A reconnect that closes with **4404** means the match is not available on that server. ### Errors, limits, and retries Socket errors include `type` and a numeric `status`; order replies also include the supplied `command_id` (or `null` if it is missing or not a string). Most errors return a string in `detail`, e.g. `{"detail":"Match has ended"}`. Schema errors return a list of validation issues in `detail`. For example, `POST /matches` with `{"opponent":"strong"}` returns **422**: ```json {"detail":[{"type":"literal_error","loc":["body","opponent"],"msg":"Input should be 'scripted'","input":"strong","ctx":{"expected":"'scripted'"}}]} ``` | Status | Meaning and action | |---|---| | **403** | Order for Red; use a Blue unit. On a stream upgrade, can mean socket capacity; back off. | | **404** | UUID unknown/expired; stop using it. For orders, it can also mean an unknown unit: check live status and fresh state. | | **405** | Method not supported for the path; check the endpoint table. | | **409** | Mismatched UUID or match already ended. Check the IDs or read the final result. | | **413** | HTTP creation body too large. | | **422** | Invalid schema or illegal order (e.g. unreachable tile, eliminated unit, insufficient coins, or reveal on cooldown). Correct it before submitting a new ID. | | **429** with `Retry-After` or `retry_after` | HTTP or socket rate limit. Wait at least that many seconds; for a new decision use fresh state. | | **429** without a retry time | Match/stream capacity: back off. For a full order-ID cache, no new IDs are admitted in that match; existing IDs still work while live. | | **503** | Match initialization failed before getting a UUID, or the service is temporarily unavailable. Back off before retrying. | WebSocket closes: **1000** after the final snapshot; **4404** for an unknown or expired UUID; **1003** for unsupported client data; **1009** for input over 32 KiB; **1012** when the server must restart before the match ends; **1013** when a socket operation times out. Reconnect with backoff. Stream capacity can deny the HTTP upgrade with **429** or **403**. If either persists, check live status and stop trying once the match ends. Don't interpret a **403** as proof the UUID is invalid. Back off on transport errors and transient **408**, **429**, **500**, **502**, **503**, or **504** responses; respect any retry time. Bound retries, including for final reads, and stop when a definitive response arrives. An ambiguous create isn't idempotent: retrying may start a second match. For an ambiguous order, reuse the same ID and body. For an ambiguous end, check status. | Limit | Default | |---|---:| | Create / order / heartbeat / end attempts per IP per rolling 60 seconds | 12 / 600 / 480 / 60 | | Active matches per IP / total | 32 / 192 | | Private sockets per IP / total | 64 / 384 | | Cached Blue command IDs per live match (including cached rejections) | 4,096 | | Create body size; WebSocket input limit | 16 KiB; 32 KiB | | Idle timeout; final snapshot retention; Red first-turn timeout | 30 s; 600 s; 5 s | Write quotas are shared across matches on the same IP and count attempts, not just successful writes. There is no limit-discovery endpoint. Don't resubmit HOLDs that are already in effect. ## Copy-and-run example This small client sends one HOLD toward a district and keeps the match alive until it reads the result. It assumes a working connection; add the reconnect and retry behavior above for unattended use. Save it as `bot.py`, install `httpx` and `websockets>=16`, and run `python bot.py https://your-service.example` with your service URL. No game SDK or source checkout is needed. ```python import asyncio import json import sys from urllib.parse import quote, urljoin, urlsplit from uuid import uuid4 import httpx from websockets.asyncio.client import connect async def heartbeat(socket): while True: await asyncio.sleep(10) await socket.send(json.dumps({"type": "heartbeat"})) async def play(base): async with httpx.AsyncClient(base_url=base.rstrip("/") + "/") as http: info = (await http.post("matches", json={})).raise_for_status().json() match = f"matches/{info['match_id']}" print("Share privately:", urljoin(base, info["match_url"]), flush=True) url = urlsplit(str(http.base_url.join(f"{match}/state"))) stream = url._replace(scheme="wss" if url.scheme == "https" else "ws").geturl() async with connect(stream) as socket: keepalive = asyncio.create_task(heartbeat(socket)) try: centers = pending = None ordered = False attempted_tick = -1 async for raw in socket: view = json.loads(raw) if view.get("type") == "heartbeat": continue if view.get("type") == "order": if view["command_id"] != pending: continue pending = None if view["status"] in (404, 409): continue if view["status"] != 200: raise RuntimeError(f"Order failed: {view['status']}") print("Queued HOLD for tick", view["accepted_tick"], flush=True) ordered = True continue if view["status"] == "finished": if not ordered: raise RuntimeError(f"No HOLD acknowledged over WebSocket " f"(match {view['status']}: {view['endReason']})") print(view["endReason"], view["result"], view["scores"]) return 0 if view["result"] in ("blue", "red", "draw") else 1 tick = view["tick"] if ordered or pending is not None or tick <= attempted_tick: continue attempted_tick = tick if centers is None: map_id, version = view["mapId"], view["mapVersion"] path = quote(map_id, safe="") board = (await http.get(f"maps/{path}.json")).raise_for_status().json() if (board["id"], board["version"]) != (map_id, version): raise RuntimeError("Map identity did not match the observation") centers = [district["center"] for district in board["districts"].values()] unit = next(unit for unit in view["units"] if unit["team"] == "blue") pending = uuid4().hex order = { "match_id": info["match_id"], "command_id": pending, "unit_id": unit["id"], "type": "HOLD", "destination": centers[0] if centers else unit["position"], } await socket.send(json.dumps({"type": "order", "order": order})) raise RuntimeError("State stream closed before the match finished") finally: keepalive.cancel() await asyncio.gather(keepalive, return_exceptions=True) raise SystemExit(asyncio.run(play(sys.argv[1]))) ```