// ============================================================================ // RynthSuite - Plugins/Shared/ActionPacer.cs // One server action at a time: RynthAi's pacing of uses, casts and combat-mode // changes on the server's answers (2026-10-06). // // Why: Drakkon's "can't use anything" and "stuck in the cast animation" stalls on // DreamWeave (ops/overnight/2026-10-06-action-pacing.md). Every stall began with a // combat-mode change sent while a corpse use was still unanswered by the server // (4 of 4 onsets; 0 stalls after ~920 uses with no such overlap). Once in that state // the server finishes nothing that waits on an animation until a relog, and the bot // made it worse by firing the next cast/use every 0.4-2.5 s because nothing waited // for the server's answer: the client busy count it paced on was zeroed and repaired // hundreds of times an hour, and "cast resolved" meant the enchantment, not the // server's UseDone. // // The rule here: // * A use, a use-on, a cast or a combat-mode change that RynthAi sends is the ONE // outstanding server action until the server answers it: // - use / use-on / cast: the next UseDone (GameEvent 0x01C7) after the send, // whatever its error (a refusal is an answer too); a wield also counts as // answered when the item reads wielded (a wield gets no UseDone); // - combat mode: the client reads the new mode and ModeSettleMs has passed // (the stance animation; the server sends no UseDone for it); // or its time limit passes (logged; nothing is force-cleared). // * While one is outstanding, RynthAi starts no other one (MayStart; mode changes // are refused right at ChangeCombatModeFor) and moves or turns the character // only to stop real movement (MoveAudit asks HoldsMovement). // * Heals keep their priority: a heal may go ahead of a corpse/door use the server // hasn't answered after HealAfterWorldUseMs (EmergencyAfterWorldUseMs at // Emergency Heal At), and one heal may follow a cast whose result is already in // (the server queues one cast behind the recoil). // // Opt-in (Enabled, RynthAi sets it at Init); off = every call goes through as before. // Linked into RynthAi only. UseAudit reports its sends through UseAudit.AfterSend. // ============================================================================ using System; using System.Collections.Generic; using RynthCore.PluginSdk; namespace RynthCore.Plugin.Shared; internal enum PacedKind { None, /// A door, corpse, portal or NPC: the server walks/turns the character to it first. WorldUse, /// A kit, potion, stone, wand or weapon (wield), scroll... in the character's own packs. ItemUse, /// A spell cast. Cast, /// A combat-mode (stance) change. CombatMode, } internal enum HealNeed { None, /// Health under a heal line. Heal, /// Health at or under Emergency Heal At. Emergency, } /// The one server action RynthAi is waiting on. internal sealed class PacedAction { public PacedKind Kind; public uint Id; public string Label = ""; public string Who = ""; public long SentMs; public int SeqAtSend; public int ModeTarget; public bool WieldedAtSend; public bool ResultSeen; // a cast's result is in (enchantment / chat); the server is in its recoil public bool HealQueued; // the one heal allowed behind that recoil went out public long ModeSeenMs; // when the client first read the requested mode public long WieldSeenMs; // when a wield first read done public readonly HashSet LoggedWaits = new(); } internal static class ActionPacer { /// Off = nothing is paced (every call goes through as before). RynthAi turns it on. public static volatile bool Enabled; /// Clock (ms); tests replace it. public static Func NowMs = () => Environment.TickCount64; // Time limits: the longest the server took to answer in 3.7 h of healthy logs (10-05/10-06, // p99 / max): corpse use 3.0 / 3.7 s, kit 2.5 s, buff cast 3.6 s, vital cast 4.7 / 5.0 s. public const long WorldUseMaxMs = 5000; public const long ItemUseMaxMs = 3500; public const long CastMaxMs = 7000; public const long ModeMaxMs = 2000; /// The stance animation after the client reads the new mode: no action before it ends. public const long ModeSettleMs = 800; /// A wield that reads done: a short settle for the wield motion. public const long WieldSettleMs = 150; /// A heal may go ahead of a door/corpse use unanswered this long (the server cancels the walk cleanly). public const long HealAfterWorldUseMs = 1000; public const long EmergencyAfterWorldUseMs = 300; /// A heal behind a stance change: once the client has read the new mode this long. public const long HealAfterModeReadMs = 300; /// An engine without UseDone: an action counts as answered after this (no real pacing). public const long NoUseDoneFallbackMs = 600; private static readonly object Gate = new(); private static PacedAction? _cur; // Counters for /ra pace and the periodic summary. private static long _started, _answered, _timedOut, _sentOverOutstanding, _modeRefused, _modeSkipped; private static long _heldStarts, _heldMoves, _healsAhead; private static long _maxWaitMs; private static string _maxWaitWhat = ""; private static readonly Dictionary _holdsByWho = new(); private static string _lastTimeout = ""; public static long Started => _started; public static long Answered => _answered; public static long TimedOut => _timedOut; public static long SentOverOutstanding => _sentOverOutstanding; public static long ModeChangesRefused => _modeRefused; public static long ModeChangesSkipped => _modeSkipped; public static long HeldStarts => _heldStarts; public static long HeldMoves => _heldMoves; public static long HealsAhead => _healsAhead; /// Back to a fresh load (Init, logout, tests). Enabled is left as it is. public static void Reset() { lock (Gate) { _cur = null; _started = _answered = _timedOut = _sentOverOutstanding = _modeRefused = _modeSkipped = 0; _heldStarts = _heldMoves = _healsAhead = 0; _maxWaitMs = 0; _maxWaitWhat = ""; _holdsByWho.Clear(); _lastTimeout = ""; } } /// Forget the outstanding action (logout, death, portal): the server dropped it. public static void Forget(string why) { lock (Gate) { _cur = null; } } // ── Recording what went out ────────────────────────────────────────────── /// /// Records an action that just went out. is the UseDone count read /// BEFORE the send. Logs once when it went out over another unanswered action (a player command, /// a meta, or a heal let ahead). /// public static void Begin(RynthCoreHost host, PacedKind kind, uint id, string label, string who, int seqAtSend, int modeTarget = 0) { if (!Enabled || kind == PacedKind.None) return; PacedAction? prev = Current(host); long now = NowMs(); var a = new PacedAction { Kind = kind, Id = id, Label = label, Who = who, SentMs = now, SeqAtSend = seqAtSend, ModeTarget = modeTarget, }; if (kind == PacedKind.ItemUse) a.WieldedAtSend = IsWieldedByPlayer(host, id); string? over = null; lock (Gate) { _started++; if (prev != null) { _sentOverOutstanding++; over = $"[Pace] {who}: {Describe(kind, label)} went out while {Describe(prev.Kind, prev.Label)} ({prev.Who}) was unanswered for {now - prev.SentMs} ms"; } _cur = a; } if (over != null) Log(host, over); } /// A cast's result (enchantment landed, "You cast ...") is in: the server is in its recoil. public static void NoteCastResult() { lock (Gate) { if (_cur is { Kind: PacedKind.Cast }) _cur.ResultSeen = true; } } // ── The outstanding action ─────────────────────────────────────────────── /// /// The action still waiting for the server's answer, or null. Each call settles answers and /// time limits first, so it is always current. /// public static PacedAction? Current(RynthCoreHost host) { if (!Enabled) return null; PacedAction? a; lock (Gate) a = _cur; if (a == null) return null; long now = NowMs(); long age = now - a.SentMs; string? answeredHow = null; bool timedOut = false; switch (a.Kind) { case PacedKind.WorldUse: case PacedKind.ItemUse: case PacedKind.Cast: { bool hasSeq = false; int seq = 0; try { hasSeq = host.HasUseDoneSeq; if (hasSeq) seq = host.GetUseDoneSeq(); } catch { hasSeq = false; } if (hasSeq && seq != a.SeqAtSend) { answeredHow = "UseDone"; } else if (a.Kind == PacedKind.ItemUse && IsWieldedByPlayer(host, a.Id) != a.WieldedAtSend) { if (a.WieldSeenMs == 0) a.WieldSeenMs = now; if (now - a.WieldSeenMs >= WieldSettleMs) answeredHow = "wield"; } else if (!hasSeq && age >= NoUseDoneFallbackMs) { answeredHow = "time (no UseDone on this engine)"; } long max = a.Kind switch { PacedKind.WorldUse => WorldUseMaxMs, PacedKind.Cast => CastMaxMs, _ => ItemUseMaxMs }; if (answeredHow == null && age >= max) timedOut = true; break; } case PacedKind.CombatMode: { int mode = -1; try { if (host.HasGetCurrentCombatMode) mode = host.GetCurrentCombatMode(); } catch { mode = -1; } if (mode == a.ModeTarget || mode < 0) { if (a.ModeSeenMs == 0) a.ModeSeenMs = now; if (age >= ModeSettleMs) answeredHow = "mode"; } if (answeredHow == null && age >= ModeMaxMs) timedOut = true; break; } } if (answeredHow == null && !timedOut) return a; string? line = null; lock (Gate) { if (!ReferenceEquals(_cur, a)) return _cur; // replaced meanwhile _cur = null; if (timedOut) { _timedOut++; _lastTimeout = $"{Describe(a.Kind, a.Label)} ({a.Who}) after {age} ms"; line = $"[Pace] no answer from the server to {Describe(a.Kind, a.Label)} ({a.Who}) in {age} ms - going on (nothing cleared)"; } else { _answered++; } } if (line != null) Log(host, line); return null; } /// True while an action is waiting for the server (out: it). public static bool Outstanding(RynthCoreHost host, out PacedAction? action) { action = Current(host); return action != null; } // ── Gates ─────────────────────────────────────────────────────────────── /// /// May send a use, a cast or a mode change now? False (with why) while /// another action waits for the server, except the heal rules in the file header. One log /// line per outstanding action and subsystem. /// public static bool MayStart(RynthCoreHost host, string who, HealNeed heal, out string why) { why = ""; PacedAction? a = Current(host); if (a == null) return true; long age = NowMs() - a.SentMs; if (heal != HealNeed.None) { if (a.Kind == PacedKind.WorldUse && age >= (heal == HealNeed.Emergency ? EmergencyAfterWorldUseMs : HealAfterWorldUseMs)) { lock (Gate) _healsAhead++; Log(host, $"[Pace] {who}: the heal goes ahead of {Describe(a.Kind, a.Label)} (unanswered for {age} ms)"); return true; } // A stance change (most often the one this heal asked for: the wand swap, or peace for // a kit): the heal goes once the client has read the new mode for HealAfterModeReadMs, // like BuffManager's emergency settle, not the full ModeSettleMs. if (a.Kind == PacedKind.CombatMode && a.ModeSeenMs != 0 && NowMs() - a.ModeSeenMs >= HealAfterModeReadMs) return true; if (a.Kind == PacedKind.Cast && a.ResultSeen && !a.HealQueued) { a.HealQueued = true; lock (Gate) _healsAhead++; return true; } } why = $"{Describe(a.Kind, a.Label)} sent {age} ms ago by {a.Who} has no answer yet"; bool log; lock (Gate) { _heldStarts++; _holdsByWho[who] = _holdsByWho.TryGetValue(who, out int n) ? n + 1 : 1; if (age > _maxWaitMs) { _maxWaitMs = age; _maxWaitWhat = Describe(a.Kind, a.Label); } log = a.LoggedWaits.Add(who); } if (log) Log(host, $"[Pace] {who} waits: {why}"); return false; } /// /// True while the outstanding action is one the server animates (all of them: the walk/turn /// to a used object, a heal or wield motion, a cast, a stance change). MoveAudit holds /// RynthAi's movement starts and turns meanwhile. /// public static bool HoldsMovement(RynthCoreHost host, out string what) { what = ""; PacedAction? a = Current(host); if (a == null) return false; what = $"{Describe(a.Kind, a.Label)} ({a.Who}, {NowMs() - a.SentMs} ms)"; lock (Gate) _heldMoves++; return true; } // ── Helpers ───────────────────────────────────────────────────────────── internal static string Describe(PacedKind kind, string label) => kind switch { PacedKind.WorldUse => $"the use of {label}", PacedKind.ItemUse => $"the use of {label}", PacedKind.Cast => $"the cast of {label}", PacedKind.CombatMode => $"the change to {label} mode", _ => label, }; internal static string ModeName(int mode) => mode switch { 1 => "Peace", 2 => "Melee", 4 => "Missile", 8 => "Magic", _ => $"mode {mode}", }; internal static bool IsWieldedByPlayer(RynthCoreHost host, uint id) { try { if (id == 0 || !host.HasGetObjectWielderInfo || !host.HasGetPlayerId) return false; uint player = host.GetPlayerId(); return player != 0 && host.TryGetObjectWielderInfo(id, out uint wielder, out _) && wielder == player; } catch { return false; } } /// World object (no container, no wielder) = the server walks to it; else an item of ours. internal static PacedKind ClassifyUse(RynthCoreHost host, uint id, bool doorOrCorpse) { if (doorOrCorpse) return PacedKind.WorldUse; try { if (host.HasGetObjectOwnershipInfo && host.TryGetObjectOwnershipInfo(id, out uint container, out uint wielder, out _)) return container == 0 && wielder == 0 ? PacedKind.WorldUse : PacedKind.ItemUse; } catch { } return PacedKind.ItemUse; } internal static int UseDoneSeqNow(RynthCoreHost host) { try { return host.HasUseDoneSeq ? host.GetUseDoneSeq() : 0; } catch { return 0; } } private static void Log(RynthCoreHost host, string line) { try { host.Log(line); } catch { } } /// Lines for /ra pace. public static string[] DescribeLines(RynthCoreHost host) { var lines = new List(); PacedAction? a = Current(host); lines.Add($"Action pacing: {(Enabled ? "on" : "off")} (one server action at a time; see ops note 2026-10-06-action-pacing)"); lines.Add(a == null ? " Waiting on: nothing" : $" Waiting on: {Describe(a.Kind, a.Label)} from {a.Who}, sent {NowMs() - a.SentMs} ms ago{(a.ResultSeen ? " (result in, recoil)" : "")}"); lock (Gate) { lines.Add($" Sent {_started}, answered {_answered}, no answer in time {_timedOut}{(_lastTimeout.Length > 0 ? $" (last: {_lastTimeout})" : "")}"); lines.Add($" Starts held {_heldStarts}, moves held {_heldMoves}, heals let ahead {_healsAhead}, sent over an unanswered one {_sentOverOutstanding}"); lines.Add($" Mode changes refused while waiting {_modeRefused}, skipped (already in that mode) {_modeSkipped}"); if (_maxWaitMs > 0) lines.Add($" Longest wait seen: {_maxWaitMs} ms ({_maxWaitWhat})"); if (_holdsByWho.Count > 0) { var parts = new List(); foreach (var kv in _holdsByWho) parts.Add($"{kv.Key} {kv.Value}"); lines.Add(" Holds by subsystem: " + string.Join(", ", parts)); } } return lines.ToArray(); } // ── The paced sends that are not uses ──────────────────────────────────── /// /// CastSpell, recorded as the outstanding action. RynthAi's callers check MayStart first; /// (a player command or meta) is never held, only recorded. /// public static bool CastSpellFor(this RynthCoreHost host, uint targetId, int spellId, string who, string label, bool asked = false) { int seq = UseDoneSeqNow(host); bool ok = host.CastSpell(targetId, spellId); if (ok) Begin(host, PacedKind.Cast, unchecked((uint)spellId), label, who, seq); return ok; } /// /// ChangeCombatMode with the pacing rules: nothing is sent when the client already reads that /// mode (the engine would push a raw 0x53 to the server anyway, and on ACE every mode change /// cancels the walk/turn of a pending use and fails a cast in progress) unless /// ; and nothing while another server action is unanswered unless /// . Returns false only when the pacing held the request back (or the /// client already reads that mode); otherwise the request was made, as a plain ChangeCombatMode /// call was before (whose result the callers never read), so their retry timers run as before. /// public static bool ChangeCombatModeFor(this RynthCoreHost host, int mode, string who, string why, bool force = false) { if (!host.HasChangeCombatMode) return true; // nothing to send or pace (the callers went on before too) if (Enabled && !force) { int current = -1; try { if (host.HasGetCurrentCombatMode) current = host.GetCurrentCombatMode(); } catch { current = -1; } if (current == mode) { lock (Gate) _modeSkipped++; return false; } PacedAction? a = Current(host); if (a != null) { bool log; lock (Gate) { _modeRefused++; log = a.LoggedWaits.Add("mode:" + who); } if (log) Log(host, $"[Pace] {who}: change to {ModeName(mode)} mode held ({why}): {Describe(a.Kind, a.Label)} sent {NowMs() - a.SentMs} ms ago by {a.Who} has no answer yet (a mode change now would cancel it on the server)"); return false; } } int seq = UseDoneSeqNow(host); if (host.ChangeCombatMode(mode)) Begin(host, PacedKind.CombatMode, 0, ModeName(mode), who, seq, mode); return true; } }