# HTTP API

All bodies are JSON and at most 8 KiB. Types live in `internal/model`.

Each player has one board. The server names a player by a random 32-hex-digit id in the `ta` cookie, which it sets on the first request without one (`HttpOnly`, `SameSite=Lax`, a year long). Scripts send the same id in the `X-Player` header instead. A player's board is the game they last started; `/api/new` replaces it. The player id never appears in a response or in a game log.

Errors return a non-2xx status and `{"error": "message"}` (`ErrorResponse`).

Every endpoint returns a full `GameState`. After victory or defeat every POST except `/api/new` and `/api/feedback` fails with 400. `phase` is one of `explore`, `combat`, `victory`, `defeat`.

`stats` are the unit's own numbers, and each worn item's `bonus` adds to them. `stats.hp` is current health. It carries from fight to fight and is capped by `maxHp` plus gear `maxHp` bonuses, so it can read above `stats.maxHp`. Empty `gear`, and `cleared` or `used` while false, are left out of the JSON. Every item has a `value` in gold. `party.potions` counts potions.

## GameState example

```json
{
  "version": 1,
  "game": "04339283a251d4d5",
  "seed": 42,
  "campaign": {
    "seed": 42,
    "systems": ["factions", "sidequests"],
    "factions": [{"id": "f1", "name": "Vampires", "theme": "undead", "power": 3}],
    "main": {
      "template": "siege",
      "name": "The Crimson Key",
      "steps": [
        {"id": "s1", "kind": "reach", "text": "Find the mine", "slots": {"poiKind": "mine", "faction": "f1", "item": "i2"}, "poi": "poi1", "done": false}
      ]
    },
    "sideQuests": []
  },
  "map": {
    "width": 1,
    "height": 1,
    "hexes": "AgQFAQ==",
    "pois": [{"id": "poi1", "kind": "mine", "name": "Dark Mine", "x": 0, "y": 0, "faction": "f1", "level": 1, "cleared": false}],
    "spawns": [{"id": "sp1", "kind": "inn", "x": 0, "y": 0, "hint": "Ask the innkeeper"}],
    "loot": [{"id": "chest1", "x": 0, "y": 0, "item": {"id": "i1", "name": "Rusty Sword", "slot": "weapon", "rarity": "common", "bonus": {"hp": 0, "maxHp": 0, "attack": 2, "defense": 0, "magic": 0, "speed": 0, "crit": 0}, "trait": "fire"}, "collected": false, "trap": true}],
    "bands": [{"id": "band1", "kind": "roam", "name": "Raiders", "faction": "f1", "level": 2, "x": 0, "y": 0, "homeX": 0, "homeY": 0, "cleared": false}],
    "landmarks": [{"id": "lm1", "kind": "lookout", "x": 0, "y": 0, "used": false}]
  },
  "party": {
    "units": [
      {
        "id": "u1", "name": "Ayla", "class": "fighter", "race": "dwarf", "level": 1, "xp": 0,
        "stats": {"hp": 10, "maxHp": 10, "attack": 3, "defense": 1, "magic": 0, "speed": 4, "crit": 5},
        "abilities": [{"id": "heavy-strike", "name": "Heavy Strike", "kind": "damage", "type": "physical", "power": 1.5, "cooldown": 2, "target": "enemy"}],
        "gear": {}
      }
    ],
    "inventory": [],
    "keys": [],
    "x": 0,
    "y": 0,
    "gold": 0
  },
  "log": [],
  "phase": "explore",
  "clock": {"day": 1, "time": 0, "dayLength": 140, "nightLength": 40},
  "summary": {"battles": 0, "kills": 0, "loot": 0, "steps": 0, "seconds": 0, "fallen": 0, "hexes": 0, "dealt": 0, "taken": 0, "crits": 0, "best": 0, "potions": 0, "camps": 0},
  "feedback": false
}
```

Combat resolves instantly on the server, so `phase` is never left at `combat`. After a fight `encounter` (`Encounter`) and `log` describe it until the next move or interact. Each log event carries its `kind`: `damage` and `aoe` hit a foe for `amount` of damage `type`, `heal` restores the target's hp, `buff` puts an effect on an ally and `debuff` on a foe, both with no hp change. A hit with `dodged` deals 0. Lifesteal is a `heal` the attacker casts on itself, and thorns are `damage` the struck unit deals back. See Combat below. Replaying the events from the starting hp gives exactly the hp every unit ends with. `summary.seconds` is the elapsed play time, frozen at victory or defeat. The boss POI only starts its fight once all other main steps are done. Every main step after the first is a `retrieve` step. It completes once its POI is cleared and its key is in `party.keys`. Keys never enter the inventory and cannot be equipped or sold.

Optional fields: `encounter` (`Encounter`, present after a fight), `rewards` (`Rewards`, present after a won fight), `found` (items auto-collected by the latest move or interact, cleared on the next action), `threat` (`Threat`, see `/api/move`), `shop` (`Shop`, present while the party stands where a trader works).

`game` is the id of this campaign, used by its share link. `summary` counts the run: `hexes` walked, damage `dealt` and `taken` by the heroes, `crits`, the `best` single hit, heroes `fallen`, `potions` drunk and nights `camps`ed. `feedback` is true once the party has fought a battle and changed gear, and stays true for up to three notes per game.

A hero at 0 hp is fallen. A fallen hero sits out fights and the odds, earns no XP, and takes no hazard or trap damage. A potion brings them back at potion strength, and camp brings every fallen hero back at full health. A shrine heals only the living.

A lost fight sets `phase: "defeat"` and every hero's `hp` to 0. The campaign is over: every action except `/api/new` and `/api/feedback` fails with 400.

## Clock

`clock.time` counts from 0 at dawn. Walking a hex spends its walking cost, and a fight spends 8. Night starts at `dayLength` and lasts `nightLength`. Dawn after a night with no rest starts the next `day` without healing. At night roaming bands move on every step and chase from farther away.

Each POI has a `level`, the enemy level of its fight. The boss is one level higher. Levels rise with the distance from the spawn, up to about 5 at the boss.

Item slots: `weapon`, `armor`, `helm`, `trinket`. `gear` maps slot to `Item`.

## Map

The map is a board of pointy-top hexes in offset coordinates: odd rows sit half a hex to the right. `hexes` is base64, four bytes per hex in row-major order: shape, biome, height, flags.

- Shapes: 0 deep water, 1 shallow, 2 plain, 3 hill, 4 mountain, 5 peak. Deep water and peaks are not walkable.
- Biomes: 0 to 8, named in `model.Biomes`.
- Flags: bit 1 forest, bit 2 road.

The outer two hexes of the map are deep water or peaks, so the board ends in sea or mountains.

Walking costs 1 on a road, 2 on a plain, 3 on shallows and hills, and 4 on mountains, plus 1 in forest. The server walks the cheapest path.

`bands` are enemies on the board:

- `roam` bands wander near home and chase a party within 5 hexes.
- `guard` bands sit on a chest.
- `mimic` bands are chests that bite.

A cleared band stays `cleared`. Backing off from a band's threat sets its `calm` to 6: it neither chases nor stops the party for that many moves.

`landmarks` fire once, when the party steps on them:

- `lookout` reveals the land around it.
- `shrine` heals the party.
- `cache` grants XP.

`loot[].trap` chests wound the party on pickup unless a rogue or ranger disarms them.

Units carry `race`. Enemies also carry `traits`, `weak` and `resist`. Items may carry one `trait`, paid for with a lower stat, and rare or better items grant one ability in their `abilities` list. Traits are listed under Combat.

`trail` lists the hexes the party walked in the latest move. `notes` lists what the walk caused, such as hazard damage, a trap, a shrine or a lookout. Shallows, mountains and three harsh biomes cost 2% of each hero's health per hex walked, never below 1 hp. Each hazard has a damage type: wading and Rime fen are frost, Mistbog is poison, Ember badlands are fire, and the climb is physical. A hero who guards the type is spared. Nothing spares the climb.

## Combat

A fight runs in rounds. Each round every standing unit acts once, fastest first (`first` acts before everyone in round 1). A unit uses one ability a turn, or `strike` when nothing else is ready. A fight lasts at most 40 rounds, and a draw is a defeat.

### Damage types and defense

There are seven damage types. `physical` and `poison` scale with `attack`, the other five with `magic`.

    damage = stat × power × roll(0.85 to 1.15) × 2 on a crit × 1.5 on a weakness × 10 / (10 + defense)

The defense factor applies only when the target guards the type. Every unit guards `physical`. A hero guards another type with a `guard-<type>` trait, an enemy with its `resist` list, and Ward guards every type. Unguarded damage ignores defense. `weak` lists the types an enemy takes 1.5 times damage from. `crit` is the percent chance of a crit. Damage is at least 1.

| Type | Stat | Single target | Every foe |
|---|---|---|---|
| `physical` | attack | Heavy Strike | Cleave |
| `poison` | attack | Envenom | Poison Cloud |
| `fire` | magic | Firebolt | Fireball |
| `frost` | magic | Ice Lance | Frost Nova |
| `lightning` | magic | Lightning Bolt | Chain Lightning |
| `holy` | magic | Smite | Radiance |
| `shadow` | magic | Shadow Bolt | Shadow Wave |

Single-target abilities have power 1.5 and cooldown 2. Abilities that hit every foe have power 0.7 and cooldown 3. Strike is physical, power 1, no cooldown. A cooldown of N means N of the unit's own turns pass before the ability is ready again.

### Effects

Casting an effect takes the caster's action. An effect lasts until the unit it lands on finishes its next turn, then it is gone: Rage and Rally boost that unit's next attack, Taunt decides each foe's next attack, and Mark holds until the marked foe has acted. There are no stuns and no damage over time.

| Ability | Kind | Effect | Cooldown |
|---|---|---|---|
| Heal | heal | Restores magic × 1.6 hp to the most hurt ally. | 1 |
| Prayer | heal | Restores magic × 0.6 hp to every ally. | 3 |
| Taunt | debuff | Every foe's next attack must target the caster. | 2 |
| Rage | buff | The caster's next attack deals double damage. | 2 |
| Sneak | buff | The caster can't be targeted, and their next hit is a crit. | 3 |
| Dodge | buff | The caster avoids the next hit aimed at them. | 2 |
| Ward | buff | Every ally guards every damage type. | 3 |
| Rally | buff | Every ally's next attack deals 30% more damage. | 3 |
| Haste | buff | The ally with the highest attack or magic acts at once. | 3 |
| Mark | debuff | One foe takes 30% more damage until its next turn ends. | 2 |

### Classes, roles and choices

Each hero draws 3 abilities from their class pool when the seed is built, and at least one of them deals damage.

| Class | Role | Pool |
|---|---|---|
| fighter | tank | Taunt, Rage, Heavy Strike, Cleave, Rally |
| rogue | striker | Sneak, Dodge, Heavy Strike, Envenom, Poison Cloud |
| mage | caster | Haste, Ward, Firebolt, Fireball, Ice Lance, Frost Nova |
| cleric | support | Heal, Prayer, Rally, Smite, Radiance |
| ranger | striker | Mark, Dodge, Heavy Strike, Lightning Bolt, Chain Lightning |

Enemies draw 2 abilities from their role, and bosses 3. Tanks draw from Taunt, Rage, Heavy Strike and Cleave. Strikers draw from Sneak, Dodge, Heavy Strike and Envenom. Casters draw from their faction's single and area attacks and Ward. Supports draw from Heal, Prayer, Rally and their faction's single attack. Vampires and witches deal shadow, cultists fire, undead frost, lizardfolk and goblins poison, and the rest physical.

Every unit chooses the same way. It uses the first of these that is ready and useful: Prayer when two allies are below 70% hp, Heal when an ally is below half, Taunt when another ally is below half and the caster is not, Dodge or Sneak when the caster is below half, Ward when the foes deal a type an ally doesn't guard. Rage, Rally, Mark and Haste only when the damage they add beats the attack the caster gives up: Rage counts the caster's next attack, Rally the whole party's next attacks, Mark the party's attacks spread over the foes, and Haste the hasted ally's attack. Otherwise it uses the attack with the most expected damage, counting weakness, guards and the number of foes.

Units pick targets by role. Sneaking units can't be picked, and a taunted unit attacks its taunter. Tanks hit whoever last hurt them, strikers the foe with the least hp, and casters and supports a random foe.

### Traits

- `lifesteal` heals 30% of damage dealt. `first` acts first in round 1, and the first hit deals 50% more.
- `sweep` (weapon) splashes single-target hits onto a second foe for half. `pierce` (weapon) ignores defense.
- `poison`, `fire`, `frost`, `lightning`, `holy` and `shadow` on a weapon or trinket turn the wielder's physical abilities into that type. They still scale with attack.
- `guard-poison`, `guard-fire`, `guard-frost`, `guard-lightning`, `guard-holy` and `guard-shadow` on armor, a helm or a trinket let defense cut that type, and spare the hero that type's hazards.
- `thorns` returns 25% of a single physical or poison hit to the attacker. `armored` adds 3 defense. `swarm` factions bring more, weaker enemies.

Gear abilities: weapons grant a single-target attack, armor Taunt, Dodge or Rage, helms Heal, Ward or Mark, and trinkets an area attack, Rally, Haste, Prayer or Sneak. `units[].abilities` lists only the hero's drawn abilities. A unit fights with those plus its gear's.

## GET /api/state

Returns the current `GameState`.

```
GET /api/state
```

Response: `GameState` (see above).

## POST /api/new

Starts a new campaign. `seed` is optional; the server picks a random one when omitted.

```json
{"seed": 42}
```

Response: `GameState` with a fresh campaign.

## POST /api/move

Moves the party toward hex `x,y`. The server paths over walkable hexes and returns the new state. The route avoids uncleared POIs and bands unless they block the only way. The party never walks onto an uncleared POI or band. It stops on the hex before it, and `threat` describes the fight. Every second step, roaming bands move. A band that ends next to the party stops the walk with a `threat`:

```json
{"poi": "poi1", "enemies": [], "odds": 82, "wounds": 35, "barred": false, "edge": {"hits": ["fire (Isolde)"], "blunted": []}}
```

```json
{"band": "band1", "enemies": [], "odds": 64, "wounds": 50, "edge": {"hits": [], "blunted": ["frost (Cael)"]}}
```

`odds` is the percent of 40 simulated fights the party wins as it stands now. `wounds` is the average percent of the party's current health lost in those fights. `barred` is true for the boss until every other main step is done, and `needs` then lists the names of the keys still missing. `edge` names each hero who deals a type an enemy is weak to, or has pierce against armor. It also names each hero who deals a type the enemies resist. Start the fight with `POST /api/interact` on the POI or band id. Any other action clears `threat`. Loot on any tile the party walks over is picked up automatically and listed in `found`; key items on a POI tile are picked up when the POI is cleared. Rejected with 400 for an unreachable tile. `steps` (optional) stops the walk after that many hexes. The client walks one hex per request, so the player can change course or stop between hexes.

```json
{"x": 12, "y": 7, "steps": 1}
```

Response: `GameState` with updated `party.x`, `party.y`, and possibly `threat`.

## GET /api/path

Previews the walk to `?x=&y=` without taking it. It does not change the state and returns a `Route`, not a `GameState`. `path` lists the hexes the party would walk, stopping before the first uncleared POI or band, which `blocked` names. `time` is the daylight the walk spends, `dusk` is true when night falls on the way, and `hazard` is the hp the party's hazards would cost, summed over the heroes, omitted when 0. Roaming bands move during a real walk, so the route can still change. Rejected with 400 for a bad query or an unreachable tile.

```json
{"path": [[12, 7], [13, 7]], "time": 5, "dusk": false, "hazard": 4}
```

## POST /api/interact

Interacts with a POI, band, loot node, or spawn structure by id (`poi1`, `band1`, `chest1`, `sp1`). Collects loot, advances mission steps, or starts the POI or band encounter. Moving already collects loot on the path, so this is only needed for loot the party stands on and has not collected, and it fails with 400 for loot already collected.

```json
{"id": "chest1"}
```

Response: `GameState`. Collected loot appears in `party.inventory` and `map.loot[].collected` becomes `true`.

## POST /api/equip

Equips an inventory item on a unit, or unequips the slot item when `unequip` is true.

```json
{"unit": "u1", "item": "i1"}
```

```json
{"unit": "u1", "item": "i1", "unequip": true}
```

Response: `GameState` with updated `party.units[].gear` and `party.inventory`.

## Traders and camping

Traders work at the spawns and at cleared POIs of kind `camp` or `village`. While the party stands on one, `shop` is set:

```json
{"id": "sp1", "name": "wagon", "stock": [], "potionPrice": 15}
```

`stock` holds three items rolled from the seed for that place, one tier above its level. Buy and sell fail with 400 away from a trader.

### POST /api/rest

Makes camp where the party stands. Body `{}`. Heals every hero to full, fallen ones included, and starts the next day at `time` 0. Fails with 400 during the day, and with 400 when an uncleared POI or band is within one hex.

### POST /api/buy

Buys a stock item by id, or a potion with `"potion"`. Fails with 400 if the party lacks the gold.

```json
{"item": "potion"}
```

### POST /api/sell

Sells a pack item for half its `value`. Quest items cannot be sold.

```json
{"item": "it-0a1b2c3d"}
```

## POST /api/drink

Drinks a potion on a hero, anywhere, healing half of their maximum health. A fallen hero gets back up. Fails with 400 with no potions or at full health.

```json
{"unit": "u1"}
```

## POST /api/feedback

Sends a free-form note about the current game. Opens once `feedback` is true. The text must hold 3 to 2000 characters. The note is stored with the game id, day and phase, and the game log beside it tells the rest.

```json
{"text": "The boss fight was too long"}
```

Response: `GameState`.

## GET /api/run/{id}

Returns the `Run` of a finished game: `game`, `seed`, `phase`, `mission`, `boss`, `day`, `keys`, `keysOf`, `gold`, `summary` and `party` (name, race, class and level per hero). Unfinished or unknown games return 404.

## GET /r/{id}

The share link. It serves the game page with `og:` and `twitter:` meta tags for the run, so a link preview shows the result. The client opens on the run's end card, with "Play this seed" and "New game".

## GET /r/{id}/card.png

The 1200 by 630 preview image of the run, drawn with the vendored fonts and cached in the data directory.

## Storage

With `--data <dir>` every game is an append-only log at `games/<game>.jsonl`. The first line is a `Header` (`game`, `seed`, `started`, `version`). Each later line is an `Entry`: the action `kind`, its time `t` in Unix milliseconds, its fields, and `err` when the server rejected it. The server rebuilds a game by replaying the accepted actions on the seed, so the log is both the save and the anonymous record of play. A game saved under another rules `version`, or one whose log no longer replays, is not loaded: its player gets a new campaign, and the old log stays as it was. `players/<player>` holds the id of the player's current game. `feedback.jsonl` holds the notes. `cards/` caches the share images. Without `--data` games live in memory.

## Limits

Requests through the proxy are limited per client address. Reads allow 20 a second with a burst of 80, actions 8 a second with a burst of 60, new games one per 30 seconds with a burst of 10, and feedback one per 10 minutes with a burst of 3. Excess requests get 429. Direct loopback requests without `X-Forwarded-For`, such as the harness, are not limited. The server keeps up to 400 boards in memory and reloads evicted ones from their logs.

## Mission templates

A mission is a list of `MissionStep`. Each step has typed `slots` (`poiKind`, `faction`, `item`) filled from the seed, so the `mine`/`vampires`/`key` template becomes `beach`/`lizardfolk`/`key` by changing slot values only.
