RynthSuite/Plugins/RynthCore.Plugin.RynthAi/Trade/AutoTradeCommands.cs
Daniel Wallace 04ecdd64f4 RynthAi jump loot: resend at once when the client's request slot refused the move
The acclient holds one pending inventory request. While it is held, it
refuses any other item move with a LOCAL chat line ("You can only move or
use one item at a time"): nothing reaches the server, no WeenieError
comes, and the engine's MoveItemExternal returns true regardless. The
looter took that send for one in flight and waited the whole answer
window (PickupAnswerWaitMs, 4-8 s) before trying again, and the retry
cost the item one of its 3 tries. At the jump-loot cadence this stalled
the loot 4-8 s at a time.

The line is now heard (NoteSlotRefusalChat, anchored at the line start,
stamped with its arrival time on the loot clock) and attributed to the
current send when it arrived within the send's window (200 ms, or 2.5 s
for a send made while the motion queue was busy, since the engine's main
thread queue holds the move that long) and no other item action of this
plugin went out between that same window before the send and the line
(UseAudit.LastItemActionAt). The send is then repeated 250 ms after it,
without a jump, never counted as one of the 3 tries or as a too-busy free
retry, for up to 11.5 s from the item's first slot refusal (the engine
clears a held slot after 10 s); then the ordinary answer wait takes over.
The refusal baseline is taken in SendLootPickup, the one path every send
goes through, own-corpse sends included.

Item actions are stamped at every UseFor and UseOnFor except the
looter's own, the wand, weapon and offhand wields, the ground pickup, the
give helper and the item tool's give, the salvage sends and panel adds,
the meta give actions and salvage-panel add, the MagTools give, drop and
dequip, the HUD and MiniRemote uses, the stack merges and the trade adds.
Not stamped: vendor buy and sell, the salvage panel execute, pack-to-pack
moves and stack splits, the legacy swap wields and the dashboard's panel
drag (the UseAudit doc names the files). Other plugins' item actions are
not seen: each plugin compiles its own copy of UseAudit.

Adapted to upstream's fight hold: no slot resend while a fight has the
tick (the client drops an item move while the character attacks); the
line is attributed by its arrival time, so the resend goes at once after
the fight, and the fresh send does not inherit the fight flag.

Gated by Jump When Looting (LootJumpEnabled, default off): the net was
measured and tuned on ACE's jump-loot cadence. With the setting off every
send keeps its old wait. The UseAudit stamps are a timestamp only.

Host tests: a slot-refused send is resent in about 250 ms with no try
used; a late line or a player's words are not ours; a line then the
server's answer at 200 ms is one move; resends go on past 7.5 s and hand
over after 11.5 s; a busy-queue send's refusal at 700 ms is its own;
another item action before the line, a UseOnFor included, suppresses it,
and so does one 1 s before a busy-queue send; the reset clears the slot
fields; the looter's own UseOnFor is not stamped, so a line after it is
still ours; with the setting off nothing changes; a refusal during a fight
(driven through the real fight hold) is resent only after it; an
own-corpse send after an earlier refusal line is one move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-07 10:07:23 -08:00

155 lines
7.3 KiB
C#

// AutoTrade commands. The /ub autotrade syntax is ported from UtilityBelt
// (https://gitlab.com/utilitybelt/utilitybelt.gitlab.io), MIT License, Copyright (c) the
// UtilityBelt contributors; see THIRD-PARTY-NOTICES.md at the root of this repository.
using System;
using System.Globalization;
using RynthCore.Plugin.RynthAi.Trade;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi;
/// <summary>
/// /ra autotrade ... (and UtilityBelt's /ub autotrade ...): parsed here (chat thread), run by
/// AutoTradeManager on the plugin tick thread. /ra trade ... drives the engine's trade calls by
/// hand (open, add, accept, decline, reset, close, state) for testing.
/// </summary>
public sealed partial class RynthAiPlugin
{
private AutoTradeManager? _autoTrade;
/// <summary>/ub autotrade ... Returns false when the verb isn't autotrade.</summary>
private bool TryHandleAutoTradeCommand(string cmd, string fullCommand)
{
if (cmd != "autotrade")
return false;
RunAutoTradeCommand(AfterWords(fullCommand, 2));
return true;
}
/// <summary>/ra autotrade [args]: the same commands as /ub autotrade.</summary>
private void HandleAutoTradeRaCommand(string[] parts)
=> RunAutoTradeCommand(parts.Length > 2 ? string.Join(" ", parts, 2, parts.Length - 2) : string.Empty);
private void RunAutoTradeCommand(string args)
{
var at = _autoTrade;
if (at == null)
{
ReplyFail("[RynthAi] AutoTrade isn't ready yet (log in first).");
return;
}
Reply.Answered(); // AutoTrade says what it did when it runs the command on the tick
at.Enqueue(() => at.Command(args));
}
/// <summary>/ra trade [state | open &lt;name|id|sel&gt; | add &lt;id|sel&gt; | accept | decline | reset | close]</summary>
private void HandleTradeCommand(string[] parts)
{
if (!Host.HasTrade)
{
ReplyFail($"[RynthAi] Player trading needs RynthCore 2026.9.x or newer (plugin API v{AutoTradeManager.RequiredApiVersion}; this engine is v{Host.Version}).");
return;
}
string verb = parts.Length > 2 ? parts[2].ToLowerInvariant() : "state";
string arg = parts.Length > 3 ? string.Join(" ", parts, 3, parts.Length - 3).Trim() : string.Empty;
switch (verb)
{
case "state":
case "status":
PrintTradeState();
break;
case "open":
{
uint target = ResolveTradeTarget(arg);
if (target == 0) { ReplyFail("[RynthAi] Usage: /ra trade open <player name|id|sel>"); break; }
ReplyIf(Host.TradeOpen(target),
$"[RynthAi] Asked {TradeName(target)} to trade.",
"[RynthAi] Could not send the trade request.");
break;
}
case "add":
{
uint item = ParseTradeId(arg);
if (item == 0) { ReplyFail("[RynthAi] Usage: /ra trade add <item id|sel>"); break; }
RynthCore.Plugin.Shared.UseAudit.NoteItemAction(); // a non-loot item action (UseAudit.LastItemActionAt)
ReplyIf(Host.TradeAdd(item),
$"[RynthAi] Adding {TradeName(item)} to the trade window.",
"[RynthAi] Could not send the add.");
break;
}
case "accept": ReplyIf(Host.TradeAccept(), "[RynthAi] Accepting the trade.", "[RynthAi] Could not send the accept."); break;
case "decline": ReplyIf(Host.TradeDecline(), "[RynthAi] Declining the trade.", "[RynthAi] Could not send the decline."); break;
case "reset": ReplyIf(Host.TradeReset(), "[RynthAi] Clearing the trade window.", "[RynthAi] Could not send the reset."); break;
case "close": ReplyIf(Host.TradeClose(), "[RynthAi] Closing the trade.", "[RynthAi] Could not send the close."); break;
default:
ReplyFail("[RynthAi] Usage: /ra trade [state | open <name|id|sel> | add <id|sel> | accept | decline | reset | close]");
break;
}
}
private void PrintTradeState()
{
if (!Host.TryGetTradeState(out TradeState st))
{
ChatLine("[RynthAi] No trade state from the engine.");
return;
}
ChatLine($"[RynthAi] Trade: {(st.IsOpen ? $"open with {TradeName(st.PartnerId)}" : "closed")}, generation {st.Generation}, seq {st.Sequence}, "
+ $"last event 0x{st.LastEventType:X4}, completed {st.CompletedCount}, watching {st.Watching}, actions {st.ActionsAvailable}.");
if (st.IsOpen)
{
ChatLine($"[RynthAi] You ({st.YourItemCount}{(st.YouAccepted ? ", accepted" : string.Empty)}): {DescribeTradeSide(TradeSide.You)}");
ChatLine($"[RynthAi] Them ({st.PartnerItemCount}{(st.PartnerAccepted ? ", accepted" : string.Empty)}): {DescribeTradeSide(TradeSide.Partner)}");
}
if (st.FailureCount > 0)
ChatLine($"[RynthAi] Last failure: {TradeName(st.LastFailureItemId)} error 0x{st.LastFailureReason:X4} ({st.FailureCount} so far).");
if (!st.IsOpen && st.LastCloseReason != 0)
ChatLine($"[RynthAi] Last close reason: 0x{st.LastCloseReason:X}.");
var at = _autoTrade;
if (at != null)
ChatLine($"[RynthAi] AutoTrade: {at.Status}");
}
private string DescribeTradeSide(TradeSide side)
{
uint[] ids = Host.GetTradeItems(side);
if (ids.Length == 0) return "(nothing)";
var names = new System.Collections.Generic.List<string>();
for (int i = 0; i < ids.Length && i < 12; i++) names.Add(TradeName(ids[i]));
return string.Join(", ", names) + (ids.Length > 12 ? $", ...{ids.Length - 12} more" : string.Empty);
}
private string TradeName(uint id)
=> id != 0 && Host.TryGetObjectName(id, out string n) && !string.IsNullOrWhiteSpace(n) ? n : $"0x{id:X8}";
private uint ParseTradeId(string token)
{
string t = token.Trim();
if (t.Length == 0) return 0;
if (t.Equals("sel", StringComparison.OrdinalIgnoreCase) || t.Equals("selected", StringComparison.OrdinalIgnoreCase))
return Host.GetSelectedItemId();
if (t.StartsWith("0x", StringComparison.OrdinalIgnoreCase)
&& uint.TryParse(t.AsSpan(2), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out uint hex))
return hex;
return uint.TryParse(t, NumberStyles.Integer, CultureInfo.InvariantCulture, out uint dec) ? dec : 0;
}
/// <summary>A player by id, "sel", or (partial) name among nearby players.</summary>
private uint ResolveTradeTarget(string arg)
{
uint id = ParseTradeId(arg);
if (id != 0) return id;
if (arg.Length == 0 || _objectCache == null) return 0;
int me = unchecked((int)_playerId);
WorldObject? partial = null;
foreach (var wo in _objectCache.GetLandscapeObjects())
{
if (wo == null || wo.Id == me || wo.ObjectClass != AcObjectClass.Player) continue;
if (string.Equals(wo.Name, arg, StringComparison.OrdinalIgnoreCase)) return unchecked((uint)wo.Id);
if (partial == null && wo.Name.IndexOf(arg, StringComparison.OrdinalIgnoreCase) >= 0) partial = wo;
}
return partial != null ? unchecked((uint)partial.Id) : 0;
}
}