// IltChatCapture.cs — Shared "send a server command and collect its reply" helper. // Originally SilentKelpie's ILT Hub (RynthAi IltHub/); moved to RynthILT 2026-10-13. // // Every ILT Hub feature that talks to ACECustom (/bank, /aug, /qb, /pets, /xp, /pb, // the login probe, /myquests, ...) goes through this one queue so that: // * only one capture is in flight at a time (replies can't be attributed to the wrong // request), // * reply lines can be eaten so a Hub refresh doesn't spam the chat window, // * an "Unknown command: X" reply is recognised uniformly (feature not on this server). // All methods must be called on the plugin pump thread (OnTick / OnChatWindowText). using System; using System.Collections.Generic; using RynthCore.PluginSdk; namespace RynthCore.Plugin.RynthILT.Hub; /// Describes one command whose reply should be captured. internal sealed class IltChatRequest { /// Text handed to InvokeChatParser, e.g. "/bank". public string Command = string.Empty; /// True for lines that belong to this reply (captured, refresh the idle timer). public Func IsResponseLine = _ => false; /// /// Optional: only these response lines arm / refresh the idle timer. Header / banner lines /// still capture, but idle completion waits until a progress line arrives (UB's /aug fetch: /// dashes and "Advanced Augmentation Levels:" must not start the 2s idle before Creature:). /// public Func? ArmsIdle; /// Optional: a line that ends the reply immediately (it is captured too). public Func? IsTerminator; /// The reply is complete after this long with no new response line. public int IdleEndMs = 2000; /// Give up if no response line arrives within this long. public int FirstLineTimeoutMs = 15000; /// Hide captured lines from the chat window. public bool Eat = true; /// Invoked once on the pump thread when the capture finishes for any reason. public Action? OnComplete; } /// What a capture produced. internal sealed class IltChatResult { public readonly List Lines = new(); /// No response line ever arrived. public bool TimedOut; /// The server answered "Unknown command: …" for this command. public bool UnknownCommand; /// The engine had no InvokeChatParser, so nothing was sent. public bool NotSent; public string? TerminatorLine; } internal sealed class IltChatCapture { private readonly RynthCoreHost _host; private readonly Queue _queue = new(); private IltChatRequest? _active; private IltChatResult? _activeResult; private long _sentAt; private long _lastLineAt; /// True once a response line that arms idle has arrived (always true when is null). private bool _idleArmed; /// Minimum spacing between two sends so the server's own command throttles aren't tripped. private const long SendSpacingMs = 400; private long _lastSendAt; private static long NowMs => Environment.TickCount64; public IltChatCapture(RynthCoreHost host) => _host = host; /// True while a capture is in flight or queued. public bool IsBusy => _active != null || _queue.Count > 0; /// True if a request with this exact command is queued or in flight (avoids duplicate refreshes). public bool IsPending(string command) { if (_active != null && string.Equals(_active.Command, command, StringComparison.OrdinalIgnoreCase)) return true; foreach (var r in _queue) if (string.Equals(r.Command, command, StringComparison.OrdinalIgnoreCase)) return true; return false; } /// Queues a capture. It is sent from once earlier captures finish. public void Enqueue(IltChatRequest request) { _queue.Enqueue(request); RynthLog.Trace(LogCat.IltChat, $"enqueue '{request.Command}' (queue={_queue.Count}, busy={_active != null})"); } /// Drops everything (logout / teardown). Pending callbacks are not invoked. public void Clear() { if (_active != null || _queue.Count > 0) RynthLog.Trace(LogCat.IltChat, $"clear: dropping active='{_active?.Command}' and {_queue.Count} queued"); _queue.Clear(); _active = null; _activeResult = null; } /// Starts queued captures and finishes the active one on idle/timeout. public void Tick() { long now = NowMs; if (_active != null && _activeResult != null) { bool gotAny = _activeResult.Lines.Count > 0; // Idle completion only after a progress line when ArmsIdle is set (header alone is not enough). bool idleReady = _active.ArmsIdle == null || _idleArmed; if (gotAny && idleReady && now - _lastLineAt >= _active.IdleEndMs) Finish(); else if ((!gotAny || !idleReady) && now - _sentAt >= _active.FirstLineTimeoutMs) { _activeResult.TimedOut = true; Finish(); } } if (_active == null && _queue.Count > 0 && now - _lastSendAt >= SendSpacingMs) StartNext(now); } /// /// Feed every incoming chat line. Returns true when the line belonged to the active /// capture and that capture asked for its lines to be eaten. /// public bool OnChatLine(string rawText) { if (_active == null || _activeResult == null) return false; string text = rawText.Trim(); if (text.Length == 0) return false; // "Unknown command: blackjack" — ACE GameActionTalk reply for unregistered commands. if (text.StartsWith("Unknown command:", StringComparison.OrdinalIgnoreCase) && CommandWordMatches(text.Substring("Unknown command:".Length).Trim())) { _activeResult.UnknownCommand = true; _activeResult.Lines.Add(text); bool eat = _active.Eat; Finish(); return eat; } if (_active.IsTerminator != null && _active.IsTerminator(text)) { _activeResult.TerminatorLine = text; _activeResult.Lines.Add(text); bool eat = _active.Eat; Finish(); return eat; } if (!_active.IsResponseLine(text)) return false; _activeResult.Lines.Add(text); // Header-only replies (e.g. /aug dashes + banner) must not start the idle clock. if (_active.ArmsIdle == null || _active.ArmsIdle(text)) { _idleArmed = true; _lastLineAt = NowMs; } RynthLog.Trace(LogCat.IltChat, $"line '{_active.Command}'{(_active.Eat ? " [eaten]" : "")}: {text}"); return _active.Eat; } private bool CommandWordMatches(string word) { if (_active == null) return false; // Request "/bank t p 5 Bob" → command word "bank". string cmd = _active.Command.TrimStart('/', '@'); int sp = cmd.IndexOf(' '); if (sp >= 0) cmd = cmd.Substring(0, sp); return string.Equals(cmd, word, StringComparison.OrdinalIgnoreCase); } private void StartNext(long now) { var req = _queue.Dequeue(); var result = new IltChatResult(); if (!_host.HasInvokeChatParser) { RynthLog.Trace(LogCat.IltChat, $"not sent '{req.Command}': engine has no InvokeChatParser"); result.NotSent = true; try { req.OnComplete?.Invoke(result); } catch (Exception ex) { RynthLog.Exception(LogCat.IltChat, ex, $"capture callback '{req.Command}'"); } return; } _active = req; _activeResult = result; _sentAt = now; _lastLineAt = now; _idleArmed = req.ArmsIdle == null; // no progress gate → idle can finish after any response line _lastSendAt = now; RynthLog.Trace(LogCat.IltChat, $"send '{req.Command}' (idle={req.IdleEndMs} ms, timeout={req.FirstLineTimeoutMs} ms, eat={req.Eat})"); _host.InvokeChatParser(req.Command); } private void Finish() { var req = _active; var res = _activeResult; _active = null; _activeResult = null; _idleArmed = false; if (req == null || res == null) return; RynthLog.Trace(LogCat.IltChat, $"complete '{req.Command}' in {NowMs - _sentAt} ms: lines={res.Lines.Count} timedOut={res.TimedOut} " + $"unknown={res.UnknownCommand} terminator={(res.TerminatorLine != null)}"); try { req.OnComplete?.Invoke(res); } catch (Exception ex) { RynthLog.Exception(LogCat.IltChat, ex, $"capture callback '{req.Command}'"); } } }