# Crusader SDK — complete documentation

<!-- docs/api.md -->

# API reference

Generated from the client and command metadata. Examples are illustrative; game state and IDs determine whether commands succeed.

<a id="state"></a>
## state

Return the current visible game state.

Returns `State`; use its owned units and buildings to choose IDs for orders. Enemy information is limited to visible state. Unit IDs can be reused after death, so read them fresh before ordering.

```python
game.state()
```

The returned `State` includes `tick`, `stock`, `units`, and `buildings`; values depend on the running game.

See also: [related reference](reference/state.md); [refusals](reference/errors.md#state).

```python
state(self) -> State
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| — | — | — | — |

**Returns:** `State`

**Refusals:** See [errors for state](reference/errors.md#state); bridge-wide validation can also reject a request.

<a id="map"></a>
## map

Return the inclusive tile rectangle as text. The default rectangle runs from (0, 0) through (399, 399), inclusive.

Returns a string. Invalid rectangles are refused; coordinates include both endpoints.

```python
game.map(220, 220, 240, 240)
```

The return is a newline-separated string; the result contents depend on the terrain.

See also: [related reference](reference/map-legend.md); [refusals](reference/errors.md#map).

```python
map(self, x0: int=0, y0: int=0, x1: int=399, y1: int=399) -> str
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `x0` | `int` | `0` | 0..399; x0 <= x1 |
| `y0` | `int` | `0` | 0..399; y0 <= y1 |
| `x1` | `int` | `399` | 0..399; x1 >= x0 |
| `y1` | `int` | `399` | 0..399; y1 >= y0 |

**Returns:** `str`

**Refusals:** See [errors for map](reference/errors.md#map); bridge-wide validation can also reject a request.

<a id="find_sites"></a>
## find_sites

Find valid building sites, optionally near a tile. The optional near tile narrows the search around a location; the default limit is 5.

Returns `list[Site]`. `limit` must be 1–50; unknown or unavailable buildings are refused. Without `near`, the driver searches around the mission keep, otherwise (235, 230). Queued builds are treated as occupied, even before the map shows them. A site does not guarantee that you can afford a build.

```python
game.find_sites("woodcutter", limit=3, near=(235, 230))
```

Each returned site has `x` and `y`; the list may be empty.

See also: [related reference](commands/economy.md#build); [refusals](reference/errors.md#find_sites).

```python
find_sites(self, building: str, limit: int=5, near: tuple[int, int] | None=None) -> list[Site]
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `building` | `str` | `required` | Building or siege engine placement name (not ID); woodcutter, stockpile, hovel, quarry, wheat_farm, hops_farm, apple_orchard, dairy_farm, mill, bakery, brewery, market, hunters_post, granary, armory, barracks, inn, chapel, church, well, fletcher, poleturner, blacksmith, armourer, tanner, mercenary_post, iron_mine, lookout_tower, perimeter_tower, defense_turret, square_tower, round_tower, gatehouse, large_gatehouse, engineers_guild, tunnelers_guild, stables, cathedral, apothecary, ox_tether, pitch_rig, maypole, dancing_bear, small_garden, medium_garden, large_garden, statue, shrine, gallows, cess_pit, stocks, burning_stake, dungeon, stretching_rack, gibbet, chopping_block, dunking_stool, gatehouse_turned, large_gatehouse_turned, drawbridge, killing_pit, pitch_ditch, dog_cage, oil_smelter, water_pot, keep, catapult, trebuchet, battering_ram, siege_tower, portable_shield, fire_ballista; availability depends on driver level and mission |
| `limit` | `int` | `5` | 1..50 |
| `near` | `tuple[int, int] \| None` | `None` | — |

**Returns:** `list[Site]`

**Refusals:** See [errors for find_sites](reference/errors.md#find_sites); bridge-wide validation can also reject a request.

<a id="look"></a>
## look

Centre the camera on a tile and return its visible area.

The current real backend refuses camera control; do not rely on this command to reveal an area.

```python
game.look(235, 230)
```

See also: [related reference](how-it-works.md); [refusals](reference/errors.md#look).

```python
look(self, x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `x` | `int` | `required` | — |
| `y` | `int` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for look](reference/errors.md#look); bridge-wide validation can also reject a request.

<a id="select"></a>
## select

Select owned soldiers by ID.

Pass 1–500 distinct IDs of your live soldiers. Invalid, enemy, or dead units are refused. Selection changes the game selection.

```python
game.select([12, 13])
```

On success the return has a `tribe` field; its value is assigned by the game.

See also: [related reference](commands/military.md#move); [refusals](reference/errors.md#select).

```python
select(self, unit_ids: Iterable[int]) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int]` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for select](reference/errors.md#select); bridge-wide validation can also reject a request.

<a id="events"></a>
## events

Return events with sequence numbers at or after since. The since value is inclusive and defaults to 0.

The driver treats `since` as an inclusive offset into its event list, from 0 through the current event count. An invalid offset is refused. Use `next_since` from `advance()` to fetch newer events; this is not a tick number. Event fields vary; do not assume optional fields are present.

```python
game.events(since=0)
```

If there are no events at or after the offset, the return is `[]`.

See also: [related reference](reference/events.md); [refusals](reference/errors.md#events).

```python
events(self, since: int=0) -> list[Event]
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `since` | `int` | `0` | 0..current event count |

**Returns:** `list[Event]`

**Refusals:** See [errors for events](reference/errors.md#events); bridge-wide validation can also reject a request.

<a id="build"></a>
## build

Place a building at the top-left tile of its footprint.

The driver checks terrain, mission menu and the game’s placement rules, then checks the live cost table for wood, stone and gold (also iron and pitch where supported). It queues placement for the next time game time moves; the response includes `queued`, `x`, `y`, and a note. Queued footprints count as occupied for later site searches. A later `build_refused` event is possible.

```python
game.build("woodcutter", 235, 230)
# On success, for the stated example and a suitable game state:
# {"queued": "woodcutter", "x": 235, "y": 230, "note": "placed when game time next moves"}
```

See also: [related reference](commands/observe.md#find_sites); [refusals](reference/errors.md#build).

```python
build(self, building: str, x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `building` | `str` | `required` | Building placement name (not ID); woodcutter, stockpile, hovel, quarry, wheat_farm, hops_farm, apple_orchard, dairy_farm, mill, bakery, brewery, market, hunters_post, granary, armory, barracks, inn, chapel, church, well, fletcher, poleturner, blacksmith, armourer, tanner, mercenary_post, iron_mine, lookout_tower, perimeter_tower, defense_turret, square_tower, round_tower, gatehouse, large_gatehouse, engineers_guild, tunnelers_guild, stables, cathedral, apothecary, ox_tether, pitch_rig, maypole, dancing_bear, small_garden, medium_garden, large_garden, statue, shrine, gallows, cess_pit, stocks, burning_stake, dungeon, stretching_rack, gibbet, chopping_block, dunking_stool, gatehouse_turned, large_gatehouse_turned, drawbridge, killing_pit, pitch_ditch, dog_cage, oil_smelter, water_pot, flag_1, flag_2, flag_3, flag_4, heads, brazier, mangonel, ballista; availability depends on driver level and mission |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |

**Returns:** `CommandResult`

**Refusals:** See [errors for build](reference/errors.md#build); bridge-wide validation can also reject a request.

<a id="demolish"></a>
## demolish

Demolish an owned building.

The ID must be an owned building and cannot be the keep. Removal occurs when game time next moves; part of the cost is refunded. A later `demolish_refused` event is possible.

```python
game.demolish(12)
# On success, for the stated example and a suitable game state:
# {"queued": "demolish", "building_id": 12, "type": "woodcutter", "note": "removed when game time next moves; part of its cost is refunded"}
```

See also: [related reference](commands/observe.md#events); [refusals](reference/errors.md#demolish).

```python
demolish(self, building_id: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `building_id` | `int` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for demolish](reference/errors.md#demolish); bridge-wide validation can also reject a request.

<a id="set_tax"></a>
## set_tax

Set tax from -3 to 8. The accepted level is -3 through 8.

Negative levels are bribes; zero means no tax and positive levels increase tax. The driver returns the selected level in `tax`. Levels outside -3..8 are refused.

```python
game.set_tax(1)
# On success, for the stated example and a suitable game state:
# {"tax": 1}
```

See also: [related reference](commands/observe.md#report); [refusals](reference/errors.md#set_tax).

```python
set_tax(self, level: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `level` | `int` | `required` | -3..8 |

**Returns:** `CommandResult`

**Refusals:** See [errors for set_tax](reference/errors.md#set_tax); bridge-wide validation can also reject a request.

<a id="set_rations"></a>
## set_rations

Set the ration level. Levels are none, half, normal, extra, and double.

The driver returns the chosen level in `rations`; other names are refused.

```python
game.set_rations("normal")
# On success, for the stated example and a suitable game state:
# {"rations": "normal"}
```

See also: [related reference](commands/observe.md#report); [refusals](reference/errors.md#set_rations).

```python
set_rations(self, level: Literal['none', 'half', 'normal', 'extra', 'double']) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `level` | `str` | `required` | none, half, normal, extra, double |

**Returns:** `CommandResult`

**Refusals:** See [errors for set_rations](reference/errors.md#set_rations); bridge-wide validation can also reject a request.

<a id="trade"></a>
## trade

Buy or sell goods in multiples of five. Quantity must be a nonzero multiple of 5. Positive values buy; negative values sell.

A market is required, and the good must be tradeable. The absolute quantity is at most 500. Purchases are queued in lots of five at the current per-five price, with gold reserved against other queued spending. Sales use game-sized lots: 5 below 50 in stock, 10 below 100, 20 below 200, otherwise 50; an exact requested sale that cannot be made in these lots is refused. The result reports queued quantity and gold; the trade executes when time next moves.

```python
game.trade("wood", 10)
```

On success the return has `queued`, `good`, `qty`, `gold`, and `note`; gold depends on the current game price.

See also: [related reference](reference/goods.md); [refusals](reference/errors.md#trade).

```python
trade(self, good: str, qty: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `good` | `str` | `required` | wood, hops, stone, iron, pitch, wheat, bread, cheese, meat, apples, ale, flour, bows, crossbows, spears, pikes, maces, swords, leather_armor, metal_armor; tradeability depends on game state |
| `qty` | `int` | `required` | nonzero multiple of 5; positive buys, negative sells |

**Returns:** `CommandResult`

**Refusals:** See [errors for trade](reference/errors.md#trade); bridge-wide validation can also reject a request.

<a id="recruit"></a>
## recruit

Recruit soldiers or mercenaries. Count defaults to 1 and must be between 1 and 50.

The unit must be offered by the mission. Depending on unit, a barracks, mercenary post, cathedral or guild is required, along with idle peasants and sufficient gold; some troops also need weapons or horses. The driver reserves resources against other queued spending. The game takes gold and weapons when time next moves; barracks soldiers appear about 40 ticks later, after their peasants walk there. Mercenaries need no weapons. Recruitment is queued, not a guarantee of immediate appearance.

```python
game.recruit("archer", count=2)
```

On success the return has `queued`, `count`, `gold`, and `note`; the gold amount depends on unit and current price.

See also: [related reference](reference/units.md); [refusals](reference/errors.md#recruit).

```python
recruit(self, unit: str, count: int=1) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit` | `str` | `required` | Unit name (not ID); archer, crossbowman, spearman, pikeman, maceman, swordsman, knight, arabian_archer, slave, slinger, assassin, horse_archer, arabian_swordsman, fire_thrower, engineer, laddermen, tunneler, monk; availability depends on driver level and mission |
| `count` | `int` | `1` | 1..50 |

**Returns:** `CommandResult`

**Refusals:** See [errors for recruit](reference/errors.md#recruit); bridge-wide validation can also reject a request.

<a id="move"></a>
## move

Order units to a tile and optional subsequent waypoints. The initial destination may be followed by at most 8 waypoints.

Movement is queued; units set off when game time next moves. Waypoints are walked in order and may be unavailable in the current task. When specified, at least one waypoint is required. In historical campaigns the lord can only move back near his keep or attack.

```python
game.move([12, 13], 230, 225, waypoints=[(235, 225)])
# On success, for the stated example and a suitable game state:
# {"queued": "move", "units": 2, "markers": [[230, 225], [235, 225]], "note": "they walk the markers in order when game time next moves"}
```

See also: [related reference](commands/observe.md#state); [refusals](reference/errors.md#move).

```python
move(self, unit_ids: Iterable[int] | None, x: int, y: int, waypoints: Iterable[Sequence[int]] | None=None) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `waypoints` | `Iterable[tuple[int, int]] \| None` | `None` | 1..8 points if provided; each must be a valid map tile (coordinates 0..399) |

**Returns:** `CommandResult`

**Refusals:** See [errors for move](reference/errors.md#move); bridge-wide validation can also reject a request.

<a id="set_stance"></a>
## set_stance

Set unit stance to stand_ground, defensive, or aggressive. Stances are stand_ground, defensive, and aggressive.

Queues a stance for exactly the specified units. `stand_ground` holds position; `aggressive` pursues nearby enemies. Other stance names are refused.

```python
game.set_stance([12, 13], "defensive")
# On success, for the stated example and a suitable game state:
# {"queued": "stance", "units": 2, "stance": "defensive"}
```

See also: [related reference](#stop); [refusals](reference/errors.md#set_stance).

```python
set_stance(self, unit_ids: Iterable[int] | None, stance: Literal['stand_ground', 'defensive', 'aggressive']) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |
| `stance` | `str` | `required` | stand_ground, defensive, aggressive |

**Returns:** `CommandResult`

**Refusals:** See [errors for set_stance](reference/errors.md#set_stance); bridge-wide validation can also reject a request.

<a id="stop"></a>
## stop

Stop the selected units.

Queues a stop instruction; units stop when game time next moves.

```python
game.stop([12, 13])
# On success, for the stated example and a suitable game state:
# {"queued": "stop", "units": 2, "note": "they stop when game time next moves"}
```

See also: [related reference](#move); [refusals](reference/errors.md#stop).

```python
stop(self, unit_ids: Iterable[int] | None) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for stop](reference/errors.md#stop); bridge-wide validation can also reject a request.

<a id="disband"></a>
## disband

Return soldiers to the campfire as peasants.

Queues disbanding; your lord cannot be disbanded. Nothing is refunded.

```python
game.disband([12, 13])
# On success, for the stated example and a suitable game state:
# {"queued": "disband", "units": 2, "note": "they turn back into peasants when game time next moves"}
```

See also: [related reference](commands/economy.md#recruit); [refusals](reference/errors.md#disband).

```python
disband(self, unit_ids: Iterable[int] | None) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for disband](reference/errors.md#disband); bridge-wide validation can also reject a request.

<a id="patrol"></a>
## patrol

Order units to patrol one to nine points. The route contains 1 to 9 points.

Units walk the points in order and back repeatedly until another order. Points must be on the map. The historical-campaign lord movement restriction also applies to patrols.

```python
game.patrol([12, 13], [(230, 225), (235, 225)])
# On success, for the stated example and a suitable game state:
# {"queued": "patrol", "units": 2, "points": [[230, 225], [235, 225]]}
```

See also: [related reference](#move); [refusals](reference/errors.md#patrol).

```python
patrol(self, unit_ids: Iterable[int] | None, points: Iterable[Sequence[int]]) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |
| `points` | `Iterable[tuple[int, int]]` | `required` | 1..9 points; each point must be a valid map tile (coordinates 0..399) |

**Returns:** `CommandResult`

**Refusals:** See [errors for patrol](reference/errors.md#patrol); bridge-wide validation can also reject a request.

<a id="attack_ground"></a>
## attack_ground

Order ranged units to attack a tile.

Only ranged soldiers can use this order: archers, crossbowmen, slingers, horse archers, Arabian archers and fire throwers. Units keep shooting at the spot from where they stand and pay less attention to other enemies than idle archers. The target must be on the map.

```python
game.attack_ground([12, 13], 240, 230)
# On success, for the stated example and a suitable game state:
# {"queued": "attack_ground", "units": 2, "x": 240, "y": 230}
```

See also: [related reference](#attack); [refusals](reference/errors.md#attack_ground).

```python
attack_ground(self, unit_ids: Iterable[int] | None, x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |

**Returns:** `CommandResult`

**Refusals:** See [errors for attack_ground](reference/errors.md#attack_ground); bridge-wide validation can also reject a request.

<a id="attack_wall"></a>
## attack_wall

Order units to attack an enemy wall tile.

The target tile must be an enemy wall; a non-wall or non-enemy wall is refused.

```python
game.attack_wall([12, 13], 240, 230)
# On success, for the stated example and a suitable game state:
# {"queued": "attack_wall", "units": 2, "x": 240, "y": 230}
```

See also: [related reference](#attack_building); [refusals](reference/errors.md#attack_wall).

```python
attack_wall(self, unit_ids: Iterable[int] | None, x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |

**Returns:** `CommandResult`

**Refusals:** See [errors for attack_wall](reference/errors.md#attack_wall); bridge-wide validation can also reject a request.

<a id="attack"></a>
## attack

Order units to attack an enemy unit.

The target must be a live enemy soldier; allied units are refused. Obtain target IDs from visible state.

```python
game.attack([12, 13], target_id=42)
# On success, for the stated example and a suitable game state:
# {"queued": "attack", "units": 2, "target_id": 42, "note": "they attack when game time next moves"}
```

See also: [related reference](commands/observe.md#state); [refusals](reference/errors.md#attack).

```python
attack(self, unit_ids: Iterable[int] | None, target_id: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |
| `target_id` | `int` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for attack](reference/errors.md#attack); bridge-wide validation can also reject a request.

<a id="attack_building"></a>
## attack_building

Order units to attack an enemy building.

The target ID must identify an enemy building. Inspect visible enemy buildings in state first.

```python
game.attack_building([12, 13], building_id=42)
# On success, for the stated example and a suitable game state:
# {"queued": "attack", "units": 2, "building_id": 42, "note": "they attack when game time next moves"}
```

See also: [related reference](commands/observe.md#state); [refusals](reference/errors.md#attack_building).

```python
attack_building(self, unit_ids: Iterable[int] | None, building_id: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |
| `building_id` | `int` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for attack_building](reference/errors.md#attack_building); bridge-wide validation can also reject a request.

<a id="build_siege"></a>
## build_siege

The 3×3 tent uses `(x, y)` as its top-left tile. Available engines are `catapult`, `trebuchet`, `battering_ram`, `siege_tower`, `portable_shield` and `fire_ballista`. Engineers walk there, build and crew the engine. Gold is charged when time moves; the driver also checks wood and stone. The mission menu, placement or resources may cause refusal. The result reports gold and crew needed; the engine later appears in `state()["units"]`.

```python
game.build_siege([101, 102], "catapult", 45, 60)
```

See also: and [refusals](reference/errors.md#build_siege).

```python
build_siege(self, engineer_ids: Iterable[int] | None, engine: Literal['catapult', 'trebuchet', 'battering_ram', 'siege_tower', 'portable_shield', 'fire_ballista'], x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `engineer_ids` | `Iterable[int] \| None` | `required` | — |
| `engine` | `str` | `required` | catapult, trebuchet, battering_ram, siege_tower, portable_shield, fire_ballista |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |

**Returns:** `CommandResult`

**Refusals:** See [errors for build_siege](reference/errors.md#build_siege); bridge-wide validation can also reject a request.

<a id="man"></a>
## man

Selected engineers walk to an owned engine and fill its vacant crew slots. The result reports `crew_needed`; a full engine is refused. At level 5 the driver checks reachability: tower engines need access via a wall and stairs.

```python
game.man([101, 102], 205)
```

See also: and [refusals](reference/errors.md#man).

```python
man(self, engineer_ids: Iterable[int] | None, engine_id: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `engineer_ids` | `Iterable[int] \| None` | `required` | — |
| `engine_id` | `int` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for man](reference/errors.md#man); bridge-wide validation can also reject a request.

<a id="unman"></a>
## unman

Order the crew of an owned, crewed engine to step off. An engine short of its full crew takes no orders; an engine with no crew is refused.

```python
game.unman(205)
```

See also: and [refusals](reference/errors.md#unman).

```python
unman(self, engine_id: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `engine_id` | `int` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for unman](reference/errors.md#unman); bridge-wide validation can also reject a request.

<a id="buy_ammo"></a>
## buy_ammo

A catapult or trebuchet buys 20 shots for 10 stone. Other engine types and insufficient stone are refused. The queued result reports `stone` and `shots`.

```python
game.buy_ammo(205)
# {"queued": "buy_ammo", "engine_id": 205, "stone": 10, "shots": 20}
```

See also: and [refusals](reference/errors.md#buy_ammo).

```python
buy_ammo(self, engine_id: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `engine_id` | `int` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for buy_ammo](reference/errors.md#buy_ammo); bridge-wide validation can also reject a request.

<a id="throw_cow"></a>
## throw_cow

A crewed catapult or trebuchet throws a dairy farm cow at an on-map tile; the carcass remains where it lands. The driver refuses other engines, no crew or no cows. Returned `cows` is the count at ordering time, not proof of impact.

```python
game.throw_cow(205, 80, 70)
```

See also: and [refusals](reference/errors.md#throw_cow).

```python
throw_cow(self, engine_id: int, x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `engine_id` | `int` | `required` | — |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |

**Returns:** `CommandResult`

**Refusals:** See [errors for throw_cow](reference/errors.md#throw_cow); bridge-wide validation can also reject a request.

<a id="set_ladder"></a>
## set_ladder

Select owned laddermen and an enemy wall tile. They carry and raise a ladder for soldiers to climb. Own and allied walls, non-wall tiles and other unit types are refused.

```python
game.set_ladder([301], 80, 70)
```

See also: and [refusals](reference/errors.md#set_ladder).

```python
set_ladder(self, unit_ids: Iterable[int] | None, x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |

**Returns:** `CommandResult`

**Refusals:** See [errors for set_ladder](reference/errors.md#set_ladder); bridge-wide validation can also reject a request.

<a id="dig_tunnel"></a>
## dig_tunnel

Select owned tunnelers and an on-map entrance tile. A tunneler digs toward the nearest enemy building; the eventual collapse damages that building. The game may refuse placement.

```python
game.dig_tunnel([302], 75, 70)
```

See also: and [refusals](reference/errors.md#dig_tunnel).

```python
dig_tunnel(self, unit_ids: Iterable[int] | None, x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |

**Returns:** `CommandResult`

**Refusals:** See [errors for dig_tunnel](reference/errors.md#dig_tunnel); bridge-wide validation can also reject a request.

<a id="repair"></a>
## repair

Repair an owned tower or gatehouse.

Only damaged owned towers and gatehouses have the repair button. The game calculates wood and stone cost from damage. Repair is refused if resources are short or enemies are nearby (15 tiles in a match against computer lords, 30 otherwise). It queues repair to full HP for the next time game time moves; the result includes wood and stone costs.

```python
game.repair(12)
```

On success the return has `queued`, `building_id`, `wood`, `stone`, and `note`; repair costs depend on damage.

See also: [related reference](commands/observe.md#building_info); [refusals](reference/errors.md#repair).

```python
repair(self, building_id: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `building_id` | `int` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for repair](reference/errors.md#repair); bridge-wide validation can also reject a request.

<a id="set_building_active"></a>
## set_building_active

Set whether buildings of this type are active. The setting applies to buildings of the specified type.

The ID identifies the type: **every owned building of that type** sleeps or wakes. Sleeping buildings stop work. Only types with a sleep button are accepted; the change takes effect when game time next moves.

```python
game.set_building_active(12, False)
```

On success the return has `queued`, `type`, `active`, and `note`; type depends on the chosen building.

See also: [related reference](commands/observe.md#building_info); [refusals](reference/errors.md#set_building_active).

```python
set_building_active(self, building_id: int, active: bool) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `building_id` | `int` | `required` | — |
| `active` | `bool` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for set_building_active](reference/errors.md#set_building_active); bridge-wide validation can also reject a request.

<a id="set_workshop_product"></a>
## set_workshop_product

Set a workshop's product. Products are bows, crossbows, spears, pikes, maces, and swords.

The ID must be an owned fletcher, poleturner or blacksmith. Fletchers make bows or crossbows, poleturners spears or pikes, and blacksmiths maces or swords; a map can also disable a product. The queued selection applies from its next piece of work.

```python
game.set_workshop_product(12, "bows")
# On success, for the stated example and a suitable game state:
# {"queued": "set_workshop_product", "building_id": 12, "weapon": "bows", "note": "it makes this from its next piece of work"}
```

See also: [related reference](commands/observe.md#building_info); [refusals](reference/errors.md#set_workshop_product).

```python
set_workshop_product(self, building_id: int, weapon: Literal['bows', 'crossbows', 'spears', 'pikes', 'maces', 'swords']) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `building_id` | `int` | `required` | — |
| `weapon` | `str` | `required` | fletcher: bows, crossbows; poleturner: spears, pikes; blacksmith: maces, swords |

**Returns:** `CommandResult`

**Refusals:** See [errors for set_workshop_product](reference/errors.md#set_workshop_product); bridge-wide validation can also reject a request.

<a id="set_food_allowed"></a>
## set_food_allowed

Allow or disallow consumption of a food.

Requires an owned granary and a game mode where its food toggles are available. This changes the food consumption flag directly; it does not sell the food. Invalid food or a non-boolean flag is refused.

```python
game.set_food_allowed("bread", False)
# On success, for the stated example and a suitable game state:
# {"food": "bread", "allowed": False}
```

See also: [related reference](commands/observe.md#report); [refusals](reference/errors.md#set_food_allowed).

```python
set_food_allowed(self, food: str, allowed: bool) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `food` | `str` | `required` | apples, cheese, meat, bread |
| `allowed` | `bool` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for set_food_allowed](reference/errors.md#set_food_allowed); bridge-wide validation can also reject a request.

<a id="set_gate"></a>
## set_gate

Set an owned gatehouse or drawbridge with a Boolean `open`. The change is queued for the next time movement. A closed gate or raised drawbridge stops everyone, including your own units.

```python
game.set_gate(42, False)
```

See also: and [refusals](reference/errors.md#set_gate).

```python
set_gate(self, building_id: int, open: bool) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `building_id` | `int` | `required` | — |
| `open` | `bool` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for set_gate](reference/errors.md#set_gate); bridge-wide validation can also reject a request.

<a id="plan_moat"></a>
## plan_moat

Mark a horizontal or vertical line of at most 100 tiles, or remove a plan with `dig=False`. Planning costs nothing. The game marks acceptable land with a two-tile brush; returned `tiles` is line length, not accepted tile count. Marking occurs when time moves; use `dig_moat` to excavate.

```python
game.plan_moat(40, 50, 50, 50)
```

See also: and [refusals](reference/errors.md#plan_moat).

```python
plan_moat(self, x1: int, y1: int, x2: int, y2: int, dig: bool=True) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `x1` | `int` | `required` | 0..399; valid map tile; line must be straight and at most 100 tiles |
| `y1` | `int` | `required` | 0..399; valid map tile; line must be straight and at most 100 tiles |
| `x2` | `int` | `required` | 0..399; valid map tile; line must be straight and at most 100 tiles |
| `y2` | `int` | `required` | 0..399; valid map tile; line must be straight and at most 100 tiles |
| `dig` | `bool` | `True` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for plan_moat](reference/errors.md#plan_moat); bridge-wide validation can also reject a request.

<a id="dig_moat"></a>
## dig_moat

Order eligible owned diggers to a tile of your existing moat plan. They dig the plan tile by tile; dug moat blocks ground units. Other units and unplanned tiles are refused.

```python
game.dig_moat([101], 40, 50)
# {"queued": "dig_moat", "units": 1, "x": 40, "y": 50}
```

See also: and [refusals](reference/errors.md#dig_moat).

```python
dig_moat(self, unit_ids: Iterable[int] | None, x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |

**Returns:** `CommandResult`

**Refusals:** See [errors for dig_moat](reference/errors.md#dig_moat); bridge-wide validation can also reject a request.

<a id="fill_moat"></a>
## fill_moat

Order eligible owned diggers to fill an enemy dug moat tile with earth. Your own or allied moat, an undug plan, and non-diggers are refused. Filling takes unit action.

```python
game.fill_moat([101], 80, 70)
```

See also: and [refusals](reference/errors.md#fill_moat).

```python
fill_moat(self, unit_ids: Iterable[int] | None, x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |

**Returns:** `CommandResult`

**Refusals:** See [errors for fill_moat](reference/errors.md#fill_moat); bridge-wide validation can also reject a request.

<a id="delete_wall"></a>
## delete_wall

Queue removal of one owned wall tile. Removal occurs when time moves; the result notes a half-stone refund, which the game halves again for a low wall. This does not remove moat plans or pitch; use `plan_moat(..., dig=False)` for a plan.

```python
game.delete_wall(40, 50)
```

See also: and [refusals](reference/errors.md#delete_wall).

```python
delete_wall(self, x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |

**Returns:** `CommandResult`

**Refusals:** See [errors for delete_wall](reference/errors.md#delete_wall); bridge-wide validation can also reject a request.

<a id="light_pitch"></a>
## light_pitch

Select archers or Arabian archers and a friendly-team pitch ditch in reach. The first selected unit must be within three tiles of a lit friendly brazier; range is checked from that unit. They shoot burning arrows to ignite the ditch.

```python
game.light_pitch([101], 45, 50)
```

See also: and [refusals](reference/errors.md#light_pitch).

```python
light_pitch(self, unit_ids: Iterable[int] | None, x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `unit_ids` | `Iterable[int] \| None` | `required` | — |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |

**Returns:** `CommandResult`

**Refusals:** See [errors for light_pitch](reference/errors.md#light_pitch); bridge-wide validation can also reject a request.

<a id="oil_duty"></a>
## oil_duty

Assign owned engineers to an owned oil smelter. They work it and can receive oil pots. Other unit or building types are refused. The separate `pour_oil` command is currently unavailable.

```python
game.oil_duty([101], 42)
```

See also: and [refusals](reference/errors.md#oil_duty).

```python
oil_duty(self, engineer_ids: Iterable[int] | None, smelter_id: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `engineer_ids` | `Iterable[int] \| None` | `required` | — |
| `smelter_id` | `int` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for oil_duty](reference/errors.md#oil_duty); bridge-wide validation can also reject a request.

<a id="pour_oil"></a>
## pour_oil

The driver currently refuses this order: the game’s pour click has not been reproduced, and a direct ground order was observed to leave a carrier waiting. It first checks for engineers and at least one carried pot, so those errors may appear instead. Use `oil_duty` to assign engineers, but do not rely on this command to pour.

```python
game.pour_oil([101], 45, 50)  # currently refused
```

See also: and [refusals](reference/errors.md#pour_oil).

```python
pour_oil(self, engineer_ids: Iterable[int] | None, x: int, y: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `engineer_ids` | `Iterable[int] \| None` | `required` | — |
| `x` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |
| `y` | `int` | `required` | 0..399; must form a valid map tile with its paired coordinate |

**Returns:** `CommandResult`

**Refusals:** See [errors for pour_oil](reference/errors.md#pour_oil); bridge-wide validation can also reject a request.

<a id="report"></a>
## report

Return a page of the scribe's book. Pages: popularity, fear, religion, army, food, population, stores, weapons, merit.

Returns a report page; availability and fields depend on the page and game state.

```python
game.report("food")
```

Returned fields vary by page: for example the army page returns `troops` and `fear_bonus`.

See also: [related reference](reference/state.md); [refusals](reference/errors.md#report).

```python
report(self, page: Literal['popularity', 'fear', 'religion', 'army', 'food', 'population', 'stores', 'weapons', 'merit']) -> ReportResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `page` | `str` | `required` | popularity, fear, religion, army, food, population, stores, weapons, merit |

**Returns:** `ReportResult`

**Refusals:** See [errors for report](reference/errors.md#report); bridge-wide validation can also reject a request.

<a id="building_info"></a>
## building_info

Return the panel information for an owned building.

Pass an owned building ID from state; the panel data depends on building type. An invalid or non-owned ID is refused.

```python
game.building_info(12)
```

Returned fields include `id` and `type`, with additional fields according to the panel.

See also: [related reference](reference/state.md); [refusals](reference/errors.md#building_info).

```python
building_info(self, building_id: int) -> BuildingInfo
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `building_id` | `int` | `required` | — |

**Returns:** `BuildingInfo`

**Refusals:** See [errors for building_info](reference/errors.md#building_info); bridge-wide validation can also reject a request.

<a id="ally_order"></a>
## ally_order

Ask a living ally to `"attack"`, `"defend"` or `"cancel"`. Attack requires the player ID of a living enemy lord; the other orders must omit `target`. The ally answers when time moves and may decline; inspect `state()["allies"]["panel"]` for the resulting order.

```python
game.ally_order(2, "attack", target=3)
```

See also: and [refusals](reference/errors.md#ally_order).

```python
ally_order(self, ally: int, order: Literal['attack', 'defend', 'cancel'], target: int | None=None) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `ally` | `int` | `required` | — |
| `order` | `str` | `required` | attack, defend, cancel |
| `target` | `int \| None` | `None` | enemy player ID with a living lord for attack; None for defend or cancel |

**Returns:** `CommandResult`

**Refusals:** See [errors for ally_order](reference/errors.md#ally_order); bridge-wide validation can also reject a request.

<a id="ally_send_goods"></a>
## ally_send_goods

Send a positive multiple of five to a living ally. You must have the requested amount; non-gold goods also need a suitable ally store with room. The driver caps the sent quantity to available room and returns it as `qty`. Goods move when time next moves.

```python
game.ally_send_goods(2, "wood", 25)
```

See also: and [refusals](reference/errors.md#ally_send_goods).

```python
ally_send_goods(self, ally: int, good: str, qty: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `ally` | `int` | `required` | — |
| `good` | `str` | `required` | wood, hops, stone, iron, pitch, wheat, bread, cheese, meat, apples, ale, gold, flour, bows, crossbows, spears, pikes, maces, swords, leather_armor, metal_armor |
| `qty` | `int` | `required` | positive multiple of 5 |

**Returns:** `CommandResult`

**Refusals:** See [errors for ally_send_goods](reference/errors.md#ally_send_goods); bridge-wide validation can also reject a request.

<a id="ally_request_goods"></a>
## ally_request_goods

Request a positive multiple of five from a living ally. For non-gold goods your store must have room for the full amount. The ally decides immediately; it keeps a reserve and will not give gold, so a request can be refused. If accepted, goods arrive when time next moves.

```python
game.ally_request_goods(2, "wood", 25)
```

See also: and [refusals](reference/errors.md#ally_request_goods).

```python
ally_request_goods(self, ally: int, good: str, qty: int) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `ally` | `int` | `required` | — |
| `good` | `str` | `required` | wood, hops, stone, iron, pitch, wheat, bread, cheese, meat, apples, ale, gold, flour, bows, crossbows, spears, pikes, maces, swords, leather_armor, metal_armor |
| `qty` | `int` | `required` | positive multiple of 5 |

**Returns:** `CommandResult`

**Refusals:** See [errors for ally_request_goods](reference/errors.md#ally_request_goods); bridge-wide validation can also reject a request.

<a id="ally_answer"></a>
## ally_answer

Answer a living ally’s outstanding goods request with a Boolean `accept`. Acceptance sends goods subject to your stock and the ally’s storage capacity; returned `qty` may be capped. Refusal tells the ally no. Either action is queued for when time next moves; no outstanding request is refused. Inspect `state()["allies"]` for requests.

```python
game.ally_answer(2, accept=False)
# {"queued": "ally_answer", "ally": 2, "accept": False,
#  "note": "when game time next moves"}
```

See also: and [refusals](reference/errors.md#ally_answer).

```python
ally_answer(self, ally: int, accept: bool) -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `ally` | `int` | `required` | — |
| `accept` | `bool` | `required` | — |

**Returns:** `CommandResult`

**Refusals:** See [errors for ally_answer](reference/errors.md#ally_answer); bridge-wide validation can also reject a request.

<a id="build_wall"></a>
## build_wall

Build a horizontal or vertical line; `kind` defaults to `"wall"` and can also select stairs or crenellations. Lines are limited to 100 tiles, or 12 for stairs. Ordinary wall costs half a stone per tile; low wall costs a quarter per tile. The driver checks affordability and placement before queuing. Stairs must start next to your wall; crenellations are laid beside an existing non-keep wall. The game builds and charges on the next command-processing frame. Stone promised to buildings, ammo or repair in the same pause is not reserved, so a line can end short.

```python
game.build_wall(40, 50, 50, 50)
```

See also: and [refusals](reference/errors.md#build_wall).

```python
build_wall(self, x1: int, y1: int, x2: int, y2: int, kind: str='wall') -> CommandResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `x1` | `int` | `required` | 0..399; valid map tile; straight line, at most 12 tiles for stairs or 100 otherwise |
| `y1` | `int` | `required` | 0..399; valid map tile; straight line, at most 12 tiles for stairs or 100 otherwise |
| `x2` | `int` | `required` | 0..399; valid map tile; straight line, at most 12 tiles for stairs or 100 otherwise |
| `y2` | `int` | `required` | 0..399; valid map tile; straight line, at most 12 tiles for stairs or 100 otherwise |
| `kind` | `str` | `'wall'` | wall, stairs, low_wall, crenel; availability depends on driver level |

**Returns:** `CommandResult`

**Refusals:** See [errors for build_wall](reference/errors.md#build_wall); bridge-wide validation can also reject a request.

<a id="advance"></a>
## advance

Advance by an integer from 1 to 3000 ticks. Queued actions can run and units need time to carry out orders. A finite remaining budget caps the actual advance, and a finished match can stop it early. The result contains the current `tick`, `ticks_left` (or `None` for no budget), and `game_over`; inspect state and returned `events` rather than assuming every queued action completed. `next_since` is the event sequence cursor for a later `events(since)` call, not a tick number.

```python
result = game.advance(100)
print(result["tick"], result["ticks_left"], result["game_over"])
```

See also: and [refusals](reference/errors.md#advance).

```python
advance(self, ticks: int) -> AdvanceResult
```

| Parameter | Type | Default | Constraints |
| --- | --- | --- | --- |
| `ticks` | `int` | `required` | 1..3000 |

**Returns:** `AdvanceResult`

**Refusals:** See [errors for advance](reference/errors.md#advance); bridge-wide validation can also reject a request.

<!-- docs/commands/allies.md -->

# Allies commands

These commands send orders and goods to allies, request goods, and answer requests.

## `ally_order`

Ask a living ally to `"attack"`, `"defend"` or `"cancel"`. Attack requires the player ID of a living enemy lord; the other orders must omit `target`. The ally answers when time moves and may decline; inspect `state()["allies"]["panel"]` for the resulting order.

```python
game.ally_order(2, "attack", target=3)
```

See also: [API reference](../api.md#ally_order) and [refusals](../reference/errors.md#ally_order).


## `ally_send_goods`

Send a positive multiple of five to a living ally. You must have the requested amount; non-gold goods also need a suitable ally store with room. The driver caps the sent quantity to available room and returns it as `qty`. Goods move when time next moves.

```python
game.ally_send_goods(2, "wood", 25)
```

See also: [API reference](../api.md#ally_send_goods) and [refusals](../reference/errors.md#ally_send_goods).


## `ally_request_goods`

Request a positive multiple of five from a living ally. For non-gold goods your store must have room for the full amount. The ally decides immediately; it keeps a reserve and will not give gold, so a request can be refused. If accepted, goods arrive when time next moves.

```python
game.ally_request_goods(2, "wood", 25)
```

See also: [API reference](../api.md#ally_request_goods) and [refusals](../reference/errors.md#ally_request_goods).


## `ally_answer`

Answer a living ally’s outstanding goods request with a Boolean `accept`. Acceptance sends goods subject to your stock and the ally’s storage capacity; returned `qty` may be capped. Refusal tells the ally no. Either action is queued for when time next moves; no outstanding request is refused. Inspect `state()["allies"]` for requests.

```python
game.ally_answer(2, accept=False)
# {"queued": "ally_answer", "ally": 2, "accept": False,
#  "note": "when game time next moves"}
```

See also: [API reference](../api.md#ally_answer) and [refusals](../reference/errors.md#ally_answer).

<!-- docs/commands/defences.md -->

# Defences commands

These commands manage gates, walls, moats, pitch, and oil.

## `set_gate`

Set an owned gatehouse or drawbridge with a Boolean `open`. The change is queued for the next time movement. A closed gate or raised drawbridge stops everyone, including your own units.

```python
game.set_gate(42, False)
```

See also: [API reference](../api.md#set_gate) and [refusals](../reference/errors.md#set_gate).


## `plan_moat`

Mark a horizontal or vertical line of at most 100 tiles, or remove a plan with `dig=False`. Planning costs nothing. The game marks acceptable land with a two-tile brush; returned `tiles` is line length, not accepted tile count. Marking occurs when time moves; use `dig_moat` to excavate.

```python
game.plan_moat(40, 50, 50, 50)
```

See also: [API reference](../api.md#plan_moat) and [refusals](../reference/errors.md#plan_moat).


## `dig_moat`

Order eligible owned diggers to a tile of your existing moat plan. They dig the plan tile by tile; dug moat blocks ground units. Other units and unplanned tiles are refused.

```python
game.dig_moat([101], 40, 50)
# {"queued": "dig_moat", "units": 1, "x": 40, "y": 50}
```

See also: [API reference](../api.md#dig_moat) and [refusals](../reference/errors.md#dig_moat).


## `fill_moat`

Order eligible owned diggers to fill an enemy dug moat tile with earth. Your own or allied moat, an undug plan, and non-diggers are refused. Filling takes unit action.

```python
game.fill_moat([101], 80, 70)
```

See also: [API reference](../api.md#fill_moat) and [refusals](../reference/errors.md#fill_moat).


## `delete_wall`

Queue removal of one owned wall tile. Removal occurs when time moves; the result notes a half-stone refund, which the game halves again for a low wall. This does not remove moat plans or pitch; use `plan_moat(..., dig=False)` for a plan.

```python
game.delete_wall(40, 50)
```

See also: [API reference](../api.md#delete_wall) and [refusals](../reference/errors.md#delete_wall).


## `light_pitch`

Select archers or Arabian archers and a friendly-team pitch ditch in reach. The first selected unit must be within three tiles of a lit friendly brazier; range is checked from that unit. They shoot burning arrows to ignite the ditch.

```python
game.light_pitch([101], 45, 50)
```

See also: [API reference](../api.md#light_pitch) and [refusals](../reference/errors.md#light_pitch).


## `oil_duty`

Assign owned engineers to an owned oil smelter. They work it and can receive oil pots. Other unit or building types are refused. The separate `pour_oil` command is currently unavailable.

```python
game.oil_duty([101], 42)
```

See also: [API reference](../api.md#oil_duty) and [refusals](../reference/errors.md#oil_duty).


## `pour_oil`

The driver currently refuses this order: the game’s pour click has not been reproduced, and a direct ground order was observed to leave a carrier waiting. It first checks for engineers and at least one carried pot, so those errors may appear instead. Use `oil_duty` to assign engineers, but do not rely on this command to pour.

```python
game.pour_oil([101], 45, 50)  # currently refused
```

See also: [API reference](../api.md#pour_oil) and [refusals](../reference/errors.md#pour_oil).


## `build_wall`

Build a horizontal or vertical line; `kind` defaults to `"wall"` and can also select stairs or crenellations. Lines are limited to 100 tiles, or 12 for stairs. Ordinary wall costs half a stone per tile; low wall costs a quarter per tile. The driver checks affordability and placement before queuing. Stairs must start next to your wall; crenellations are laid beside an existing non-keep wall. The game builds and charges on the next command-processing frame. Stone promised to buildings, ammo or repair in the same pause is not reserved, so a line can end short.

```python
game.build_wall(40, 50, 50, 50)
```

See also: [API reference](../api.md#build_wall) and [refusals](../reference/errors.md#build_wall).

<!-- docs/commands/economy.md -->

# Economy commands

These commands manage construction, production, trade, and recruitment. Building placement uses the top-left tile of the footprint. Mutating commands can be refused after game over or when the tick budget is exhausted. IDs and coordinates below are illustrative.

## `build`

Place a building at the top-left tile of its footprint. [API reference](../api.md#build).

The driver checks terrain, mission menu and the game’s placement rules, then checks the live cost table for wood, stone and gold (also iron and pitch where supported). It queues placement for the next time game time moves; the response includes `queued`, `x`, `y`, and a note. Queued footprints count as occupied for later site searches. A later `build_refused` event is possible.

```python
game.build("woodcutter", 235, 230)
# On success, for the stated example and a suitable game state:
# {"queued": "woodcutter", "x": 235, "y": 230, "note": "placed when game time next moves"}
```

See also: [related reference](observe.md#find_sites); [refusals](../reference/errors.md#build).


## `demolish`

Demolish an owned building. [API reference](../api.md#demolish).

The ID must be an owned building and cannot be the keep. Removal occurs when game time next moves; part of the cost is refunded. A later `demolish_refused` event is possible.

```python
game.demolish(12)
# On success, for the stated example and a suitable game state:
# {"queued": "demolish", "building_id": 12, "type": "woodcutter", "note": "removed when game time next moves; part of its cost is refunded"}
```

See also: [related reference](observe.md#events); [refusals](../reference/errors.md#demolish).


## `set_tax`

Set tax from -3 to 8. The accepted level is -3 through 8. [API reference](../api.md#set_tax).

Negative levels are bribes; zero means no tax and positive levels increase tax. The driver returns the selected level in `tax`. Levels outside -3..8 are refused.

```python
game.set_tax(1)
# On success, for the stated example and a suitable game state:
# {"tax": 1}
```

See also: [related reference](observe.md#report); [refusals](../reference/errors.md#set_tax).


## `set_rations`

Set the ration level. Levels are none, half, normal, extra, and double. [API reference](../api.md#set_rations).

The driver returns the chosen level in `rations`; other names are refused.

```python
game.set_rations("normal")
# On success, for the stated example and a suitable game state:
# {"rations": "normal"}
```

See also: [related reference](observe.md#report); [refusals](../reference/errors.md#set_rations).


## `trade`

Buy or sell goods in multiples of five. Quantity must be a nonzero multiple of 5. Positive values buy; negative values sell. [API reference](../api.md#trade).

A market is required, and the good must be tradeable. The absolute quantity is at most 500. Purchases are queued in lots of five at the current per-five price, with gold reserved against other queued spending. Sales use game-sized lots: 5 below 50 in stock, 10 below 100, 20 below 200, otherwise 50; an exact requested sale that cannot be made in these lots is refused. The result reports queued quantity and gold; the trade executes when time next moves.

```python
game.trade("wood", 10)
```

On success the return has `queued`, `good`, `qty`, `gold`, and `note`; gold depends on the current game price.

See also: [related reference](../reference/goods.md); [refusals](../reference/errors.md#trade).


## `recruit`

Recruit soldiers or mercenaries. Count defaults to 1 and must be between 1 and 50. [API reference](../api.md#recruit).

The unit must be offered by the mission. Depending on unit, a barracks, mercenary post, cathedral or guild is required, along with idle peasants and sufficient gold; some troops also need weapons or horses. The driver reserves resources against other queued spending. The game takes gold and weapons when time next moves; barracks soldiers appear about 40 ticks later, after their peasants walk there. Mercenaries need no weapons. Recruitment is queued, not a guarantee of immediate appearance.

```python
game.recruit("archer", count=2)
```

On success the return has `queued`, `count`, `gold`, and `note`; the gold amount depends on unit and current price.

See also: [related reference](../reference/units.md); [refusals](../reference/errors.md#recruit).


## `repair`

Repair an owned tower or gatehouse. [API reference](../api.md#repair).

Only damaged owned towers and gatehouses have the repair button. The game calculates wood and stone cost from damage. Repair is refused if resources are short or enemies are nearby (15 tiles in a match against computer lords, 30 otherwise). It queues repair to full HP for the next time game time moves; the result includes wood and stone costs.

```python
game.repair(12)
```

On success the return has `queued`, `building_id`, `wood`, `stone`, and `note`; repair costs depend on damage.

See also: [related reference](observe.md#building_info); [refusals](../reference/errors.md#repair).


## `set_building_active`

Set whether buildings of this type are active. The setting applies to buildings of the specified type. [API reference](../api.md#set_building_active).

The ID identifies the type: **every owned building of that type** sleeps or wakes. Sleeping buildings stop work. Only types with a sleep button are accepted; the change takes effect when game time next moves.

```python
game.set_building_active(12, False)
```

On success the return has `queued`, `type`, `active`, and `note`; type depends on the chosen building.

See also: [related reference](observe.md#building_info); [refusals](../reference/errors.md#set_building_active).


## `set_workshop_product`

Set a workshop's product. Products are bows, crossbows, spears, pikes, maces, and swords. [API reference](../api.md#set_workshop_product).

The ID must be an owned fletcher, poleturner or blacksmith. Fletchers make bows or crossbows, poleturners spears or pikes, and blacksmiths maces or swords; a map can also disable a product. The queued selection applies from its next piece of work.

```python
game.set_workshop_product(12, "bows")
# On success, for the stated example and a suitable game state:
# {"queued": "set_workshop_product", "building_id": 12, "weapon": "bows", "note": "it makes this from its next piece of work"}
```

See also: [related reference](observe.md#building_info); [refusals](../reference/errors.md#set_workshop_product).


## `set_food_allowed`

Allow or disallow consumption of a food. [API reference](../api.md#set_food_allowed).

Requires an owned granary and a game mode where its food toggles are available. This changes the food consumption flag directly; it does not sell the food. Invalid food or a non-boolean flag is refused.

```python
game.set_food_allowed("bread", False)
# On success, for the stated example and a suitable game state:
# {"food": "bread", "allowed": False}
```

See also: [related reference](observe.md#report); [refusals](../reference/errors.md#set_food_allowed).

<!-- docs/commands/military.md -->

# Military commands

These commands issue orders to units, including movement, stance, patrol, and attacks. Pass 1–500 distinct IDs of your live soldiers, invalid IDs are refused. Although the client accepts `None`, the current real driver requires explicit IDs. Orders are queued and take effect as game time moves. Game over and exhausted tick budgets can also cause refusals. IDs and coordinates in examples are illustrative.

## `move`

Order units to a tile and optional subsequent waypoints. The initial destination may be followed by at most 8 waypoints. [API reference](../api.md#move).

Movement is queued; units set off when game time next moves. Waypoints are walked in order and may be unavailable in the current task. When specified, at least one waypoint is required. In historical campaigns the lord can only move back near his keep or attack.

```python
game.move([12, 13], 230, 225, waypoints=[(235, 225)])
# On success, for the stated example and a suitable game state:
# {"queued": "move", "units": 2, "markers": [[230, 225], [235, 225]], "note": "they walk the markers in order when game time next moves"}
```

See also: [related reference](observe.md#state); [refusals](../reference/errors.md#move).


## `set_stance`

Set unit stance to stand_ground, defensive, or aggressive. Stances are stand_ground, defensive, and aggressive. [API reference](../api.md#set_stance).

Queues a stance for exactly the specified units. `stand_ground` holds position; `aggressive` pursues nearby enemies. Other stance names are refused.

```python
game.set_stance([12, 13], "defensive")
# On success, for the stated example and a suitable game state:
# {"queued": "stance", "units": 2, "stance": "defensive"}
```

See also: [related reference](#stop); [refusals](../reference/errors.md#set_stance).


## `stop`

Stop the selected units. [API reference](../api.md#stop).

Queues a stop instruction; units stop when game time next moves.

```python
game.stop([12, 13])
# On success, for the stated example and a suitable game state:
# {"queued": "stop", "units": 2, "note": "they stop when game time next moves"}
```

See also: [related reference](#move); [refusals](../reference/errors.md#stop).


## `disband`

Return soldiers to the campfire as peasants. [API reference](../api.md#disband).

Queues disbanding; your lord cannot be disbanded. Nothing is refunded.

```python
game.disband([12, 13])
# On success, for the stated example and a suitable game state:
# {"queued": "disband", "units": 2, "note": "they turn back into peasants when game time next moves"}
```

See also: [related reference](economy.md#recruit); [refusals](../reference/errors.md#disband).


## `patrol`

Order units to patrol one to nine points. The route contains 1 to 9 points. [API reference](../api.md#patrol).

Units walk the points in order and back repeatedly until another order. Points must be on the map. The historical-campaign lord movement restriction also applies to patrols.

```python
game.patrol([12, 13], [(230, 225), (235, 225)])
# On success, for the stated example and a suitable game state:
# {"queued": "patrol", "units": 2, "points": [[230, 225], [235, 225]]}
```

See also: [related reference](#move); [refusals](../reference/errors.md#patrol).


## `attack_ground`

Order ranged units to attack a tile. [API reference](../api.md#attack_ground).

Only ranged soldiers can use this order: archers, crossbowmen, slingers, horse archers, Arabian archers and fire throwers. Units keep shooting at the spot from where they stand and pay less attention to other enemies than idle archers. The target must be on the map.

```python
game.attack_ground([12, 13], 240, 230)
# On success, for the stated example and a suitable game state:
# {"queued": "attack_ground", "units": 2, "x": 240, "y": 230}
```

See also: [related reference](#attack); [refusals](../reference/errors.md#attack_ground).


## `attack_wall`

Order units to attack an enemy wall tile. [API reference](../api.md#attack_wall).

The target tile must be an enemy wall; a non-wall or non-enemy wall is refused.

```python
game.attack_wall([12, 13], 240, 230)
# On success, for the stated example and a suitable game state:
# {"queued": "attack_wall", "units": 2, "x": 240, "y": 230}
```

See also: [related reference](#attack_building); [refusals](../reference/errors.md#attack_wall).


## `attack`

Order units to attack an enemy unit. [API reference](../api.md#attack).

The target must be a live enemy soldier; allied units are refused. Obtain target IDs from visible state.

```python
game.attack([12, 13], target_id=42)
# On success, for the stated example and a suitable game state:
# {"queued": "attack", "units": 2, "target_id": 42, "note": "they attack when game time next moves"}
```

See also: [related reference](observe.md#state); [refusals](../reference/errors.md#attack).


## `attack_building`

Order units to attack an enemy building. [API reference](../api.md#attack_building).

The target ID must identify an enemy building. Inspect visible enemy buildings in state first.

```python
game.attack_building([12, 13], building_id=42)
# On success, for the stated example and a suitable game state:
# {"queued": "attack", "units": 2, "building_id": 42, "note": "they attack when game time next moves"}
```

See also: [related reference](observe.md#state); [refusals](../reference/errors.md#attack_building).

<!-- docs/commands/observe.md -->

# Observe commands

These commands inspect visible state, map tiles, events, reports, and owned objects. Some also change the camera or selection. IDs and coordinates below are illustrative.

## `state`

Return the current visible game state. [API reference](../api.md#state).

Returns `State`; use its owned units and buildings to choose IDs for orders. Enemy information is limited to visible state. Unit IDs can be reused after death, so read them fresh before ordering.

```python
game.state()
```

The returned `State` includes `tick`, `stock`, `units`, and `buildings`; values depend on the running game.

See also: [related reference](../reference/state.md); [refusals](../reference/errors.md#state).


## `map`

Return the inclusive tile rectangle as text. The default rectangle runs from (0, 0) through (399, 399), inclusive. [API reference](../api.md#map).

Returns a string. Invalid rectangles are refused; coordinates include both endpoints.

```python
game.map(220, 220, 240, 240)
```

The return is a newline-separated string; the result contents depend on the terrain.

See also: [related reference](../reference/map-legend.md); [refusals](../reference/errors.md#map).


## `find_sites`

Find valid building sites, optionally near a tile. The optional near tile narrows the search around a location; the default limit is 5. [API reference](../api.md#find_sites).

Returns `list[Site]`. `limit` must be 1–50; unknown or unavailable buildings are refused. Without `near`, the driver searches around the mission keep, otherwise (235, 230). Queued builds are treated as occupied, even before the map shows them. A site does not guarantee that you can afford a build.

```python
game.find_sites("woodcutter", limit=3, near=(235, 230))
```

Each returned site has `x` and `y`; the list may be empty.

See also: [related reference](economy.md#build); [refusals](../reference/errors.md#find_sites).


## `look`

Centre the camera on a tile and return its visible area. [API reference](../api.md#look).

The current real backend refuses camera control; do not rely on this command to reveal an area.

```python
game.look(235, 230)
```

See also: [related reference](../how-it-works.md); [refusals](../reference/errors.md#look).


## `select`

Select owned soldiers by ID. [API reference](../api.md#select).

Pass 1–500 distinct IDs of your live soldiers. Invalid, enemy, or dead units are refused. Selection changes the game selection.

```python
game.select([12, 13])
```

On success the return has a `tribe` field; its value is assigned by the game.

See also: [related reference](military.md#move); [refusals](../reference/errors.md#select).


## `events`

Return events with sequence numbers at or after since. The since value is inclusive and defaults to 0. [API reference](../api.md#events).

The driver treats `since` as an inclusive offset into its event list, from 0 through the current event count. An invalid offset is refused. Use `next_since` from `advance()` to fetch newer events; this is not a tick number. Event fields vary; do not assume optional fields are present.

```python
game.events(since=0)
```

If there are no events at or after the offset, the return is `[]`.

See also: [related reference](../reference/events.md); [refusals](../reference/errors.md#events).


## `report`

Return a page of the scribe's book. Pages: popularity, fear, religion, army, food, population, stores, weapons, merit. [API reference](../api.md#report).

Returns a report page; availability and fields depend on the page and game state.

```python
game.report("food")
```

Returned fields vary by page: for example the army page returns `troops` and `fear_bonus`.

See also: [related reference](../reference/state.md); [refusals](../reference/errors.md#report).


## `building_info`

Return the panel information for an owned building. [API reference](../api.md#building_info).

Pass an owned building ID from state; the panel data depends on building type. An invalid or non-owned ID is refused.

```python
game.building_info(12)
```

Returned fields include `id` and `type`, with additional fields according to the panel.

See also: [related reference](../reference/state.md); [refusals](../reference/errors.md#building_info).

<!-- docs/commands/siege.md -->

# Siege commands

These commands construct and crew siege engines and order specialist troops.

## `build_siege`

The 3×3 tent uses `(x, y)` as its top-left tile. Available engines are `catapult`, `trebuchet`, `battering_ram`, `siege_tower`, `portable_shield` and `fire_ballista`. Engineers walk there, build and crew the engine. Gold is charged when time moves; the driver also checks wood and stone. The mission menu, placement or resources may cause refusal. The result reports gold and crew needed; the engine later appears in `state()["units"]`.

```python
game.build_siege([101, 102], "catapult", 45, 60)
```

See also: [API reference](../api.md#build_siege) and [refusals](../reference/errors.md#build_siege).


## `man`

Selected engineers walk to an owned engine and fill its vacant crew slots. The result reports `crew_needed`; a full engine is refused. At level 5 the driver checks reachability: tower engines need access via a wall and stairs.

```python
game.man([101, 102], 205)
```

See also: [API reference](../api.md#man) and [refusals](../reference/errors.md#man).


## `unman`

Order the crew of an owned, crewed engine to step off. An engine short of its full crew takes no orders; an engine with no crew is refused.

```python
game.unman(205)
```

See also: [API reference](../api.md#unman) and [refusals](../reference/errors.md#unman).


## `buy_ammo`

A catapult or trebuchet buys 20 shots for 10 stone. Other engine types and insufficient stone are refused. The queued result reports `stone` and `shots`.

```python
game.buy_ammo(205)
# {"queued": "buy_ammo", "engine_id": 205, "stone": 10, "shots": 20}
```

See also: [API reference](../api.md#buy_ammo) and [refusals](../reference/errors.md#buy_ammo).


## `throw_cow`

A crewed catapult or trebuchet throws a dairy farm cow at an on-map tile; the carcass remains where it lands. The driver refuses other engines, no crew or no cows. Returned `cows` is the count at ordering time, not proof of impact.

```python
game.throw_cow(205, 80, 70)
```

See also: [API reference](../api.md#throw_cow) and [refusals](../reference/errors.md#throw_cow).


## `set_ladder`

Select owned laddermen and an enemy wall tile. They carry and raise a ladder for soldiers to climb. Own and allied walls, non-wall tiles and other unit types are refused.

```python
game.set_ladder([301], 80, 70)
```

See also: [API reference](../api.md#set_ladder) and [refusals](../reference/errors.md#set_ladder).


## `dig_tunnel`

Select owned tunnelers and an on-map entrance tile. A tunneler digs toward the nearest enemy building; the eventual collapse damages that building. The game may refuse placement.

```python
game.dig_tunnel([302], 75, 70)
```

See also: [API reference](../api.md#dig_tunnel) and [refusals](../reference/errors.md#dig_tunnel).

<!-- docs/commands/time.md -->

# Time commands

This command advances the game clock.

## `advance`

Advance by an integer from 1 to 3000 ticks. Queued actions can run and units need time to carry out orders. A finite remaining budget caps the actual advance, and a finished match can stop it early. The result contains the current `tick`, `ticks_left` (or `None` for no budget), and `game_over`; inspect state and returned `events` rather than assuming every queued action completed. `next_since` is the event sequence cursor for a later `events(since)` call, not a tick number.

```python
result = game.advance(100)
print(result["tick"], result["ticks_left"], result["game_over"])
```

See also: [API reference](../api.md#advance) and [refusals](../reference/errors.md#advance).

<!-- docs/concepts.md -->

# Concepts

## Time and pause

The real driver uses a game module to pause at a target tick. `advance(ticks)` requests 1–3000 ticks, then returns the current tick, remaining budget if configured, and game-over status. A match can end before the requested interval. A game month is 800 ticks. Do not assume a command's effects are immediate: advance time and inspect state again.

## Coordinates and IDs

Map coordinates are tile `(x, y)` pairs; map rectangles are inclusive. A building's coordinates identify the top-left tile of its footprint. Use `find_sites` to find candidate positions, then handle refusal because game conditions can change. Unit and building IDs come from state; they refer to the current game, not stable identities across matches. Most orders require owned units or buildings. Enemy targets and allies have command-specific rules.

## Events and refusals

`events(since)` uses an event-list offset; after reading a batch, advance the offset by its length. The real backend checks that the offset is between zero and the current event count. Event fields vary. The published `AdvanceResult` type mentions `events` and `next_since`, but the current real backend does not return them from `advance`; use `events` separately. Similarly, the backend's events do not necessarily contain the `seq` declared by the public type. See [events](reference/events.md).

A command may be refused by validation or game conditions. The client raises `CrusaderError` for bridge error responses. A successful request does not guarantee an order will achieve its intended outcome; inspect subsequent state and events. See [errors](reference/errors.md).

<!-- docs/how-it-works.md -->

# How it works

The Python client sends command requests to the bridge. The bridge validates the command and arguments, serializes backend calls, and returns JSON. The real backend starts or attaches to the supported game under Linux/Wine, reads game state from process memory, and uses the included UCP3 module for tick control and a command mailbox. The module submits game commands through the game's own command queue. Some driver operations also write limited process memory directly.

## Memory boundary

The process-memory layer verifies the executable SHA-256 and that the verified file is mapped by the process, then requires a layout sanity check. It checks mappings and permissions on access, bounds each operation to a single mapped region and at most 1 MiB, and limits writes to fixed ranges or validated dynamic module regions. Dynamic hook addresses come from the module log. These checks reduce accidental misuse; they are not a security sandbox for a compromised local process or trusted driver. Arbitrary memory access is not exposed as a bridge command. The module mailbox includes in-game write and function-call primitives used by the trusted driver; a compromised same-user process or a driver bug could abuse them.

The backend depends on a specific executable and memory layout, process permissions, Wine and the module. Other versions can fail or behave incorrectly. The port and Docker integration have been tested offline only and still require a live game run. Game state and command support are not complete; in particular, `look` is refused by the current real backend.

The container starts UCP3 with `--ucp-no-security` so it can load the unsigned local module; this also enables the UCP3 console.

<!-- docs/index.md -->

# Documentation

Crusader SDK is an unofficial Python client and bridge for Stronghold Crusader. You must supply your own supported game files; the SDK does not include the game.

- [Quickstart](quickstart.md): install the client and run the experimental Docker setup.
- [Concepts](concepts.md): ticks, coordinates, IDs, events, and refusals.
- [API reference](api.md): client methods and arguments.
- [Protocol](protocol.md): HTTP, MCP, authentication, and response behavior.
- [How it works](how-it-works.md): game integration and memory boundary.
- References: [state](reference/state.md), [events](reference/events.md), [buildings](reference/buildings.md), [units](reference/units.md), [goods](reference/goods.md), [map legend](reference/map-legend.md), and [errors](reference/errors.md).
- [Legal notice](../LEGAL.md) and [security](../SECURITY.md).

<!-- docs/protocol.md -->

# Bridge protocol

The bridge serves REST and stateless streamable HTTP MCP from the same application. MCP tools use the command names and wire parameters in the [API reference](api.md); the MCP endpoint is `/mcp`. Both transports invoke the same serialized backend. `GET /health` returns `{"ok": true}` and checks the bridge, not game readiness.

## REST

Send `POST /api/{command}` with a JSON object of arguments. For example:

```sh
curl -X POST http://127.0.0.1:8000/api/state \
  -H 'Content-Type: application/json' -d '{}'
```

A successful response is `{"result": ...}`. An unknown command returns 404; malformed input, invalid arguments, and backend errors normally return 400 with `{"error": "..."}`. The Python `map` method uses the wire command `ascii_map`; `find_sites` sends `near_x` and `near_y` together.

Slow REST requests stream whitespace as keepalives before the final JSON object. A client must allow leading JSON whitespace and read the entire response. Once streaming has started the HTTP status is already 200, even if the final object contains an error; inspect the body. The Python client does this. Requests can take a long time: its default timeout is 600 seconds.

## Access control

The server defaults to loopback and no authentication. Configure `CRUSADER_TOKEN` to require `Authorization: Bearer <token>` on every route except `/health`, including MCP. The server also accepts `--token`, but prefer the environment variable to avoid exposing the token in command-line arguments. The Python client reads `CRUSADER_TOKEN` or accepts an explicit `token` in `Game` and `Game.connect`; the explicit value takes precedence. A token is not transport encryption; use an appropriate secure channel and do not expose an unauthenticated bridge to untrusted networks. Requests are limited to 64 KiB. All routes require a loopback `Host` by default; repeat `--allow-host` for additional host authorities. An `Origin`, if sent, must be loopback, and every POST requires `Content-Type: application/json`.

<!-- docs/quickstart.md -->

# Quickstart

## Install the client

The client requires Python 3.10 or later. From a checkout:

```sh
python -m pip install --pre crusader-sdk   # or, from a checkout: python -m pip install .
```

The client needs a running bridge and does not start the game itself. Against a bridge on the default local address:

```python
from crusader import Game, CrusaderError

game = Game.connect()  # or Game.connect("http://127.0.0.1:8000")
try:
    print(game.state())
    print(game.map(0, 0, 20, 20))
    print(game.advance(100))
except CrusaderError as exc:
    print(f"Bridge refused the request: {exc}")
```

`CRUSADER_URL` overrides the default URL when no URL is passed. Set `CRUSADER_TOKEN` to the bridge token for authenticated requests, or pass `token=` to `Game` or `Game.connect`. Prefer the environment variable over command-line arguments for secrets. `advance` changes the game; choose a tick count appropriate for your match. See [concepts](concepts.md), the [API reference](api.md), and [protocol](protocol.md).

## Run the bridge

For a bridge installation, install the optional dependencies with `python -m pip install --pre 'crusader-sdk[bridge]'` (or `'.[bridge]'` from a checkout), then run `crusader-bridge --help` for match and process options. The real backend requires the supported game, Wine/Linux process access, and the included UCP3 module. Integration needs a live game run. The `--backend module:callable` option is a development hook for selecting an explicit backend factory. Alternatively, the following experimental Docker setup packages the runtime.

## Run with Docker

This container setup is experimental and has not yet been verified with a live game. You need Docker and your own legally obtained, supported Stronghold Crusader game folder. The image targets `linux/amd64`; other hosts require Docker's amd64 emulation.

From the repository root, verify the executable and build the image:

```sh
./scripts/check-game-files.sh "/path/to/your/game"
./scripts/build-image.sh
```

The game folder must contain `Stronghold Crusader.exe` with the supported SHA-256. The build downloads and verifies UCP3; it does not include the game. Optionally, check a UCP3 archive separately with `./scripts/check-game-files.sh "/path/to/your/game" "/path/to/UCP3.zip"`.

Set `CRUSADER_TOKEN` in the host environment, replace the example path with the absolute path to your game folder, and run:

```sh
docker run --rm --name crusader-sdk \
  --platform linux/amd64 \
  --cap-drop ALL \
  --cap-add SYS_PTRACE \
  -e CRUSADER_TOKEN \
  --mount type=bind,src="/path/to/your/game",dst=/game,readonly \
  -p 127.0.0.1:8000:8000 \
  crusader-sdk:local --host 0.0.0.0
```

The command adds only `SYS_PTRACE` for game-process access; whether it is required has not been verified. Do not use `--privileged` or host networking. The bridge binds to all container interfaces so Docker can publish it, but the published port is restricted to host loopback. The bridge is unauthenticated unless a token is configured; do not expose it to untrusted networks. Other containers on the same Docker network may still reach it.

Check the bridge from the host:

```sh
curl http://127.0.0.1:8000/health
```

The container copies the mounted game to `/opt/crusader` and runs the copy. The original mount remains read-only. Saves are in `/home/crusader/Stronghold Crusader/Saves` inside the container and are lost when the `--rm` container is removed. To load an existing save, place it in the source game's `Saves` folder before starting and pass `--match load:NAME` after the image name (alongside `--host 0.0.0.0`). Stop the container with `docker stop crusader-sdk`.

<!-- docs/reference/buildings.md -->

# Buildings

A player building in `State.buildings` has `id`, `type`, `x` and `y`. Enemy records additionally have `owner`, `hp` and `max_hp`. The driver defines `(x, y)` as the top-left tile of a square footprint. Names below are placement names; read-back names can differ (all three garden sizes read back as `garden`). Availability depends on driver level and game state.

Costs below were recorded from the game in the supplied import reference and findings; the driver reads costs from the running game, so check the active game for authoritative values. Unknown production does not mean the building produces nothing.

Every footprint tile must be on the map, free and level with the other tiles. The terrain column adds the driver's special checks; the game may impose additional conditions. A recognized name does not guarantee valid or affordable placement.

| Building | Footprint (tiles) | Cost | Additional terrain check | Production |
|---|---:|---|---|---|
| `woodcutter` | 3 × 3 | 3 wood | not specified beyond general checks | unknown |
| `stockpile` | 5 × 5 | free | not specified beyond general checks | unknown |
| `hovel` | 4 × 4 | 6 wood | not specified beyond general checks | unknown |
| `quarry` | 6 × 6 | 20 wood | not specified beyond general checks | unknown |
| `keep` | 7 × 7 | unknown (read from game) | not specified beyond general checks | unknown |
| `wheat_farm` | 9 × 9 | 15 wood | farmable grass | unknown |
| `hops_farm` | 9 × 9 | 15 wood | farmable grass | unknown |
| `apple_orchard` | 11 × 11 | 5 wood | farmable grass | unknown |
| `dairy_farm` | 10 × 10 | 10 wood | farmable grass | unknown |
| `mill` | 3 × 3 | 20 wood | not specified beyond general checks | wheat to flour |
| `bakery` | 4 × 4 | 10 wood | not specified beyond general checks | flour to bread |
| `brewery` | 4 × 4 | 10 wood | not specified beyond general checks | unknown |
| `market` | 5 × 5 | 5 wood | not specified beyond general checks | unknown |
| `hunters_post` | 3 × 3 | 5 wood | not specified beyond general checks | unknown |
| `granary` | 4 × 4 | 5 wood | not specified beyond general checks | unknown |
| `armory` | 4 × 4 | 5 wood | not specified beyond general checks | unknown |
| `barracks` | 4 × 4 | 15 stone | not specified beyond general checks | unknown |
| `inn` | 5 × 5 | 20 wood, 100 gold | not specified beyond general checks | unknown |
| `chapel` | 6 × 6 | 250 gold | not specified beyond general checks | unknown |
| `church` | 9 × 9 | 500 gold | not specified beyond general checks | unknown |
| `well` | 3 × 3 | 30 gold | not specified beyond general checks | unknown |
| `fletcher` | 4 × 4 | 20 wood, 100 gold | not specified beyond general checks | bows (wood) or crossbows |
| `poleturner` | 4 × 4 | 10 wood, 100 gold | not specified beyond general checks | spears (wood) or pikes |
| `blacksmith` | 4 × 4 | 20 wood, 200 gold | not specified beyond general checks | maces (iron) or swords |
| `armourer` | 4 × 4 | 20 wood, 100 gold | not specified beyond general checks | metal armor (iron) |
| `tanner` | 4 × 4 | 10 wood, 100 gold | not specified beyond general checks | leather armor (dairy cows) |
| `mercenary_post` | 4 × 4 | 10 wood | not specified beyond general checks | unknown |
| `iron_mine` | 4 × 4 | 20 wood | iron ore | unknown |
| `lookout_tower` | 3 × 3 | 10 stone | not specified beyond general checks | unknown |
| `perimeter_tower` | 4 × 4 | 10 stone | not specified beyond general checks | unknown |
| `defense_turret` | 5 × 5 | 15 stone | not specified beyond general checks | unknown |
| `square_tower` | 6 × 6 | 35 stone | not specified beyond general checks | unknown |
| `round_tower` | 6 × 6 | 40 stone | not specified beyond general checks | unknown |
| `gatehouse` | 5 × 5 | 10 stone | not specified beyond general checks | unknown |
| `large_gatehouse` | 7 × 7 | 20 stone | not specified beyond general checks | unknown |
| `engineers_guild` | 5 × 5 | 10 wood, 100 gold | not specified beyond general checks | unknown |
| `tunnelers_guild` | 5 × 5 | 10 wood, 100 gold | not specified beyond general checks | unknown |
| `stables` | 6 × 6 | 20 wood, 400 gold | not specified beyond general checks | unknown |
| `cathedral` | 13 × 13 | 1000 gold | not specified beyond general checks | unknown |
| `apothecary` | 6 × 6 | 20 wood, 150 gold | not specified beyond general checks | unknown |
| `ox_tether` | 2 × 2 | 5 wood | not specified beyond general checks | ox carries quarry stone to stockpile |
| `pitch_rig` | 4 × 4 | unknown (read from game) | marsh (game check) | unknown |
| `maypole` | 3 × 3 | unknown (read from game) | not specified beyond general checks | unknown |
| `dancing_bear` | 5 × 5 | unknown (read from game) | not specified beyond general checks | unknown |
| `small_garden` | 2 × 2 | unknown (read from game) | not specified beyond general checks | unknown |
| `medium_garden` | 3 × 3 | unknown (read from game) | not specified beyond general checks | unknown |
| `large_garden` | 4 × 4 | unknown (read from game) | not specified beyond general checks | unknown |
| `statue` | 2 × 2 | unknown (read from game) | not specified beyond general checks | unknown |
| `shrine` | 2 × 2 | unknown (read from game) | not specified beyond general checks | unknown |
| `gallows` | 2 × 2 | unknown (read from game) | not specified beyond general checks | unknown |
| `cess_pit` | 5 × 5 | unknown (read from game) | not specified beyond general checks | unknown |
| `stocks` | 3 × 3 | unknown (read from game) | not specified beyond general checks | unknown |
| `burning_stake` | 3 × 3 | unknown (read from game) | not specified beyond general checks | unknown |
| `dungeon` | 5 × 5 | unknown (read from game) | not specified beyond general checks | unknown |
| `stretching_rack` | 3 × 3 | unknown (read from game) | not specified beyond general checks | unknown |
| `gibbet` | 2 × 2 | unknown (read from game) | not specified beyond general checks | unknown |
| `chopping_block` | 3 × 3 | unknown (read from game) | not specified beyond general checks | unknown |
| `dunking_stool` | 5 × 5 | unknown (read from game) | not specified beyond general checks | unknown |
| `gatehouse_turned` | 5 × 5 | 10 stone | not specified beyond general checks | unknown |
| `large_gatehouse_turned` | 7 × 7 | 20 stone | not specified beyond general checks | unknown |
| `drawbridge` | 5 × 5 | 10 wood | not specified beyond general checks | unknown |
| `killing_pit` | 1 × 1 | 6 wood | not specified beyond general checks | unknown |
| `pitch_ditch` | 1 × 1 | 1 pitch | not specified beyond general checks | unknown |
| `dog_cage` | 3 × 3 | 10 wood, 100 gold | not specified beyond general checks | unknown |
| `oil_smelter` | 4 × 4 | 10 iron, 100 gold | not specified beyond general checks | unknown |
| `water_pot` | 4 × 4 | 60 gold | not specified beyond general checks | unknown |

The game requires a new granary to touch an existing one. A drawbridge must sit on a gatehouse gate axis. An ox tether is needed to deliver a quarry’s stone. These are game checks or behaviors beyond the general terrain checks.

<!-- docs/reference/errors.md -->

# Refusals and errors

Generated by static AST inspection. Dynamic expressions are shown as Python source, not literal messages. Helper-method refusals are attributed through static self-call reachability; conditional paths may not apply to every invocation. Server validations may apply to multiple commands.

<a id="state"></a>
## state

- No game refusal found by static self-call inspection.

<a id="map"></a>
## map

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'invalid map rectangle'` (game.py:3311)

<a id="find_sites"></a>
## find_sites

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `f'unknown building {building!r}' (dynamic expression)` (game.py:2307)
- `'limit must be 1..50'` (game.py:2311)
- `f"cannot build {building}: this mission's build menu does not offer it" (dynamic expression)` (game.py:2312)

<a id="look"></a>
## look

- `'camera control is not supported'` (game.py:3308)

<a id="select"></a>
## select

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)

<a id="events"></a>
## events

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'invalid event offset'` (game.py:3297)

<a id="build"></a>
## build

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f'unknown building {building!r}; one of {self.building_names}' (dynamic expression)` (game.py:1540)
- `'x and y must be integers'` (game.py:1541)
- `f'cannot place {building} at ({x},{y}): {err}' (dynamic expression)` (game.py:1543)
- `f"cannot build {building}: this mission's build menu does not offer it" (dynamic expression)` (game.py:1545)
- `f'cannot place {building} at ({x},{y}): the game refuses it ({place_reason(reason)})' (dynamic expression)` (game.py:1546)
- `f"{building} needs {iron} iron and {pitch} pitch; have {stock['iron']}, {stock['pitch']}" (dynamic expression)` (game.py:1554)
- `f"{building} needs {wood} wood, {stone} stone, {gold} gold; have {stock['wood']}, {stock['stone']}, {stock['gold']}" (dynamic expression)` (game.py:1558)
- `f'a drawbridge goes in front of the gate of one of your gatehouses; ({x},{y}) is not such a spot' (dynamic expression)` (game.py:1567)
- `'x and y must be integers'` (game.py:1603)
- `f'({x},{y}) is off the map' (dynamic expression)` (game.py:1606)
- `f'cannot put {name} at ({x},{y}): it goes on top of one of your walls or towers' (dynamic expression)` (game.py:1618)
- `'x and y must be integers'` (game.py:2104)
- `f'({x},{y}) is off the map' (dynamic expression)` (game.py:2107)
- `f'a {name} goes on top of one of your square or round towers; ({x},{y}) is not one' (dynamic expression)` (game.py:2116)
- `f'tower {bid} already carries an engine' (dynamic expression)` (game.py:2121)
- `f'a unit stands on ({x},{y}); click a free spot on the tower top' (dynamic expression)` (game.py:2122)
- `f'you cannot pay for a {name}' (dynamic expression)` (game.py:2124)
- `'tower mount spot is off the map'` (game.py:2127)

<a id="demolish"></a>
## demolish

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'building_id must be an integer'` (game.py:1578)
- `f"no building of yours has id {building_id}; see state()['buildings']" (dynamic expression)` (game.py:1581)
- `'the keep cannot be demolished'` (game.py:1583)

<a id="set_tax"></a>
## set_tax

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'tax level must be in -3..8'` (game.py:1595)

<a id="set_rations"></a>
## set_rations

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f'rations must be one of {RATION_NAMES}' (dynamic expression)` (game.py:2302)

<a id="trade"></a>
## trade

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f"unknown good {good!r}; one of {sorted((g for g in GOODS if g != 'gold'))}" (dynamic expression)` (game.py:2355)
- `f'{good} cannot be traded' (dynamic expression)` (game.py:2359)
- `'qty must be a non-zero multiple of 5 (at most 500): > 0 buys, < 0 sells'` (game.py:2360)
- `'you need a market to trade'` (game.py:2364)
- `f'{qty} {good} cost {lots * buy} gold ({buy} per 5); you have {gold} not yet spent' (dynamic expression)` (game.py:2370)
- `f'cannot sell exactly {-qty} {good} from {stock[good]}: the game sells 5 at a time below 50 in stock, 10 below 100, 20 below 200, else 50' (dynamic expression)` (game.py:2387)

<a id="recruit"></a>
## recruit

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f'unknown unit {unit!r}; one of {offered}' (dynamic expression)` (game.py:2411)
- `'count must be 1..50'` (game.py:2412)
- `f'this mission does not offer {unit}' (dynamic expression)` (game.py:2413)
- `'you need a barracks to recruit'` (game.py:2419)
- `f'{count} {unit} cost {count * gold} gold; you have {have} not yet spent' (dynamic expression)` (game.py:2426)
- `f'each {unit} needs one {names[r]}; you have {have} not yet used' (dynamic expression)` (game.py:2429)
- `f'each knight needs a horse from your stables; you have {horses} not yet used' (dynamic expression)` (game.py:2432)
- `f'each recruit needs an idle peasant at the campfire; you have {idle} not yet used' (dynamic expression)` (game.py:2435)
- `'you need a mercenary post to hire mercenaries'` (game.py:2450)
- `f'{count} {unit} cost {gold} gold; you have {have} not yet spent' (dynamic expression)` (game.py:2453)
- `f'each recruit needs an idle peasant at the campfire; you have {idle} not yet used' (dynamic expression)` (game.py:2455)
- `'you need a cathedral to train monks'` (game.py:2484)
- `f'you need {guild} to recruit {unit}' (dynamic expression)` (game.py:2488)
- `f'{count} {unit} cost {gold} gold; you have {have} not yet spent' (dynamic expression)` (game.py:2491)
- `f'each recruit needs an idle peasant at the campfire; you have {idle} not yet used' (dynamic expression)` (game.py:2493)

<a id="move"></a>
## move

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'waypoints are not available in this task'` (game.py:2617)
- `f'({x},{y}) is off the map' (dynamic expression)` (game.py:2630)
- `'in a historical campaign your lord can only go back to his keep or attack'` (game.py:2658)
- `f'{what} must be a list of [x, y] pairs' (dynamic expression)` (game.py:2662)
- `f'between {least} and {MAX_MARKERS} markers in all (the game keeps 9)' (dynamic expression)` (game.py:2669)
- `f'({x},{y}) is off the map' (dynamic expression)` (game.py:2674)

<a id="set_stance"></a>
## set_stance

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `f'stance must be one of {list(STANCES)}' (dynamic expression)` (game.py:2685)

<a id="stop"></a>
## stop

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'an instruction takes at most 3 parameters'` (game.py:2606)

<a id="disband"></a>
## disband

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'an instruction takes at most 3 parameters'` (game.py:2606)
- `'your lord cannot be disbanded'` (game.py:2702)

<a id="patrol"></a>
## patrol

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'in a historical campaign your lord can only go back to his keep or attack'` (game.py:2658)
- `f'{what} must be a list of [x, y] pairs' (dynamic expression)` (game.py:2662)
- `f'between {least} and {MAX_MARKERS} markers in all (the game keeps 9)' (dynamic expression)` (game.py:2669)
- `f'({x},{y}) is off the map' (dynamic expression)` (game.py:2674)

<a id="attack_ground"></a>
## attack_ground

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'only ranged soldiers (archers, crossbowmen, slingers, horse archers, Arabian archers, fire throwers) can attack the ground'` (game.py:2729)
- `f'({x},{y}) is off the map' (dynamic expression)` (game.py:2734)

<a id="attack_wall"></a>
## attack_wall

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'an instruction takes at most 3 parameters'` (game.py:2606)
- `f'({x},{y}) is not a wall tile' (dynamic expression)` (game.py:2749)
- `f"the wall at ({x},{y}) is not an enemy's (player {owner})" (dynamic expression)` (game.py:2751)

<a id="attack"></a>
## attack

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'an instruction takes at most 3 parameters'` (game.py:2606)
- `'give exactly one of target_id or building_id'` (game.py:2764)
- `f"building {building_id} is not an enemy building; see state()['enemy']['buildings']" (dynamic expression)` (game.py:2771)
- `f"unit {target_id} is not a live enemy soldier; see state()['units']" (dynamic expression)` (game.py:2785)
- `f"unit {target_id} belongs to your ally (player {t['owner']})" (dynamic expression)` (game.py:2793)

<a id="attack_building"></a>
## attack_building

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'an instruction takes at most 3 parameters'` (game.py:2606)
- `'give exactly one of target_id or building_id'` (game.py:2764)
- `f"building {building_id} is not an enemy building; see state()['enemy']['buildings']" (dynamic expression)` (game.py:2771)
- `f"unit {target_id} is not a live enemy soldier; see state()['units']" (dynamic expression)` (game.py:2785)
- `f"unit {target_id} belongs to your ally (player {t['owner']})" (dynamic expression)` (game.py:2793)

<a id="build_siege"></a>
## build_siege

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'only engineers can do this; select engineers'` (game.py:2828)
- `f'unknown engine {engine!r}; one of {sorted(SIEGE_ENGINES)}' (dynamic expression)` (game.py:2839)
- `f"cannot build {engine}: this mission's siege menu does not offer it" (dynamic expression)` (game.py:2840)
- `'x and y must be integers'` (game.py:2845)
- `f'cannot place a {engine} tent at ({x},{y}): {err}' (dynamic expression)` (game.py:2847)
- `f'cannot place a {engine} tent at ({x},{y}): the game refuses it ({place_reason(reason)})' (dynamic expression)` (game.py:2849)
- `f"a {engine} needs {gold} gold; you have {stock['gold']}" (dynamic expression)` (game.py:2857)

<a id="man"></a>
## man

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'an instruction takes at most 3 parameters'` (game.py:2606)
- `f"unit {engine_id} is not one of your siege engines; see state()['units']" (dynamic expression)` (game.py:2807)
- `'only engineers can do this; select engineers'` (game.py:2828)
- `f"{self.engine_names[e['type']]} {engine_id} already has its full crew of {CREW_SIZE[e['type']]}" (dynamic expression)` (game.py:2882)
- `f"your engineers cannot reach {self.engine_names[e['type']]} {engine_id} (on a tower, they need a wall with stairs onto it)" (dynamic expression)` (game.py:2886)

<a id="unman"></a>
## unman

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'an instruction takes at most 3 parameters'` (game.py:2606)
- `f"unit {engine_id} is not one of your siege engines; see state()['units']" (dynamic expression)` (game.py:2807)
- `f"{self.engine_names[e['type']]} {engine_id} has no crew" (dynamic expression)` (game.py:2917)

<a id="buy_ammo"></a>
## buy_ammo

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f"unit {engine_id} is not one of your siege engines; see state()['units']" (dynamic expression)` (game.py:2807)
- `f"only catapults and trebuchets take ammo; {engine_id} is a {self.engine_names[e['type']]}" (dynamic expression)` (game.py:2926)
- `f'ammo costs {AMMO_STONE} stone; you have {stone}' (dynamic expression)` (game.py:2931)

<a id="throw_cow"></a>
## throw_cow

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'an instruction takes at most 3 parameters'` (game.py:2606)
- `f"unit {engine_id} is not one of your siege engines; see state()['units']" (dynamic expression)` (game.py:2807)
- `f"only catapults and trebuchets throw cows; {engine_id} is a {self.engine_names[e['type']]}" (dynamic expression)` (game.py:2941)
- `f"{self.engine_names[e['type']]} {engine_id} has no crew" (dynamic expression)` (game.py:2945)
- `"you have no cows to throw (a dairy farm's cattle are your cows)"` (game.py:2946)
- `f'({x},{y}) is off the map' (dynamic expression)` (game.py:2947)

<a id="set_ladder"></a>
## set_ladder

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'an instruction takes at most 3 parameters'` (game.py:2606)
- `'only laddermen can set a ladder; select laddermen'` (game.py:2958)
- `f'({x},{y}) is not a wall tile' (dynamic expression)` (game.py:2964)
- `f"the wall at ({x},{y}) is not an enemy's (player {owner})" (dynamic expression)` (game.py:2966)

<a id="dig_tunnel"></a>
## dig_tunnel

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'only tunnelers can dig a tunnel; select tunnelers'` (game.py:2979)
- `f'({x},{y}) is off the map' (dynamic expression)` (game.py:2983)
- `f'cannot dig a tunnel at ({x},{y}): the game refuses it ({place_reason(reason)})' (dynamic expression)` (game.py:2987)

<a id="repair"></a>
## repair

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'building_id must be an integer'` (game.py:1630)
- `f"no building of yours has id {building_id}; see state()['buildings']" (dynamic expression)` (game.py:1639)
- `f"building {building_id} is a {b['type']}, not a {what}" (dynamic expression)` (game.py:1641)
- `f"a {b['type']} has no repair button; towers and gatehouses do" (dynamic expression)` (game.py:1650)
- `f"{b['type']} {building_id} is not damaged" (dynamic expression)` (game.py:1652)
- `f'cannot repair while the enemy is near (within {radius} tiles)' (dynamic expression)` (game.py:1657)
- `f"repairing needs {wood} wood; you have {stock['wood']}" (dynamic expression)` (game.py:1663)
- `f"repairing needs {stone} stone; you have {stock['stone']}" (dynamic expression)` (game.py:1664)

<a id="set_building_active"></a>
## set_building_active

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'building_id must be an integer'` (game.py:1630)
- `f"no building of yours has id {building_id}; see state()['buildings']" (dynamic expression)` (game.py:1639)
- `f"building {building_id} is a {b['type']}, not a {what}" (dynamic expression)` (game.py:1641)
- `'active must be true or false'` (game.py:1681)
- `f"a {b['type']} cannot be put to sleep (its panel has no sleep button)" (dynamic expression)` (game.py:1683)

<a id="set_workshop_product"></a>
## set_workshop_product

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'building_id must be an integer'` (game.py:1630)
- `f"no building of yours has id {building_id}; see state()['buildings']" (dynamic expression)` (game.py:1639)
- `f"building {building_id} is a {b['type']}, not a {what}" (dynamic expression)` (game.py:1641)
- `f"a {b['type']} makes {pair[0]} or {pair[1]}" (dynamic expression)` (game.py:1705)
- `f'this map does not let you make {weapon}' (dynamic expression)` (game.py:1707)

<a id="set_food_allowed"></a>
## set_food_allowed

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f'food must be one of {sorted(FOOD_SLOT)}' (dynamic expression)` (game.py:1721)
- `'allowed must be true or false'` (game.py:1722)
- `"the granary's food toggles are not available here"` (game.py:1723)
- `'you need a granary: its panel has the food toggles'` (game.py:1724)

<a id="set_gate"></a>
## set_gate

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'building_id must be an integer'` (game.py:1630)
- `f"no building of yours has id {building_id}; see state()['buildings']" (dynamic expression)` (game.py:1639)
- `f"building {building_id} is a {b['type']}, not a {what}" (dynamic expression)` (game.py:1641)
- `'open must be true or false'` (game.py:1743)

<a id="plan_moat"></a>
## plan_moat

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'x1, y1, x2, y2 must be integers'` (game.py:2073)
- `'a line runs straight: x1 == x2 or y1 == y2'` (game.py:2074)
- `f'a line is at most {most} tiles' (dynamic expression)` (game.py:2076)
- `f'({x},{y}) is off the map' (dynamic expression)` (game.py:2081)
- `'dig must be true or false'` (game.py:2288)

<a id="dig_moat"></a>
## dig_moat

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f'only {DIGGER_NAMES} dig moats' (dynamic expression)` (game.py:2089)
- `'x and y must be integers'` (game.py:2090)
- `f'({x},{y}) is not a tile of your moat plan; plan_moat first' (dynamic expression)` (game.py:2093)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'an instruction takes at most 3 parameters'` (game.py:2606)

<a id="fill_moat"></a>
## fill_moat

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f'only {DIGGER_NAMES} fill moats' (dynamic expression)` (game.py:2255)
- `'x and y must be integers'` (game.py:2256)
- `f"({x},{y}) is not a moat you can fill (only an enemy's dug moat)" (dynamic expression)` (game.py:2262)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'an instruction takes at most 3 parameters'` (game.py:2606)

<a id="delete_wall"></a>
## delete_wall

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'x and y must be integers'` (game.py:2235)
- `f'({x},{y}) is not one of your wall tiles' (dynamic expression)` (game.py:2238)

<a id="light_pitch"></a>
## light_pitch

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'only archers and Arabian archers light pitch'` (game.py:2203)
- `'x and y must be integers'` (game.py:2204)
- `f'there is no pitch ditch of yours at ({x},{y})' (dynamic expression)` (game.py:2213)
- `'no brazier of yours is lit beside your archers (their first unit must stand within 3 tiles of one)'` (game.py:2217)
- `f'the pitch at ({x},{y}) is too far from your archers' (dynamic expression)` (game.py:2222)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'an instruction takes at most 3 parameters'` (game.py:2606)

<a id="oil_duty"></a>
## oil_duty

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'building_id must be an integer'` (game.py:1630)
- `f"no building of yours has id {building_id}; see state()['buildings']" (dynamic expression)` (game.py:1639)
- `f"building {building_id} is a {b['type']}, not a {what}" (dynamic expression)` (game.py:1641)
- `'only engineers work an oil smelter'` (game.py:2138)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'an instruction takes at most 3 parameters'` (game.py:2606)

<a id="pour_oil"></a>
## pour_oil

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'only engineers pour oil'` (game.py:2151)
- `'an engineer pours oil only while he carries a pot; oil_duty first'` (game.py:2154)
- `"pouring oil is not available yet (the game's pour click is not reproduced); see the docs"` (game.py:2162)
- `f'({x},{y}) is off the map' (dynamic expression)` (game.py:2165)
- `'unit_ids must be a list of 1..500 distinct integers'` (game.py:2581)
- `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)` (game.py:2591)
- `'an instruction takes at most 3 parameters'` (game.py:2606)

<a id="report"></a>
## report

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `f'unknown page {page!r}; one of {list(REPORT_PAGES)}' (dynamic expression)` (game.py:1929)

<a id="building_info"></a>
## building_info

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'building_id must be an integer'` (game.py:1978)
- `f'building {building_id} is not one of yours' (dynamic expression)` (game.py:1980)

<a id="ally_order"></a>
## ally_order

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f'player {ally} is not your ally; allies: {sorted(self.allies)}' (dynamic expression)` (game.py:1753)
- `f'your ally (player {ally}) has no lord left' (dynamic expression)` (game.py:1754)
- `"order must be 'attack', 'defend' or 'cancel'"` (game.py:1775)
- `f'target must be an enemy player with a lord; one of {sorted(alive)}' (dynamic expression)` (game.py:1778)
- `'only an attack order takes a target'` (game.py:1781)

<a id="ally_send_goods"></a>
## ally_send_goods

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f'player {ally} is not your ally; allies: {sorted(self.allies)}' (dynamic expression)` (game.py:1753)
- `f'your ally (player {ally}) has no lord left' (dynamic expression)` (game.py:1754)
- `f'unknown good {good!r}; one of {sorted(GOODS)}' (dynamic expression)` (game.py:1760)
- `'qty must be a positive multiple of 5 no greater than 2147483645'` (game.py:1762)
- `f"you have {self._stock()['gold']} gold, not {qty}" (dynamic expression)` (game.py:1797)
- `f'you have {have} {what}, not {qty}' (dynamic expression)` (game.py:1800)
- `f'your ally has no store for {what}' (dynamic expression)` (game.py:1802)
- `f'your ally has no room for {what}' (dynamic expression)` (game.py:1803)

<a id="ally_request_goods"></a>
## ally_request_goods

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f'player {ally} is not your ally; allies: {sorted(self.allies)}' (dynamic expression)` (game.py:1753)
- `f'your ally (player {ally}) has no lord left' (dynamic expression)` (game.py:1754)
- `f'unknown good {good!r}; one of {sorted(GOODS)}' (dynamic expression)` (game.py:1760)
- `'qty must be a positive multiple of 5 no greater than 2147483645'` (game.py:1762)
- `f'you have no store for {good}' (dynamic expression)` (game.py:1833)
- `f'you have room for {room} {good}, not {qty}' (dynamic expression)` (game.py:1834)
- `f'your ally refuses to give {qty} {good}' (dynamic expression)` (game.py:1835)

<a id="ally_answer"></a>
## ally_answer

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f'player {ally} is not your ally; allies: {sorted(self.allies)}' (dynamic expression)` (game.py:1753)
- `f'your ally (player {ally}) has no lord left' (dynamic expression)` (game.py:1754)
- `f"you have {self._stock()['gold']} gold, not {qty}" (dynamic expression)` (game.py:1797)
- `f'you have {have} {what}, not {qty}' (dynamic expression)` (game.py:1800)
- `f'your ally has no store for {what}' (dynamic expression)` (game.py:1802)
- `f'your ally has no room for {what}' (dynamic expression)` (game.py:1803)
- `'accept must be true or false'` (game.py:1860)
- `f'your ally (player {ally}) has not asked you for anything' (dynamic expression)` (game.py:1862)

<a id="build_wall"></a>
## build_wall

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `f'kind must be one of {list(self.wall_kinds)}' (dynamic expression)` (game.py:2515)
- `'x1, y1, x2, y2 must be integers'` (game.py:2516)
- `'a wall runs straight: x1 == x2 or y1 == y2'` (game.py:2517)
- `f"a {kind} line is at most {(12 if kind == 'stairs' else 100)} tiles" (dynamic expression)` (game.py:2519)
- `f'({x},{y}) is off the map' (dynamic expression)` (game.py:2529)
- `f'tile ({x},{y}) is not free' (dynamic expression)` (game.py:2539)
- `f'({x},{y}): {place_reason(19)} (crenellations are laid beside a wall)' (dynamic expression)` (game.py:2540)
- `f'tile ({x},{y}) is not free' (dynamic expression)` (game.py:2545)
- `f'stairs must start next to one of your walls; ({x},{y}) is not' (dynamic expression)` (game.py:2549)
- `f'{new} tiles of {kind} cost {new / 2:g} stone; you have {half / 2:g}' (dynamic expression)` (game.py:2564)

<a id="advance"></a>
## advance

- `f'game over: {self.game_over}' (dynamic expression)` (game.py:1522)
- `msg (dynamic expression)` (game.py:1524)
- `'tick budget exhausted'` (game.py:1528)
- `'ticks must be 1..3000'` (game.py:2993)

## Bridge-wide and other source refusals

These are listed by enclosing function because dispatch and shared helpers can serve several commands. This includes setup and non-command errors.

- game.py:1753 / `_ally`: `f'player {ally} is not your ally; allies: {sorted(self.allies)}' (dynamic expression)`
- game.py:1754 / `_ally`: `f'your ally (player {ally}) has no lord left' (dynamic expression)`
- game.py:2658 / `_campaign_lord`: `'in a historical campaign your lord can only go back to his keep or attack'`
- game.py:1522 / `_check`: `f'game over: {self.game_over}' (dynamic expression)`
- game.py:1524 / `_check`: `msg (dynamic expression)`
- game.py:1528 / `_check_budget`: `'tick budget exhausted'`
- game.py:887 / `_click_until`: `f'gave up waiting for {what}' (dynamic expression)`
- game.py:1603 / `_decorate`: `'x and y must be integers'`
- game.py:1606 / `_decorate`: `f'({x},{y}) is off the map' (dynamic expression)`
- game.py:1618 / `_decorate`: `f'cannot put {name} at ({x},{y}): it goes on top of one of your walls or towers' (dynamic expression)`
- game.py:2807 / `_engine`: `f"unit {engine_id} is not one of your siege engines; see state()['units']" (dynamic expression)`
- game.py:2828 / `_engineers`: `'only engineers can do this; select engineers'`
- game.py:1760 / `_goods_amount`: `f'unknown good {good!r}; one of {sorted(GOODS)}' (dynamic expression)`
- game.py:1762 / `_goods_amount`: `'qty must be a positive multiple of 5 no greater than 2147483645'`
- game.py:1449 / `_initialize`: `'game_dir must be an absolute path inside the game process'`
- game.py:1459 / `_initialize`: `'game process changed during startup'`
- game.py:1465 / `_initialize`: `'tick_budget must be a positive integer'`
- game.py:1468 / `_initialize`: `'seed must be in 1..2^31-1'`
- game.py:1477 / `_initialize`: `'match must be Skirmish, CastleBuilder, or LoadSave'`
- game.py:2073 / `_line`: `'x1, y1, x2, y2 must be integers'`
- game.py:2074 / `_line`: `'a line runs straight: x1 == x2 or y1 == y2'`
- game.py:2076 / `_line`: `f'a line is at most {most} tiles' (dynamic expression)`
- game.py:2081 / `_line`: `f'({x},{y}) is off the map' (dynamic expression)`
- game.py:2669 / `_markers`: `f'between {least} and {MAX_MARKERS} markers in all (the game keeps 9)' (dynamic expression)`
- game.py:2674 / `_markers`: `f'({x},{y}) is off the map' (dynamic expression)`
- game.py:2104 / `_mount`: `'x and y must be integers'`
- game.py:2107 / `_mount`: `f'({x},{y}) is off the map' (dynamic expression)`
- game.py:2116 / `_mount`: `f'a {name} goes on top of one of your square or round towers; ({x},{y}) is not one' (dynamic expression)`
- game.py:2121 / `_mount`: `f'tower {bid} already carries an engine' (dynamic expression)`
- game.py:2122 / `_mount`: `f'a unit stands on ({x},{y}); click a free spot on the tower top' (dynamic expression)`
- game.py:2124 / `_mount`: `f'you cannot pay for a {name}' (dynamic expression)`
- game.py:2127 / `_mount`: `'tower mount spot is off the map'`
- game.py:2606 / `_order`: `'an instruction takes at most 3 parameters'`
- game.py:2581 / `_own_army`: `'unit_ids must be a list of 1..500 distinct integers'`
- game.py:2591 / `_own_army`: `f"unit {i} is not one of your live soldiers; see state()['units'] (owner 1)" (dynamic expression)`
- game.py:1630 / `_own_building`: `'building_id must be an integer'`
- game.py:1639 / `_own_building`: `f"no building of yours has id {building_id}; see state()['buildings']" (dynamic expression)`
- game.py:1641 / `_own_building`: `f"building {building_id} is a {b['type']}, not a {what}" (dynamic expression)`
- game.py:2662 / `_points`: `f'{what} must be a list of [x, y] pairs' (dynamic expression)`
- game.py:2484 / `_recruit_guild`: `'you need a cathedral to train monks'`
- game.py:2488 / `_recruit_guild`: `f'you need {guild} to recruit {unit}' (dynamic expression)`
- game.py:2491 / `_recruit_guild`: `f'{count} {unit} cost {gold} gold; you have {have} not yet spent' (dynamic expression)`
- game.py:2493 / `_recruit_guild`: `f'each recruit needs an idle peasant at the campfire; you have {idle} not yet used' (dynamic expression)`
- game.py:2450 / `_recruit_mercenary`: `'you need a mercenary post to hire mercenaries'`
- game.py:2453 / `_recruit_mercenary`: `f'{count} {unit} cost {gold} gold; you have {have} not yet spent' (dynamic expression)`
- game.py:2455 / `_recruit_mercenary`: `f'each recruit needs an idle peasant at the campfire; you have {idle} not yet used' (dynamic expression)`
- game.py:1424 / `_require_game_pid`: `'a verified Game process is required'`
- game.py:1797 / `_send`: `f"you have {self._stock()['gold']} gold, not {qty}" (dynamic expression)`
- game.py:1800 / `_send`: `f'you have {have} {what}, not {qty}' (dynamic expression)`
- game.py:1802 / `_send`: `f'your ally has no store for {what}' (dynamic expression)`
- game.py:1803 / `_send`: `f'your ally has no room for {what}' (dynamic expression)`
- game.py:647 / `_ucp_log`: `'bridge log not available'`
- game.py:685 / `_xdo`: `'CRUSADER_CONTAINER must be set when running outside the game container'`
- game.py:2993 / `advance`: `'ticks must be 1..3000'`
- game.py:1860 / `ally_answer`: `'accept must be true or false'`
- game.py:1862 / `ally_answer`: `f'your ally (player {ally}) has not asked you for anything' (dynamic expression)`
- game.py:1775 / `ally_order`: `"order must be 'attack', 'defend' or 'cancel'"`
- game.py:1778 / `ally_order`: `f'target must be an enemy player with a lord; one of {sorted(alive)}' (dynamic expression)`
- game.py:1781 / `ally_order`: `'only an attack order takes a target'`
- game.py:1833 / `ally_request_goods`: `f'you have no store for {good}' (dynamic expression)`
- game.py:1834 / `ally_request_goods`: `f'you have room for {room} {good}, not {qty}' (dynamic expression)`
- game.py:1835 / `ally_request_goods`: `f'your ally refuses to give {qty} {good}' (dynamic expression)`
- game.py:3311 / `ascii_map`: `'invalid map rectangle'`
- game.py:2764 / `attack`: `'give exactly one of target_id or building_id'`
- game.py:2771 / `attack`: `f"building {building_id} is not an enemy building; see state()['enemy']['buildings']" (dynamic expression)`
- game.py:2785 / `attack`: `f"unit {target_id} is not a live enemy soldier; see state()['units']" (dynamic expression)`
- game.py:2793 / `attack`: `f"unit {target_id} belongs to your ally (player {t['owner']})" (dynamic expression)`
- game.py:2729 / `attack_ground`: `'only ranged soldiers (archers, crossbowmen, slingers, horse archers, Arabian archers, fire throwers) can attack the ground'`
- game.py:2734 / `attack_ground`: `f'({x},{y}) is off the map' (dynamic expression)`
- game.py:2749 / `attack_wall`: `f'({x},{y}) is not a wall tile' (dynamic expression)`
- game.py:2751 / `attack_wall`: `f"the wall at ({x},{y}) is not an enemy's (player {owner})" (dynamic expression)`
- game.py:1540 / `build`: `f'unknown building {building!r}; one of {self.building_names}' (dynamic expression)`
- game.py:1541 / `build`: `'x and y must be integers'`
- game.py:1543 / `build`: `f'cannot place {building} at ({x},{y}): {err}' (dynamic expression)`
- game.py:1545 / `build`: `f"cannot build {building}: this mission's build menu does not offer it" (dynamic expression)`
- game.py:1546 / `build`: `f'cannot place {building} at ({x},{y}): the game refuses it ({place_reason(reason)})' (dynamic expression)`
- game.py:1554 / `build`: `f"{building} needs {iron} iron and {pitch} pitch; have {stock['iron']}, {stock['pitch']}" (dynamic expression)`
- game.py:1558 / `build`: `f"{building} needs {wood} wood, {stone} stone, {gold} gold; have {stock['wood']}, {stock['stone']}, {stock['gold']}" (dynamic expression)`
- game.py:1567 / `build`: `f'a drawbridge goes in front of the gate of one of your gatehouses; ({x},{y}) is not such a spot' (dynamic expression)`
- game.py:2839 / `build_siege`: `f'unknown engine {engine!r}; one of {sorted(SIEGE_ENGINES)}' (dynamic expression)`
- game.py:2840 / `build_siege`: `f"cannot build {engine}: this mission's siege menu does not offer it" (dynamic expression)`
- game.py:2845 / `build_siege`: `'x and y must be integers'`
- game.py:2847 / `build_siege`: `f'cannot place a {engine} tent at ({x},{y}): {err}' (dynamic expression)`
- game.py:2849 / `build_siege`: `f'cannot place a {engine} tent at ({x},{y}): the game refuses it ({place_reason(reason)})' (dynamic expression)`
- game.py:2857 / `build_siege`: `f"a {engine} needs {gold} gold; you have {stock['gold']}" (dynamic expression)`
- game.py:2515 / `build_wall`: `f'kind must be one of {list(self.wall_kinds)}' (dynamic expression)`
- game.py:2516 / `build_wall`: `'x1, y1, x2, y2 must be integers'`
- game.py:2517 / `build_wall`: `'a wall runs straight: x1 == x2 or y1 == y2'`
- game.py:2519 / `build_wall`: `f"a {kind} line is at most {(12 if kind == 'stairs' else 100)} tiles" (dynamic expression)`
- game.py:2529 / `build_wall`: `f'({x},{y}) is off the map' (dynamic expression)`
- game.py:2539 / `build_wall`: `f'tile ({x},{y}) is not free' (dynamic expression)`
- game.py:2540 / `build_wall`: `f'({x},{y}): {place_reason(19)} (crenellations are laid beside a wall)' (dynamic expression)`
- game.py:2545 / `build_wall`: `f'tile ({x},{y}) is not free' (dynamic expression)`
- game.py:2549 / `build_wall`: `f'stairs must start next to one of your walls; ({x},{y}) is not' (dynamic expression)`
- game.py:2564 / `build_wall`: `f'{new} tiles of {kind} cost {new / 2:g} stone; you have {half / 2:g}' (dynamic expression)`
- game.py:1978 / `building_info`: `'building_id must be an integer'`
- game.py:1980 / `building_info`: `f'building {building_id} is not one of yours' (dynamic expression)`
- game.py:2926 / `buy_ammo`: `f"only catapults and trebuchets take ammo; {engine_id} is a {self.engine_names[e['type']]}" (dynamic expression)`
- game.py:2931 / `buy_ammo`: `f'ammo costs {AMMO_STONE} stone; you have {stone}' (dynamic expression)`
- game.py:2235 / `delete_wall`: `'x and y must be integers'`
- game.py:2238 / `delete_wall`: `f'({x},{y}) is not one of your wall tiles' (dynamic expression)`
- game.py:1578 / `demolish`: `'building_id must be an integer'`
- game.py:1581 / `demolish`: `f"no building of yours has id {building_id}; see state()['buildings']" (dynamic expression)`
- game.py:1583 / `demolish`: `'the keep cannot be demolished'`
- game.py:2089 / `dig_moat`: `f'only {DIGGER_NAMES} dig moats' (dynamic expression)`
- game.py:2090 / `dig_moat`: `'x and y must be integers'`
- game.py:2093 / `dig_moat`: `f'({x},{y}) is not a tile of your moat plan; plan_moat first' (dynamic expression)`
- game.py:2979 / `dig_tunnel`: `'only tunnelers can dig a tunnel; select tunnelers'`
- game.py:2983 / `dig_tunnel`: `f'({x},{y}) is off the map' (dynamic expression)`
- game.py:2987 / `dig_tunnel`: `f'cannot dig a tunnel at ({x},{y}): the game refuses it ({place_reason(reason)})' (dynamic expression)`
- game.py:2702 / `disband`: `'your lord cannot be disbanded'`
- game.py:3297 / `events`: `'invalid event offset'`
- game.py:2255 / `fill_moat`: `f'only {DIGGER_NAMES} fill moats' (dynamic expression)`
- game.py:2256 / `fill_moat`: `'x and y must be integers'`
- game.py:2262 / `fill_moat`: `f"({x},{y}) is not a moat you can fill (only an enemy's dug moat)" (dynamic expression)`
- game.py:2307 / `find_sites`: `f'unknown building {building!r}' (dynamic expression)`
- game.py:2311 / `find_sites`: `'limit must be 1..50'`
- game.py:2312 / `find_sites`: `f"cannot build {building}: this mission's build menu does not offer it" (dynamic expression)`
- game.py:1162 / `game_call`: `'at most 4 arguments'`
- game.py:616 / `game_pid`: `'game is not running'`
- game.py:2203 / `light_pitch`: `'only archers and Arabian archers light pitch'`
- game.py:2204 / `light_pitch`: `'x and y must be integers'`
- game.py:2213 / `light_pitch`: `f'there is no pitch ditch of yours at ({x},{y})' (dynamic expression)`
- game.py:2217 / `light_pitch`: `'no brazier of yours is lit beside your archers (their first unit must stand within 3 tiles of one)'`
- game.py:2222 / `light_pitch`: `f'the pitch at ({x},{y}) is too far from your archers' (dynamic expression)`
- game.py:908 / `load_save`: `f'save {name!r} is not in the load list exactly once: {names}' (dynamic expression)`
- game.py:918 / `load_save`: `f'selected row is not {name!r}' (dynamic expression)`
- game.py:3308 / `look`: `'camera control is not supported'`
- game.py:1459 / `lookup`: `'game process changed during startup'`
- game.py:2882 / `man`: `f"{self.engine_names[e['type']]} {engine_id} already has its full crew of {CREW_SIZE[e['type']]}" (dynamic expression)`
- game.py:2886 / `man`: `f"your engineers cannot reach {self.engine_names[e['type']]} {engine_id} (on a tower, they need a wall with stairs onto it)" (dynamic expression)`
- game.py:2617 / `move`: `'waypoints are not available in this task'`
- game.py:2630 / `move`: `f'({x},{y}) is off the map' (dynamic expression)`
- game.py:2138 / `oil_duty`: `'only engineers work an oil smelter'`
- game.py:2288 / `plan_moat`: `'dig must be true or false'`
- game.py:2151 / `pour_oil`: `'only engineers pour oil'`
- game.py:2154 / `pour_oil`: `'an engineer pours oil only while he carries a pot; oil_duty first'`
- game.py:2162 / `pour_oil`: `"pouring oil is not available yet (the game's pour click is not reproduced); see the docs"`
- game.py:2165 / `pour_oil`: `f'({x},{y}) is off the map' (dynamic expression)`
- game.py:2411 / `recruit`: `f'unknown unit {unit!r}; one of {offered}' (dynamic expression)`
- game.py:2412 / `recruit`: `'count must be 1..50'`
- game.py:2413 / `recruit`: `f'this mission does not offer {unit}' (dynamic expression)`
- game.py:2419 / `recruit`: `'you need a barracks to recruit'`
- game.py:2426 / `recruit`: `f'{count} {unit} cost {count * gold} gold; you have {have} not yet spent' (dynamic expression)`
- game.py:2429 / `recruit`: `f'each {unit} needs one {names[r]}; you have {have} not yet used' (dynamic expression)`
- game.py:2432 / `recruit`: `f'each knight needs a horse from your stables; you have {horses} not yet used' (dynamic expression)`
- game.py:2435 / `recruit`: `f'each recruit needs an idle peasant at the campfire; you have {idle} not yet used' (dynamic expression)`
- game.py:1650 / `repair`: `f"a {b['type']} has no repair button; towers and gatehouses do" (dynamic expression)`
- game.py:1652 / `repair`: `f"{b['type']} {building_id} is not damaged" (dynamic expression)`
- game.py:1657 / `repair`: `f'cannot repair while the enemy is near (within {radius} tiles)' (dynamic expression)`
- game.py:1663 / `repair`: `f"repairing needs {wood} wood; you have {stock['wood']}" (dynamic expression)`
- game.py:1664 / `repair`: `f"repairing needs {stone} stone; you have {stock['stone']}" (dynamic expression)`
- game.py:1929 / `report`: `f'unknown page {page!r}; one of {list(REPORT_PAGES)}' (dynamic expression)`
- game.py:1238 / `save_game`: `'save name must be at most 249 ASCII bytes and contain no slash'`
- game.py:1681 / `set_building_active`: `'active must be true or false'`
- game.py:1683 / `set_building_active`: `f"a {b['type']} cannot be put to sleep (its panel has no sleep button)" (dynamic expression)`
- game.py:1721 / `set_food_allowed`: `f'food must be one of {sorted(FOOD_SLOT)}' (dynamic expression)`
- game.py:1722 / `set_food_allowed`: `'allowed must be true or false'`
- game.py:1723 / `set_food_allowed`: `"the granary's food toggles are not available here"`
- game.py:1724 / `set_food_allowed`: `'you need a granary: its panel has the food toggles'`
- game.py:1743 / `set_gate`: `'open must be true or false'`
- game.py:2958 / `set_ladder`: `'only laddermen can set a ladder; select laddermen'`
- game.py:2964 / `set_ladder`: `f'({x},{y}) is not a wall tile' (dynamic expression)`
- game.py:2966 / `set_ladder`: `f"the wall at ({x},{y}) is not an enemy's (player {owner})" (dynamic expression)`
- game.py:2302 / `set_rations`: `f'rations must be one of {RATION_NAMES}' (dynamic expression)`
- game.py:2685 / `set_stance`: `f'stance must be one of {list(STANCES)}' (dynamic expression)`
- game.py:1595 / `set_tax`: `'tax level must be in -3..8'`
- game.py:1705 / `set_workshop_product`: `f"a {b['type']} makes {pair[0]} or {pair[1]}" (dynamic expression)`
- game.py:1707 / `set_workshop_product`: `f'this map does not let you make {weapon}' (dynamic expression)`
- game.py:718 / `start_match`: `f'expected menu {nxt} after {screen}, got {i32(pid, MENU)}' (dynamic expression)`
- game.py:826 / `start_mission`: `'the trail map is not the Crusader Trail'`
- game.py:845 / `start_mission`: `f'{name}: expected {m}, the game has {got}' (dynamic expression)`
- game.py:777 / `start_skirmish`: `'expected exactly one AI lord, in slot 2'`
- game.py:780 / `start_skirmish`: `f'map {map_name!r} is not in the skirmish list exactly once' (dynamic expression)`
- game.py:785 / `start_skirmish`: `'the selected map row is not the one asked for'`
- game.py:2941 / `throw_cow`: `f"only catapults and trebuchets throw cows; {engine_id} is a {self.engine_names[e['type']]}" (dynamic expression)`
- game.py:2945 / `throw_cow`: `f"{self.engine_names[e['type']]} {engine_id} has no crew" (dynamic expression)`
- game.py:2946 / `throw_cow`: `"you have no cows to throw (a dairy farm's cattle are your cows)"`
- game.py:2947 / `throw_cow`: `f'({x},{y}) is off the map' (dynamic expression)`
- game.py:2355 / `trade`: `f"unknown good {good!r}; one of {sorted((g for g in GOODS if g != 'gold'))}" (dynamic expression)`
- game.py:2359 / `trade`: `f'{good} cannot be traded' (dynamic expression)`
- game.py:2360 / `trade`: `'qty must be a non-zero multiple of 5 (at most 500): > 0 buys, < 0 sells'`
- game.py:2364 / `trade`: `'you need a market to trade'`
- game.py:2370 / `trade`: `f'{qty} {good} cost {lots * buy} gold ({buy} per 5); you have {gold} not yet spent' (dynamic expression)`
- game.py:2387 / `trade`: `f'cannot sell exactly {-qty} {good} from {stock[good]}: the game sells 5 at a time below 50 in stock, 10 below 100, 20 below 200, else 50' (dynamic expression)`
- game.py:1154 / `ui_write`: `'size must be 1, 2 or 4'`
- game.py:2917 / `unman`: `f"{self.engine_names[e['type']]} {engine_id} has no crew" (dynamic expression)`
- game.py:675 / `wait_for`: `f'timed out waiting for {what}' (dynamic expression)`
- server.py:321 / `api`: `'body must be a JSON object'`
- server.py:163 / `create_app`: `'slow_threshold must be positive'`
- server.py:166 / `create_app`: `'invalid allowed host'`
- server.py:179 / `create_app`: `f"unknown arguments: {', '.join(sorted(unknown))}" (dynamic expression)`
- server.py:183 / `create_app`: `f'missing argument: {key}' (dynamic expression)`
- server.py:195 / `create_app`: `f'invalid argument: {key}' (dynamic expression)`
- server.py:207 / `create_app`: `f'invalid argument: {key}' (dynamic expression)`
- server.py:211 / `create_app`: `f'{key} must be {minimum}..{maximum}' (dynamic expression)`
- server.py:222 / `create_app`: `f'invalid argument: {key}' (dynamic expression)`
- server.py:226 / `create_app`: `'qty must be a valid multiple of 5'`
- server.py:228 / `create_app`: `'points must contain 1..9 points'`
- server.py:230 / `create_app`: `'at most 8 waypoints are allowed'`
- server.py:234 / `create_app`: `f'command unavailable: {name}' (dynamic expression)`
- server.py:239 / `create_app`: `'near_x and near_y must be supplied together'`
- server.py:321 / `create_app`: `'body must be a JSON object'`
- server.py:179 / `invoke_inner`: `f"unknown arguments: {', '.join(sorted(unknown))}" (dynamic expression)`
- server.py:183 / `invoke_inner`: `f'missing argument: {key}' (dynamic expression)`
- server.py:195 / `invoke_inner`: `f'invalid argument: {key}' (dynamic expression)`
- server.py:207 / `invoke_inner`: `f'invalid argument: {key}' (dynamic expression)`
- server.py:211 / `invoke_inner`: `f'{key} must be {minimum}..{maximum}' (dynamic expression)`
- server.py:222 / `invoke_inner`: `f'invalid argument: {key}' (dynamic expression)`
- server.py:226 / `invoke_inner`: `'qty must be a valid multiple of 5'`
- server.py:228 / `invoke_inner`: `'points must contain 1..9 points'`
- server.py:230 / `invoke_inner`: `'at most 8 waypoints are allowed'`
- server.py:234 / `invoke_inner`: `f'command unavailable: {name}' (dynamic expression)`
- server.py:239 / `invoke_inner`: `'near_x and near_y must be supplied together'`

<!-- docs/reference/events.md -->

# Events

`events(since=0)` returns the event list from the zero-based offset `since`; it must be an integer from zero through the current event count, inclusive. Use `next_since` from an advance result as the next offset. The driver stores `type` and driver-relative `tick` on every event. It does **not** add the `seq` required by the public `Event` TypedDict; `month` and `message` are optional in that type, not universal fields. TypedDicts describe responses and do not validate them.

| `type` | Additional fields and meaning |
| --- | --- |
| `lord_died` | The player's starting lord is no longer alive; emitted once when tracked. |
| `enemy_lord_died` | `player`: owner of a starting enemy lord, emitted once per lord. |
| `match_end` | `result` is `won` or `lost`. Mission events also have `game_over_flag`, `menu`, and `winners` (eight player flags); skirmish events instead have `winner` (1 on a win, otherwise a list of surviving enemy player IDs or `None`). |
| `month_end` | `month` (completed driver months), `gold`, `popularity`, `population`, `game_tick` (absolute game tick), `army`, `enemy_army`, `lord_alive`. AI games add `enemy_buildings` and `enemy_lords_alive`; missions with AI also add `enemy_lord_hp` (player IDs as string keys) and `lord_hp`. |
| `build_refused` | `building`, `x`, `y`; ordinary builds add `reason`, while wall lines add `tiles` and `built`. Detection occurs after time moves. |
| `demolish_refused` | `building_id` and `type` identify the building still present after time moves. Here `type` overwrites the event kind in the emitted dictionary: the actual returned `type` is the building type, not `demolish_refused`. |
| `order_stalled` | `cmd`, `ordered_at`, `units` (count), target fields (`x` and `y`, `target_id`, or `building_id`), `at` (first surviving unit's coordinates), and `note`. Mission order monitoring emits it when an order appears dropped. |

The watcher docstring also mentions siege arrival and defeat, but the current emission sites do not emit those events. `AdvanceResult` declares `tick`, `ticks_left`, `game_over`, `events`, and `next_since`; as in state, an unlimited budget can make `ticks_left` null despite its declared integer type.

<!-- docs/reference/goods.md -->

# Goods

The driver's stock snapshot uses the names and numeric good IDs below. Categories describe the driver's food slots and stores or weapons pages, not a guarantee of tradeability. Market prices and tradeable flags are read from the running game. Other uses are unknown unless listed.

| Good | ID | Driver category | Known use or source |
|---|---:|---|---|
| `wood` | 2 | stores page | unknown |
| `hops` | 3 | stores page | unknown |
| `stone` | 4 | stores page | unknown |
| `iron` | 6 | stores page | unknown |
| `pitch` | 7 | stores page | unknown |
| `wheat` | 9 | stores page | unknown |
| `bread` | 10 | food; granary | unknown |
| `cheese` | 11 | food; granary | unknown |
| `meat` | 12 | food; granary | unknown |
| `apples` | 13 | food; granary | unknown |
| `ale` | 14 | stores page | unknown |
| `gold` | 15 | currency | also exposed as `State.gold` |
| `flour` | 16 | stores page | unknown |
| `bows` | 17 | weapons page | fletcher product |
| `crossbows` | 18 | weapons page | fletcher product |
| `spears` | 19 | weapons page | poleturner product |
| `pikes` | 20 | weapons page | poleturner product |
| `maces` | 21 | weapons page | blacksmith product |
| `swords` | 22 | weapons page | blacksmith product |
| `leather_armor` | 23 | weapons page | unknown |
| `metal_armor` | 24 | weapons page | unknown |

Food is stored in the granary, weapons and armor in the armory, and other goods in the stockpile. Wheat is milled into flour and baked into bread; workers carry wood or iron to weapon workshops. The tanner uses dairy cows for leather armor.

<!-- docs/reference/map-legend.md -->

# Map legend

The driver's text map renders each tile using the first matching condition below:

| Character | Meaning |
| --- | --- |
| space | Outside the valid tile area. |
| Building letter or `B` | A building occupies the tile; `B` is the fallback when its name has no mapped letter. |
| `~` | Tile lacks the land flag. |
| `f` | Farmland. |
| `^` | A blocked or wall tile. |
| `,` | Land with a farmable logic flag. |
| `.` | Other land. |

Building letters are `h` hovel, `w` woodcutter, `m` market, `c` chapel or church, `a` apple orchard, `d` dairy farm, `p` hunters post, `f` wheat farm, `n` mill, `k` bakery, `g` granary, `s` stockpile, `q` quarry, `b` brewery, `i` inn, `o` well, `j` hops farm, and `K` keep. Thus `f` is ambiguous between a wheat farm and farmland. The map character alone is not a complete building-placement test; the driver also checks units and other conditions.

`ascii_map(x0=0, y0=0, x1=399, y1=399)` returns newline-separated rows for an inclusive rectangle. Coordinates must be integers within the map, with lower bounds no greater than upper bounds. Building lookup happens before terrain checks, and `B` also covers unrecognized building names. This is a terrain/building display, not a unit display.

<!-- docs/reference/state.md -->

# State

`state()` returns visible game state. These TypedDicts describe responses; they do not validate them at runtime.

| Field | Meaning |
| --- | --- |
| `tick`, `month` | Driver-relative elapsed ticks and completed months, respectively. |
| `ticks_per_month`, `ticks_left` | Month length (800 ticks) and remaining budget. `ticks_left` can be `None` with no budget despite its declared `int` type. |
| `game_over` | End reason or `None`. |
| `gold`, `stock` | Gold and named goods; gold also appears in `stock`. |
| `popularity`, `population`, `housing` | Current player values. |
| `tax`, `rations` | Tax is the raw value minus 3; rations is a name for recognized values, otherwise the raw number. |
| `date` | Game `month` and `year`, distinct from completed driver months. |
| `buildings` | Player-owned buildings, each with `id`, `type`, `x`, `y`. |
| `idle_peasants`, `units`, `lord_alive` | Idle peasant count, visible units and tracked player lord status. |

Each unit has `id`, `type`, `owner`, `x`, `y`, `hp`. At level 3 or higher, player-owned catapults and trebuchets include `ammo`; `cows` is included when positive. Missions exclude units with zero HP; non-missions may list them.

Mode-specific fields:

- `enemy` appears in AI games, with `lords` and `buildings`. Each enemy building has `id`, `type`, `x`, `y`, `owner`, `hp`, `max_hp`.
- `mission` appears when set.
- `allies` appears when allies exist: `players` is a sorted list of player IDs, `lords` is a list of lord records, and at level 6 or higher `panel` has one entry per ally. Each panel entry has `player`, `request` (`None` or `{good, qty}`), and `order` (`None`, `defend`, or `{attack: target}`).

Each enemy or ally lord record has `owner` and `alive`; a live lord additionally has `id`, `x`, `y`, `hp`. See [units](units.md) and [buildings](buildings.md).

`RawState` is a separate direct-memory snapshot: `tick` (absolute game tick), `paused`, `month`, `year`, `tax`, `rations`, `popularity`, `population`, `housing`, and `stock`. Tax and rations are raw, not normalized as in `State`.

<!-- docs/reference/units.md -->

# Units

A `Unit` has `id`, `type`, `owner`, `x`, `y` and `hp`; `ammo` and `cows` are optional. The driver reports recognized live unit types and excludes zero-health units in missions. A lord record has `owner` and `alive`; its `id`, position and health are optional.

Costs are per unit. European troop prices and equipment below were recorded in the supplied import reference; the driver reads them from the running game, which is authoritative. Recruits require an idle peasant. Roles below list only capabilities explicitly identified in the driver, not a complete combat description. Availability and command acceptance depend on game state and driver level.

| Unit | Cost | Recruitment building | Known role or action |
|---|---|---|---|
| `archer` | 12 gold, bow | `barracks` | can dig moat; can light pitch; ranged; attack ground |
| `crossbowman` | 20 gold, crossbow, leather armor | `barracks` | ranged; attack ground |
| `spearman` | 8 gold, spear | `barracks` | can dig moat |
| `pikeman` | 20 gold, pike, metal armor | `barracks` | can dig moat |
| `maceman` | 20 gold, mace, leather armor | `barracks` | can dig moat |
| `swordsman` | 40 gold, sword, metal armor | `barracks` | unknown |
| `knight` | 40 gold, sword, metal armor; horse at level 2+ | `barracks` | unknown |
| `arabian_archer` | 75 gold | `mercenary_post` | can light pitch; ranged; attack ground |
| `slave` | 5 gold | `mercenary_post` | can dig moat |
| `slinger` | 12 gold | `mercenary_post` | ranged; attack ground |
| `assassin` | 60 gold | `mercenary_post` | unknown |
| `horse_archer` | 80 gold | `mercenary_post` | ranged; attack ground |
| `arabian_swordsman` | 80 gold | `mercenary_post` | unknown |
| `fire_thrower` | 100 gold | `mercenary_post` | ranged; attack ground |
| `engineer` | 30 gold | `engineers_guild` | can dig moat; can operate oil smelter |
| `laddermen` | 4 gold | `engineers_guild` | raise ladders against enemy walls |
| `tunneler` | 30 gold | `tunnelers_guild` | dig tunnel toward enemy wall or building |
| `monk` | 10 gold | `cathedral` | unknown |
| `lord` | unknown | `unknown` | unknown |

The driver also names siege engines when enabled. The table does not establish their recruitment costs or buildings.
