This page describes the one supported way to write a PrivBot plugin: the layers, who owns what, which
thread runs what, and the ctx.* API the layers share. Every name on this page exists in the
shared library.
Read with: Getting started (a running plugin in 15 minutes), Threading and pitfalls (the rules that break plugins), cookbook/ (one page per plugin type) and The API index. The working example is the example node and its test in your starter project.
The layers at a glance
RuneLite event bus (client thread, or PrivBot's event bridge)
| @Subscribe onGameTick / onGameStateChanged / onChatMessage ...
v
+---------------------+ Start / Stop +-----------------------+
| MyPlugin |----------------->| MyRunState |
| DI, lifecycle, UI, | | volatile fields |
| event forwarding | | synchronized moves |
+---------------------+ | sessionEpoch |
| taskTree.onGameTick() +-----------------------+
v (a signal; returns at once) ^ read / bump
+---------------------+ owns +-------------------------------+
| MyTaskTree |-------->| TaskNodeRunner<MyTaskContext> |
+---------------------+ | owns the ScriptExecutor worker|
+-------------------------------+
| 1. selectNode() client thread, one ReadScope:
| every enabled node's shouldExecute(ctx), read-only
| 2. executeNode() script worker: the winner's execute(ctx)
v
+----------------------------+
| SimpleNode.execute(ctx) |--> ctx.myService.step(ctx)
+----------------------------+ | dispatch through ctx.* facades
| ctx.sleepUntil(proof || abort, ms)
v
game client
Sidebar / studio / overlay: read RunState, node status and a per-tick Snapshot. Never the client.
Plugin: the entry point
MyPlugin extends net.runelite.client.plugins.Plugin. It is thin.
| Owns | Never does |
|---|---|
Guice injection of PrivContext, ConfigManager, ClientToolbar, OverlayManager, the config |
Read the client |
startUp(): create RunState, TaskTree, event dispatcher, UI |
Wait or sleep |
shutDown(): stop automation, taskTree.shutdown(), close overlays, ui.detach(), dispose the studio |
Dispatch game actions |
startPlugin() / stopPlugin() behind the panel's Start/Stop |
Disk I/O on the client thread or EDT |
@Subscribe handlers that forward to the dispatcher or TaskTree |
Start a second worker |
startUp() builds everything but does not start automation. Automation starts when the user presses
Start. stopPlugin() calls runState.stopAutomation() (bumps the epoch) before
taskTree.pauseAutomation() (stops the runner), so work in flight abandons its result.
@Inject private PrivContext privContext;
@Override
protected void startUp() {
runState = new MyRunState();
taskTree = new MyTaskTree(privContext, runState, config);
events = new MyEventDispatcher(runState, taskTree);
ui = PluginUi.attach(clientToolbar, "My Plugin", () -> MyPanel.create(this),
MyPlugin.class, "/com/example/myplugin/icon.png");
}
@Subscribe
public void onGameTick(GameTick event) {
MyEventDispatcher d = events;
if (d != null && d.onGameTick(event)) { // false for a stopped plugin, before any client read
publishHud(); // the HUD gets published state only
}
}
RunState: shared state with an epoch
One mutable object shared by the plugin, panel, overlay, event handlers and the script worker.
- Independent values are
volatile(enabled,status, counters). - Transitions that change several fields together are
synchronized(resetSession,stopAutomation,onDisconnect,onReconnect,onDeath,onRespawn). sessionEpochis avolatile long. Start, Stop, disconnect and death bump it. Work that spans ticks captures it first and gives up when it changes.onDisconnect()returnstrueonly for the first of a burst of disconnect states.onReconnect()returnstrueonly when a real disconnect is pending.
Reference: ExampleRunState.
TaskContext: facades plus your services
MyTaskContext extends privbot.task.PrivTaskContext. The constructor takes the injected
PrivContext, so every ctx.* facade is inherited. Never re-declare a facade and never add an
executor here.
Add:
public final MyRunState runState;andpublic final MyConfig config;- One field per capability service (
fighting,supplies,loot, ...). Services hold the domain logic; nodes stay one decision long. shouldAbort(long epoch): true once Stop, disconnect or death invalidated the work.- An override of
sleepUntilso each confirmation poll is one fresh, batched read.
public final class MyTaskContext extends PrivTaskContext {
public final MyRunState runState;
public final MyConfig config;
public final MyCombatService fighting = new MyCombatService();
public MyTaskContext(PrivContext priv, MyRunState runState, MyConfig config) {
super(priv);
this.runState = runState;
this.config = config;
}
/** Poll every 100 ms; each poll is one scoped read. Never wait inside read(). */
@Override
public boolean sleepUntil(BooleanSupplier condition, int timeoutMs) {
return super.sleepUntil(() -> Boolean.TRUE.equals(read(condition::getAsBoolean)), 100, timeoutMs);
}
public boolean shouldAbort(long epoch) {
return !runState.enabled || epoch != runState.sessionEpoch || Thread.currentThread().isInterrupted();
}
}
PrivTaskContext also gives you:
| Member | Use |
|---|---|
sleep(long), sleep(int, int) |
Worker only. Returns false on the client thread or when interrupted. |
sleepUntil(cond, timeoutMs), sleepUntil(cond, pollMs, timeoutMs), sleepWhile(cond, timeoutMs) |
Bounded waits, worker only. |
sleepTick(), sleepTicks(n) |
Wait for game ticks, worker only. |
read(Supplier<T>) |
One batched, read-only visit to the client thread. null when it could not be served. |
onClientThread(Supplier<T>) |
Run on the client thread; null when dropped. Prefer read. |
runOnClientThread(Runnable) |
Fire and forget on the client thread. |
human (privbot.behavior.Human) |
Random pacing helpers (random, roll, afterTicks). Script worker only. |
getClient() |
The raw client. Reads on it are not marshalled; wrap them in read(...). |
priv() |
The full PrivContext. |
TaskTree: the only runner owner
MyTaskTree builds the context, creates the one TaskNodeRunner, registers nodes, and forwards
lifecycle calls. Nothing else in the plugin touches the runner.
public final class MyTaskTree {
private final TaskNodeRunner<MyTaskContext> runner;
private final MyTaskContext context;
public MyTaskTree(PrivContext priv, MyRunState runState, MyConfig config) {
context = new MyTaskContext(priv, runState, config);
runner = new TaskNodeRunner<MyTaskContext>(context, () -> runState.enabled) {
@Override
public TaskNode<MyTaskContext> selectNode() {
return ReadScope.scope(super::selectNode); // one read scope per selection pass
}
};
runner.addNodes(new DeathRecoveryNode(), new EatFoodNode(), new AttackNode());
runner.initialize();
}
public void beginAutomationSession() { context.resetEncounter(); runner.initialize(); runner.start(); }
public void pauseAutomation() { runner.stop(); context.resetEncounter(); }
public void shutdown() { runner.shutdown(); }
public void onDisconnect() { runner.onDisconnect(); context.resetEncounter(); }
public void onReconnect() { runner.onReconnect(); }
public void onGameTick() {
// A region load can publish a tick with no local player. Skip it.
if (context.runState.enabled && context.game.isLoggedIn() && context.user.getLocation() != null) {
runner.onGameTick();
}
}
}
TaskNodeRunner: worker, selection, priorities, grace
privbot.task.TaskNodeRunner<C> owns the script worker (ScriptExecutor). Each signalled tick it:
- Selects on the client thread: calls
shouldExecute(ctx)on every enabled node and picks the highest priority that returnstrue. Equal priorities keep registration order. A predicate that throws is logged and skipped. - Executes the winner's
execute(ctx)on the worker. Only one node runs per tick.
| Call | Who calls it | Effect |
|---|---|---|
new TaskNodeRunner<>(context, () -> runState.enabled) |
TaskTree | Holds the context; ticks are skipped while the guard is false. A one-argument form without the guard also exists. |
addNodes(...), addNode(n), initialize() |
TaskTree | Register nodes; clear tracking state. |
start() |
TaskTree on Start | Starts the owned worker. Safe to call again. |
onGameTick() |
TaskTree from the tick handler | Signals the worker and returns at once. |
stop() |
TaskTree on Stop | Stops the worker (waits up to 2 s), resets nodes. start() may follow. |
shutdown() |
TaskTree on shutDown() |
Stops the worker and calls cleanup() on every node. |
onDisconnect() |
TaskTree, once per real disconnect | Pauses the worker and resets nodes on the next cycle. |
onReconnect() / onReconnect(graceTicks) |
TaskTree, once per real reconnect | Resumes after 5 idle ticks (or graceTicks). |
setWorkerPrelude(Runnable) |
TaskTree | Per-tick observation run on the worker before selection. Bounded reads only; no dispatch, no sleep. |
getActiveTaskName(), getActiveTaskStatus() |
Panel, overlay | Published node name and status. |
The runner can also hold every node for a safety reason. Its status then reads HELD: <reason> and
nodes resume on their own once the user resumes. Do not try to work around a hold.
Nodes: one decision each
A node extends privbot.task.SimpleNode<C> and makes one decision.
super(name, priority): higher priority wins. Use aTaskPriorityBandsconstant when one fits.shouldExecute(ctx): read-only. It runs on the client thread inside the selection read scope. No dispatch, no sleep, noctx.human, no RunState writes, no disk.execute(ctx): runs on the worker. Call one bounded service method. Setstatus(...)before and after so the panel shows the real outcome. Returntruewhen the tick was consumed.- Do not cache
PrivNPC,PrivItem,PrivObjectorPlayerin node fields.
public final class EatFoodNode extends SimpleNode<MyTaskContext> {
public EatFoodNode() { super("Eat Food", TaskPriorityBands.HAZARD_SECONDARY_HIGH); }
@Override public boolean shouldExecute(MyTaskContext ctx) {
return ctx.runState.enabled && ctx.supplies.needsFood(ctx) && ctx.supplies.canEat(ctx);
}
@Override public boolean execute(MyTaskContext ctx) {
status("Eating");
boolean consumed = ctx.supplies.eat(ctx);
status("%s", ctx.supplies.status());
return consumed;
}
}
Group nodes that compete locally with privbot.task.Parent<C> and privbot.task.Child<C>. The
parent's priority competes with the runner's other nodes; children compete inside the parent.
shouldExecuteParent(ctx) is a read-only group gate. Override isComplete and reset only for
multi-tick node state, and cleanup only for resources the node owns.
Priority bands
privbot.task.TaskPriorityBands holds optional named integers. Higher wins. The constants:
| Constant | Value | Meant for |
|---|---|---|
EMERGENCY_OVERRIDE |
300 | Emergency stops that preempt everything |
RECOVERY_MAX / RECOVERY_MIN |
250 / 240 | Death recovery, reconnect grace, supply abort, stuck recovery |
HAZARD_PRIMARY |
200 | Mechanics that kill if ignored this tick |
MOVEMENT |
150 | Positioning, travel, off-anchor correction |
HAZARD_SECONDARY_HIGH |
95 | Secondary hazards; eating in ordinary combat |
HAZARD_SECONDARY_MEDIUM |
90 | Secondary hazards between 95 and 80 |
HAZARD_SECONDARY_LOW |
80 | Bottom of the secondary hazard band |
COMBAT_SPECIAL |
80 | Special attacks inside combat |
COX_OLM_COMBAT |
75 | One raid's combat coordinator |
COMBAT_GEAR |
70 | Gear switches |
COMBAT_LOOT |
65 | Loot before choosing a new target |
PREP_BEFORE_COMBAT |
65 | Setup that must finish before combat starts |
COMBAT_ATTACK |
60 | Attacking the current target |
POST_RAID |
40 | Post-encounter loot and leave |
PREP_HIGH / PREP_LOW |
35 / 30 | Supplies and presets |
LOBBY_HIGH / LOBBY_LOW |
25 / 21 | Lobby, rewards, task assignment |
GAUNTLET_* |
200 / 190 / 75 / 60 / 40 / 20 | Illustrative values from one boss plugin |
Some constants share a value (COMBAT_SPECIAL = HAZARD_SECONDARY_LOW = 80, COMBAT_LOOT =
PREP_BEFORE_COMBAT = 65). Give your top-level nodes distinct values. When you need a value between
two bands, write it relative to one (TaskPriorityBands.HAZARD_PRIMARY - 5) and say why in a comment.
A higher node that must yield to a lower one says so in its own gate (a travel node at MOVEMENT
that checks !(needsFood && canEat)).
Services: dispatch plus proof
A service is a plain class held as a field on the TaskContext. It owns the real work:
- Re-acquire the target at use (the one seen during selection may be gone).
- Capture
long epoch = ctx.runState.sessionEpoch;. - Dispatch once through a
ctx.*verb.truemeans the dispatch was accepted, nothing more. - Wait, bounded, for the state that proves it:
ctx.sleepUntil(() -> ctx.shouldAbort(epoch) || proof, ms). - Count consecutive failures. At a limit, pause with a reason instead of retrying forever.
- Expose
status()for the node andreset()for disconnect, death and Stop.
Cross-thread fields in a service are volatile or Atomic*. See
ExampleSupplyService.
The ctx facades
privbot.context.PrivContext is a Guice singleton with 34 public facade fields. PrivTaskContext
mirrors every one as ctx.<field> (same objects). Reads marshal to the client thread themselves.
| Field | Type (privbot.hooks) |
Purpose |
|---|---|---|
ctx.inventory |
Inventory |
Carried items: snapshots, counts and item actions (eat, drink, wield, use, drop). |
ctx.bank |
Bank |
Bank interface: open, withdraw, deposit, close and bank contents. |
ctx.npcs |
NPCs |
NPC queries (query()) and NPC interactions. |
ctx.objects |
GameObjects |
Scene object queries and interactions. |
ctx.graphics |
GraphicsObjects |
Scene graphics objects (spot animations drawn in the world). Query only. |
ctx.groundItems |
GroundItems |
Ground item queries and pickup, including policy-driven loot. |
ctx.equipment |
Equipment |
Worn items: snapshots, queries, counts and unequip. |
ctx.players |
PlayersHook |
Other players in the scene: query and player options (Trade, Follow). |
ctx.prayer |
Prayer |
Prayer state reads, prayer toggles and the mounted prayer book. |
ctx.combat |
Combat |
Attacking, special attack, combat-state reads and attack corridors. |
ctx.skills |
Skills |
Skill levels, real and boosted. |
ctx.magic |
Magic |
Spell casting and autocast. |
ctx.teleporter |
Teleporter |
Teleport spells, tabs, item teleports and configured transports. |
ctx.trade |
Trade |
Player-to-player trade. |
ctx.shop |
Shop |
NPC shops: open, buy and sell. |
ctx.widgets |
Widgets |
Widget queries, widget clicks and the drawn interface roots. |
ctx.dialogue |
Dialogue |
Chat dialogues: continue, options and dialogue text. |
ctx.user |
User |
Local-player state: position, movement, animation, hitpoints, levels, overhead prayer. |
ctx.game |
Game |
Game-wide state: login, tick count, instance, side tabs, run toggle, server name. |
ctx.chat |
Chat |
Chatbox reads (from a buffer your plugin feeds) and sending chat lines or commands. |
ctx.friends |
Friends |
Friends list reads. |
ctx.vars |
Vars |
Raw varbit and varp reads. |
ctx.workflow |
Workflows |
Runs saved Builder workflows from a plugin. |
ctx.places |
Places |
Named-location registry (banks, NPC anchors, areas) shared with travel. |
ctx.travel |
Travel |
Getting to a place: walking, transports, teleports and navigation sessions; go(Destination) is a job that ends DONE only when the player is inside the destination's radius. |
ctx.production |
Production |
Production (make-X) interfaces for skilling. |
ctx.memory |
Blackboard |
Run-scoped key-value scratchpad. Not game state. |
ctx.effects |
Effects |
Creates plugin-owned effect trackers; your plugin forwards the events. |
ctx.actions |
Actions |
Factories for worker-polled action-confirmation trackers. |
ctx.threats |
Threats |
snapshot(ThreatQuery): a detached per-tick copy of the fight (NPCs, projectiles, graphics, HP, chosen prayers) for the pure planners in privbot.mechanics. |
ctx.hazards |
Hazards |
newMap() and safeTile(...): the nearest walkable tile out of every hazard and clear of big NPCs. |
ctx.targets |
Targets |
newLock() picks and keeps a target from a snapshot; resolve(view) turns it back into a live NPC. |
ctx.loot |
Loot |
collect(LootSpec) job: picks up wanted drops, one proved item per step. |
ctx.sustain |
Sustain |
maintain(ctx, SustainPlan): eats, drinks and boost doses, and reports a SustainOutcome. |
ctx.loadouts |
Loadouts |
captureWorn() / captureCarried() read a GearSetup; save, load, names, delete keep it per account; equip(GearSetup) is a job that puts the worn pieces on. |
ctx.restock |
Restock |
to(RestockTarget): a job that banks until the player wears and carries a setup, the same on every server. |
ctx.recovery |
Recovery |
watch() (a DeathWatch), held() / holdReason(), and afterDeath(RecoveryPlan): respawn, reclaim, restock and travel back as one job. |
ctx.capture |
Capture |
start(pluginId, owner), record(stream, row), event(name, row), stop(): a recording of what your plugin saw. Costs nothing before start. |
Conventions every facade follows:
- Name then action.
ctx.objects.interact("Bank booth", "Bank"),ctx.inventory.interact("Shark", "Eat"). - Verbs return
truefor an accepted dispatch, not for a finished action. Confirm the change. - Reads may answer
null,-1,0,falseor an empty result when the client cannot answer. Unreadable is not a negative answer. Prefer the reads that say so:ItemContainerSnapshot.available,ctx.user.overheadProtection().isReadable(),ctx.prayer.mountedBook() == Prayer.Book.UNKNOWN,ctx.skills.observedLevel(skill, boosted)(Integer, null when unreadable),ctx.game.observedRunEnabled(),ctx.combat.specialAttackPercentOrNull(). - A verb that logs
[PrivBot API] unsupportedhas no mapping or path on this server. Do not work around it with opcodes or ids in the plugin.
Mechanics and jobs
privbot.mechanics is a pure package: value types (ThreatSnapshot, HazardMap, LootSpec, SustainPlan,
TargetSpec, PrayerPlanner, CueTimeline and others) with no client, adapter or thread calls. The
ctx.threats, ctx.hazards, ctx.targets, ctx.loot and ctx.sustain facades read the game and feed these
types; a read that cannot be answered returns Observed (unreadable) or null, never an empty result.
Work that spans ticks is a Job (privbot.mechanics). A node calls job.step(ctx) once per tick (per pass)
until it finishes; ctx.loot.collect(spec), ctx.restock.to(target), ctx.travel.go(destination), ctx.loadouts.equip(setup)
and ctx.recovery.afterDeath(plan) are jobs. cancel() stops one that is running. step returns a JobState: RUNNING (call again), DONE
(finished and proved), FAILED (it tried and could not; reason() says why, and a new job may retry) or
UNSUPPORTED (this server or situation cannot do it; final, do not retry). Step it only from the script
worker that owns the PrivTaskContext; it waits through ctx.sleepUntil and never blocks by itself.
Exact signatures: the API index, or the api_type tool of the AI agent tools.
Queries and wrappers
query() is the escape hatch when the intent verbs do not fit. Terminal operations may return
null or an empty list.
| Facade | query() type |
Element type |
|---|---|---|
ctx.npcs |
privbot.query.NPCQuery |
privbot.wrappers.PrivNPC |
ctx.objects |
privbot.query.ObjectQuery |
privbot.wrappers.PrivObject |
ctx.groundItems |
privbot.query.GroundItemQuery |
privbot.wrappers.PrivGroundItem |
ctx.inventory, ctx.equipment, ctx.bank |
privbot.query.ItemQuery |
privbot.wrappers.PrivItem |
ctx.widgets |
privbot.query.WidgetQuery |
RuneLite Widget |
ctx.graphics |
privbot.query.GraphicsObjectQuery |
RuneLite GraphicsObject |
ctx.players |
the player query that ctx.players.query() returns |
RuneLite Player |
// Queries are mutable and single-use, and filter predicates run on the calling thread.
// From the worker, wrap a query whose predicates read actor state in ctx.read(...).
PrivNPC target = ctx.read(() -> ctx.npcs.query()
.withName("Guard")
.alive()
.withinTiles(10)
.where(n -> n.getInteracting() == null)
.nearest());
if (target != null && target.attack()) { /* then confirm the fight started */ }
Inside shouldExecute you are already on the client thread, so no wrapper is needed there.
Wrappers are views of live client objects. Use them in the same step that found them, then drop
them. To act on the same thing next tick, keep a detached identity (NPC id + index, object id + tile,
item id + slot) and query again. PrivNPC.exists() says whether the NPC is still the live entry at
its index.
Batched reads: ctx.read(...)
ctx.read(supplier) enters the client thread once and opens a privbot.context.ReadScope. Inside
it, inventory, equipment, collision and reachability snapshots are read once and reused. It returns
null when the read could not be served.
Boolean ready = ctx.read(() -> {
ItemContainerSnapshot carried = ctx.inventory.snapshot();
ItemContainerSnapshot worn = ctx.equipment.snapshot();
return carried.available && worn.available
&& carried.firstWithAction("Eat") != null && worn.has("Rune scimitar");
});
boolean equipped = Boolean.TRUE.equals(ready); // null = could not read, not "no"
Rules: only reads inside read; no dispatch, no waits. The runner already scopes each selection
pass, so shouldExecute methods share snapshots automatically. ReadScope.once(key, supplier)
dedupes your own repeated read inside a scope.
ItemContainerSnapshot: detached item facts
ctx.inventory.snapshot() and ctx.equipment.snapshot() return
privbot.hooks.container.ItemContainerSnapshot: an immutable list of items with no client
references, safe on any thread.
| Member | Meaning |
|---|---|
available |
false = the container could not be read. It is not an empty container. |
items, size(), freeSlots(capacity) |
Contents. freeSlots(28) for the inventory. |
count(int id), count(String exactName), count(Predicate) |
Total stack quantity. |
first(String), firstOf(String...), slot(int), id(int), firstWithAction(String) |
One Item or null. |
has(String), hasAny(String...), names() |
Convenience checks. |
Item.id, .name, .slot, .quantity, .actions(), .hasAction(String) |
Item fields. |
An unavailable snapshot can neither trigger nor confirm an action. Act on a chosen item with
ctx.inventory.interact(item, "Eat"), which re-checks slot, id and action before dispatch.
Travel: NavigationSession
For short hops, ctx.travel.walkTo(tile), ctx.travel.to(placeName) and ctx.travel.toBank()
block until arrival or failure (worker only). For a journey, hold one session and step it each tick:
NavigationOptions options = new NavigationOptions();
options.arriveRadius = 3;
NavigationSession journey = ctx.travel.session(destination, options, NavigationSession.Policy.defaults());
// In a service called from execute(), once per tick:
NavigationSession.Result r = journey.step(() -> ctx.shouldAbort(epoch));
// PENDING: keep stepping next tick. ARRIVED / INTERRUPTED / FAILED are terminal and sticky.
// Stop or disconnect: journey.cancel(). Start a new session for a new journey.
NavigationSession, NavigationOptions and SceneReachability live in privbot.movement.pathing.
Policy.defaults() bounds retries, stalls, progress and total time. ctx.travel.reachability() and
ctx.combat.collision() give conservative geometry for "can I reach / hit this tile".
UI kit surfaces
Every plugin uses the shared kit for its three surfaces. Recipes and the rules a review applies: Cookbook: overlays and UI. Types: https://privbot.dev/javadoc/privbot/ui/package-summary.html.
| Surface | API | Rule |
|---|---|---|
| Sidebar | PrivBotPanel.builder(name)...build() attached with PluginUi.attach(...), removed with ui.detach() |
Suppliers read RunState and node status only. |
| Studio | FxStudioShell.forConfig(title, subtitle, config, configManager).build() |
One page per @ConfigSection; values write live. |
| Overlays | PrivBotOverlays.panel(...) / scene(client) over a Snapshot<S>, installed with PrivBotOverlays.install(...) |
Render reads the snapshot and nothing else. |
Threading model
| Thread | Runs | Allowed | Never |
|---|---|---|---|
| Client thread (or PrivBot's event thread on Impact, Elorin and SpawnPK) | @Subscribe handlers |
Record, forward, bump RunState, signal the runner | Wait, dispatch, disk, long scans |
| Client thread, selection pass | shouldExecute of every node |
Read-only facade calls inside one ReadScope |
Dispatch, sleep, state writes |
| Script worker (owned by the runner) | execute, services |
Facade verbs, ctx.sleepUntil, ctx.read batches |
Thread.sleep, a second worker |
| Swing EDT / JavaFX thread | Panel, studio | Widgets, published snapshots, RunState, status() |
Game reads, waits, disk |
| Overlay render | Rows / SceneCanvas composers |
snapshot.get() |
Anything else |
| Your own daemon executor | Disk, JSON, diagnostics | Detached values handed over | Client reads |
- Facades marshal through
privbot.context.GameThread.ensure(...): inline when already on the client thread, otherwise queued and waited for with a bound. A dropped read returnsnull. - Do not wrap facade calls in your own
GameThread.ensureorClientThread.invoke. Usectx.readto batch. - Never wait inside
ctx.readorctx.onClientThread. The wait goes outside; the observation goes inside. - Overlays render a snapshot published on the game tick.
Full rules and the reasons behind them: Threading and pitfalls.
Server-aware facades
These sit beside the facades above. They are how a plugin finds out what the current server can do, instead of guessing.
| Feature | Shape |
|---|---|
| Server and capability query | ctx.capabilities (privbot.api.Capabilities: server(), support(Capability), supports(Capability), note(Capability)), and ctx.server() returning privbot.api.ServerId. A capability with no evidence is Support.UNKNOWN, never UNSUPPORTED. |
| Server id translation | ctx.ids (privbot.api.Ids): animation(int osrsId), graphic(int), varbit(int) and inverses, each an OptionalInt (empty = cannot translate) |
| Explicit outcomes | privbot.api.Outcome with Status { DISPATCHED, UNSUPPORTED, NOT_FOUND, NOT_READY, REFUSED, FAILED }, a reason and dispatched(); newer verbs return it, boolean verbs stay |
| Tri-state reads | privbot.api.Observed<T>: value present / observed absent / unreadable |
| Local player, events, services | ctx.player (tri-state reads of the local player), ctx.events (polled typed events: projectile, hitsplat, animation, local death, graphic; it starts no thread, so your GameTick handler calls ctx.events.onGameTick() itself, only while the plugin runs, and Stop calls ctx.events.clear()), ctx.teleports, ctx.loadouts, ctx.restock and ctx.recovery; loadouts, restock and recovery answer "unsupported" on a server that has no such service |
| API version and manifest | privbot.api.ApiVersion.CURRENT, and the Plugin-Api-Version and Plugin-Servers manifest entries; see PrivBot plugin API: versioning and compatibility |
| Per-server support matrix | The generated support table per facade and server: What works on each server |
privbot.api.Outcome, Observed, Capabilities and Ids are in privbot.api, which is public. A few types
that ctx returns, such as the player query, are not in a public package. Hold them in a var, or pass them
straight on; do not name them in your own signatures.
PvP snapshots, switches, effect trackers and queued hotkeys are described in the PvP cookbook.
