Detached reads and policy
Read a single snapshot per tick using ctx.pvp.snapshot(PvpQuery.all().within(15)). Check
Observed.isPresent() first: an unreadable snapshot is not an empty player list. snapshot.get()
provides local(), opponents(), find(name) and currentTarget(). Each PlayerView is detached;
individual unreadable fields are null. For overhead and skull, the readable absence is "NONE".
currentTarget() can also be null when the target is unreadable or outside the query.
The weapon ID and name are null when appearance encoding or item definitions cannot be read; an ID of -1 means
the weapon slot was read as empty. When the server appearance format is not supported, its encoding stays unknown.
For a position-filtered snapshot, an unreadable player tile makes the snapshot unreadable; a name filter also
requires the names needed to decide whether players match.
For decisions that also need threats, inventory, equipment and the spec orb, use
ctx.pvp.fight(PvpQuery.all(), ThreatQuery.all()). It collects those components in one client-thread callback.
The returned frame's auxiliary components can be null when unreadable; check each one before making a decision.
Its levels() component holds boosted and real combat levels, with each unavailable level represented as null.
For newly observed local hits and graphics, retain one ctx.pvp.fightObserver(...) on the runner worker and call
observe() each tick. Its first readable event lists, and lists after read gaps, are null while it establishes a
baseline. A readable empty list means no new event in that sample. NPC target observations are nullable: use observedTargetsUs() and observedTargetsOther() rather than the
legacy boolean accessors when an unknown attacker must remain unknown. Graphic IDs are server IDs, not assumed hostile;
match them against verified server cues before feeding ThreatMemory. Call reset() at Stop, death, disconnect,
or a new client session. A dispatched action is not proof that it landed.
ctx.pvp.wildernessLevel(verifiedRules) applies a caller-supplied WildernessModel to the server tile.
Only add zones that have been verified for the server: uncovered or conflicting zones return UNREADABLE, not level 0.
A coordinate result does not prove a teleport is permitted. No built-in cross-server wilderness rules are asserted.
ctx.pvp.escape(safeDestination, lowerWaypoint, verifiedRules, teleportLimit) creates a worker-stepped, cancellable
job using the existing travel path. For a teleport escape, provide a waypoint whose verified level is within the
teleport limit. The job pauses and cancels movement when the level is unreadable; DONE requires reaching the destination
and a fresh level-zero reading. The caller remains responsible for the destination, route and server rules.
ctx.pvp.riskValue(frame, itemRules, skulled, protectItem, ordinarySlots, skulledSlots, prayerAddsSlot)
uses both detached containers and explicit per-item values and death treatment. Every occupied item needs a rule;
missing data yields UNREADABLE. The output is an estimate, not a server loss guarantee or market quote.
ctx.pvp.measuredDamage(weapon, special) exposes the bundled Elorin PvP capture distribution and sample count.
It is a historical estimate, not proof of a current maximum; other or unknown servers return UNREADABLE, and a
weapon without a row returns ABSENT. Pass its copied survival array to KnockoutRisk.Candidate.measured(...) only
when the model is appropriate for the current fight.
Keep one OverheadWatch per opponent. Call observe(tick, opponent.overhead()) and pass its
blockedSet(tick) to StylePolicy.choose(available, blocked, weights, random). The default debounce
is two ticks. A null overhead leaves the watch unchanged; guard decisions when the current reading is
unreadable. The policy returns null if every available style is blocked.
The watch retains its last established block while a new overhead is being debounced. Style selection itself
rolls on every call; retain a chosen style separately if it should persist between decisions.
Switching and effects
Call ctx.loadouts.switchTo(wornSetup) once to send a same-tick switch. Inspect sent(),
notCarried(), failed() and unreadable(); sending is not proof. Record the attempt with
SwitchCheck.sent(tick, result.verificationSetup()) and on later ticks call observe(tick, wornDiff) with
SetupDiff.worn(result.verificationSetup(), equipmentSnapshot) or null. The verification setup records the IDs
actually selected for accepted name-matched clicks; do not use it when the result is unreadable.
DONE proves the resolved set is worn; FAILED exposes stillMissing();
UNREADABLE proves neither. Respect backingOff(tick) after repeated failures.
AttackTiming provides pure estimates for a confirmed attack fire, subsequent confirmed eats and pending-send
deadlines. AttackFireDetector, OwnAttackClock and OpponentAttackClock add caller-supplied, server-specific
cue tracking. ctx.pvp.cues() supplies the server's verified cue set as Observed<PvpCues>: on Elorin an
incomplete seed from historical captures, in Elorin's own ids; on every other server UNREADABLE until a set is
verified, so one server's ids never reach another. An id missing from a set is unknown, not "not an attack".
(ElorinPvpCues is the same seed, deprecated since 1.2.1.) Their estimates do not prove an attack fired or cannot arrive sooner; an accepted send and an expired
pending window are not outcomes. OpponentEnergy is an upper bound based on verified regeneration and exact-tick,
independently confirmed spends, not a direct reading; reset it if an unmodeled energy restoration is possible.
StylePlanner, ConsumePlanner, PvpArbiter, ThreatMemory, SpecialAttackPolicy, GraniteMaulDecision and
KnockoutWeaponDecision and IncomingStyleDecision are pure decisions over supplied facts. They do not dispatch actions. Keep each history on
the runner worker, feed the same tick once, and independently confirm the resulting game state. The individual
rules are available for composition; a complete action-policy coordinator and comprehensive server cue tables are not yet supplied.
When composing PvpActionPlanner, use ConsumePlanner.State.fromFrame for the same fight frame and prefer
PvpActionPlanner.planWithSpecialSet, which derives special-set readiness from that frame. An unreadable container or invalid/empty setup
returns unknown; a proposed equip does not prove that gear is worn. InstantMaulPlan can propose the flagship's
same-tick equip, attack resend, and orb sequence only when the caller selects verified server rules; its result
identifies the acceptance dependencies. PvpMaulCoordinator combines it with an ordinary plan from the same frame
and arbiter facts; consumption and an existing generic-special episode take precedence. Dispatchers must recheck
the decision tick before dependent sends, honor the returned dependencies, and verify the resulting equipment and
special attack. Use PvpArbiter.Action.attack(opponent, style) for a frame-derived target: the coordinator retains
an ordinary attack before the orb only when it targets that exact observed opponent. A pending maul retains gear
ownership; when same-tick sequencing is unverified, a preparatory equip can be proposed alone and must be observed
before a later orb action.
KnockoutWeaponPlan maps a same-tick KO decision to exact carried gear and requires a complete main set before
returning. Feed a retained SwitchCheck with accepted return sends and later worn snapshots; only allow another
return when it is neither pending nor backed off. PvpFinisherCoordinator combines it with the maul and ordinary plans, giving an eligible maul priority;
KO attacks wait until the weapon is observed worn. These are proposals: dispatch and outcome confirmation remain
the caller's responsibility.
PvpFightHistory coordinates the detached health, threat and attack histories once per tick and returns an incoming
style recommendation. Supply current lock, targeting and cue facts, then record accepted sends and separately
confirmed outcomes on its own-attack clock. Create a new history after a session boundary.
OpponentLockTracker applies target and follow rules to caller-supplied same-tick candidates. Mark scans complete
only when they actually cover the relevant players; unknown death, targeting, distance or busy state can hold the
selection. The tracker coalesces repeated calls for a tick, and it does not establish attacker attribution itself.
Use PvpFightHistory.Inputs.fromLock to bind a usable lock to the matching observation. A null result means there is
no usable current lock; callers should handle release and session boundaries before feeding history.
fightObserver includes a same-batch, unfiltered player sample and, where mapped, an NPC attacker scan in the
threat-query radius. Incomplete scans, unknown targets and followers of uncertain ownership cannot prove that an
opponent is the only attacker. Choose a radius suitable for the encounter; neither scan covers actors beyond it.
On Elorin, keep a SpellEffects from ctx.pvp.effects() for the fight and feed local and opponent graphic and
animation observations once per tick. Null inputs do not change state. Report damage through the
corresponding damage methods if tracking whether Vengeance has been used. Freeze duration and the
500-tick Tele Block estimate are upper bounds; early breaks and a protection-prayer reduction are not
observed. The tracker translates animation IDs for Elorin; graphics use their observed IDs. On other or unknown
servers effects() still returns a tracker, but one with no verified cue set: it ignores every observation and
readable(), frozenState, vengeanceUpState and teleblockedState answer UNREADABLE. Check
fx.readable().isPresent() (and PVP_EFFECTS) before acting on it:
SpellEffects fx = ctx.pvp.effects(); // never throws
if (fx.readable().isUnreadable()) {
// no verified freeze / Vengeance / Tele Block cues here: treat every effect as unknown
}
Observed<Boolean> frozen = fx.frozenState(tick); // UNREADABLE, never "no", without verified cues
Its booleans describe cues observed by this tracker, not confirmed current effects: an unobserved cue can make a result false, and an early break or missed hit can make it stale. In particular, an unseen Vengeance cast is not proof that the spell is ready.
Hotkeys
Bind named actions with ctx.hotkeys.bind("switch", configuredKeybind), then call start() when the
plugin starts. In a node, drain ctx.hotkeys.drain() and act on the returned names on the worker.
Call stop() on plugin stop; it clears queued presses. Use unbind() or unbindAll() when changing
bindings. The studio captures Keybind config fields; Escape cancels capture and Backspace clears it.
start() fails explicitly if the input manager is unavailable.
Legacy recipes
The following recipes illustrate older manual implementations. Prefer the facades above for new code.
A plugin that fights other players: reads the opponent, picks a style their prayer does not block, switches gear and prayers, eats, uses specials and freezes. Read PrivBot plugin concepts first.
Node layout
The runner runs one node per tick. A player in a fight often eats, switches prayer and attacks in the same tick. With one single-purpose node per action that takes several ticks. The reference plugin therefore puts one combat coordinator above the single-purpose nodes; it decides every channel for the tick and dispatches them together. The single-purpose nodes stay as the fallback when the coordinator is switched off.
| Node | Priority | shouldExecute (read-only) |
execute calls |
|---|---|---|---|
DeathNode |
RECOVERY_MIN (240) |
Polled HP is 0, or recovery active | recovery.step(ctx) |
ArenaNode (lobby, re-entry) |
RECOVERY_MIN - 10 (230) |
Out of the fight area with a fight to find | arena.step(ctx) |
CombatNode (coordinator) |
RECOVERY_MIN - 20 (220) |
In a fight and the coordinator is enabled | engine.tick(ctx): eat, prayer, gear, attack in one pass |
EmergencyEatNode |
HAZARD_PRIMARY (200) |
HP under the emergency floor | supplies.eat(ctx) |
RestorePrayerNode |
HAZARD_SECONDARY_MEDIUM (90) |
Prayer points low | supplies.restore(ctx) |
EatNode |
HAZARD_SECONDARY_MEDIUM - 5 (85) |
HP under the eat threshold | supplies.eat(ctx) |
SpecialAttackNode |
COMBAT_SPECIAL (80) |
Energy readable and enough, opponent in range | fighting.special(ctx) |
FreezeNode |
COMBAT_SPECIAL - 5 (75) |
Opponent not frozen, a freeze spell available | fighting.freeze(ctx) |
GearSwitchNode |
COMBAT_GEAR (70) |
Worn set does not match the chosen style (per slot) | gear.switchTo(ctx) |
AttackNode |
COMBAT_ATTACK (60) |
Opponent in view and not being attacked | fighting.attack(ctx) |
ProtectionPrayerNode |
50 | Wanted protection not showing | prayers.protect(ctx) |
OffensivePrayerNode |
45 | Wanted offensive prayer not on | prayers.offensive(ctx) |
ObserveNode |
1 | Running | Status: why nothing else applies |
Services to write
| Service | Owns |
|---|---|
opponent |
One detached Opponent record per tick: name, tile, overhead, whether they target you |
policy |
Pure rules: which style beats their overhead, when to spec, when to freeze, when to eat |
gear |
Gear sets per style, matched per slot (multiset), the switch and its proof |
prayers |
Protection and offensive prayers, confirmed by the overhead |
supplies |
Food and restores, chosen from snapshots |
engine (optional) |
The per-tick coordinator that runs the channels above in one pass |
Recipe: read the opponent once per tick
/** Detached: no client references, safe on any thread. */
public static final class Opponent {
public final String name;
public final WorldPoint tile;
public final HeadIcon overhead; // null: none drawn, or not readable (see pitfalls)
public final boolean targetingMe;
// constructor omitted
}
public Opponent read(MyTaskContext ctx, String name) {
return ctx.read(() -> {
Player me = ctx.user.getLocalPlayer();
Player p = ctx.players.query().excludeLocal().withName(name).withinTiles(15).nearest();
if (p == null) {
return null;
}
return new Opponent(p.getName(), p.getWorldLocation(), p.getOverheadIcon(),
me != null && me.equals(p.getInteracting()));
});
}
ctx.players.query() returns a player query over RuneLite Player. Its filters read the
client on the calling thread, so run the whole query inside ctx.read(...). Keep the name (your
identity for the opponent) and drop the Player.
Recipe: choose a style their overhead does not block
enum Style { MELEE, RANGED, MAGIC }
/** Pure: unit test it. Returns null when the overhead cannot decide it. */
static Style choose(HeadIcon theirs, EnumSet<Style> available) {
for (Style s : new Style[] {Style.MAGIC, Style.RANGED, Style.MELEE}) {
if (available.contains(s) && !blocks(theirs, s)) {
return s;
}
}
return null;
}
static boolean blocks(HeadIcon icon, Style s) {
if (icon == null) return false;
switch (s) {
case MELEE: return icon == HeadIcon.MELEE;
case RANGED: return icon == HeadIcon.RANGED;
default: return icon == HeadIcon.MAGIC;
}
// Extend for the combined and curse icons your server draws.
}
Recipe: switch gear, counted per slot
public boolean switchTo(MyTaskContext ctx, List<String> set) {
long epoch = ctx.runState.sessionEpoch;
ItemContainerSnapshot worn = ctx.equipment.snapshot();
ItemContainerSnapshot carried = ctx.inventory.snapshot();
if (!worn.available || !carried.available) {
status = "Gear unreadable";
return false;
}
List<String> missing = GearSets.missing(set, worn); // per slot; see the pitfalls page, rule 12
Set<Integer> claimed = new HashSet<>();
for (String piece : missing) {
ItemContainerSnapshot.Item item = carried.first(i -> i.nameMatches(piece)
&& !claimed.contains(i.slot) && (i.hasAction("Wield") || i.hasAction("Wear")));
if (item != null && ctx.inventory.interact(item, item.hasAction("Wield") ? "Wield" : "Wear")) {
claimed.add(item.slot); // never click one slot for two pieces
}
}
if (claimed.isEmpty()) {
return fail("No carried piece of the set");
}
int expected = missing.size() - claimed.size();
boolean done = ctx.sleepUntil(() -> {
ItemContainerSnapshot now = ctx.equipment.snapshot();
return ctx.shouldAbort(epoch) || (now.available && GearSets.missing(set, now).size() <= expected);
}, 1_800);
status = done ? "Switched " + claimed.size() + " pieces" : "Gear switch did not land";
return true;
}
GearSets.missing is the multiset match from
Threading and pitfalls, rule 12.
Recipe: attack or cast, with the reason when it does not go out
public boolean attack(MyTaskContext ctx, String name, String spell) {
long epoch = ctx.runState.sessionEpoch;
PrivPlayer target = ctx.read(() -> ctx.players.nearest(name));
if (target == null) {
return fail(name + " is not in view");
}
if (spell != null) {
Magic.CastResult r = ctx.magic.castOnPlayerOutcome(spell, target);
if (!r.sent()) {
return fail(spell + " on " + name + ": " + r); // outcome and gate, e.g. REFUSED[...]
}
} else if (!ctx.combat.attackPlayer(target.getPlayer())) {
return fail("Attack on " + name + " was not accepted");
}
boolean engaged = ctx.sleepUntil(() -> ctx.shouldAbort(epoch) || ctx.combat.isInCombat(), 1_800);
return engaged || fail("Attack on " + name + " did not start a fight");
}
ctx.magic.castOnPlayerOutcome(...) returns Magic.CastResult with outcome() (DISPATCHED,
POSTED_UNCONFIRMED, REFUSED, FAILED, ...), gate() and sent(). Player options such as Trade
and Follow go through ctx.players.interact(name, option) or ctx.trade.request(player); never
replay a captured menu entry.
Pitfalls for PvP plugins
- One node per tick. Several single-action nodes cannot act in one tick. Use a coordinator for the in-fight channels, or accept the delay knowingly.
- A gear set is a multiset. Two pieces can share a name. Count per slot, claim each inventory slot once (rule 12).
- Overhead ids are server-assigned. The shared reads translate them through the server's table.
Never index
HeadIcon.values()with a raw id (rule 13). Do not confuse the skull with the overhead prayer; a read that is "always melee" for every opponent is a mis-read, not a meta. - Legacy player read: an opponent's overhead has no "cannot read" form in this recipe.
Player.getOverheadIcon()answersnullfor "no prayer", and on some servers also when it cannot read. Do not make an expensive or irreversible choice on anullalone; cross-check over several ticks.ctx.playergives tri-state reads of your own player;ctx.pvpprovides a separate unreadable value for an opponent. - Your own protection: confirm with
ctx.user.overheadProtection().shows(slot), notctx.prayer.isActive(name), which readsfalsewhen it cannot read. - Combat level is not an identity, and
PrivPlayer.getCombatLevel()documents that on one server it does not hold the displayed level. Identify the opponent by name. - Hits on you (
HitsplatApplied) and projectile events are not delivered the same way on every server; the per-server table is What works on each server. Poll your HP for eating decisions. - Death is polled, and a death bumps the epoch so nothing in flight completes after it (rule 2).
- Record what you fought in. If you log fights, log the style and the worn set per sample; without them a bad session cannot be explained.
Read next
Keep the fight rules in a pure class with no ctx in it, so the testkit can run them directly.
Unit-test this with the testkit, see Testing plugins.
