Developer docs

Cookbook: boss mechanics

A plugin for one encounter: telegraphed attacks to pray against, hazard tiles to step off, phases with different gear, then loot and restock between kills. Read PrivBot plugin concepts first; this page assumes the combat layout from combat-slayer.md.

Node layout

Bosses need more ordering than the named bands give, so both reference plugins write values relative to a band. Declare them in one place with the reason.

Node Priority shouldExecute (read-only) execute calls
SurvivalStopNode EMERGENCY_OVERRIDE (300) HP or supplies under a hard floor stop the plugin with a reason
EscapeOneShotNode RECOVERY_MAX - 5 (245) A one-shot telegraph was seen mechanics.escape(ctx)
EatNode RECOVERY_MIN (240) HP below the boss threshold, food carried supplies.eat(ctx)
DodgeNode HAZARD_PRIMARY (200) The player's tile is in the current hazard set mechanics.dodge(ctx)
PrayerNode HAZARD_PRIMARY - 5 (195) The wanted protection is not showing on the overhead prayers.switchTo(ctx)
RestorePrayerNode HAZARD_PRIMARY - 10 (190) Prayer points low, a restore carried supplies.restore(ctx)
PositionNode / EnterNode MOVEMENT (150) Not at the fight position, or not in the arena yet position.step(ctx)
SpecialAttackNode COMBAT_SPECIAL (80) Energy readable and enough, the phase allows it fighting.special(ctx)
GearSwitchNode COMBAT_GEAR (70) The worn set does not match the phase (counted per slot) gear.switchStep(ctx)
LootNode COMBAT_LOOT (65) Boss dead and wanted loot in range loot.pickup(ctx)
AttackNode COMBAT_ATTACK (60) Boss attackable and not already engaged fighting.attack(ctx)
RestockNode LOBBY_HIGH (25) Between kills, supplies short restock.step(ctx)
ObserveNode 1 Running Sets a status that says why nothing else applies

Ordering notes from the references: a step that avoids a one-shot outranks eating; eating outranks routine dodging; the protection switch sits just below dodging so a dodge is never delayed by a prayer click. Pick your own order from what kills you, and write the reason next to the number.

Services to write

Service Owns
encounter A thread-safe tracker fed by event handlers (projectiles, graphics, NPC spawns, hitsplats)
view One immutable EncounterView per tick: boss identity and tile, hazard tiles, phase, player tile
prayers Which protection the next attack needs (pure policy), the switch, overhead confirmation
mechanics Safe-tile choice (pure policy) and the step to it with arrival proof
gear Phase gear sets, counted per slot
supplies, loot, restock As in combat-slayer.md and Cookbook: banking loop

Keep every decision rule (which prayer for which telegraph, which tile is safe, which phase) a pure static function over the view. Those are the parts you can unit test without a client.

Recipe: record events, decide on the worker

// Plugin: forward the payload, nothing else. Handlers run on the event thread.
@Subscribe
public void onProjectileMoved(ProjectileMoved e) {
    MyRunState s = runState;
    if (s != null && s.enabled) {
        encounter.projectile(e.getProjectile().getId());
    }
}

@Subscribe
public void onGraphicsObjectCreated(GraphicsObjectCreated e) {
    MyRunState s = runState;
    if (s != null && s.enabled) {
        encounter.graphic(e.getGraphicsObject().getId());
    }
}

// Tracker: O(1) writes from the event thread, reads from the worker.
public final class EncounterTracker {
    private final ConcurrentHashMap<Integer, Long> lastSeenMs = new ConcurrentHashMap<>();

    public void projectile(int id) { lastSeenMs.put(id, System.currentTimeMillis()); }
    public void graphic(int id)    { lastSeenMs.put(id, System.currentTimeMillis()); }

    public boolean seenWithin(int id, long ms) {
        Long t = lastSeenMs.get(id);
        return t != null && System.currentTimeMillis() - t <= ms;
    }

    public void reset() { lastSeenMs.clear(); }
}

A graphic's created event is posted once per graphic. For "is the hazard still there", read the live list (ctx.graphics.query()) in the view below; do not wait for a re-post. Which of these events a server delivers differs per server; the per-server table is What works on each server.

Recipe: one encounter view per tick

// TaskTree constructor: observation runs on the worker before each selection pass.
runner.setWorkerPrelude(() -> context.view = context.read(() -> EncounterView.capture(context)));

/** Immutable. Built inside ctx.read, so every read here is on the client thread. */
public static final class EncounterView {
    public final int bossIndex;                // -1 when the boss is not present
    public final WorldPoint bossTile;
    public final WorldPoint playerTile;
    public final Set<WorldPoint> hazards;

    static EncounterView capture(MyTaskContext ctx) {
        PrivNPC boss = ctx.npcs.query().withId(BOSS_IDS).alive().nearest();
        Set<WorldPoint> hazards = new HashSet<>();
        for (GraphicsObject g : ctx.graphics.query().withId(HAZARD_GRAPHIC_IDS).withinTiles(15).list()) {
            hazards.add(WorldPoint.fromLocal(ctx.getClient(), g.getLocation()));
        }
        return new EncounterView(
                boss == null ? -1 : boss.getIndex(),
                boss == null ? null : boss.getWorldLocation(),
                ctx.user.getLocation(),
                Collections.unmodifiableSet(hazards));
    }
    // constructor omitted
}

context.view is a volatile field on your TaskContext. null means the view could not be read: nodes gate on ctx.view != null, never on a default. BOSS_IDS and HAZARD_GRAPHIC_IDS come from that server's own data, with the evidence next to the constant; animation and graphic ids differ by server. Translation from OSRS ids is ctx.ids.graphic(osrsId), an OptionalInt that is empty when the id cannot be translated.

Recipe: pray against the telegraph, confirm by the overhead

/** Pure policy: unit test it. */
static String wanted(EncounterTracker seen) {
    if (seen.seenWithin(MAGIC_PROJECTILE_ID, 1_200)) return "Protect from Magic";
    if (seen.seenWithin(RANGED_PROJECTILE_ID, 1_200)) return "Protect from Missiles";
    return null;
}

/** Selection. */
public boolean needsSwitch(MyTaskContext ctx) {
    String prayer = wanted(ctx.encounter);
    if (prayer == null) return false;
    Boolean showing = ctx.user.overheadProtection().shows(prayer);
    return showing != null && !showing;              // unreadable: do not toggle blind
}

/** Worker. */
public boolean switchTo(MyTaskContext ctx) {
    long epoch = ctx.runState.sessionEpoch;
    String prayer = wanted(ctx.encounter);
    if (prayer == null) return false;
    ctx.prayer.activate(prayer);                     // true = accepted: confirm by the overhead
    boolean on = ctx.sleepUntil(() -> ctx.shouldAbort(epoch)
            || Boolean.TRUE.equals(ctx.user.overheadProtection().shows(prayer)), 1_200);
    status = on ? prayer + " on" : prayer + " did not show";
    return true;
}

If the server mounts a different prayer book, check ctx.prayer.mountedBook() and pick the matching prayer name ("Deflect Magic" on the curses book, "Protect from Magic" otherwise). Prayer.Book.UNKNOWN means "cannot tell", so hold the switch.

Recipe: step off a hazard with arrival proof

public boolean dodge(MyTaskContext ctx) {
    long epoch = ctx.runState.sessionEpoch;
    EncounterView view = ctx.view;
    if (view == null || view.playerTile == null) return false;
    WorldPoint safe = ctx.read(() -> safeTile(ctx.travel.reachability(), view));
    if (safe == null) {
        status = "No safe tile in reach";
        return false;
    }
    ExactStepHandle step = ctx.travel.exactStep(safe, () -> !ctx.shouldAbort(epoch), 1_800);
    if (!step.accepted()) {
        return fail("Step to " + safe + " was not accepted");
    }
    ActionStatus s = step.poll();
    while (!s.terminal()) {
        if (ctx.shouldAbort(epoch)) {
            step.cancel();
            return true;
        }
        ctx.sleep(50);
        s = step.poll();
    }
    return s == ActionStatus.CONFIRMED || fail("Did not reach " + safe + ": " + s);
}

/** Pure policy: the reachable tile nearest the player that is in no hazard. */
static WorldPoint safeTile(SceneReachability scene, EncounterView view) {
    WorldPoint best = null;
    for (int dx = -3; dx <= 3; dx++) {
        for (int dy = -3; dy <= 3; dy++) {
            WorldPoint t = view.playerTile.dx(dx).dy(dy);
            if (view.hazards.contains(t) || !scene.contains(t)) continue;
            if (best == null || t.distanceTo(view.playerTile) < best.distanceTo(view.playerTile)) best = t;
        }
    }
    return best;
}

ctx.travel.exactStep(...) returns a privbot.movement.pathing.ExactStepHandle: one walk to that exact tile, then poll() on the worker until a terminal privbot.actions.confirm.ActionStatus (CONFIRMED, TIMED_OUT, CANCELLED, REJECTED). Never use ctx.travel.walkTo(...) to dodge: it plans a route, may use teleports, and blocks up to two minutes.

Reading the fight

ctx.threats.snapshot(query) reads the NPCs, projectiles, graphics, hitpoints and the prayers you name in one client-thread batch and returns an Observed<ThreatSnapshot>: plain immutable data. Feed it to the pure planners in privbot.mechanics instead of reading the client again. Call it from the runner worker or a node; it marshals its own read.

// Fields on a service: pure, unit-testable, worker thread only.
private final AttackCues cues = AttackCues.builder()
        .animation(BOSS_MAGIC_ANIM, CombatStyle.MAGIC)
        .animation(BOSS_RANGED_ANIM, CombatStyle.RANGED)
        .projectile(MAGIC_BALL_ID, CombatStyle.MAGIC)
        .build();
private final PrayerPlanner planner = new PrayerPlanner(cues, PrayerPlanner.Options.defaults());
private final ShotTracker shotTracker = new ShotTracker();
private final CueTimeline timeline = new CueTimeline();

private static final ThreatQuery QUERY = ThreatQuery.all()
        .within(20)
        .npcs(TargetSpec.named("My Boss"))
        .prayers(CombatStyle.MAGIC.protectPrayer(), CombatStyle.RANGED.protectPrayer());

/** Worker, once per game tick. Returns the style to pray against, or null when unknown (never "nothing to do"). */
CombatStyle read(MyTaskContext ctx) {
    Observed<ThreatSnapshot> seen = ctx.threats.snapshot(QUERY);
    if (!seen.isReadable()) return null;              // unreadable is not "nothing is happening": do not toggle blind
    ThreatSnapshot snap = seen.get();

    // 1) Which animation each boss NPC is playing, by index, decides the style from the telegraph.
    Map<Integer, Integer> animations = new HashMap<>();
    for (NpcView npc : snap.npcs()) {
        if (!npc.dead()) animations.put(npc.index(), npc.animation());
    }
    CombatStyle fromAnimation = planner.plan(animations, snap.tick());

    // 2) Projectiles that are new this tick are launches; the latest launch wins, not the latest to land.
    for (ShotView shot : shotTracker.fresh(snap.shots())) {
        CombatStyle style = cues.projectile(shot.id());
        if (style != null) timeline.offer(style, shot.startCycle());
    }

    return timeline.current() != null ? timeline.current() : fromAnimation;
}

// The caller compares the wanted style with what is showing and switches only when they differ, confirming the
// switch by the overhead exactly as in the previous recipe (ctx.user.overheadProtection().shows(prayer)).

What the snapshot guarantees: a present value means every required read worked, so an empty shots() is "none in flight", never "could not read". The result is unreadable (reason names what failed, for example "projectiles") when the client is logged out, the local player or its tile is missing, the projectile list cannot be read, or a client read throws. Smaller gaps do not discard the snapshot: hp(), maxHp() and prayerPoints() are null, not 0, when only that read failed, and a prayer you asked about that cannot be read is in unreadablePrayers() (a prayer is in activePrayers(), in unreadablePrayers(), or in neither, which means it read as off). activePrayers() is a quick check; to confirm a protection prayer after switching, use the overhead as in the previous recipe. NPCs, shots and graphics on another plane than the player are left out. Keep the previous snapshot rather than substituting an empty one when a read comes back unreadable.

Per NPC and per shot, "unknown" is kept apart from "no":

  • NpcView.tile() is the south-west corner of the footprint on every server. On Elorin, Impact and other supported clients the drawn position of a big NPC is its centre and slides while it walks, so the snapshot reads the server tile instead. size() is 0 when the size cannot be read (never a guessed 1).
  • NpcView.overhead() is a HeadIcon name such as "MAGIC", "NONE" (NpcView.NO_OVERHEAD) when the read worked and no icon shows, or null when it could not be read. Only "NONE" means "not praying".
  • ShotView.targetsUs() is TRUE or FALSE when the projectile's target was read, and null when it could not be, including a shot aimed at a tile rather than an actor. null is unknown, not "not us": do not drop the shot from your prayer decision because of it.

Looting

ctx.loot.collect(spec) returns a Job you step once per tick. Describe what you want with a LootSpec, keep the job in the plugin's state, and branch on its state and reason.

LootSpec spec = LootSpec.builder().names("Bones", "Big bones").range(8).maxPicks(5).build();

// in the plugin's state, created once per visit:
Job pickup = ctx.loot.collect(spec);

// in a node's execute, once per tick:
JobState state = pickup.step(ctx);
if (state == JobState.DONE && pickup.reason().equals("inventory full")) { /* bank or drop */ }
if (state == JobState.FAILED) { /* pickup.reason(): "inventory unreadable" (5 steps in a row) or "gave up on N drop(s) that did not arrive" */ }
if (state == JobState.UNSUPPORTED) { /* "ground items unreadable": this client cannot scan the ground; do not retry */ }

Each step takes the nearest wanted drop, then waits up to 2.4 s for that item's carried count to rise. That is the proof: a stackable you already carry counts only when its quantity rises, not when a slot fills. A drop whose count did not rise three times (same id and tile) is given up on for the rest of the job; when the only wanted drops left in range are ones it gave up on, the job ends FAILED with "gave up on N drop(s) that did not arrive" (they are still on the ground, so this is not "nothing left"). DONE reasons are "nothing left" (no wanted drop in range at all), "inventory full" (nothing is clicked once it is full, except a stackable you already carry) and "max picks reached". An unreadable inventory keeps the job RUNNING with reason "inventory unreadable"; it is never treated as "nothing left". A ground that cannot be scanned at all (the client has no ground-item API) ends the job UNSUPPORTED with reason "ground items unreadable": that is permanent for the client, so do not start the job again. The proof is for the stack the Take was actually sent for.

Staying alive

ctx.sustain.maintain(ctx, plan) is the whole eat/brew/restore/boost upkeep in one call. Describe it once with a SustainPlan, keep the plan in the plugin's state (its BoostDosePolicy objects remember a dose in flight), and call it from one node on the worker.

private final SustainPlan plan = SustainPlan.builder()
        .eatBelowPct(55).foods("Shark", "Manta ray").comboFoods("Karambwan")
        .brewBelowPct(80).brews("Saradomin brew(4)", "Saradomin brew(3)")
        .restoreBelowPoints(20).restores("Super restore(4)", "Super restore(3)")
        .boost(Skill.STRENGTH, BoostDosePolicy.overload(), "Overload (4)", "Overload (3)")
        .build();

// in a node's execute:
SustainOutcome out = ctx.sustain.maintain(ctx, plan);
switch (out.kind()) {
    case OUT_OF:
        if (out.reason().equals("food")) { /* leave the fight: HP is low and nothing carried can heal it */ }
        else { /* "boost": a dose is due and none is carried; a missing dose is not being out of food */ }
        break;
    case UNREADABLE: /* hold: do not act on, or against, a value you could not read */ break;
    case FAILED:     /* out.reason() says why (refused, count did not drop, boost never appeared) */ break;
    default:         /* ACTED or NOTHING */
}

One call makes at most one consume: food, else a brew when HP is low and there is no food, else a brew at the brew threshold, else a prayer restore, else the first due boost. The exception is the combo eat: when the plan lists combo foods and one is carried, its click is sent straight after the first food's click, before any waiting, so both land in the same tick (the decision uses the HP read before the first Eat). One bounded wait proves both. A carried combo food is eaten with every Eat, whatever the HP; leave comboFoods empty to opt out. The outcome is about the first food; out.comboLanded() says whether the combo food was consumed too, and reason() names it either way.

Blocking cost. A call that clicks waits for its proof on your thread: up to 1200 ms. The plugin's other nodes do not run meanwhile. Call it from the node with the lowest latency need, and never between two prayer switches that must land on consecutive ticks; a call that clicks nothing returns at once.

What ACTED proves: the clicked item's carried count dropped within 1200 ms. If the click was refused or the count did not drop you get FAILED with that item, and for a boost the policy throttles the next try and counts the failure. If the click went out but the inventory cannot be read afterwards you get UNREADABLE with the clicked item: the consume is unknown, so it is not counted as a failure. A dose that was confirmed drunk but whose boost never showed makes the policy fail closed: later calls return FAILED ("boost never appeared") and drink nothing until you call reset() on that BoostDosePolicy.

Unreadable hitpoints, max hitpoints or inventory give UNREADABLE and no click, and so does an exception from a read or the click. Unreadable prayer points only skip the prayer rule. An unreadable boost is never treated as expired and is never fed to its policy; when nothing else is due the call returns UNREADABLE naming the skill, not NOTHING. After the failure limit the policy still retries once its settle window passes, so count FAILED results and stop the plan yourself if a dose keeps failing.

Dodging

ctx.hazards owns no hazard data. You keep a HazardMap (ctx.hazards.newMap()), add the tiles that hurt as you see them, and ask for the nearest tile that is out of every hazard.

private HazardMap hazards;    // plugin state, worker thread only; set once: hazards = ctx.hazards.newMap();

// each tick, from the snapshot you already took:
for (GraphicView g : snap.graphics()) {
    if (g.id() == FIRE_POOL) hazards.add(g.tile(), snap.tick());            // lasts HazardMap.DEFAULT_TTL_TICKS
}
// Always snap.tick(): safeTile checks the map against client.getTickCount(), the same clock. Your own counter or
// System.currentTimeMillis() would expire hazards at the wrong moment, or never.
hazards.prune(snap.tick());

// when the player's tile is dangerous:
Observed<WorldPoint> safe = ctx.hazards.safeTile(hazards, 6, snap.npcs(), Footprint.SAFE_GAP);
if (safe.isPresent()) { /* walk to safe.get() and prove you arrived */ }
else if (safe.isAbsent()) { /* nothing within 6 tiles qualifies: use a different escape */ }
else { /* unreadable: collision data or the player's tile could not be read; do not guess a tile */ }

A present tile is reachable from the player's own tile by walking collision on the same plane (one reachable grid answers both "can stand" and "can walk"), is not dangerous on the current game tick, is at least minGap tiles from every NPC footprint you pass in avoid, and is never the tile you are standing on. It is a tile, not a step: the walk and the arrival check are yours. Fill the HazardMap with ThreatSnapshot.tick() values only: that is the clock safeTile compares against. Where supported, the search starts from your server tile (the drawn tile trails it while you walk), falling back to the drawn tile when the server tile cannot be read. An NPC in avoid on another plane is ignored, and one whose size is unknown (size() 0) is kept away from as if it were 5x5. Unreadable means the client is not logged in, the player's tile cannot be read, or the scene's collision is not usable on the player's plane; with no collision every tile would look free, so nothing is guessed. Absent means the read worked and nothing in range qualifies.

Picking a target

ctx.targets.newLock() gives you a TargetLock, which picks an NPC from the views in a threat snapshot and sticks to it, so the bot does not flip between two NPCs every tick. ctx.targets.resolve(view) turns the chosen view back into a live NPC to attack.

private TargetLock lock;                                                    // plugin state, one per fight; lock = ctx.targets.newLock();
private static final TargetSpec SPEC = TargetSpec.named("Rock crab").ignore("Rocks");

private int lastAttackIndex = -1;                                           // plugin state
private int lastAttackTick = Integer.MIN_VALUE;

// once per tick, after the snapshot:
NpcView pick = lock.choose(snap.npcs(), snap.currentTargetIndex(), snap.player(), SPEC);
boolean alreadyOnIt = pick != null && pick.index() == snap.currentTargetIndex();
boolean throttled = pick != null && pick.index() == lastAttackIndex && snap.tick() - lastAttackTick < 3;
if (pick != null && !alreadyOnIt && !throttled) {
    PrivNPC live = ctx.targets.resolve(pick);
    if (live != null && live.interact("Attack")) {
        lastAttackIndex = pick.index();
        lastAttackTick = snap.tick();
    }
}

Click Attack only when the pick is not already your target, and at most once per 3 ticks for the same NPC: a player does not re-click a monster they are already fighting, and the same Attack sent every tick is a pattern a detection system can count. TargetSpec.any() matches every NPC, TargetSpec.ids(...) matches by NPC id, and a null spec passed to choose means any(). A plain name in TargetSpec.named(...) matches by containment both ways ("spectre" matches "Aberrant spectre", and "aberrant spectre" also matches "Spectre"); prefix it with = or call contains(false) for an exact match.

choose returns the current target if it still matches, else the locked one, else the first match already attacking you, else the nearest free match (ties go to the lower index). The lock is the pair (index, id): the server reuses indices, so an index that now holds another id is a different NPC and the lock is dropped. resolve asks for a fresh NPC list and returns the NPC at the view's index only when it also has the view's id. null means "do not act on this view": the index is empty, holds another NPC, or the list could not be read. It does not prove the NPC died; take a new snapshot before deciding that.

Dying and getting back

Watch for death by polling, never by subscribing. ctx.recovery.watch() returns a DeathWatch, a small state machine you feed once per tick:

private DeathWatch death;                                 // plugin state, worker thread only

// on Start (ctx is injected after construction, so never in a field initializer):
death = ctx.recovery.watch();                             // or new DeathWatch(Set.of(836, 19836)) on Elorin

// once per tick, from the snapshot you already took (null when a value could not be read):
switch (death.observe(snap.hp(), animation, playerTile, snap.tick())) {
    case DEAD:      /* start the recovery job (once) */ break;
    case RESPAWNED: /* the first tick that proves you are back */ break;
    case UNKNOWN:   /* hitpoints unreadable: neither dead nor alive; do nothing */ break;
    default:        /* ALIVE */
}

DEAD means hitpoints are 0 or a death animation is showing, and it stays DEAD until the respawn is proved by a few live ticks or a moved tile. death.diedAt() is the tile you died on. Hitpoints 0 always catch a death, on every server. The animation is only a faster cue: ctx.recovery.watch() uses 836, the OSRS death animation, and Elorin's player animations are the OSRS id + 19000, so its death animation is 19836. Pass new DeathWatch(Set.of(836, 19836)) to also catch the animation on Elorin.

ctx.recovery.afterDeath(plan) is the job that does the rest:

RecoveryPlan plan = RecoveryPlan.builder()
        .restock(RestockTarget.builder().worn(wornSetup).carried(carriedSetup).build())
        .back(Destination.at("Zulrah", new WorldPoint(2268, 3070, 0), 4).viaTeleport("Zul-Andra"))
        .build();

private Job recovery;                                     // plugin state

// in the recovery node's execute, once per tick, while dead or recovering:
if (recovery == null) recovery = ctx.recovery.afterDeath(plan);
JobState s = recovery.step(ctx);
if (s == JobState.DONE) { recovery = null; }
else if (s != JobState.RUNNING) { status = recovery.reason(); recovery = null; /* stop the plugin or hand over */ }

Stages, in order, each one bounded by its own step budget:

  1. Respawn. Waits (150 steps) until hitpoints are above 0 and the tile is readable. Unreadable hitpoints or tile never count as respawned.
  2. Reclaim. Impact has an "Unclaimed items at Death" reclaim and the job runs it (200 steps). On every other server the stage is skipped, and the final reason says so ("no item reclaim on this server"): a skip is not a failure, and the items there are yours to fetch.
  3. Restock. The plan's ctx.restock.to job, if you planned one (500 steps). Restock does not travel: it needs a bank within reach of the respawn point, or it fails "restock: bank did not open". If you respawn away from a bank, either restock at home (where the respawn puts you next to one) or plan the restock yourself: use a plan whose back travels to a bank, then run ctx.restock.to there before heading out.
  4. Back. The plan's ctx.travel.go job, if you planned one (300 steps).

A reclaim that gave up ends the job FAILED "reclaim: item reclaim failed". DONE reads "respawned; ran: ...; skipped: ..." and means each planned stage's own job ended DONE, so it carries that job's proof. A failing stage ends the job FAILED with its reason prefixed by the stage ("restock: bank has none: Shark"); a stage past its budget is cancelled and ends it with <stage>: took too long.

Held. When PrivBot holds all bot actions (the forced-move guard found the player moved by something that was not the bot, for example a staff pull), ctx.recovery.held() is TRUE and ctx.recovery.holdReason() says why. The job then stays RUNNING with the reason "held: ..." and no stage budget runs out, so a hold is waited out instead of being turned into a failure. Both are Observed: unreadable is not "not held". If the hold cannot be read five steps in a row the job ends FAILED "held: unreadable". Hold your own nodes the same way.

A second death. If you die again during the reclaim, restock or back stage, that stage is stopped and the job waits for the respawn again (the reclaim is re-armed). A further death ends it FAILED "died again during recovery". Call recovery.cancel() to stop it yourself: the job ends FAILED "cancelled" and stops the stage that was running.

Getting there

ctx.travel.go(destination) is a job that walks to a place and proves it arrived. A Destination is a name, a centre tile and an arrival radius, with an optional teleport to try first:

Destination zulrah = Destination.at("Zulrah", new WorldPoint(2268, 3070, 0), 4)   // radius 4 tiles
        .viaTeleport("Zul-Andra");                                                 // optional, tried once

private Job journey;                                    // plugin state

if (journey == null) journey = ctx.travel.go(zulrah);
JobState s = journey.step(ctx);                         // at most one action, waits at most 2.4 s
if (s == JobState.DONE) { journey = null; }            // "arrived": the tile is inside the radius
else if (s != JobState.RUNNING) { status = journey.reason(); journey = null; }
  • Arrival is only inside the radius. DONE needs the player's tile (the server tile where available) inside destination.contains(...): same plane, Chebyshev distance at most the radius. Being close, or having sent the walk, is not arrival.
  • A teleport landing is not arrival. The teleport is tried once, only when you start more than 30 tiles away, and wherever it lands the job keeps walking from there.
  • Stuck. The job fails with no progress toward <name> when the distance did not shrink for 20 steps; a route that failed or was cancelled is restarted once, then fails with route failed: <why>. UNSUPPORTED "navigation unavailable" means this client has no path planner: do not retry.
  • Unreadable. An unreadable tile is never arrival and never lack of progress: the job stays RUNNING ("position unreadable") and fails after 5 in a row.
  • Cancel. journey.cancel() stops the walk that is in flight (call it on Stop, death and disconnect); a finished job cancels its own route.

Stuck and frozen

Two pure helpers in privbot.mechanics notice a bot that has stopped working. Neither reads the client: you feed them values each tick and decide what to do. Both are single-thread: call them from the thread that runs your tick.

private final ProgressWatchdog stuck = new ProgressWatchdog(30_000);  // 30 s of counted idle time
private final WorldFreeze frozen = new WorldFreeze(16);               // 16 ticks, about 10 seconds

// when something useful happens (a kill, a pickup, a step that landed):
stuck.progress(System.currentTimeMillis());

// each tick:
long now = System.currentTimeMillis();
stuck.held(Observed.isTrue(ctx.recovery.held()), now);   // a deliberate wait or a hold is not "stuck"
if (stuck.stalled(now)) { /* nothing useful for 30 s: reset the plugin's state or walk somewhere known */ }

// world freeze: a fight always moves something. Hash what moves (our tile and HP, each NPC's index, tile,
// animation and health) with WorldFreeze.mix(hash, value) and feed it with the tick number:
long fp = 0;
fp = WorldFreeze.mix(fp, playerTile.getX());
// ... mix every value that moves ...
if (frozen.observe(snap.tick(), fp)) { /* the room has not changed for 16 ticks: a missed death or disconnect */ }
// Unreadable room: do NOT call observe (a fingerprint of nothing looks frozen). Call frozen.reset() instead.

stalled is true only when at least the limit of counted time passed with no progress call, and time spent held is not counted. Before the first call a watchdog reports not stalled. observe ignores a repeated tick number (it neither counts nor resets) and starts over when the tick number goes backwards. Both prove silence, not cause.

Recording what you saw

ctx.capture writes rows to disk so a run can be reviewed afterwards. It costs nothing until you start it: before start, record and event are no-ops, so calling them every tick on a stopped plugin does no work.

ctx.capture.start("my-boss", MyPlugin.class);            // call from Start, not from startUp
ctx.capture.record("ticks", Map.of("hp", hp, "boss", bossAnim));   // one row in the "ticks" stream
ctx.capture.event("phase-two", Map.of("tick", tick));              // one named event
ctx.capture.stop();                                       // on Stop

Rows are queued to a background writer: a true from start means a run folder is reserved, not that a row reached the disk. Values must be JSON-friendly (numbers, strings, booleans, lists, maps). If the tick cannot be read the row is recorded with tick -1 rather than lost.

Pitfalls for boss plugins

  • Pray from the telegraph, not the hit. By the time a hitsplat arrives the attack was decided. Record the earliest signal the server gives (projectile, graphic, animation) and switch on it.
  • Confirm a protection by the overhead. ctx.prayer.isActive(name) reads false when it cannot read, and on some servers a prayer's state flips for a tick and reverts. The drawn overhead (ctx.user.overheadProtection().shows(slot)) is what the boss sees.
  • A waiting execute blocks every node. Keep waits short (one tick or two) and exit on the conditions that matter more (a new telegraph, low HP).
  • Ids are per server. The same boss can use different animation, graphic and NPC ids on two servers. Keep each id with its evidence; do not borrow RuneLite constants (rule 13).
  • Hazards that cover the whole floor are not tile hazards. Check what a graphic means before you add it to the dodge set, or the plugin will try to step off everything.
  • Death is polled (rule 2), and a death bumps the epoch so a dodge or switch in flight abandons its result.
  • Overlays draw the view, not the client. Publish the hazard tiles and countdowns into a Snapshot on the tick (Cookbook: overlays and UI).
  • Restock and death recovery. Use ctx.restock.to and ctx.recovery.afterDeath (see Dying and getting back); the reclaim stage exists on Impact only and is skipped, with a reason, elsewhere.

The starter project's example node and its test show the node and service layout; the hazard and prayer rules above are the part you write per boss.

Unit-test this with the testkit, see Testing plugins.