Docs menu

How it's built

For contributors. The bot is a Bun and TypeScript program on top of Mineflayer. The AI model chooses what to do; everything that touches the game is code that checks the world after it acts.

The folders

FolderWhat's in it
src/index.tsThe entry: connects, registers the reflexes, the timers and the chat listeners.
src/core/The body and what guards it: the arbiter, leases, reflexes, primitives, containers, results, the narrator.
src/actions/Capabilities built on the primitives: movement, digging, crafting, storage, cooking, farming. The reflex modules live here too.
src/commands/One module per thing the owner can ask for, and the one list of them.
src/managers/Chat in, model calls, the command queue, memory on disk, the stuck watch.
src/skills/Longer behaviour: getting items, the milestones, the mine, the farm, the home, and endgame/.
src/planner/The diary, the goals, the day plan and its runner, spending.
src/roles/The jobs: one file each, and the runner that starts their shifts.
src/config/, src/schemas/Settings checked at start, and the Zod schemas for commands and memory.

From a chat line to an action

  1. index.ts listens for chat and whispers and passes them to handleChat in managers/chatGateway.ts. Anyone but the owner is ignored.
  2. tryFastPath answers a fixed set of phrases in code: stop, come, follow me, status, coordinates, the diary, the plan, spending, the job. No model call.
  3. Anything else goes to managers/aiManager.ts, which sends it to the model with the recent conversation, a line about the bot's state, and every command as a strict tool.
  4. Each tool call the model returns becomes a command. A few answer at once; the rest go through queueCommand in managers/actionManager.ts, which proposes a task to the arbiter.
  5. The arbiter runs the task: the command's execute calls actions, the actions call primitives, and the command speaks through the narrator.

One arbiter, seven priorities

Everything the bot does is a task in core/arbiter.ts. There is no queue in the database and no polling loop: proposing a task, or a task ending, schedules the next.

BucketNameWhat runs there
0SurvivalAir, lava, being buried.
1ThreatCreepers, fights, getting unstuck, eating when starving.
2OwnerThe owner's commands.
3RoleShifts of a job.
4UpkeepThe night routine, restocking food, gear.
5SelfMilestones and plan steps.
6IdleChores.

A task is a TaskSpec: a name, a bucket and a run function, plus optional interrupts, resume, yields, watchProgress, maxMs, onStart and onEnd. propose(spec) hands it in.

  • A task in a lower bucket cuts in on the running one. In the same bucket, only one marked interrupts does, as when the owner calls the bot.
  • The task cut off gets its resume called and goes back to the front of the queue with what's left. Counted work says how far it got with reportProgress.
  • "stop", a stuck task and a task past its maxMs are cancelled without a resume.
  • Inside a task, check isCommandCancelled() in loops.

Reflexes and leases

Reflexes don't cancel tasks. The body has three resources in core/leases.ts: movement, hands and window (an open chest or furnace). The running task holds them by default.

  • A reflex runs inside asReflex(name, fn) and takes the resources urgently. The task waits at its next primitive and carries on when the reflex lets go; a walk that was cut off is walked again.
  • Upkeep, like eating or putting on armor, uses borrow: it waits for a gap between two of the task's actions.
  • Tasks never call bot.* themselves. The primitives wait their turn for them.

Primitives and results

Every change to the game goes through core/primitives.ts (goTo, breakBlock, placeBlockAt, equipItem, craftWith, useBlock, hitEntity, sleepIn and the rest) or core/containers.ts (chests and furnaces).

A primitive checks before it acts, acts under a time limit and the task's stop signal, then looks at the world again. A block that came back after digging is a failure, not a success.

It returns an ActionResult:

type ActionResult<T = void> =
  | { ok: true; value: T }
  | { ok: false; reason: FailReason; detail: string };

FailReason is a fixed list: aborted, interrupted, timeout, disconnected, unreachable, out_of_reach, unknown_block, not_found, no_tool, refused, reverted, forbidden, occupied, no_support, full, missing_items, error. Use describeFailure(result) to turn one into a chat line.

The boundary check. scripts/checkBoundaries.ts counts direct game-changing calls outside src/core/: bot.dig, bot.placeBlock, bot.equip, bot.chat and the like, and any use of the pathfinder or combat plugins. Each file has an allowed count, and the count may only go down. bun run check fails if you add one.

The narrator

Everything the bot says goes through core/narrator.ts. Don't call bot.chat.

CallForRules
reply(text)An answer to the owner.Never dropped. Goes back on the channel the owner used.
report(text)How a task ended.The same line isn't repeated within 30 seconds. Held while the owner is offline.
chatter(text, topic)Running commentary.The newest line per topic wins. Dropped when the task ends.

Lines are spaced by SERVER_CHAT_SPACING_MS so the server doesn't kick the bot for spam.

Memory

Memory is one JSON file per world, in worlds/, picked from the world the server reports at login. It's read and written through managers/persistenceManager.ts (getMemory, updateMemory) and checked against a Zod schema; managers/migrate.ts upgrades older files.

It holds places, chests and what's in them, the bed, the last death, milestones reached, the diary, the plan, lessons, the job and the keep-out areas.

What the bot has right now is never stored: tool tiers, food, shelter and bed are computed on each call in skills/capabilities.ts.

Getting an item

There is one way to get an item: acquire(item, count, world) in skills/acquire.ts.

It asks the craft planner what's missing. For each missing raw material it tries the sources in skills/world.ts, in order: its chests, chopping trees, mining stone, breaking gravel, hunting sheep, mining ore, smelting. Each source may need something first, such as a pickaxe, and that's acquired the same way.

The ensure* helpers are thin wrappers over acquire. They must not call each other.

Adding a command

A command is a module in src/commands/ with three exports:

// src/commands/Diary.ts, shortened
import { z } from "zod";
import { reply } from "../core/narrator";

export const description = `Tells the owner what the bot did today, from its diary.
Example: "What did you do today?", "Read me your diary".`;

export const parameters = z.object({
  yesterday: z.boolean().nullable().describe("True for yesterday, null or false for today."),
});

export async function execute(args: { yesterday?: boolean | null } = {}): Promise<void> {
  reply("...");
}
  1. Write the module. The description is what the model reads, so say when to use the command and give example phrases.
  2. Parameters are strict. Every field is present; one that may be left out is .nullable(), never .optional().
  3. Add its line to src/commands/all.ts: export * as Diary from "./Diary";. That's the registration. The name becomes diary, and the model's tool list is built from this file.
  4. Load heavy modules lazily. Inside a command, import the curriculum, the planner, roles and other commands with await import(...). A static import closes a cycle through the registry.
  5. Act through actions and primitives, and speak with reply, report or chatter.
  6. Update the count in tests/commandList.test.ts, then regenerate the site's command reference.

Optional: a command that should answer at once or cut in on running work is added to the lists at the top of managers/aiManager.ts; one that should resume after being cut off, to the lists in managers/actionManager.ts.

Adding a goal or a job

  • A planner goal is one entry in GOALS in planner/goals.ts, over a skill that already exists: feasible says whether it's possible now, ready whether it can start from where the bot stands. A new argument is a nullable field in StepSchema in planner/plan.ts.
  • A job is a file in src/roles/ that exports a shift, an entry in JOBS in roles/role.ts, and a line in roles/runner.ts.

Tests and checks

bun run tsc     # types
bun run test    # the tests in tests/
bun run check   # types, the boundary check and the tests
  • Tests never call the model: the test setup puts the spending cap at zero.
  • Tests use throwaway memory files, never a real world's.
  • There are about 75 test files. Pure parts, like geometry, plans and choosing what to store, are tested without a game; tests/fakeBody.ts stands in for the bot where one is needed.

What tests can't show is checked in a real game. docs/testing-backlog.md in the bot's repository lists what still waits for that.

The source is on GitHub. For players, the other pages describe the same things from the outside: its own life, reflexes, the planner and jobs.