# How the AI works

A look under the hood, from how a bot exists as a player to how it perceives, plans, decides and acts.

AI Players bots run on a scripted, deterministic "utility AI", the same kind of game AI that strategy and simulation
games use. There's no machine learning or language model involved. This page walks through its parts, from the
bottom up.

## Embodiment: a bot is a player

Each bot is a server-side player entity (`ServerPlayer`) connected through a fake network connection, the same
pattern the [Carpet](https://github.com/gnembon/fabric-carpet) mod uses for its fake players. The server treats it
like any connected player. It loads chunks around it, saves its player data, ticks its physics, hunger and health,
and fires player events for other mods.

A few small mixins smooth over the differences with a real client. Bots take knockback like a player, freeze during
`/tick freeze`, don't take a player slot (configurable), can be hidden from the tab list, and don't announce
advancements. A real client also enforces some movement rules on itself (sprinting limits, sneaking speed, movement
statistics and exhaustion). Bots have no client, so they apply these rules themselves.

## Three layers

The behavior engine runs in three layers, each at its own pace:

| Layer | Runs | Job |
| :---- | :--- | :-- |
| **Strategy** | every second (interrupts every tick) | Choose an objective: what's most worth doing now. |
| **Tasks** | every tick | Run the objective's task tree: walk there, mine this, craft that. |
| **Motor** | every tick | Turn tasks into inputs: movement keys, looking, clicking, using items. |

At the start of every server tick, a shared scheduler visits the bots in turn within a time budget
(`ai_tick_budget_ms_per_bot`, 1.5 ms per live bot by default, capped at `ai_tick_budget_ms`, 12.0 ms). Cheap work
like following a path or aiming always runs. Expensive work (perception scans, preparing path searches, re-scoring
objectives) draws from the budget and is spread over ticks, and bots don't re-score on the same tick. If something in
a bot's brain throws an error, it's caught and logged at most once a minute, and that bot resets to idle. The error
never reaches the server.

Everything in the brain counts server ticks, with one exception. A path search's time limit (the difficulty's
`path_max_millis`) is a wall-clock bound, because the search runs on its own thread. That limit runs on the
[**bot clock**](/ai-players/reference/server-config/#the-bot-clock), which the scheduler hands the server's tick
rate at the start of each tick. At the default `20` it's the wall clock. At `n` the limit is scaled by 20/n. At
`game` a bot decides in the same number of ticks whatever `/tick rate` is set to, like a mob. The search converts the
limit to wall time once, when it starts. The budget is kept off the clock on purpose, since it caps what the bots
cost the server, while the clock sets how fast they think.

## Perception

- **Blocks:** each bot indexes the blocks around it (within its difficulty's `perception_radius`) by category, like
  logs, stone, each ore, crops, water, lava, beds, chests, workstations, portals and so on. It scans a few chunk
  sections per tick and keeps the index fresh as blocks change.
- **Entities:** every half a second it checks nearby entities in its line of sight and field of view, and gets the
  result after its `reaction_ticks`. Each one is classified as a **threat** (hostile mob, enemy, grudge target),
  **prey**, a **friend** (ally, villager, player-built golem) or **neutral**.
- **Events:** a few things are noticed through the game's own events instead of by looking. A chest opened, a block
  broken or farmland trampled in a base ([offenses](/ai-players/guide/combat/#offenses-in-the-base)) is matched
  against what each base bot had in view at that tick. The same goes for a `/teammsg` answer to a call for help.
- **Sound:** a creeper's hiss within seven blocks behind the bot, or one walking up behind it within six, is heard
  and treated like a creeper seen.
- **Far sightings:** by day under the open sky a bot notices grazing animals out to 96 blocks, past its perception
  radius, and remembers the flock without fighting or hunting what it sees that far.
- **The End:** a bot there reads the End's state every second (whether the exit portal is open, the dragon is alive,
  an egg sits on the pillar) and follows a thrown eye of ender's flight for its bearing. It recognizes a stronghold by
  eight stone bricks seen together, an end city by eight purpur blocks or end rods, and a ship by its dragon head or
  framed elytra.

## Memory

- **Persistent memory** is saved in the world's roster. It holds the bot's home, bed, crafting table and base, the
  Nether camp and known portals, and chests with their contents (shulker boxes included). It remembers resource
  locations, the furnaces it loaded and left, the mine and night strip mine (or the mine dug from a burrow), the first
  house's quarry, the shulker box it placed, the flocks it has seen (for three days), the stations of other mods it
  uses and the last level their shells read, and its fields, wart plot and pen. It knows villages, Nether fortresses (blaze spawners and wart
  gardens), bastions and warped forests, strongholds and end cities. It also keeps enemy sightings, the enemy-faction
  bases it has learned, grudges and their causes, its death position, and its arrival point in the End.
- **Faction memory** is shared by faction mates. It holds the base, its chests, its wall (fence or fortress, with the
  moat's cells), its machine yard and the machines in it, its decoy and the theft it last noticed. It tracks enemy sightings and the enemy-faction bases the
  faction has learned (their chests and contents, gates, golems, traps laid, and the guard that spotted a raider). It
  knows villages and Nether and End structures, whether roles are handed out by size, and who's building what. It
  also keeps the faction's [End record](/ai-players/guide/the-end/#technical-details): the portal room, the frames
  filled, the dragon, the exit portal, the egg and its chest, the gateway, the landing, the city, its ship and the
  elytra brought home.
- **Transient memory** holds the current target (and the runner it's chasing) and the path. It keeps recent failures,
  so a bot doesn't keep retrying the same impossible thing, and recently broken blocks ("own works"), so its own
  mining shaft isn't mistaken for a trap. Beyond those, it tracks the blocks it gave up on for the day, prey
  sightings from the last five minutes, the smith it just leveled, a raid it has decided on for the night, an open
  call and its party, and the eye bearing and legs of a stronghold search.

## Knowledge and planning

At server start (and after `/reload`), AI Players builds a picture of how items are made:

- a **recipe graph** from the server's own recipes (crafting, smelting, blasting, smoking, smithing) plus
  data-driven brewing chains (`data/<namespace>/aiplayers/potion/*.json`), so modded recipes work automatically;
- a **drop table** from the blocks' loot tables, sampled per tool rung;
- the **rungs** of the gear ladder (the six vanilla tiers built in, plus any a plugin registers, each with its
  tools, armor, mining level, rank and how it wears), which tool each block needs, and the dimension each block
  category or monster lives in;
- the **ores** found in `c:ores/*` tags and the **crops** in `#minecraft:crops`, learned without a plugin;
- the **stations**, **supplies** and **structure needs** plugins register for other mods' machines, with their
  machine recipes ([mod integration](/ai-players/reference/mod-integration/)).

When a bot needs an item, the **acquisition planner** works out the cheapest way to get it from what the bot holds,
remembers and sees. It can take the item from the inventory or a chest (what the chest holds first, even when it's
less than the plan needs), mine it, kill something that drops it (including dusk monster hunts for string, bones
and arrows), craft it, smelt it, smith it, brew it, work it at a registered machine (placing the machine, feeding
its supply and building its shell if need be), or buy it from a villager. If a step's source is in another
dimension, the planner wraps the step in a portal trip out and a portal trip back. Each option is costed by distance
and time, recursively, with a depth limit and cycle detection. A plan that would have to make a hoard item from
scratch while the chests are short of it fails with `needs <item> stocked` instead, and the `hoard` objective fills
it. If a step fails, the bot plans again.

## Choosing what to do

Every objective has a score:

```txt title="Formula"
score = weight × urgency × feasibility × (1 − risk × (1 − risk_tolerance))
```

- **weight**: the play style's weight for the objective's family. Unweighted survival needs (like the first house,
  or low food stock once the bot holds a stone pickaxe) use a weight of `1.0`.
- **urgency**: how much the bot needs it (hunger, health, threats, darkness, the gear gap to its goal, how far its
  stockpiles are below target...).
- **feasibility**: whether the first steps can happen now (a known source, the materials, a reachable site).
- **risk**: threats nearby and distance from home, softened by the style's `risk_tolerance`.

The running objective gets a 15% bonus so the bot doesn't flip between close options. Surviving, fighting, orders
and the load of held ore (at dusk, or the next pickaxe's three ore at any hour) are interrupts. They're checked every
tick and can cut in. A ready bot's End trip (`the_end`, `outer_islands`) ranks above every `gear`, `mine`, `build`
and `explore` objective, whatever their weights. Its `end` weight only scales it against the other families.

At night, when the difficulty sets `night_work: true`, a bot that has a bed or a burrow only considers night-safe
objectives: indoors at the base, underground in the night strip mine, fishing in the yard, or a mine dug from a
burrow. That way it keeps working instead of sleeping until every human player is in bed. Work it has begun runs to
its end, a night job that fails twice is held until morning, and a bot that has decided to raid keeps its night for
the raid. The End has no night at all. An objective whose work fails goes on a 600-tick cooldown with its reason,
which shows in `/aiplayer info`. On difficulties with `decision_quality` below 1, the bot occasionally picks its
second-best objective.

Three guards keep the choice honest. The **thrash guard** cools down an objective (reason `thrash`) when its turn
ends within two seconds of starting three times in a row. The **stall guard** reads the bot's own state once a
second (its block, inventory and tool wear, its own edits, open menus, health, food). After a minute awake with
nothing changed, it fails the running tree as `stalled`. If that happens again on the same spot, or the bot stalls
with no tree running at all, the guard walks it out to open ground, never a random step. Leaves that have to stand
still *declare* their wait (a short smelt, sleep, the night indoors, a trade, an ordered `stay`), and the wait counts
as progress until its deadline. The **escape ladder** catches a bot that moves but gets nowhere: within eight
blocks of one spot for 3000 ticks awake, with nothing broken, placed, picked up or opened, it's stuck, and each
time it's found stuck again it climbs a rung (fail and cool, walk out, relocate to the nearest known safe place,
relocate again with a doubled cooldown, then a `stuck` call to its faction), never a random step and never a death
on purpose. A long smelt works differently. The bot loads the furnace and leaves it, the objective that needs the
ingots is held back until the furnace is due, and a *collect* term of `survive` brings the bot back for the result.

## Tasks

Each objective builds a **task tree** from the current situation. Tasks are composed with sequences, selectors,
retries and guards, down to leaves like `GoTo`, `Dig`, `MineBlocks`, `Craft`, `Smelt`, `Smith`, `Enchant`, `Brew`,
`Drink`, `Heal`, `Eat`, `Fish`, `Shear`, `BuildStructure`, `BuildPortal`, `Travel`, `TendCrops`, `TradeWith`,
`BuildGolem`, `DigMoat`, `PourLava`, `LayDecoy`, `Breach`, `LootChest`, `FightTarget`, `FightFromTower`,
`FightFromDoorway`, the generic layer's `WorkMachine`, `Recharge` and `BuildShell`, and the End's own: throwing and following an eye, filling a frame, crossing a gateway by pearl,
island hopping, the crystal shots, the dragon fight, the egg's punch and drop, the city raid, the shulker duel, the
ship's loot and a flight. A search cut by its time limit is retried after 100 ticks, at most twice in a row, and
never counts as a failure. Every task has a progress watchdog that fails it if nothing moves forward for too long.
Failures bubble up with a reason.

## Motor

- **Pathfinding:** an A* search over block positions. It runs on a background thread against a snapshot of the
  world, with node and time limits from the difficulty (the time limit is on the bot clock). Bots can walk, jump,
  step up, drop, parkour, swim, climb ladders and vines, open doors and gates, dig through blocks, pillar up,
  unpillar, pillar down from a ledge and bridge across gaps. With a water bucket they land long drops on poured water
  and ride a water column up a wall. With a boat they row across open water longer than eight blocks. Going through a
  hidden base's sealed mouth, they `unseal` it and reseal it behind them. In the End, paths treat the void (nothing
  solid within eight blocks under a cell) as a cost. They keep a block away from it and never drop into it or jump
  over it. The dragon's breath is kept two blocks off, and bridging the void (sneaking to the edge and placing a
  block against the one the bot stands on) is a movement of its own. Bots avoid lava, fire, magma, soul sand, cactus,
  berry bushes, powder snow and other hazards. When a search runs out of budget, the bot follows the best partial
  path and searches again from there.
- **Movement:** the path follower presses the same movement keys a player would (forward, strafe, jump, sneak,
  sprint) and lets vanilla physics do the rest. A boat is paddled with the same keys, through a mixin that runs
  vanilla's client-side boat control on the server for a bot. Elytra flight works the same way. The bot puts the
  elytra on in place of its chestplate through the inventory, jumps off an edge and opens it in the air. It holds a
  pitch and turns toward its target, fires a rocket from its hand when it runs short on height, and pulls level over
  the ground to land. Bots never teleport or move through blocks. The only teleports are a thrown ender pearl and the
  game's portals and gateways.
- **Interaction:** every block break, placement, item use, attack, container click, craft, enchantment and trade
  goes through the same server-side handlers a real client's packets reach, so reach, cooldowns, break speed and
  other mods' hooks all apply. A bucket is poured and scooped only once the bot's own look ray lands on the cell.
- **Combat:** a combat controller handles standoff distance, strafing, timed swings and critical hits. Bots raise
  shields against melee, shooters within 16 blocks and swelling creepers, and use axes against shields. They duel
  creepers with hit-and-step-back (or brace a shield against one swelling too close), and against archers they rush
  in a sprinting serpentine, duck into cover or wall the archer off. They chase a target that runs, heal at the
  retreat line with a sprinting step back, fight a pack from a two-block tower or a doorway, wall themselves in
  underground rather than run with a monster at their heels, use combat potions, and shoot bows with lead.

## Determinism

Given the same situation, a bot makes the same choice. There's no external service and no learned model behind it.
Some choices are seeded per bot (like the size of its house), so different bots look and act a little differently
while each bot stays consistent.
