Files
pepa-pi-bot/runtime/skills/gather-stone.js
T
mayatnikovandClaude Opus 4.7 28f5d9e483 fix(perception): use numeric block ids — callback matchers silently fail under ViaBackwards
Root cause of "bot just stands still": every gather.* skill was using
bot.findBlock({ matching: (b) => names.includes(b.name) }), and under
mineflayer 1.21.4 + ViaBackwards the Block objects fed into the
callback have a wrong .name field (Block.type / numeric id is still
correct — this is mineflayer issue #2347). Every search returned null,
every skill reported "no_target", reflex looped wander → tunnel-out
forever. The bot's logs said "dispatch ok" while the operator watched
it pace in circles.

Proven live with a new diag.match skill on play.xmatic.team:
  findBlocks({matching: numericIds})              → 50 hits
  findBlocks({matching: (b) => b.name === ...})   →  0 hits  ← the bug
  findBlock({matching: (b) => b.name === ...})    → null     ← the bug
  findBlock({matching: numericIds})               → dark_oak_log @ (606,62,110)

After this fix the same bot from the same spawn dispatches gather.logs
and reaches the chop loop ("chop: dark_oak_log at 606,62,110 (tool=fists)")
instead of returning "no reachable log within 64 blocks".

Changes:
- runtime/perception.js (new): findBlocksByName / findNearestBlockByName
  centralise the numeric-id workaround for any future skill.
- runtime/actions.js: chopNearestTree, sleepInBed, placeCraftingTable now
  use perception. Also load mineflayer-tool plugin alongside collectblock
  (collectblock 1.6 hard-requires bot.tool to dispatch a dig).
- gather-stone, gather-wool, deposit-surplus rewritten to numeric-id
  search. gather-wool also loads mineflayer-tool.
- diagnose-scan.js (new): two diagnostic skills — diag.scan reports
  findBlocks counts per radius for common blocks; diag.match cross-tests
  the four matcher styles so this regression can be re-proven on demand.
- runtime/skills/index.js: registers diag.scan + diag.match.

Memory: project_findblock_callback_broken_under_viabackwards.md.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 13:45:29 +03:00

160 lines
5.3 KiB
JavaScript

// gather.stone — find a nearby stone/cobble/deepslate block, equip a
// pickaxe (best available), path to it and mine it. Stone-tier mining
// needs at least a wooden pickaxe — the preconditions enforce that.
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 toolPkg from "mineflayer-tool";
const toolPlugin = toolPkg.plugin ?? toolPkg.default?.plugin ?? toolPkg.default ?? toolPkg;
import { pickaxes } from "./groups.js";
import { info, warn } from "../log.js";
import { findNearestBlockByName } from "../perception.js";
const STONE_NAMES = ["stone", "cobblestone", "deepslate", "cobbled_deepslate", "andesite", "diorite", "granite"];
let pluginLoaded = new WeakSet();
function ensurePathfinder(bot) {
if (pluginLoaded.has(bot)) return;
bot.loadPlugin(pathfinder);
pluginLoaded.add(bot);
}
let toolLoaded = new WeakSet();
function ensureTool(bot) {
if (toolLoaded.has(bot)) return;
bot.loadPlugin(toolPlugin);
toolLoaded.add(bot);
}
let collectBlockLoaded = new WeakSet();
function ensureCollectBlock(bot) {
ensurePathfinder(bot);
ensureTool(bot);
if (collectBlockLoaded.has(bot)) return;
bot.loadPlugin(collectBlockPlugin);
collectBlockLoaded.add(bot);
}
function setMovementsForGather(bot) {
const m = new Movements(bot);
m.canDig = true;
m.allow1by1towers = false;
bot.pathfinder.setMovements(m);
}
const PICKAXE_PRIORITY = ["netherite_pickaxe", "diamond_pickaxe", "iron_pickaxe", "stone_pickaxe", "wooden_pickaxe"];
async function equipBestPickaxe(bot) {
for (const name of PICKAXE_PRIORITY) {
const item = bot.inventory.items().find((i) => i.name === name);
if (item) {
try {
await bot.equip(item, "hand");
return name;
} catch {}
}
}
return null;
}
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));
}
const stoneBlacklist = new WeakMap();
const BLACKLIST_TTL_MS = 5 * 60_000;
function getBlacklist(bot) {
let m = stoneBlacklist.get(bot);
if (!m) {
m = new Map();
stoneBlacklist.set(bot, m);
}
const now = Date.now();
for (const [k, exp] of m) if (exp < now) m.delete(k);
return m;
}
export const skill = Object.freeze({
id: "gather.stone",
title: "Gather cobblestone",
timeoutMs: 90_000,
preconditions(ctx) {
if (!ctx?.bot) return { ok: false, code: "no_bot", detail: "bot missing" };
const available = pickaxes(ctx.bot);
if (available.size === 0) {
return { ok: false, code: "unsupported_version", detail: "no pickaxes in registry" };
}
const owned = ctx.bot.inventory.items().some((i) => available.has(i.name));
if (!owned) {
return { ok: false, code: "missing_tool", detail: "no pickaxe in inventory" };
}
return { ok: true };
},
async execute(ctx) {
const bot = ctx.bot;
const blacklist = getBlacklist(bot);
// Numeric-id search — callback matcher returns 0 under ViaBackwards. See runtime/perception.js.
const target = findNearestBlockByName(bot, STONE_NAMES, {
maxDistance: 32,
predicate: (b) => !blacklist.has(`${b.position.x},${b.position.y},${b.position.z}`),
});
if (!target) {
return { ok: false, code: "no_target", detail: "no reachable stone within 32 blocks", worldDelta: null };
}
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"})`);
const targetPos = target.position.clone();
try {
try {
await withTimeout(bot.lookAt(targetPos.offset(0.5, 0.5, 0.5), true), 2_000, "lookAt(stone)");
} catch {}
await withTimeout(bot.collectBlock.collect(target), 60_000, "collectStone");
const after = bot.blockAt(targetPos);
if (after && STONE_NAMES.includes(after.name)) {
warn("action", `gather.stone reported ok but block still at ${targetPos.x},${targetPos.y},${targetPos.z} — silent dig failure`);
const key = `${targetPos.x},${targetPos.y},${targetPos.z}`;
blacklist.set(key, Date.now() + BLACKLIST_TTL_MS);
return {
ok: false,
code: "silent_dig_failure",
detail: "block still exists after collect — protocol/anti-cheat issue",
worldDelta: null,
};
}
return {
ok: true,
code: "done",
detail: { blockType: target.name, at: targetPos },
worldDelta: { minedAt: targetPos, blockType: target.name },
};
} catch (e) {
warn("action", `gather.stone failed: ${e.message}`);
const key = `${target.position.x},${target.position.y},${target.position.z}`;
blacklist.set(key, Date.now() + BLACKLIST_TTL_MS);
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?.blockType;
},
recover(ctx, result) {
if (result.code === "no_target") return { hint: "wander", reason: "no stone within 32 blocks" };
return null;
},
});