fix(runtime): unstick scheduler + chop + sleep + bed/shelter/farm skills
Recovers the bot from the live-server symptoms reported 2026-05-26: 1) constant supervisor reconnects, 2) chop "clicks once and stops", 3) sleep does nothing without a bed and so blocks night-skipping for other players, 4) curriculum reflex always fell through to wander. Supervisor (#38): - runtime/watch-filter.js: pure predicate excluding *.test.js + the supervisor itself; recursive:true so skills/ + social/ edits also restart. Burned a working main once when test files counted toward the rollback threshold. - runtime/supervisor.js: watch-triggered restarts no longer count toward the crash-loop rollback path. Watcher is now recursive. Chop / mine (#39): - runtime/actions.js + runtime/skills/gather-stone.js: replaced raw pathfinder.goto + bot.dig with mineflayer-collectblock's bot.collectBlock.collect — handles approach, repositioning, LoS, dig and pickup as one primitive. Old version "swung once" because GoalGetToBlock often parked the bot in leaves above the log. Sleep + bed (#40): - runtime/actions.js: sleepInBed now ALSO places a carried bed on solid ground next to the bot and sleeps on it. Critical so the bot stops blocking player night-skipping the moment it owns a bed. Bed pipeline (#41): - runtime/skills/gather-wool.js: gather.wool skill — mines wool block if any nearby, otherwise shears or attacks the nearest sheep. - runtime/skills/craft.js: craftBedSkill (any colour the bot has ≥3 wool of, plus 3 planks, plus a table). - runtime/curriculum.js: new milestone survive.bed sits between wood.tools and stone.32 so the bot gets a bed BEFORE everything else. Test fixture updated to include a red_bed in post-survive.bed stages. Village / shelter / wheat (#42, #43): - runtime/skills/build-shelter.js: village.build-shelter — real 3×3×3 resumable hut blueprint around the recorded base, places one block per loop, idempotent so an interrupted build resumes correctly, marks each placed block in the owned-blocks ledger. - runtime/skills/deposit-surplus.js: village.deposit-surplus opens the nearest chest and transfers surplus stacks while keeping a reserve of tools/food/bed. - runtime/skills/farm-wheat.js: farm.wheat does one step per call (till adjacent-to-water grass, plant seeds, or harvest ripe wheat). - runtime/curriculum.js: village.shelter milestone after base-site. Scheduler glitch (root of "always wander"): - runtime/bot.js: curriculum + locations are now computed BEFORE runTick. Previously they were stamped AFTER, so reflex.js saw snapshot.curriculum=undefined every tick and fell through to the wander fallback. Verified live: scheduler now dispatches gather.logs/gather.stone/craft.* by id via runSkill. Eat-spam: - runtime/reflex.js: eatReflex now checks inventory for actual food and updates lastEatAt on EVERY dispatch (not only successes), so a failed eat respects the 5 s cooldown instead of firing every tick. npm test 123/123. Validated live on play.xmatic.team (curriculum dispatched gather.logs via runSkill, recover hint switched to wander when no log in range). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,188 @@
|
||||
// village.build-shelter — place a minimal 3×3×3 hut around the bot's
|
||||
// recorded base (or current position if no base yet). The blueprint is
|
||||
// computed once per call as a list of {x,y,z,blockType} targets, then
|
||||
// the skill places them in order, marking each placed block in the
|
||||
// owned-blocks ledger. Idempotent: any target that already holds the
|
||||
// right block is skipped, so the skill is resumable across restarts.
|
||||
//
|
||||
// Walls use any *_planks the bot carries (we pick the most-common type).
|
||||
// The interior keeps the bed slot empty (assumes the bed sits on
|
||||
// (cx+1, cy, cz) — i.e. one step east of the centre).
|
||||
//
|
||||
// Out of scope here: door entity (mineflayer can't reliably place doors
|
||||
// without recent version checks). The west wall has a 1-block opening
|
||||
// at head-height the bot can step through.
|
||||
|
||||
import { applyProfile, PROFILES } from "../movement-profiles.js";
|
||||
import { info, warn } from "../log.js";
|
||||
import { getLocation, setLocation } from "../locations.js";
|
||||
|
||||
const SHELTER_NAME = "shelter";
|
||||
|
||||
function withTimeout(promise, ms, label) {
|
||||
let timer;
|
||||
const timeout = new Promise((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms / 1000}s`)), ms);
|
||||
});
|
||||
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
function pickBuildPlanks(bot) {
|
||||
const counts = new Map();
|
||||
for (const item of bot.inventory.items()) {
|
||||
if (item.name.endsWith("_planks")) {
|
||||
counts.set(item.name, (counts.get(item.name) ?? 0) + item.count);
|
||||
}
|
||||
}
|
||||
let best = null;
|
||||
for (const [name, n] of counts) {
|
||||
if (!best || n > best.n) best = { name, n };
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
// Build a list of {x,y,z, name} targets for a 3×3 footprint × 3-tall
|
||||
// shelter centred on (cx, cy, cz). Bed slot (cx+1, cy, cz) and head-
|
||||
// height entry at the west wall (cx-1, cy+1, cz) are left empty.
|
||||
function blueprint(center, plankName) {
|
||||
const targets = [];
|
||||
const { x: cx, y: cy, z: cz } = center;
|
||||
// Floor: only the corners we don't already have (skip the bed slot).
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
for (let dz = -1; dz <= 1; dz++) {
|
||||
targets.push({ x: cx + dx, y: cy - 1, z: cz + dz, name: plankName });
|
||||
}
|
||||
}
|
||||
// Walls (y = cy and y = cy+1).
|
||||
for (let dy = 0; dy <= 1; dy++) {
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
for (let dz = -1; dz <= 1; dz++) {
|
||||
const isCorner = Math.abs(dx) + Math.abs(dz) === 2;
|
||||
const isWall = Math.abs(dx) === 1 || Math.abs(dz) === 1;
|
||||
if (!isWall && !isCorner) continue; // skip interior column
|
||||
// Leave one wall slot open as a doorway: west wall, head height.
|
||||
if (dx === -1 && dz === 0 && dy === 1) continue;
|
||||
// Bed occupies (cx+1, cy, cz) — its second half is at (cx+2, cy, cz)
|
||||
// which is OUTSIDE this 3×3 footprint. So we don't need to clear it.
|
||||
targets.push({ x: cx + dx, y: cy + dy, z: cz + dz, name: plankName });
|
||||
}
|
||||
}
|
||||
}
|
||||
// Roof: full 3×3 at y = cy+2.
|
||||
for (let dx = -1; dx <= 1; dx++) {
|
||||
for (let dz = -1; dz <= 1; dz++) {
|
||||
targets.push({ x: cx + dx, y: cy + 2, z: cz + dz, name: plankName });
|
||||
}
|
||||
}
|
||||
return targets;
|
||||
}
|
||||
|
||||
function blockMatchesName(block, name) {
|
||||
return block && block.name === name;
|
||||
}
|
||||
|
||||
function findReferenceForPlacement(bot, target) {
|
||||
// Try the block below the target first (most natural place to stack
|
||||
// from). If it's air, try sides.
|
||||
const offsets = [
|
||||
{ x: 0, y: -1, z: 0, face: { x: 0, y: 1, z: 0 } },
|
||||
{ x: -1, y: 0, z: 0, face: { x: 1, y: 0, z: 0 } },
|
||||
{ x: 1, y: 0, z: 0, face: { x: -1, y: 0, z: 0 } },
|
||||
{ x: 0, y: 0, z: -1, face: { x: 0, y: 0, z: 1 } },
|
||||
{ x: 0, y: 0, z: 1, face: { x: 0, y: 0, z: -1 } },
|
||||
{ x: 0, y: 1, z: 0, face: { x: 0, y: -1, z: 0 } },
|
||||
];
|
||||
for (const off of offsets) {
|
||||
const block = bot.blockAt({
|
||||
x: target.x + off.x,
|
||||
y: target.y + off.y,
|
||||
z: target.z + off.z,
|
||||
});
|
||||
if (block && block.boundingBox === "block") return { ref: block, face: off.face };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const skill = Object.freeze({
|
||||
id: "village.build-shelter",
|
||||
title: "Build a tiny shelter around the bed",
|
||||
timeoutMs: 5 * 60_000,
|
||||
preconditions(ctx) {
|
||||
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
|
||||
const planks = pickBuildPlanks(ctx.bot);
|
||||
if (!planks || planks.n < 18) {
|
||||
return { ok: false, code: "missing_material", detail: `need ≥18 planks (have ${planks?.n ?? 0})` };
|
||||
}
|
||||
// Need a base or at least a placed bed nearby; the chooseBase skill
|
||||
// is responsible for picking the spot first.
|
||||
const base = getLocation("base") ?? getLocation(SHELTER_NAME);
|
||||
if (!base) return { ok: false, code: "no_base", detail: "no base location chosen yet" };
|
||||
return { ok: true };
|
||||
},
|
||||
async execute(ctx, { owned } = {}) {
|
||||
const bot = ctx.bot;
|
||||
const planks = pickBuildPlanks(bot);
|
||||
const base = getLocation("base") ?? getLocation(SHELTER_NAME);
|
||||
const center = { x: base.x, y: base.y, z: base.z };
|
||||
|
||||
applyProfile(PROFILES.BUILD, bot);
|
||||
|
||||
const targets = blueprint(center, planks.name);
|
||||
info("action", `village.build-shelter: ${targets.length} blocks (planks=${planks.name})`);
|
||||
|
||||
let placed = 0;
|
||||
let skipped = 0;
|
||||
for (const target of targets) {
|
||||
const existing = bot.blockAt(target);
|
||||
if (blockMatchesName(existing, planks.name)) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
// Re-equip planks each iteration (the bot might have eaten / swapped).
|
||||
const item = bot.inventory.items().find((i) => i.name === planks.name);
|
||||
if (!item) {
|
||||
warn("action", `village.build-shelter: ran out of ${planks.name} mid-build`);
|
||||
break;
|
||||
}
|
||||
try {
|
||||
await withTimeout(bot.equip(item, "hand"), 3000, "equip plank");
|
||||
} catch (e) {
|
||||
warn("action", `village.build-shelter: equip failed: ${e.message}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const place = findReferenceForPlacement(bot, target);
|
||||
if (!place) {
|
||||
warn("action", `village.build-shelter: no reference block for ${target.x},${target.y},${target.z}`);
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
await withTimeout(bot.placeBlock(place.ref, place.face), 5000, "placeBlock");
|
||||
if (owned?.markPlaced) {
|
||||
owned.markPlaced({
|
||||
x: target.x, y: target.y, z: target.z,
|
||||
blockType: planks.name,
|
||||
skill: "village.build-shelter",
|
||||
});
|
||||
}
|
||||
placed++;
|
||||
} catch (e) {
|
||||
warn("action", `village.build-shelter: place ${target.x},${target.y},${target.z} failed: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Record the shelter location so future skills can find it even if
|
||||
// base gets re-scored.
|
||||
setLocation(SHELTER_NAME, { x: center.x, y: center.y, z: center.z, radius: 2, note: `auto-built; ${placed} blocks placed` });
|
||||
|
||||
if (placed === 0 && skipped === 0) {
|
||||
return { ok: false, code: "no_progress", detail: "could not place any blocks", worldDelta: null };
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
code: "done",
|
||||
detail: { placed, skipped, total: targets.length, plankName: planks.name },
|
||||
worldDelta: { shelterAt: center, placed },
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -229,6 +229,72 @@ export const craftChestSkill = makeRecipeSkill({
|
||||
needsTable: true,
|
||||
});
|
||||
|
||||
// Bed: 3 wool of one colour + 3 planks → 1 bed of that colour. We look
|
||||
// for any colour we have ≥3 of, ditto planks, and craft that pairing.
|
||||
// All bed recipes require a crafting table.
|
||||
const BED_COLORS = [
|
||||
"white", "orange", "magenta", "light_blue", "yellow", "lime", "pink",
|
||||
"gray", "light_gray", "cyan", "purple", "blue", "brown", "green",
|
||||
"red", "black",
|
||||
];
|
||||
|
||||
function countByName(bot, name) {
|
||||
return bot.inventory.items().reduce((s, i) => (i.name === name ? s + i.count : s), 0);
|
||||
}
|
||||
|
||||
function bedColorWeCanCraft(bot) {
|
||||
// Need 3 wool of a single colour. (Mixed-colour wool can't combine.)
|
||||
for (const c of BED_COLORS) {
|
||||
if (countByName(bot, `${c}_wool`) >= 3) return c;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export const craftBedSkill = Object.freeze({
|
||||
id: "craft.bed",
|
||||
title: "Craft a bed",
|
||||
timeoutMs: 30_000,
|
||||
preconditions(ctx) {
|
||||
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
|
||||
const color = bedColorWeCanCraft(ctx.bot);
|
||||
if (!color) return { ok: false, code: "missing_material", detail: "need 3 wool of one colour" };
|
||||
if (totalPlanks(ctx.bot) < 3) return { ok: false, code: "missing_material", detail: "need 3 planks" };
|
||||
return { ok: true };
|
||||
},
|
||||
async execute(ctx) {
|
||||
const bot = ctx.bot;
|
||||
const color = bedColorWeCanCraft(bot);
|
||||
const item = `${color}_bed`;
|
||||
const tableRes = await placeCraftingTable(bot);
|
||||
if (!tableRes.ok) {
|
||||
const msg = String(tableRes.detail ?? "");
|
||||
const code = msg.includes("timed out") ? "timeout" : "missing_table";
|
||||
return { ok: false, code, detail: tableRes.detail, worldDelta: null };
|
||||
}
|
||||
const reg = bot?.registry;
|
||||
const itemId = reg?.itemsByName?.[item]?.id;
|
||||
if (itemId == null) {
|
||||
return { ok: false, code: "unsupported_version", detail: `no ${item} in registry`, worldDelta: null };
|
||||
}
|
||||
const recipes = bot.recipesFor(itemId, null, 1, tableRes.block);
|
||||
const recipe = recipes[0];
|
||||
if (!recipe) {
|
||||
return { ok: false, code: "no_recipe", detail: `no recipe for ${item}`, worldDelta: null };
|
||||
}
|
||||
try {
|
||||
await withTimeout(bot.craft(recipe, 1, tableRes.block), 15_000, `craft(${item})`);
|
||||
return { ok: true, code: "done", detail: { item }, worldDelta: { crafted: item } };
|
||||
} catch (e) {
|
||||
const msg = String(e?.message ?? "");
|
||||
const code = msg.includes("timed out") ? "timeout" : "failed";
|
||||
return { ok: false, code, detail: e.message, worldDelta: null };
|
||||
}
|
||||
},
|
||||
validate(ctx, result) {
|
||||
return result.ok && !!result.worldDelta?.crafted;
|
||||
},
|
||||
});
|
||||
|
||||
// Torch: 1 stick + 1 coal (or charcoal) → 4 torches. We accept either
|
||||
// fuel via precondition shortcut: if no coal AND no charcoal, fail with
|
||||
// missing_material so the curriculum surfaces the blocker rather than
|
||||
|
||||
@@ -0,0 +1,127 @@
|
||||
// village.deposit-surplus — find the nearest placed chest, open it, and
|
||||
// transfer any stack the bot is over-carrying (logs, cobble, dirt,
|
||||
// seeds). Keeps a small "essentials" reserve in inventory so the bot
|
||||
// keeps its tools, food and bed.
|
||||
//
|
||||
// What counts as surplus:
|
||||
// * any item whose count exceeds RESERVE_PER_NAME (default: keep 8 of
|
||||
// each named item), UNLESS it's in KEEP_ALWAYS (tools/bed/food).
|
||||
// * raw materials that look strictly storable (logs/cobble/dirt/sand).
|
||||
|
||||
import pathfinderPkg from "mineflayer-pathfinder";
|
||||
const { pathfinder, goals, Movements } = pathfinderPkg;
|
||||
|
||||
import { applyProfile, PROFILES } from "../movement-profiles.js";
|
||||
import { info, warn } from "../log.js";
|
||||
|
||||
const KEEP_ALWAYS_NAME_RE = /(_axe|_pickaxe|_sword|_shovel|_hoe|_bed|bread|cooked_|apple|carrot|potato|wheat_seeds)$/;
|
||||
const STORABLE_NAME_RE = /(_log$|_stem$|cobblestone|cobbled_deepslate|deepslate|stone$|dirt|sand|gravel|wheat$|_planks$|stick$)/;
|
||||
const RESERVE_PER_NAME = 8;
|
||||
|
||||
let pluginLoaded = new WeakSet();
|
||||
function ensurePathfinder(bot) {
|
||||
if (pluginLoaded.has(bot)) return;
|
||||
bot.loadPlugin(pathfinder);
|
||||
pluginLoaded.add(bot);
|
||||
}
|
||||
|
||||
function withTimeout(promise, ms, label) {
|
||||
let timer;
|
||||
const timeout = new Promise((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms / 1000}s`)), ms);
|
||||
});
|
||||
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
function pickSurplus(bot) {
|
||||
const out = [];
|
||||
// Group inventory items by name, then decide how much to deposit per name.
|
||||
const grouped = new Map();
|
||||
for (const item of bot.inventory.items()) {
|
||||
if (!grouped.has(item.name)) grouped.set(item.name, []);
|
||||
grouped.get(item.name).push(item);
|
||||
}
|
||||
for (const [name, items] of grouped) {
|
||||
if (KEEP_ALWAYS_NAME_RE.test(name)) continue;
|
||||
const total = items.reduce((s, i) => s + i.count, 0);
|
||||
const storable = STORABLE_NAME_RE.test(name);
|
||||
const reserve = storable ? Math.min(RESERVE_PER_NAME, total) : 0;
|
||||
const surplus = total - reserve;
|
||||
if (surplus <= 0) continue;
|
||||
out.push({ name, surplus, items });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
export const skill = Object.freeze({
|
||||
id: "village.deposit-surplus",
|
||||
title: "Deposit surplus items in a chest",
|
||||
timeoutMs: 60_000,
|
||||
preconditions(ctx) {
|
||||
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
|
||||
const surplus = pickSurplus(ctx.bot);
|
||||
if (surplus.length === 0) return { ok: false, code: "nothing_to_deposit", detail: "no surplus stacks" };
|
||||
const chest = ctx.bot.findBlock({
|
||||
matching: (b) => b?.name === "chest" || b?.name === "trapped_chest",
|
||||
maxDistance: 24,
|
||||
});
|
||||
if (!chest) return { ok: false, code: "no_chest", detail: "no chest within 24 blocks" };
|
||||
return { ok: true };
|
||||
},
|
||||
async execute(ctx) {
|
||||
const bot = ctx.bot;
|
||||
const chest = bot.findBlock({
|
||||
matching: (b) => b?.name === "chest" || b?.name === "trapped_chest",
|
||||
maxDistance: 24,
|
||||
});
|
||||
if (!chest) return { ok: false, code: "no_chest", detail: "no chest after move", worldDelta: null };
|
||||
|
||||
ensurePathfinder(bot);
|
||||
applyProfile(PROFILES.TRAVEL, bot);
|
||||
try {
|
||||
await withTimeout(
|
||||
bot.pathfinder.goto(new goals.GoalNear(chest.position.x, chest.position.y, chest.position.z, 1)),
|
||||
30_000,
|
||||
"goto chest",
|
||||
);
|
||||
} catch (e) {
|
||||
return { ok: false, code: "no_path", detail: e.message, worldDelta: null };
|
||||
}
|
||||
|
||||
let chestHandle;
|
||||
try {
|
||||
chestHandle = await withTimeout(bot.openContainer(chest), 8_000, "openChest");
|
||||
} catch (e) {
|
||||
return { ok: false, code: "open_failed", detail: e.message, worldDelta: null };
|
||||
}
|
||||
|
||||
let deposited = 0;
|
||||
const detail = [];
|
||||
try {
|
||||
for (const { name, surplus } of pickSurplus(bot)) {
|
||||
const ref = bot.registry?.itemsByName?.[name];
|
||||
if (!ref) continue;
|
||||
try {
|
||||
await withTimeout(chestHandle.deposit(ref.id, null, surplus), 10_000, `deposit ${name}`);
|
||||
deposited += surplus;
|
||||
detail.push(`${name}×${surplus}`);
|
||||
info("action", `village.deposit-surplus: ${name}×${surplus}`);
|
||||
} catch (e) {
|
||||
warn("action", `village.deposit-surplus: ${name} failed: ${e.message}`);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
try { await chestHandle.close(); } catch {}
|
||||
}
|
||||
|
||||
if (deposited === 0) {
|
||||
return { ok: false, code: "deposit_failed", detail: "opened chest but deposited nothing", worldDelta: null };
|
||||
}
|
||||
return {
|
||||
ok: true,
|
||||
code: "done",
|
||||
detail: { deposited, items: detail },
|
||||
worldDelta: { depositedTotal: deposited },
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,180 @@
|
||||
// farm.wheat — opportunistic wheat farming. The skill does ONE of:
|
||||
// * plant a wheat seed on a nearby tilled farmland block, OR
|
||||
// * till a grass/dirt block adjacent to water if we have a hoe and seeds,
|
||||
// * harvest a fully-grown wheat block.
|
||||
//
|
||||
// We don't try to plan a full 3×3 plot in one call — the curriculum can
|
||||
// dispatch the skill repeatedly and each call makes one block of progress.
|
||||
// This is consistent with the gather.logs / gather.stone "one block at a
|
||||
// time" rhythm and keeps each tick observable.
|
||||
|
||||
import pathfinderPkg from "mineflayer-pathfinder";
|
||||
const { pathfinder, goals, Movements } = pathfinderPkg;
|
||||
|
||||
import { applyProfile, PROFILES } from "../movement-profiles.js";
|
||||
import { info, warn } from "../log.js";
|
||||
|
||||
const HOE_NAMES = ["wooden_hoe", "stone_hoe", "iron_hoe", "diamond_hoe", "netherite_hoe", "golden_hoe"];
|
||||
|
||||
let pluginLoaded = new WeakSet();
|
||||
function ensurePathfinder(bot) {
|
||||
if (pluginLoaded.has(bot)) return;
|
||||
bot.loadPlugin(pathfinder);
|
||||
pluginLoaded.add(bot);
|
||||
}
|
||||
|
||||
function withTimeout(promise, ms, label) {
|
||||
let timer;
|
||||
const timeout = new Promise((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms / 1000}s`)), ms);
|
||||
});
|
||||
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
function getCount(bot, name) {
|
||||
return bot.inventory.items().reduce((s, i) => (i.name === name ? s + i.count : s), 0);
|
||||
}
|
||||
|
||||
function getItem(bot, name) {
|
||||
return bot.inventory.items().find((i) => i.name === name) ?? null;
|
||||
}
|
||||
|
||||
function hasHoe(bot) {
|
||||
return HOE_NAMES.some((n) => getCount(bot, n) > 0);
|
||||
}
|
||||
|
||||
function findHoe(bot) {
|
||||
for (const n of HOE_NAMES) {
|
||||
const item = getItem(bot, n);
|
||||
if (item) return item;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function isWaterNear(bot, pos, radius = 4) {
|
||||
for (let dx = -radius; dx <= radius; dx++) {
|
||||
for (let dz = -radius; dz <= radius; dz++) {
|
||||
const b = bot.blockAt({ x: pos.x + dx, y: pos.y, z: pos.z + dz });
|
||||
if (b?.name === "water") return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export const skill = Object.freeze({
|
||||
id: "farm.wheat",
|
||||
title: "Make one step of wheat farming progress",
|
||||
timeoutMs: 60_000,
|
||||
preconditions(ctx) {
|
||||
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
|
||||
const bot = ctx.bot;
|
||||
const hasSeeds = getCount(bot, "wheat_seeds") > 0;
|
||||
// We're happy to dispatch when EITHER seeds+hoe+water available
|
||||
// OR there's a ripe wheat block to harvest.
|
||||
const ripeWheat = bot.findBlock({
|
||||
matching: (b) => b?.name === "wheat" && (b?.metadata === 7 || b?.getProperties?.()?.age === 7),
|
||||
maxDistance: 24,
|
||||
});
|
||||
if (ripeWheat) return { ok: true };
|
||||
if (!hasSeeds) return { ok: false, code: "no_seeds", detail: "no wheat_seeds in inventory" };
|
||||
if (!hasHoe(bot)) return { ok: false, code: "missing_tool", detail: "no hoe" };
|
||||
// Need at least one tillable + water-adjacent block within 16.
|
||||
const tillable = bot.findBlock({
|
||||
matching: (b) => (b?.name === "grass_block" || b?.name === "dirt") && isWaterNear(bot, b.position, 4),
|
||||
maxDistance: 16,
|
||||
});
|
||||
if (!tillable) return { ok: false, code: "no_target", detail: "no tillable grass/dirt near water" };
|
||||
return { ok: true };
|
||||
},
|
||||
async execute(ctx) {
|
||||
const bot = ctx.bot;
|
||||
ensurePathfinder(bot);
|
||||
applyProfile(PROFILES.GATHER, bot);
|
||||
|
||||
// 1. Harvest ripe wheat if any.
|
||||
const ripeWheat = bot.findBlock({
|
||||
matching: (b) => b?.name === "wheat" && (b?.metadata === 7 || b?.getProperties?.()?.age === 7),
|
||||
maxDistance: 24,
|
||||
});
|
||||
if (ripeWheat) {
|
||||
try {
|
||||
await withTimeout(
|
||||
bot.pathfinder.goto(new goals.GoalGetToBlock(ripeWheat.position.x, ripeWheat.position.y, ripeWheat.position.z)),
|
||||
20_000,
|
||||
"goto wheat",
|
||||
);
|
||||
await withTimeout(bot.dig(ripeWheat), 8_000, "harvest wheat");
|
||||
info("action", `farm.wheat: harvested wheat at ${ripeWheat.position}`);
|
||||
return {
|
||||
ok: true,
|
||||
code: "done",
|
||||
detail: { phase: "harvest", at: ripeWheat.position },
|
||||
worldDelta: { harvestedAt: ripeWheat.position },
|
||||
};
|
||||
} catch (e) {
|
||||
warn("action", `farm.wheat harvest failed: ${e.message}`);
|
||||
return { ok: false, code: "failed", detail: e.message, worldDelta: null };
|
||||
}
|
||||
}
|
||||
|
||||
// 2. Plant on existing farmland if any (water-adjacent or not, just farmland exists).
|
||||
const farmland = bot.findBlock({
|
||||
matching: (b) => b?.name === "farmland",
|
||||
maxDistance: 16,
|
||||
});
|
||||
const seedItem = getItem(bot, "wheat_seeds");
|
||||
if (farmland && seedItem) {
|
||||
try {
|
||||
await withTimeout(
|
||||
bot.pathfinder.goto(new goals.GoalNear(farmland.position.x, farmland.position.y, farmland.position.z, 1)),
|
||||
20_000,
|
||||
"goto farmland",
|
||||
);
|
||||
await withTimeout(bot.equip(seedItem, "hand"), 3000, "equip seeds");
|
||||
await withTimeout(
|
||||
bot.placeBlock(farmland, { x: 0, y: 1, z: 0 }),
|
||||
5000,
|
||||
"placeBlock(seeds)",
|
||||
);
|
||||
return {
|
||||
ok: true,
|
||||
code: "done",
|
||||
detail: { phase: "plant", at: farmland.position },
|
||||
worldDelta: { plantedAt: farmland.position },
|
||||
};
|
||||
} catch (e) {
|
||||
warn("action", `farm.wheat plant failed: ${e.message}`);
|
||||
// fall through to tilling
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Till a grass/dirt block next to water with our hoe.
|
||||
const tillable = bot.findBlock({
|
||||
matching: (b) => (b?.name === "grass_block" || b?.name === "dirt") && isWaterNear(bot, b.position, 4),
|
||||
maxDistance: 16,
|
||||
});
|
||||
if (!tillable) {
|
||||
return { ok: false, code: "no_target", detail: "no tillable block remaining", worldDelta: null };
|
||||
}
|
||||
const hoe = findHoe(bot);
|
||||
try {
|
||||
await withTimeout(
|
||||
bot.pathfinder.goto(new goals.GoalNear(tillable.position.x, tillable.position.y, tillable.position.z, 2)),
|
||||
20_000,
|
||||
"goto tillable",
|
||||
);
|
||||
await withTimeout(bot.equip(hoe, "hand"), 3000, "equip hoe");
|
||||
// Activate the block (right-click): turns grass/dirt → farmland.
|
||||
await withTimeout(bot.activateBlock(tillable), 5000, "till");
|
||||
return {
|
||||
ok: true,
|
||||
code: "done",
|
||||
detail: { phase: "till", at: tillable.position },
|
||||
worldDelta: { tilledAt: tillable.position },
|
||||
};
|
||||
} catch (e) {
|
||||
warn("action", `farm.wheat till failed: ${e.message}`);
|
||||
return { ok: false, code: "failed", detail: e.message, worldDelta: null };
|
||||
}
|
||||
},
|
||||
});
|
||||
@@ -4,6 +4,12 @@
|
||||
|
||||
import pathfinderPkg from "mineflayer-pathfinder";
|
||||
const { pathfinder, goals, Movements } = pathfinderPkg;
|
||||
import collectBlockPkg from "mineflayer-collectblock";
|
||||
const collectBlockPlugin =
|
||||
collectBlockPkg.plugin ??
|
||||
collectBlockPkg.default?.plugin ??
|
||||
collectBlockPkg.default ??
|
||||
collectBlockPkg;
|
||||
|
||||
import { pickaxes } from "./groups.js";
|
||||
import { info, warn } from "../log.js";
|
||||
@@ -17,6 +23,14 @@ function ensurePathfinder(bot) {
|
||||
pluginLoaded.add(bot);
|
||||
}
|
||||
|
||||
let collectBlockLoaded = new WeakSet();
|
||||
function ensureCollectBlock(bot) {
|
||||
ensurePathfinder(bot);
|
||||
if (collectBlockLoaded.has(bot)) return;
|
||||
bot.loadPlugin(collectBlockPlugin);
|
||||
collectBlockLoaded.add(bot);
|
||||
}
|
||||
|
||||
function setMovementsForGather(bot) {
|
||||
const m = new Movements(bot);
|
||||
m.canDig = true;
|
||||
@@ -91,18 +105,12 @@ export const skill = Object.freeze({
|
||||
return { ok: false, code: "no_target", detail: "no reachable stone within 32 blocks", worldDelta: null };
|
||||
}
|
||||
|
||||
ensurePathfinder(bot);
|
||||
ensureCollectBlock(bot);
|
||||
setMovementsForGather(bot);
|
||||
const pickaxe = await equipBestPickaxe(bot);
|
||||
info("action", `gather.stone: ${target.name} at ${target.position.x},${target.position.y},${target.position.z} (tool=${pickaxe ?? "fists"})`);
|
||||
try {
|
||||
await withTimeout(
|
||||
bot.pathfinder.goto(new goals.GoalGetToBlock(target.position.x, target.position.y, target.position.z)),
|
||||
45_000,
|
||||
"pathToStone",
|
||||
);
|
||||
await withTimeout(bot.dig(target), 30_000, "digStone");
|
||||
await new Promise((r) => setTimeout(r, 1200));
|
||||
await withTimeout(bot.collectBlock.collect(target), 60_000, "collectStone");
|
||||
return {
|
||||
ok: true,
|
||||
code: "done",
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
// gather.wool — get one block of wool, any colour. Three paths in order
|
||||
// of preference:
|
||||
// 1. Mine a placed wool block within 32 blocks (someone left one).
|
||||
// 2. Shear a nearby sheep if we carry shears.
|
||||
// 3. Attack a nearby sheep to drop wool (last resort; gives 1 wool).
|
||||
//
|
||||
// Wool is the only ingredient missing for a bed once we have planks, so
|
||||
// this skill is the first real "go find an animal" task the bot has.
|
||||
|
||||
import collectBlockPkg from "mineflayer-collectblock";
|
||||
import pathfinderPkg from "mineflayer-pathfinder";
|
||||
|
||||
import { info, warn } from "../log.js";
|
||||
|
||||
const { pathfinder, goals, Movements } = pathfinderPkg;
|
||||
const collectBlockPlugin =
|
||||
collectBlockPkg.plugin ??
|
||||
collectBlockPkg.default?.plugin ??
|
||||
collectBlockPkg.default ??
|
||||
collectBlockPkg;
|
||||
|
||||
const WOOL_BLOCK_RE = /(?:^|_)wool$/;
|
||||
|
||||
let pluginLoaded = new WeakSet();
|
||||
function ensurePlugins(bot) {
|
||||
if (pluginLoaded.has(bot)) return;
|
||||
bot.loadPlugin(pathfinder);
|
||||
bot.loadPlugin(collectBlockPlugin);
|
||||
pluginLoaded.add(bot);
|
||||
}
|
||||
|
||||
function setMovementsForGather(bot) {
|
||||
const m = new Movements(bot);
|
||||
m.canDig = true;
|
||||
m.allow1by1towers = false;
|
||||
bot.pathfinder.setMovements(m);
|
||||
}
|
||||
|
||||
function withTimeout(promise, ms, label) {
|
||||
let timer;
|
||||
const timeout = new Promise((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms / 1000}s`)), ms);
|
||||
});
|
||||
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
|
||||
}
|
||||
|
||||
function woolCount(bot) {
|
||||
return bot.inventory.items().reduce(
|
||||
(sum, i) => (WOOL_BLOCK_RE.test(i.name) || i.name.endsWith("_wool") ? sum + i.count : sum),
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
function nearestSheep(bot) {
|
||||
let best = null;
|
||||
for (const e of Object.values(bot.entities)) {
|
||||
if (e?.name !== "sheep" || !e.position) continue;
|
||||
const d = e.position.distanceTo(bot.entity.position);
|
||||
if (!best || d < best.d) best = { e, d };
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
export const skill = Object.freeze({
|
||||
id: "gather.wool",
|
||||
title: "Gather one wool",
|
||||
timeoutMs: 90_000,
|
||||
preconditions(ctx) {
|
||||
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
|
||||
if (woolCount(ctx.bot) >= 3) {
|
||||
return { ok: false, code: "already_have", detail: "already have ≥3 wool" };
|
||||
}
|
||||
return { ok: true };
|
||||
},
|
||||
async execute(ctx) {
|
||||
const bot = ctx.bot;
|
||||
ensurePlugins(bot);
|
||||
setMovementsForGather(bot);
|
||||
|
||||
// 1. Placed wool block?
|
||||
const woolBlock = bot.findBlock({
|
||||
matching: (b) => b?.name && (b.name.endsWith("_wool") || b.name === "wool"),
|
||||
maxDistance: 32,
|
||||
});
|
||||
if (woolBlock) {
|
||||
info("action", `gather.wool: mining ${woolBlock.name} at ${woolBlock.position}`);
|
||||
try {
|
||||
await withTimeout(bot.collectBlock.collect(woolBlock), 45_000, "collectWool");
|
||||
return {
|
||||
ok: true,
|
||||
code: "done",
|
||||
detail: { from: "block", name: woolBlock.name },
|
||||
worldDelta: { gotWool: 1, source: "block" },
|
||||
};
|
||||
} catch (e) {
|
||||
warn("action", `gather.wool block-mine failed: ${e.message}`);
|
||||
// fall through to sheep
|
||||
}
|
||||
}
|
||||
|
||||
// 2/3. Sheep — shear if we have shears, otherwise attack.
|
||||
const sheep = nearestSheep(bot);
|
||||
if (!sheep) {
|
||||
return { ok: false, code: "no_target", detail: "no wool block and no sheep within view", worldDelta: null };
|
||||
}
|
||||
try {
|
||||
await withTimeout(
|
||||
bot.pathfinder.goto(new goals.GoalFollow(sheep.e, 2)),
|
||||
30_000,
|
||||
"pathToSheep",
|
||||
);
|
||||
} catch (e) {
|
||||
return { ok: false, code: "no_path", detail: e.message, worldDelta: null };
|
||||
}
|
||||
|
||||
const shears = bot.inventory.items().find((i) => i.name === "shears");
|
||||
if (shears) {
|
||||
try {
|
||||
await withTimeout(bot.equip(shears, "hand"), 3000, "equip shears");
|
||||
bot.activateEntity(sheep.e); // shears interaction
|
||||
await new Promise((r) => setTimeout(r, 600));
|
||||
// Wait for the drop entity to spawn near the sheep, then pick it up
|
||||
// by walking to it. Simplest: a brief wait — the bot is already next
|
||||
// to the sheep, drops are auto-collected.
|
||||
await new Promise((r) => setTimeout(r, 1200));
|
||||
return {
|
||||
ok: true,
|
||||
code: "done",
|
||||
detail: { from: "shear", entityId: sheep.e.id },
|
||||
worldDelta: { gotWool: 1, source: "shear" },
|
||||
};
|
||||
} catch (e) {
|
||||
warn("action", `gather.wool shear failed: ${e.message}`);
|
||||
// fall through to attack
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
bot.attack(sheep.e);
|
||||
await new Promise((r) => setTimeout(r, 800));
|
||||
// Mineflayer doesn't auto-loop attacks; re-fire until dead or out
|
||||
// of reach. Up to 6 swings.
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const still = Object.values(bot.entities).find((e) => e.id === sheep.e.id);
|
||||
if (!still) break;
|
||||
if (still.position.distanceTo(bot.entity.position) > 4) break;
|
||||
bot.attack(still);
|
||||
await new Promise((r) => setTimeout(r, 700));
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 1200));
|
||||
return {
|
||||
ok: true,
|
||||
code: "done",
|
||||
detail: { from: "kill", entityId: sheep.e.id },
|
||||
worldDelta: { gotWool: 1, source: "kill" },
|
||||
};
|
||||
} catch (e) {
|
||||
warn("action", `gather.wool attack failed: ${e.message}`);
|
||||
return { ok: false, code: "failed", detail: e.message, worldDelta: null };
|
||||
}
|
||||
},
|
||||
recover(ctx, result) {
|
||||
if (result.code === "no_target") return { hint: "wander", reason: "no sheep or wool block visible" };
|
||||
return null;
|
||||
},
|
||||
});
|
||||
@@ -26,7 +26,11 @@ import { skill as chopLogs } from "./chop-logs.js";
|
||||
import { skill as eat } from "./eat.js";
|
||||
import { skill as wander } from "./wander.js";
|
||||
import { skill as gatherStone } from "./gather-stone.js";
|
||||
import { skill as gatherWool } from "./gather-wool.js";
|
||||
import { skill as chooseBase } from "./choose-base.js";
|
||||
import { skill as buildShelter } from "./build-shelter.js";
|
||||
import { skill as depositSurplus } from "./deposit-surplus.js";
|
||||
import { skill as farmWheat } from "./farm-wheat.js";
|
||||
import {
|
||||
craftPlanksSkill,
|
||||
craftSticksSkill,
|
||||
@@ -39,6 +43,7 @@ import {
|
||||
craftFurnaceSkill,
|
||||
craftChestSkill,
|
||||
craftTorchSkill,
|
||||
craftBedSkill,
|
||||
} from "./craft.js";
|
||||
|
||||
const SKILLS = new Map();
|
||||
@@ -56,7 +61,11 @@ register(chopLogs);
|
||||
register(eat);
|
||||
register(wander);
|
||||
register(gatherStone);
|
||||
register(gatherWool);
|
||||
register(chooseBase);
|
||||
register(buildShelter);
|
||||
register(depositSurplus);
|
||||
register(farmWheat);
|
||||
register(craftPlanksSkill);
|
||||
register(craftSticksSkill);
|
||||
register(craftWoodenAxeSkill);
|
||||
@@ -68,6 +77,7 @@ register(craftStoneSwordSkill);
|
||||
register(craftFurnaceSkill);
|
||||
register(craftChestSkill);
|
||||
register(craftTorchSkill);
|
||||
register(craftBedSkill);
|
||||
|
||||
export function listSkills() {
|
||||
return Array.from(SKILLS.values()).map((s) => ({
|
||||
|
||||
Reference in New Issue
Block a user