Developer docs

Threading and pitfalls

The rules below are the ones that have broken real PrivBot plugins. Each has the rule, why it exists, and a short do / don't. They apply on every server. Background: PrivBot plugin concepts (layers, threads, ctx.*). The Lint column gives the lint rule id that an upload build reports as LINT.<id> (see Uploading your plugin).

# Rule Lint
1 true means dispatched, not done W002
2 Poll for death; never subscribe to it E011
3 Unreadable is not "no"
4 Read on the client thread, wait on the worker E002, E005, E010
5 A stopped plugin costs nothing
6 Disconnects, hops and region loads
7 Event handlers only record and signal W006
8 Refresh wrappers; never keep them across ticks W007
9 Bounded retries with a reason E003
10 A changed config default needs a migration
11 Widget text is not proof a dialogue is on screen
12 A gear set is a multiset
13 Server ids are not RuneLite enum ordinals E006
14 Overlays render a snapshot E008

1. true means dispatched, not done

Rule. A ctx.* verb that returns true only says the client accepted the action. Confirm the game state change with a bounded wait on a fresh read before you count it, chain the next step, or reset a retry counter.

Why. The server can ignore an action, the target can die or move, an interface can close. On some servers an interface state read can also stay "open" after the interface closed: ctx.bank.isOpen() and ctx.trade.isOpen() have both read true for screens that were gone. A plugin that trusts the return value counts eats that never happened, presses accept on a trade that was never requested, and skips opening a bank that is closed. The only reliable proof is a read that moved.

Action Proof
Eat, drink Count of that item id dropped (or HP rose)
Wield, wear The worn snapshot holds the item
Withdraw, pick up Inventory count of that id rose
Deposit, drop Inventory count of that id fell
Attack ctx.combat.isInCombat() turned true, or the NPC's getInteracting() is you
Prayer ctx.user.overheadProtection().shows(slot) for protection prayers, else ctx.prayer.isActive(name)
Dialogue / widget click A fresh surface: different text or options, or ctx.widgets.interactConfirmed(...)
// Do: dispatch once, then wait for the count to move.
long epoch = ctx.runState.sessionEpoch;
ItemContainerSnapshot before = ctx.inventory.snapshot();
ItemContainerSnapshot.Item food = before.available ? before.firstWithAction("Eat") : null;
if (food == null || !ctx.inventory.interact(food, "Eat")) {
    return false;
}
int held = before.count(food.id);
boolean eaten = ctx.sleepUntil(() -> {
    ItemContainerSnapshot now = ctx.inventory.snapshot();
    return ctx.shouldAbort(epoch) || (now.available && now.count(food.id) < held);
}, 2_400);
// Don't
ctx.inventory.eat("Shark");
ctx.runState.foodEaten++;                    // counted a dispatch, not an eat
if (!ctx.bank.isOpen()) { ctx.bank.open(); } // isOpen() can read true for a closed bank

2. Poll for death; never subscribe to it

Rule. Detect the local player's death by polling hitpoints on the worker. Never use @Subscribe onAnimationChanged (or any event) for your own death.

Why. On at least one server the client never delivers its own death through the event bus: a plugin waiting for that event saw nothing for a whole session while the player sat dead or respawned. Reading hitpoints by polling works everywhere. Count a death once (RunState onDeath() only counts while recovery is not already active) and bump the epoch so work in flight stops.

// Do: a recovery node gates on a polled read.
public final class DeathRecoveryNode extends SimpleNode<MyTaskContext> {
    public DeathRecoveryNode() { super("Death Recovery", TaskPriorityBands.RECOVERY_MIN); }

    @Override public boolean shouldExecute(MyTaskContext ctx) {
        return ctx.runState.deathRecoveryActive
                || (ctx.user.getMaxHitpoints() > 0 && ctx.user.getHitpoints() <= 0);
    }

    @Override public boolean execute(MyTaskContext ctx) {
        ctx.runState.onDeath();          // counts once, bumps sessionEpoch
        ctx.resetEncounter();
        status("Waiting for respawn");
        if (ctx.sleepUntil(() -> ctx.user.getHitpoints() > 0, 10_000)) {
            ctx.runState.onRespawn();
        }
        return true;
    }
}

For a stricter gate, ctx.skills.observedLevel(Skill.HITPOINTS, true) returns null when the level cannot be read, so a failed read never looks like 0 HP.

// Don't
@Subscribe
public void onAnimationChanged(AnimationChanged e) {
    if (e.getActor() == client.getLocalPlayer() && e.getActor().getAnimation() == 836) {
        runState.onDeath();              // never fires on some servers
    }
}

3. Unreadable is not "no"

Rule. A read the client could not answer must not become a negative answer. Use the reads that can say "cannot tell", and do nothing (or wait) when they do.

Why. Many reads return a primitive default when they cannot read: 0, -1, false, an empty list. ctx.inventory.isEmpty() reads true and isFull() reads false when the inventory could not be read; ctx.prayer.isActive(name) reads false; ctx.user.getHitpoints(), ctx.combat.getSpecialAttackPercent() and ctx.bank.count(name) read 0. Acting on those has withdrawn into a full inventory, toggled a prayer that was already on (turning it off), and reported "no opponent prayer" for an opponent who was praying. Every silent wrong-read incident in PrivBot's history came through this path.

Question Ambiguous read Read that can say "cannot tell"
What do I carry / wear? isEmpty(), isFull(), count(...) ctx.inventory.snapshot() / ctx.equipment.snapshot(): check .available
Which overhead is drawn on me? ctx.prayer.isActive(name) ctx.user.overheadProtection(): isReadable(), shows(String prayerName) returns Boolean
Which prayer book is mounted? ctx.prayer.mountedBook(): Prayer.Book.UNKNOWN
A skill level ctx.skills.boosted("Attack") (0) ctx.skills.observedLevel(Skill.ATTACK, true) (Integer)
Special attack getSpecialAttackPercent() (0) ctx.combat.specialAttackPercentOrNull(), specialAttackArmedOrNull()
Run / instance isRunEnabled(), isInInstance() ctx.game.observedRunEnabled(), observedRunEnergy(), observedInInstance()
Auto retaliate ctx.combat.getAutoRetaliate() (Boolean)
Which interfaces are drawn? ctx.widgets.drawnRoots(): null = this server cannot say
Any batched read ctx.read(...) returns null when it could not be served
// Do
ItemContainerSnapshot carried = ctx.inventory.snapshot();
if (!carried.available) {
    return false;                         // cannot tell: act on a later tick
}
boolean empty = carried.size() == 0;      // an observed empty inventory

Boolean showing = ctx.user.overheadProtection().shows("Protect from Melee");
if (showing == null) {
    return false;                         // cannot tell: never toggle blind
}
if (!showing) {
    ctx.prayer.activate("Protect from Melee");
}
// Don't
if (ctx.inventory.isEmpty()) { ctx.bank.withdrawAll("Shark"); }     // "empty" may mean unreadable
boolean equipped = ctx.read(() -> ctx.equipment.contains("Whip"));   // NPE when read() returns null

Prefer the tri-state reads: privbot.api.Observed<T> (present / observed absent / unreadable), as returned by ctx.player, ctx.vars (observedVarp, observedVarbit, byName) and ctx.skills. The observed* reads on ctx.game return null when the client cannot answer.

4. Read on the client thread, wait on the worker

Rule. Game reads happen on the client thread; waits and dispatch happen on the runner's worker. Never block the client thread, the event handler thread or a UI thread. Never wait inside ctx.read(...).

Why. Game state belongs to the client thread. Facades marshal there through privbot.context.GameThread.ensure(...) (inline when already there, otherwise queued with a bound; a dropped read returns null). If you block the thread that serves those queues, every later read times out and returns null, or the client deadlocks. A wait inside ctx.read holds the client thread for the whole wait. Raw reads on ctx.getClient() are not marshalled at all. ctx.sleep(...) returns false without sleeping on the client thread, so a sleep in shouldExecute silently does nothing.

Where May May not
shouldExecute, shouldExecuteParent, service predicates Facade reads Dispatch, sleep, ctx.human, RunState writes, disk (E010)
execute, services Verbs, ctx.sleepUntil, ctx.read batches Thread.sleep (E002), a second worker
@Subscribe, panel suppliers, studio callbacks Record, forward, read published state Waits, game reads, disk
Overlay render snapshot.get() Anything else
// Do (worker)
boolean ready = Boolean.TRUE.equals(ctx.read(() ->
        ctx.inventory.snapshot().has("Shark") && ctx.user.getHitpoints() > 0));
if (ready && ctx.inventory.eat("Shark")) {
    ctx.sleepUntil(() -> ctx.user.isAnimating(), 1_200);      // the wait is outside read
}
GameState state = ctx.read(() -> ctx.getClient().getGameState());   // raw read, marshalled
// Don't
ctx.read(() -> ctx.npcs.attack("Goblin") && ctx.sleepUntil(() -> ctx.combat.isInCombat(), 3_000));
GameThread.ensure(() -> ctx.inventory.count("Shark"));   // facades already marshal; adds latency
Thread.sleep(600);                                       // E002: use ctx.sleepUntil or ctx.sleepTick
ctx.getClient().getLocalPlayer().getWorldLocation();     // E005: raw read off the client thread

UI callbacks (a studio button, a panel action) hand work to a worker and return. Results come back with SwingUtilities.invokeLater or Platform.runLater, skipped if the window closed. Disk and JSON writes go to your own daemon executor, never the client thread, the EDT or the JavaFX thread.

5. A stopped plugin costs nothing

Rule. While stopped, a plugin does no sampling, probing, capture or HUD building. Return from onGameTick (and every other handler that would read the client) before the first client read.

Why. Every installed plugin is loaded and subscribed in every client, started or not. One plugin that kept sampling gear, inventory and widgets every few ticks while stopped stalled the client thread every few seconds for everyone who had it installed. Users install many plugins and run one.

// Do
@Subscribe
public void onGameTick(GameTick event) {
    MyRunState state = runState;
    MyTaskTree tree = taskTree;
    if (state == null || tree == null || !state.enabled) {
        return;                                  // nothing read while stopped
    }
    tree.onGameTick();
    overlays.publish(tree.getContext());         // HUD built only while running
}
// Don't
@Subscribe
public void onGameTick(GameTick event) {
    hud.publish(new HudState(ctx.user.getHitpoints(), ctx.inventory.snapshot()));  // runs while stopped
    if (runState.enabled) taskTree.onGameTick();
}

6. Disconnects, hops and region loads

Rule. Deduplicate disconnect events, bump sessionEpoch once per real disconnect, resume only after a real disconnect, and let the runner own the grace window.

Why. LOGIN_SCREEN, HOPPING, CONNECTION_LOST and LOGGING_IN arrive back to back. Region and cave loads also post LOGGED_IN without any disconnect. A tick can publish with no local player during a region load. Without dedupe a plugin resets twice, resumes on a region load, or tears down a route because the player read null for one tick.

// Do: RunState
public synchronized boolean onDisconnect() {
    if (reconnectPending) return false;          // duplicate of this burst
    reconnectPending = true;
    sessionEpoch++;
    if (enabled) status = "Reconnecting";
    return true;
}
public synchronized boolean onReconnect() {
    if (!reconnectPending) return false;         // a region load, not a reconnect
    reconnectPending = false;
    return true;
}

// Do: event dispatcher
GameState s = event.getGameState();
if (s == GameState.LOGIN_SCREEN || s == GameState.HOPPING
        || s == GameState.CONNECTION_LOST || s == GameState.LOGGING_IN) {
    if (runState.onDisconnect()) taskTree.onDisconnect();    // runner.onDisconnect() + resetEncounter()
} else if (s == GameState.LOGGED_IN && runState.onReconnect()) {
    taskTree.onReconnect();                                   // runner.onReconnect(): 5 idle ticks
}

// Do: TaskTree.onGameTick skips transient ticks
if (runState.enabled && ctx.game.isLoggedIn() && ctx.user.getLocation() != null) runner.onGameTick();
// Don't
if (event.getGameState() == GameState.LOGGED_IN) taskTree.onReconnect();   // fires on every region load
Field lifetime Examples Cleared on
Transient Current target, pending pickup, route step, dialogue surface, navigation session Disconnect, death, Stop
Session Kills, loot value, deaths Start
Account Loadouts, bindings Account change
Configuration @ConfigItem values Never

Use runner.onReconnect(graceTicks) when the server needs longer to settle. Add a reconnect grace node (at TaskPriorityBands.RECOVERY_MAX) only when session setup must run before anything else.

7. Event handlers only record and signal

Rule. @Subscribe handlers record the event payload, bump RunState and forward. Nothing slow. Never wait, dispatch, scan or write to disk in a handler.

Why. Handlers run on the thread that posts the event: the client thread, or PrivBot's event thread on Impact, Elorin and SpawnPK. Anything slow there delays every tick and frame for the whole client. Work you do there also races the worker that owns actions.

// Do: O(1) record of the event payload into a thread-safe tracker the worker reads later
@Subscribe
public void onGraphicsObjectCreated(GraphicsObjectCreated e) {
    MyRunState state = runState;
    if (state != null && state.enabled) {
        hazards.record(e.getGraphicsObject().getId());
    }
}

@Subscribe
public void onChatMessage(ChatMessage e) {
    Chat.recordMessage(e.getMessage());          // feeds ctx.chat.containsMessage(...)
}
// Don't
@Subscribe
public void onGameTick(GameTick e) {
    if (ctx.inventory.isFull()) ctx.bank.depositInventory();   // dispatch on the event thread
    Files.writeString(log, ...);                                // disk on the event thread
}

For observation that must run every tick before selection, use runner.setWorkerPrelude(...) (bounded reads, no dispatch, no sleep) instead of a second worker.

8. Refresh wrappers; never keep them across ticks

Rule. PrivNPC, PrivObject, PrivGroundItem, PrivItem and RuneLite Player are views of live client objects. Use them in the step that found them. Keep a detached identity (NPC id + index, object id + tile, item id + slot, player name) and query again next time.

Why. NPCs die and despawn, an index is reused by another NPC, items move slots, and the client may reuse definition objects. A wrapper held across ticks acts on the wrong thing or on nothing.

// Do: re-acquire at use, then act at once
PrivNPC target = ctx.read(() -> ctx.npcs.query().withName(names).alive().nearest());
if (target == null) { status = "No target"; return false; }
if (!target.attack()) { return recordFailure("Attack not accepted"); }
// Don't
public final class AttackNode extends SimpleNode<MyTaskContext> {
    private PrivNPC target;                      // W007: stale after the next tick
}

9. Bounded retries with a reason

Rule. Every wait has a timeout and an abort term. Every repeated failure is counted; at a limit, back off or pause and say why in status. Never loop until success. Never swallow an exception.

Why. A verb can fail for good: unsupported on this server, an unreachable target, a wrong name in the config. A plugin that retries every tick hides the cause, burns every tick, and never reaches the node that would fix it.

// Do
private static final int MAX_FAILED_ATTACKS = 3;
private volatile int failedAttacks;

private boolean recordFailure(String reason) {
    status = reason;
    if (++failedAttacks >= MAX_FAILED_ATTACKS) {
        log.warn("{}; {} consecutive failures", reason, failedAttacks);
        status = reason + " (check the target name)";
    }
    return false;
}
// After a confirmed success: failedAttacks = 0;
// For loot that did not land: backoffUntilMillis = now + 1_500 rather than a permanent blacklist.
// Don't
while (!ctx.bank.open()) { }                     // spins forever on a server without a bank path
try { ctx.npcs.attack("Goblin"); } catch (Exception ignored) { }   // E003

Waits always look like ctx.sleepUntil(() -> ctx.shouldAbort(epoch) || proof, timeoutMs).

10. A changed config default needs a migration

Rule. When you change a default in your @ConfigGroup interface, rename a key's meaning, or remove a key, add a versioned step with privbot.config.ConfigMigration and run it first in startUp().

Why. Every plugin load writes every config value to the shared settings file. RuneLite replaces a saved value only when it no longer parses. An old default that still parses therefore outlives your change on every existing install: a boss plugin ran a whole fight on a hazard setting its author had turned off a release earlier.

// Do: first thing in startUp()
List<ConfigMigration.Change> changed = ConfigMigration.run(
        ConfigMigration.of(configManager, "my-plugin"),
        ConfigMigration.replaceIfEquals(1, "eatAtPercent", "40", "50"),   // only if still the old default
        ConfigMigration.unset(2, "legacyMode"));                          // a key that no longer exists

run applies each step whose version is above the stored settingsVersion once, never throws, and leaves a value the user changed alone. replaceIfEquals compares the saved string exactly (enums are saved by name).

// Don't: edit the default and assume users get it
@ConfigItem(keyName = "eatAtPercent", name = "Eat below HP %", description = "...")
default int eatAtPercent() { return 50; }    // existing installs keep 40 forever

11. Widget text is not proof a dialogue is on screen

Rule. Decide dialogue state from the dialogue reads (canContinue(), isViewingOptions(), getOptions(), getText()), not from text matches. Confirm a click by a fresh surface. Never type text unless an input prompt is open.

Why. ctx.dialogue.contains(text) matches any visible widget text, including chat history lines. On some servers a closed interface keeps its text and reads as not hidden, so "the text is there" stays true after the dialogue closed; ctx.widgets.drawnRoots() (where the server supports it) says which interfaces are actually drawn. "Still visible" is not confirmation. Text typed while no input prompt is open goes to public chat.

// Do
List<String> options = ctx.dialogue.getOptions();
if (options.stream().anyMatch(o -> o.contains("Give me a task"))
        && ctx.dialogue.select("Give me a task")) {
    ctx.sleepUntil(() -> !ctx.dialogue.getOptions().equals(options), 2_400);   // a new surface
}

if (ctx.dialogue.isEnterInputOpen()) {
    // only now is it safe to type into the prompt
}
// Don't
if (ctx.dialogue.contains("Give me a task")) {    // also matches a chat line that says it
    ctx.dialogue.select("Give me a task");
}
ctx.sleepUntil(() -> ctx.widgets.has("Continue"), 2_000);   // "still visible" proves nothing

12. A gear set is a multiset

Rule. When you compare a loadout with worn or carried items, count per slot. A name is not a slot.

Why. Two pieces can share a name (a robe top and robe bottom both named "Ghostly robe"). A check like worn.has(name) is satisfied by one item for both entries, so the missing piece is never reported, and an equip loop clicks the same inventory slot twice. One PvP plugin fought a whole session in half a set because of this.

// Do: each wanted name must claim a distinct slot
static List<String> missing(List<String> wanted, ItemContainerSnapshot worn) {
    Set<Integer> taken = new HashSet<>();
    List<String> missing = new ArrayList<>();
    for (String name : wanted) {
        ItemContainerSnapshot.Item hit = worn.first(i -> i.nameMatches(name) && !taken.contains(i.slot));
        if (hit == null) {
            missing.add(name);
        } else {
            taken.add(hit.slot);
        }
    }
    return missing;    // call only when worn.available
}
// Don't
List<String> missing = wanted.stream().filter(n -> !worn.has(n)).collect(Collectors.toList());

13. Server ids are not RuneLite enum ordinals

Rule. Do not turn a server's raw id into a RuneLite enum by ordinal, and do not assume RuneLite or OSRS id constants mean the same thing on a private server. Prefer names and the translated reads.

Why. Overhead icon, animation, graphic and varbit ids are assigned per server. HeadIcon.values()[raw] is right only on a server whose ids follow RuneLite's order; on another it returned a confident wrong icon for some ids and null ("no prayer") for others. RuneLite Varbits constants are OSRS ids; on a server with its own varbit table they can be undefined or name an unrelated value.

// Do
User.Overhead mine = ctx.user.overheadProtection();      // translated through the server's table
if (mine.isReadable() && mine.icon() == HeadIcon.MELEE) { /* ... */ }
ctx.prayer.isActive("Protect from Melee");               // by name
ctx.npcs.query().withName("Goblin");                     // names over ids
// An id you must use comes from that server's own data, with the evidence next to the constant.
// Don't
HeadIcon icon = HeadIcon.values()[rawId];
int value = ctx.vars.getVarbit(4070);                    // an OSRS id; may be undefined here
if (server.equals("Elorin")) { /* opcode or id */ }      // E006: no server branches in plugins

Per-server translation is ctx.ids.animation(osrsId), graphic and varbit, each an OptionalInt, and ctx.server() returns a typed privbot.api.ServerId.

14. Overlays render a snapshot

Rule. Build an immutable view on the game tick, publish it into a privbot.ui.overlay.Snapshot<S>, and let the overlay render read only that snapshot. Never call a client hook or a ctx.* facade from render. Draw tiles through SceneCanvas, never RuneLite Perspective.

Why. Render runs every frame on a thread that, on some servers, cannot call client hooks at all. A read there either fails or stalls drawing. On Impact and Elorin RuneLite Perspective silently draws nothing; the kit's SceneProjection works on every server. Colours come from the shared theme so every plugin looks the same.

// Do
private final Snapshot<View> view = Snapshot.empty();

// on the game tick, while running
View v = ctx.read(() -> new View(ctx.user.getHitpoints(), ctx.user.getMaxHitpoints(), dangerTiles()));
if (v != null) view.publish(v);

// overlay
PrivBotOverlays.panel("My Plugin").visibleWhen(this::isEnabled)
        .rows(view, (r, s) -> r.fraction("HP", s.hp, s.maxHp, ColorRamp.percentBelow(50)));
// Don't (inside render)
graphics.drawString("HP " + ctx.user.getHitpoints(), 10, 10);       // a client read per frame
Polygon p = Perspective.getCanvasTilePoly(client, localPoint);       // draws nothing on some servers
graphics.setColor(new Color(255, 0, 0));                            // private palette (E008)

Recipes: Cookbook: overlays and UI. Types: https://privbot.dev/javadoc/privbot/ui/package-summary.html.

More pitfalls

  • Off-screen targets. Some servers refuse an interaction whose target has no clickable point on screen; the verb returns false. Walk toward the target first (ctx.travel.walkTo(tile)), then try again. Treat false as "not dispatched", never as done.
  • Player options. Trade, Follow and other player options need live menu data. Use ctx.players.interact(name, "Trade") or ctx.trade.request(player). Never replay a captured menu entry.
  • Your own target. The local player's getInteracting() can read null mid-fight on some servers. Use ctx.combat.isInCombat() or the NPC's getInteracting() instead.
  • MenuOptionClicked for bot actions. On Impact, Elorin and SpawnPK this event can be synthesized, and getItemId() can hold the target identifier rather than an item id. Classify by getMenuOption() (the verb).
  • Events posted once. A graphic's created event is posted once per graphic. To know whether a hazard is still there, poll ctx.graphics.query() instead of waiting for a re-post.
  • Chat reads. ctx.chat.containsMessage(...) only sees lines your plugin recorded with Chat.recordMessage(...) from onChatMessage.
  • Chat send. ctx.chat.sendMessage(...) exists but was not working on the live servers as of 2026-11-04. Treat it as unsupported until ctx.capabilities reports Capability.CHAT_SEND as supported.
  • Void verbs. ctx.inventory.dropAll(...) and dropAllExcept(...) return nothing. Confirm the count fell.
  • Names. Facades return names with colour tags removed. ItemContainerSnapshot.count(String) matches the exact name, case-insensitively; first(String) falls back to a substring match.
  • Held runner. The runner can pause all nodes for a safety reason; its status reads HELD: <reason>. Nodes resume on their own when the user resumes. Do not work around it.
  • Priorities. Two top-level nodes with the same priority run in registration order, silently (W001). Give them distinct values.
  • Stop order. stopPlugin() bumps the epoch (runState.stopAutomation()) before stopping the runner, so a confirmation in flight abandons its result instead of acting after Stop.

Lint rules referenced here

Id Catches
E002 Thread.sleep in plugin code
E003 A swallowed exception
E005 A raw client scene read
E006 Server-specific branching
E008 Hand-rolled UI instead of the kit
E010 A shouldExecute / shouldExecuteParent that is not read-only
E011 Death detected through onAnimationChanged
W001 A priority collision
W002 An isOpen() gate
W006 A fat @Subscribe handler
W007 A cached wrapper field