feat(rynthai): infinite-attribute raiser and Server Features gate

Attribute raiser (IltHub/IltAttributeRaiser, drawn by the engine's Skills panel >
Progression): for servers where attributes and vitals go past the retail cap.
Like UB's Leaftide XP Calculator it asks the server: "/xp all" for each stat's
next-level cost, "/attr <abbr> 1" to raise, waiting for the "[ATTR] ... raised"
reply and re-reading the costs before the next raise. Raise now / auto-raise
(every N minutes) spend only on the ticked stats, never below the reserve, in
the set order and mode (priority, round robin, cheapest first), up to 200
raises a run. +1 / +10 send "/attr <abbr> N" directly. Safety: a run decides
only from the costs it just read, ignores a reply about another stat, stops if
the world leaves Server Features or /xp goes off, never runs alongside the
spend-before-/enl loop (either way round), and ends itself after 45 s with no
reply. Chat: /ra hub attr run|stop|costs|status|auto on|off|every|raise.
Saved per character in ilt-hub.json.

Server Features (Settings > Misc, both the engine panel and the legacy ImGui
window): a list of world-name patterns (* wildcard, case-insensitive; default
"InfiniteLeaftide, *Leaftide*") plus a manual override now decide whether the
ILT Hub, Mini Remote, Progression planners and the raiser run, replacing the
hard-coded name check in IltServerOptions.IsIltLikeWorld. The per-character
"Treat this world as ILT" override still counts. Features still follow the
server's own report. Saved in the RynthAi profile and carried by the settings
bridge (FeatureServerNames, ForceServerFeatures, ServerFeaturesStatus).

Tests: RynthAiHostTests AttributeRaiserTests (patterns, list/override, pick
modes, limits, order repair, server line parsing, a full run on the fake host,
gating, and the safety cases). Host suite: 369 tests, only the 2 failures the
untouched base also has when run off Windows (Windows paths).

Pairs with the engine half in rynth/RynthCore PR #2 (Progression tab section, Settings text row).

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
BlankenshipG 2026-10-07 02:24:39 +00:00
commit 8cab76b545
13 changed files with 1133 additions and 13 deletions

View file

@ -0,0 +1,569 @@
// IltAttributeRaiser.cs — Infinite attributes: spend unassigned XP with the server's /attr.
//
// ACECustom (Infinite Leaftide) lets attributes and vitals go past the retail cap, so the
// client's XP tables stop applying. The server is the only source of truth:
// "/xp all" → "[XP] Your XP cost for next 1 Strength level is: 1,234" per stat
// "/attr <abbr> <n>" → "[ATTR] Strength attribute raised by 1, costing 1,234!"
// (Same commands UB's Leaftide XP Calculator drives; it raises one level at a time and
// re-reads the costs after each confirmation, which is what this does too.)
//
// Raise now / auto-raise run one loop: read costs → pick a stat → /attr <abbr> 1 → wait for
// the [ATTR] reply → read costs again → ... until nothing ticked is affordable, a reply is
// not a success, or MaxRaisesPerRun. Only the ticked stats are ever spent on, never below
// the reserve (AttrKeepXp). Which stat comes next depends on the raise mode:
// Priority the first ticked stat in the order that is affordable (fills the top stat)
// RoundRobin one level per ticked stat in order, then around again
// Cheapest the ticked stat with the lowest next-level cost
// Manual +N buttons send "/attr <abbr> N" straight to the server (its reply shows in chat).
//
// Gated on ServerFeatureGate (via IltServerOptions.IsIltLikeWorld) and on the server not
// reporting /xp off. Everything here runs on the plugin pump thread.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal sealed class IltAttributeRaiser
{
/// <summary>Raise modes (IltCharacterState.AttrRaiseMode).</summary>
public enum Mode { Priority = 0, RoundRobin = 1, Cheapest = 2 }
/// <summary>/attr abbreviation, display name, vital?</summary>
public sealed record Stat(string Abbr, string Name, bool Vital);
public static readonly Stat[] Stats =
{
new("str", "Strength", false), new("end", "Endurance", false), new("coo", "Coordination", false),
new("qui", "Quickness", false), new("foc", "Focus", false), new("sel", "Self", false),
new("hea", "Health", true), new("sta", "Stamina", true), new("man", "Mana", true),
};
/// <summary>UB's default priority (Coordination, Quickness, Strength, Endurance, Focus, Self, vitals).</summary>
public static readonly string[] DefaultOrder = { "coo", "qui", "str", "end", "foc", "sel", "hea", "sta", "man" };
public const int MaxRaisesPerRun = 200;
private const long FirstAutoDelayMs = 30_000; // after login / arming, before the first auto run
private const int ReplyTimeoutMs = 8000;
/// <summary>A run with no reply/step for this long is ended (a lost callback must not wedge it).</summary>
private const long StallMs = 45_000;
/// <summary>"Your base Strength is now 250!" / "Your base Maximum Health is now 900!" (older servers / UB wording).</summary>
private static readonly Regex BaseNow = new(@"Your base (?:Maximum )?(\w+) is now (\d+)!", RegexOptions.Compiled | RegexOptions.CultureInvariant);
private readonly IltHubContext _ctx;
// Last known costs (display, and the passive chat reader). A run decides only from _runCosts:
// the costs in the "/xp all" reply read right before that step, never an older value.
private readonly Dictionary<string, long> _cost = new(StringComparer.OrdinalIgnoreCase);
private Dictionary<string, long> _runCosts = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, int> _base = new(StringComparer.OrdinalIgnoreCase);
private long _costsAtMs;
// Run state. _runId guards against a capture that completes after Stop / a newer run.
private enum Phase { Idle, ReadingCosts, Raising }
private Phase _phase;
private int _runId;
private bool _runAuto;
private int _runRaised;
private long _runSpent;
private readonly Dictionary<string, int> _runGains = new(StringComparer.OrdinalIgnoreCase);
private int _rrNext;
private string _raisingAbbr = string.Empty;
private long _raisingCost;
private long _lastProgressMs;
private long _nextAutoAtMs;
private volatile string _status = "Idle.";
private volatile string _lastRun = string.Empty;
public IltAttributeRaiser(IltHubContext ctx) => _ctx = ctx;
/// <summary>
/// True while another XP spender runs (IltProgression's spend-before-/enl loop sends /attr
/// outside the capture queue). Nothing here starts, by hand or on the timer, while it is.
/// </summary>
public Func<bool>? HoldOff { get; set; }
private bool HeldOff
{
get { try { return HoldOff?.Invoke() == true; } catch { return false; } }
}
private IltCharacterState C => _ctx.State.Character;
public bool Running => _phase != Phase.Idle;
// ── Order / selection helpers (also used by IltHubStore.Normalize) ─────────
public static Stat? Find(string keyOrName)
{
if (string.IsNullOrWhiteSpace(keyOrName)) return null;
string k = keyOrName.Trim();
foreach (var s in Stats)
if (s.Abbr.Equals(k, StringComparison.OrdinalIgnoreCase) || s.Name.Equals(k, StringComparison.OrdinalIgnoreCase))
return s;
// Cost lines may say "MaxHealth" / "Maximum Health"; the reply may abbreviate.
string lower = k.ToLowerInvariant().Replace(" ", "");
if (lower.StartsWith("maximum")) lower = lower.Substring(7);
else if (lower.StartsWith("max")) lower = lower.Substring(3);
foreach (var s in Stats)
if (s.Name.Equals(lower, StringComparison.OrdinalIgnoreCase) || lower.StartsWith(s.Abbr, StringComparison.Ordinal))
return s;
return null;
}
/// <summary>All nine abbreviations exactly once: saved order first, missing ones appended, junk dropped.</summary>
public static List<string> RepairOrder(List<string>? order)
{
var result = new List<string>();
foreach (string k in order ?? new List<string>())
{
Stat? s = Find(k);
if (s != null && !result.Contains(s.Abbr)) result.Add(s.Abbr);
}
foreach (string k in DefaultOrder)
if (!result.Contains(k)) result.Add(k);
return result;
}
public static List<string> RepairSelection(List<string>? selection)
{
var result = new List<string>();
foreach (string k in selection ?? new List<string>())
{
Stat? s = Find(k);
if (s != null && !result.Contains(s.Abbr)) result.Add(s.Abbr);
}
return result;
}
/// <summary>
/// Picks the next stat to raise. Pure (unit-testable): <paramref name="order"/> is the
/// priority order, <paramref name="ticked"/> the stats allowed, <paramref name="cost"/> the
/// known next-level costs, <paramref name="budget"/> what may be spent. Round robin starts at
/// <paramref name="rrNext"/> and returns the index after the pick there.
/// </summary>
public static string? Pick(Mode mode, IReadOnlyList<string> order, ICollection<string> ticked,
IReadOnlyDictionary<string, long> cost, long budget, ref int rrNext)
{
if (budget <= 0 || order.Count == 0) return null;
bool Affordable(string k) => ticked.Contains(k) && cost.TryGetValue(k, out long c) && c > 0 && c <= budget;
switch (mode)
{
case Mode.RoundRobin:
for (int step = 0; step < order.Count; step++)
{
int i = ((rrNext % order.Count) + step) % order.Count;
if (!Affordable(order[i])) continue;
rrNext = i + 1;
return order[i];
}
return null;
case Mode.Cheapest:
string? best = null;
long bestCost = long.MaxValue;
foreach (string k in order) // ties go to the higher-priority stat
{
if (!Affordable(k)) continue;
long c = cost[k];
if (c < bestCost) { best = k; bestCost = c; }
}
return best;
default:
foreach (string k in order)
if (Affordable(k)) return k;
return null;
}
}
// ── Gate ──────────────────────────────────────────────────────────────────
/// <summary>Why the raiser can't run here, or null when it can.</summary>
public string? Blocker()
{
if (!_ctx.Options.IsIltLikeWorld)
return "Server features are off for this world (Settings > Misc > Server Features).";
if (_ctx.Options.IsOff(IltFeature.Xp)) return "This server reports /xp as unavailable.";
if (!_ctx.Host.HasInvokeChatParser) return "This engine build can't send chat commands.";
return null;
}
// ── Pump-thread lifecycle ─────────────────────────────────────────────────
/// <summary>Tick. <paramref name="holdOff"/>: another XP spender (auto-enlighten's loop) is running.</summary>
public void Tick(long nowMs, bool holdOff)
{
if (Running && nowMs - _lastProgressMs > StallMs) { Finish($"Stopped: no reply for {StallMs / 1000} s."); return; }
if (!C.AttrAutoRaise || Running || holdOff || HeldOff) return;
if (_nextAutoAtMs == 0) { _nextAutoAtMs = nowMs + FirstAutoDelayMs; return; }
if (nowMs < _nextAutoAtMs) return;
_nextAutoAtMs = nowMs + Math.Clamp(C.AttrAutoRaiseMinutes, 1, 1440) * 60_000L;
if (Blocker() != null || C.AttrRaiseStats.Count == 0) return;
if (_ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp) <= Math.Max(0, C.AttrKeepXp)) return;
Start(auto: true);
}
/// <summary>Passive: keeps costs / base values current when the player runs the commands by hand.</summary>
public void OnChat(string text)
{
var cost = IltParse.XpCost.Match(text);
if (cost.Success)
{
Stat? s = Find(cost.Groups[1].Value);
if (s != null) { _cost[s.Abbr] = IltParse.ParseLeadingLong(cost.Groups[2].Value); _costsAtMs = IltHubContext.NowMs; }
return;
}
var now = BaseNow.Match(text);
if (now.Success)
{
Stat? s = Find(now.Groups[1].Value);
if (s != null && int.TryParse(now.Groups[2].Value, out int v)) _base[s.Abbr] = v;
}
}
public void OnLogout()
{
_runId++;
_phase = Phase.Idle;
_cost.Clear();
_runCosts.Clear();
_base.Clear();
_costsAtMs = 0;
_nextAutoAtMs = 0;
_status = "Idle.";
}
// ── Runs ──────────────────────────────────────────────────────────────────
/// <summary>Starts a spend run (manual "Raise now" or the auto timer).</summary>
public void Start(bool auto)
{
if (Running) return;
string? blocked = Blocker();
if (blocked != null) { _status = blocked; return; }
if (HeldOff) { _status = "Auto-enlighten is spending XP right now; try again when it finishes."; return; }
if (C.AttrRaiseStats.Count == 0) { _status = "Tick at least one attribute or vital to raise."; return; }
_runId++;
_runAuto = auto;
_runRaised = 0;
_runSpent = 0;
_runGains.Clear();
_rrNext = 0;
_runCosts = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
_lastProgressMs = IltHubContext.NowMs;
RynthLog.Trace(LogCat.IltProgression, $"attr raise run {_runId} start (auto={auto}, mode={(Mode)C.AttrRaiseMode}, keep={C.AttrKeepXp}, stats={string.Join(",", C.AttrRaiseStats)})");
ReadCosts(_runId, thenStep: true);
}
public void Stop(string why = "Stopped.")
{
if (!Running) return;
Finish(why);
}
/// <summary>Re-reads the costs only (the panel's Refresh button).</summary>
public void RefreshCosts()
{
if (Running || Blocker() != null) return;
ReadCosts(_runId, thenStep: false);
}
/// <summary>"+N" button: sends "/attr abbr N" as-is; the server's reply shows in chat.</summary>
public void RaiseManual(string key, int levels)
{
Stat? s = Find(key);
if (s == null || levels <= 0) return;
if (Running) { _status = "Wait for the current raise run to finish (or Stop it)."; return; }
string? blocked = Blocker();
if (blocked != null) { _status = blocked; return; }
if (HeldOff) { _status = "Auto-enlighten is spending XP right now; try again when it finishes."; return; }
levels = Math.Min(levels, 1000);
RynthLog.Trace(LogCat.IltProgression, $"attr manual raise {s.Abbr} +{levels}");
int run = _runId;
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = $"/attr {s.Abbr} {levels}",
IsResponseLine = IsAttrReply,
IsTerminator = IsAttrReply,
IdleEndMs = 600,
FirstLineTimeoutMs = ReplyTimeoutMs,
Eat = false,
OnComplete = r =>
{
string reply = r.TerminatorLine ?? r.Lines.FirstOrDefault() ?? (r.TimedOut ? "no reply" : "");
_status = $"{s.Name} +{levels}: {reply}";
if (run == _runId && !Running) ReadCosts(_runId, thenStep: false);
},
});
_status = $"Sent /attr {s.Abbr} {levels}...";
}
private static bool IsAttrReply(string t)
=> t.StartsWith("[ATTR]", StringComparison.OrdinalIgnoreCase) || t.StartsWith("Your base", StringComparison.OrdinalIgnoreCase);
private void ReadCosts(int run, bool thenStep)
{
// A plain refresh doesn't stack on one already queued; a run always gets its own reply.
if (!thenStep && _ctx.Capture.IsPending("/xp all")) return;
if (thenStep)
{
_phase = Phase.ReadingCosts;
if (_runRaised == 0) _status = "Reading XP costs (/xp all)...";
}
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = "/xp all",
IsResponseLine = t => t.StartsWith("[XP]", StringComparison.OrdinalIgnoreCase),
IdleEndMs = 900,
FirstLineTimeoutMs = ReplyTimeoutMs,
Eat = true,
OnComplete = r => Guard(run, () =>
{
if (r.UnknownCommand) { _ctx.Options.Set(IltFeature.Xp, IltTri.Off); if (run == _runId && thenStep) Finish("This server has no /xp command."); return; }
var fresh = new Dictionary<string, long>(StringComparer.OrdinalIgnoreCase);
foreach (string line in r.Lines)
{
var m = IltParse.XpCost.Match(line);
if (!m.Success) continue;
Stat? s = Find(m.Groups[1].Value);
if (s == null) continue;
fresh[s.Abbr] = IltParse.ParseLeadingLong(m.Groups[2].Value);
}
foreach (var kv in fresh) _cost[kv.Key] = kv.Value;
if (fresh.Count > 0) _costsAtMs = IltHubContext.NowMs;
RynthLog.Trace(LogCat.IltProgression, $"attr costs: {fresh.Count} line(s) (timedOut={r.TimedOut})");
if (!thenStep || run != _runId || !Running) return;
if (fresh.Count == 0) { Finish(r.TimedOut ? "No reply to /xp all." : "No cost lines in the /xp all reply."); return; }
_runCosts = fresh; // a stat missing from this reply is not raised this step
_lastProgressMs = IltHubContext.NowMs;
Step(run);
}),
});
}
private void Step(int run)
{
if (run != _runId || !Running) return;
// The world can leave Server Features (or /xp go off) mid-run, and auto-enlighten can start.
if (Blocker() is string blocked) { Finish("Stopped: " + blocked); return; }
if (HeldOff) { Finish("Stopped: auto-enlighten started spending XP."); return; }
if (_runRaised >= MaxRaisesPerRun) { Finish($"Stopped after {MaxRaisesPerRun} raises (runs again later)."); return; }
long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
long budget = have - Math.Max(0, C.AttrKeepXp);
var ticked = new HashSet<string>(C.AttrRaiseStats, StringComparer.OrdinalIgnoreCase);
string? pick = Pick((Mode)Math.Clamp(C.AttrRaiseMode, 0, 2), C.AttrOrder, ticked, _runCosts, budget, ref _rrNext);
if (pick == null)
{
Finish(_runRaised == 0
? (budget <= 0 ? "Nothing to spend (unassigned XP is at or below the reserve)."
: "Nothing affordable among the ticked stats.")
: string.Empty);
return;
}
Stat s = Find(pick)!;
_phase = Phase.Raising;
_raisingAbbr = s.Abbr;
_raisingCost = _runCosts.TryGetValue(s.Abbr, out long c) ? c : 0;
_status = $"Raising {s.Name} +1 (cost {IltParse.Compact(_raisingCost)})...";
_ctx.Capture.Enqueue(new IltChatRequest
{
Command = $"/attr {s.Abbr} 1",
IsResponseLine = IsAttrReply,
IsTerminator = IsAttrReply,
IdleEndMs = 600,
FirstLineTimeoutMs = ReplyTimeoutMs,
Eat = true,
OnComplete = r => Guard(run, () => OnRaiseReply(run, s, r)),
});
}
private void OnRaiseReply(int run, Stat s, IltChatResult r)
{
if (run != _runId || !Running) return;
string reply = r.TerminatorLine ?? r.Lines.FirstOrDefault() ?? string.Empty;
var ok = IltParse.AttrRaised.Match(reply);
var baseNow = BaseNow.Match(reply);
// The reply must be about the stat we raised (another /attr sender could answer first).
if (ok.Success && Find(ok.Groups[1].Value) != s) ok = Match.Empty;
if (baseNow.Success && Find(baseNow.Groups[1].Value) != s) baseNow = Match.Empty;
if (!ok.Success && !baseNow.Success)
{
RynthLog.Trace(LogCat.IltProgression, $"attr raise {s.Abbr}: not a success ('{reply}', timedOut={r.TimedOut}, unknown={r.UnknownCommand})");
Finish(r.UnknownCommand ? "This server has no /attr command."
: reply.Length > 0 ? $"Server: {reply}" : "No reply to /attr.");
return;
}
long spent = ok.Success ? IltParse.ParseLeadingLong(ok.Groups[3].Value) : _raisingCost;
int levels = ok.Success && int.TryParse(ok.Groups[2].Value, out int n) ? n : 1;
if (baseNow.Success && int.TryParse(baseNow.Groups[2].Value, out int v)) _base[s.Abbr] = v;
else if (_base.TryGetValue(s.Abbr, out int b)) _base[s.Abbr] = b + levels;
_runGains[s.Abbr] = (_runGains.TryGetValue(s.Abbr, out int g) ? g : 0) + levels;
_runRaised += levels;
_runSpent += spent;
_cost.Remove(s.Abbr); // its next level costs more; re-read before deciding again
_runCosts.Clear();
_lastProgressMs = IltHubContext.NowMs;
_status = $"Raised {s.Name} (+{_runRaised} this run, {IltParse.Compact(_runSpent)} XP)...";
ReadCosts(run, thenStep: true);
}
/// <summary>Runs a capture callback; an exception ends the run instead of leaving it Running.</summary>
private void Guard(int run, Action body)
{
try { body(); }
catch (Exception ex)
{
RynthLog.Exception(LogCat.IltProgression, ex, "attr raise callback");
if (run == _runId && Running) Finish("Stopped: internal error (see the RynthAi log).");
}
}
private void Finish(string reason)
{
_phase = Phase.Idle;
_runId++; // late callbacks from this run are ignored
string summary = _runRaised > 0
? "Raised " + string.Join(", ", C.AttrOrder.Where(_runGains.ContainsKey).Select(k => $"{Find(k)!.Name} +{_runGains[k]}"))
+ $" ({IltParse.Compact(_runSpent)} XP)."
: string.Empty;
string text = (summary + (reason.Length > 0 ? (summary.Length > 0 ? " " : "") + reason : "")).Trim();
if (text.Length == 0) text = "Done.";
_status = text;
_lastRun = $"{DateTime.Now:t} {(_runAuto ? "auto" : "manual")}: {text}";
RynthLog.Trace(LogCat.IltProgression, $"attr raise run finished: {text}");
if (_runRaised > 0) _ctx.Chat($"[ILT Hub] Attribute raise ({(_runAuto ? "auto" : "manual")}): {text}");
}
// ── Engine Skills panel bridge ────────────────────────────────────────────
/// <summary>Appends <c>"attr":{...}</c> for the Progression tab.</summary>
public void AppendJson(StringBuilder sb)
{
string? blocked = Blocker();
long have = _ctx.Inventory.PlayerQuad(IltInventory.QuadAvailableXp);
long budget = have - Math.Max(0, C.AttrKeepXp);
long now = IltHubContext.NowMs;
sb.Append("\"attr\":{\"off\":").Append(blocked != null ? "true" : "false");
Str(sb, "reason", blocked ?? string.Empty);
sb.Append(",\"auto\":").Append(C.AttrAutoRaise ? "true" : "false")
.Append(",\"every\":").Append(Math.Clamp(C.AttrAutoRaiseMinutes, 1, 1440))
.Append(",\"mode\":").Append(Math.Clamp(C.AttrRaiseMode, 0, 2))
.Append(",\"running\":").Append(Running ? "true" : "false");
Str(sb, "keep", C.AttrKeepXp > 0 ? IltParse.Compact(C.AttrKeepXp) : "0");
// The reserve box edits the exact number (the compact form above is lossy).
Str(sb, "keepFull", IltParse.N0(Math.Max(0, C.AttrKeepXp)));
Str(sb, "status", _status);
Str(sb, "lastRun", _lastRun);
Str(sb, "unassigned", $"Unassigned XP {IltParse.Compact(have)}"
+ (C.AttrKeepXp > 0 ? $" (spendable {IltParse.Compact(Math.Max(0, budget))})" : ""));
string next = !C.AttrAutoRaise ? string.Empty
: Running ? "running"
: _nextAutoAtMs <= 0 ? "soon"
: IltParse.Duration(TimeSpan.FromMilliseconds(Math.Max(0, _nextAutoAtMs - now)));
Str(sb, "next", next);
Str(sb, "costsAge", _costsAtMs == 0 ? "costs not read yet" : $"costs read {Ago(now - _costsAtMs)} ago");
var ticked = new HashSet<string>(C.AttrRaiseStats, StringComparer.OrdinalIgnoreCase);
sb.Append(",\"rows\":[");
bool first = true;
foreach (string k in C.AttrOrder)
{
Stat? s = Find(k);
if (s == null) continue;
if (!first) sb.Append(',');
first = false;
bool known = _cost.TryGetValue(s.Abbr, out long c) && c > 0;
sb.Append('{');
Str(sb, "key", s.Abbr, first: true);
Str(sb, "label", s.Name);
sb.Append(",\"vital\":").Append(s.Vital ? "true" : "false")
.Append(",\"on\":").Append(ticked.Contains(s.Abbr) ? "true" : "false")
.Append(",\"base\":").Append(_base.TryGetValue(s.Abbr, out int b) ? b : -1)
.Append(",\"afford\":").Append(known && c <= budget ? "true" : "false");
Str(sb, "cost", known ? IltParse.Compact(c) : "?");
sb.Append('}');
}
sb.Append("]}");
}
private static string Ago(long ms)
{
long sec = Math.Max(0, ms / 1000);
return sec < 60 ? $"{sec}s" : sec < 3600 ? $"{sec / 60}m" : $"{sec / 3600}h {sec % 3600 / 60}m";
}
private static void Str(StringBuilder sb, string name, string value, bool first = false)
{
if (!first) sb.Append(',');
sb.Append('"').Append(name).Append("\":\"").Append(RynthAiPlugin.JsonEscape(value ?? string.Empty)).Append('"');
}
/// <summary>"prog attr…" commands from the Skills panel. Returns false when the verb isn't ours.</summary>
public bool HandleRemote(string verb, string[] a)
{
string arg1 = a.Length > 1 ? a[1] : string.Empty;
string arg2 = a.Length > 2 ? a[2] : string.Empty;
switch (verb)
{
case "attrauto":
C.AttrAutoRaise = arg1.Equals("on", StringComparison.OrdinalIgnoreCase);
_nextAutoAtMs = C.AttrAutoRaise ? IltHubContext.NowMs + FirstAutoDelayMs : 0;
if (!C.AttrAutoRaise && Running && _runAuto) Stop("Auto-raise turned off.");
return true;
case "attrevery":
if (int.TryParse(arg1, out int min))
{
C.AttrAutoRaiseMinutes = Math.Clamp(min, 1, 1440);
if (C.AttrAutoRaise) _nextAutoAtMs = IltHubContext.NowMs + C.AttrAutoRaiseMinutes * 60_000L;
}
return true;
case "attrmode":
if (int.TryParse(arg1, out int mode)) C.AttrRaiseMode = Math.Clamp(mode, 0, 2);
return true;
case "attrkeep":
if (arg1.Length == 0 || arg1 == "0") C.AttrKeepXp = 0;
else if (IltParse.TryParseAmount(arg1, out long keep)) C.AttrKeepXp = Math.Max(0, keep);
return true;
case "attron":
{
Stat? s = Find(arg1);
if (s == null) return true;
bool on = arg2.Equals("on", StringComparison.OrdinalIgnoreCase);
C.AttrRaiseStats.RemoveAll(x => x.Equals(s.Abbr, StringComparison.OrdinalIgnoreCase));
if (on) C.AttrRaiseStats.Add(s.Abbr);
return true;
}
case "attrmove":
{
Stat? s = Find(arg1);
if (s == null) return true;
int i = C.AttrOrder.FindIndex(x => x.Equals(s.Abbr, StringComparison.OrdinalIgnoreCase));
int j = arg2.Equals("up", StringComparison.OrdinalIgnoreCase) ? i - 1
: arg2.Equals("top", StringComparison.OrdinalIgnoreCase) ? 0 : i + 1;
if (i < 0 || j < 0 || j >= C.AttrOrder.Count || i == j) return true;
string item = C.AttrOrder[i];
C.AttrOrder.RemoveAt(i);
C.AttrOrder.Insert(j, item);
return true;
}
case "attrorderreset":
C.AttrOrder = new List<string>(DefaultOrder);
return true;
case "attrraise":
if (int.TryParse(arg2, out int levels)) RaiseManual(arg1, levels);
return true;
case "attrrun": Start(auto: false); return true;
case "attrstop": Stop(); return true;
case "attrcosts": RefreshCosts(); return true;
}
return false;
}
}

View file

@ -50,7 +50,9 @@ internal sealed class IltHubController
var capture = new IltChatCapture(host);
var inventory = new IltInventory(host, cache);
IltHubContext? ctxRef = null;
var options = new IltServerOptions(host, capture, state, text => ctxRef?.Chat(text));
var options = new IltServerOptions(host, capture, state, text => ctxRef?.Chat(text), settings);
// Settings > Misc shows whether the per-character Hub override is on too.
ServerFeatureGate.HubForceProvider = () => state.ForceLeaftideFeatures;
_ctx = new IltHubContext(host, state, store, capture, options, inventory, settings) { SaveCombatSettings = saveCombatSettings };
ctxRef = _ctx;
_quests = quests;
@ -361,6 +363,7 @@ internal sealed class IltHubController
case "profile": HandleProfile(args.Skip(1).ToArray()); break;
case "suit": HandleSuit(args.Skip(1).ToArray()); break;
case "clap": Gear.ChunkClap.ClapNow(manual: true); break;
case "attr": HandleAttr(args.Skip(1).ToArray()); break;
case "confirm": RunPending(); break;
case "cancel":
_ctx.Chat(_pendingAction != null ? $"[ILT Hub] Cancelled '{_pendingLabel}'." : "[ILT Hub] Nothing to cancel.");
@ -370,6 +373,7 @@ internal sealed class IltHubController
_ctx.Chat("[ILT Hub] /ra hub [show|hide|toggle] (Mini Remote)|refresh|bank|status|force on|off|clap|confirm|cancel");
_ctx.Chat("[ILT Hub] /ra hub open character|quests|pets|banking|gear|games|guardian [show|hide|toggle]");
_ctx.Chat("[ILT Hub] /ra hub profile list|save <name> [shared]|load <name> /ra hub suit list|test|load [name]");
_ctx.Chat("[ILT Hub] /ra hub attr run|stop|costs|status|auto on|off|every <min>|raise <stat> <n> (Skills panel > Progression)");
_ctx.Chat("[ILT Hub] /ra quests [refresh|check <regex>|window [show|hide]|favhud [show|hide]] /ra pets [show|hide]");
_ctx.Chat("[ILT Hub] /ra guardian [window|translate <text>|handin|stop|chat on|off|auto on|off|buy on|off|refresh|status]");
break;
@ -377,6 +381,29 @@ internal sealed class IltHubController
return true;
}
/// <summary>"/ra hub attr ...": the attribute raiser from chat (same verbs as the Progression tab).</summary>
private void HandleAttr(string[] a)
{
var raiser = Progression.Attributes;
string sub = a.Length > 0 ? a[0].ToLowerInvariant() : "status";
switch (sub)
{
case "run": raiser.HandleRemote("attrrun", new[] { "attrrun" }); break;
case "stop": raiser.HandleRemote("attrstop", new[] { "attrstop" }); break;
case "costs": raiser.HandleRemote("attrcosts", new[] { "attrcosts" }); break;
case "auto": raiser.HandleRemote("attrauto", new[] { "attrauto", a.Length > 1 ? a[1] : "off" }); break;
case "every": raiser.HandleRemote("attrevery", new[] { "attrevery", a.Length > 1 ? a[1] : "5" }); break;
case "raise" when a.Length > 2: raiser.HandleRemote("attrraise", new[] { "attrraise", a[1], a[2] }); break;
default:
var c = _ctx.State.Character;
string blocked = raiser.Blocker() ?? "ready";
_ctx.Chat($"[ILT Hub] Attribute raiser: {blocked}; auto={(c.AttrAutoRaise ? $"on every {c.AttrAutoRaiseMinutes}m" : "off")} "
+ $"mode={(IltAttributeRaiser.Mode)c.AttrRaiseMode} keep={IltParse.Compact(c.AttrKeepXp)} "
+ $"stats={(c.AttrRaiseStats.Count > 0 ? string.Join(",", c.AttrOrder.Where(c.AttrRaiseStats.Contains)) : "none ticked")}");
return;
}
}
/// <summary>Applies show / hide / toggle to a section window and says what happened.</summary>
private void OpenSection(IltSection section, string mode)
{

View file

@ -166,6 +166,19 @@ public sealed class IltCharacterState
/// <summary>Spend unassigned XP with /attr before sending /enl (enlightening wipes unspent XP).</summary>
public bool AutoEnlightenSpendXpFirst;
// ── Attribute raiser (IltAttributeRaiser; Skills panel > Progression) ──
/// <summary>Spend unassigned XP on the ticked attributes/vitals every AttrAutoRaiseMinutes.</summary>
public bool AttrAutoRaise;
public int AttrAutoRaiseMinutes = 5;
/// <summary>IltAttributeRaiser.Mode: 0 priority (top of the order first), 1 round robin, 2 cheapest first.</summary>
public int AttrRaiseMode;
/// <summary>Unassigned XP the raiser never spends.</summary>
public long AttrKeepXp;
/// <summary>/attr abbreviations in raise-priority order (all nine; repaired on load).</summary>
public List<string> AttrOrder = new(IltAttributeRaiser.DefaultOrder);
/// <summary>/attr abbreviations the raiser may spend on ("Raise now" and auto-raise).</summary>
public List<string> AttrRaiseStats = new();
/// <summary>Quest Tracker search box contents.</summary>
public string QuestFilter = string.Empty;
public string QbFilter = string.Empty;

View file

@ -101,6 +101,11 @@ internal sealed class IltHubStore
s.Character.QuestFavorites ??= new();
s.Character.QuestFavorites.RemoveAll(string.IsNullOrWhiteSpace);
s.Character.AugTargets = new Dictionary<string, int>(s.Character.AugTargets ?? new(), StringComparer.OrdinalIgnoreCase);
s.Character.AttrOrder = IltAttributeRaiser.RepairOrder(s.Character.AttrOrder);
s.Character.AttrRaiseStats = IltAttributeRaiser.RepairSelection(s.Character.AttrRaiseStats);
s.Character.AttrAutoRaiseMinutes = Math.Clamp(s.Character.AttrAutoRaiseMinutes, 1, 1440);
s.Character.AttrRaiseMode = Math.Clamp(s.Character.AttrRaiseMode, 0, 2);
s.Character.AttrKeepXp = Math.Max(0, s.Character.AttrKeepXp);
s.Character.CharmsSeen = new Dictionary<string, IltCharmSeen>(s.Character.CharmsSeen ?? new(), StringComparer.OrdinalIgnoreCase);
s.Gear ??= new IltGearState();
s.Gear.DispelInclusions ??= new();

View file

@ -7,7 +7,9 @@
// server pops its own Yes/No dialog — the host cannot (and must not) click it.
// Optional auto-enlighten is disarmed every session and needs a hard confirm.
// XP : the Skills panel plans attribute/vital raises from the client's exact XP tables;
// this module only spends unassigned XP ("/attr") before an auto-enlighten.
// this module spends unassigned XP ("/attr") before an auto-enlighten, and owns the
// infinite-attribute raiser (IltAttributeRaiser: server costs from "/xp all", manual
// or timed raises in a chosen order) drawn in the same tab.
using System;
using System.Collections.Generic;
using System.Linq;
@ -104,7 +106,15 @@ internal sealed class IltProgression : IIltFeature
private long _spendLastAt, _spendLastXp;
private Action? _afterSpend;
public IltProgression(IltHubContext ctx) => _ctx = ctx;
/// <summary>Infinite-attribute raiser (Progression tab "Attribute raiser" section).</summary>
public IltAttributeRaiser Attributes { get; }
public IltProgression(IltHubContext ctx)
{
_ctx = ctx;
// Never two /attr spenders at once: the raiser waits while the spend-before-/enl loop runs.
Attributes = new IltAttributeRaiser(ctx) { HoldOff = () => _spending };
}
private IltCharacterState C => _ctx.State.Character;
@ -168,6 +178,7 @@ internal sealed class IltProgression : IIltFeature
RefreshFacts();
}
TickSpend(nowMs);
Attributes.Tick(nowMs, holdOff: _spending);
if (_autoArmed && C.AutoEnlightenEnabled && !_spending
&& nowMs - _lastAutoCheck >= Math.Max(10, C.AutoEnlightenCheckSeconds) * 1000L)
@ -179,6 +190,7 @@ internal sealed class IltProgression : IIltFeature
public bool OnChat(string text)
{
Attributes.OnChat(text);
if (text.Contains("You have become enlightened", StringComparison.OrdinalIgnoreCase)
|| text.Contains("You have risen to a higher tier of enlightenment", StringComparison.OrdinalIgnoreCase))
{
@ -192,6 +204,7 @@ internal sealed class IltProgression : IIltFeature
{
_autoArmed = false;
_spending = false;
Attributes.OnLogout();
lock (_augLevels) _augLevels.Clear();
}
@ -245,6 +258,7 @@ internal sealed class IltProgression : IIltFeature
private void TryAutoEnlighten(long now)
{
if (_ctx.Options.IsOff(IltFeature.Enl)) return;
if (Attributes.Running) return; // the raiser is spending XP; check again next interval
if (now - _lastEnlSentAt < AutoEnlCooldownMs) return;
if (NextEnlBlockers().Count > 0) return;
if (C.AutoEnlightenSpendXpFirst && _unassignedXp > 0)
@ -296,12 +310,14 @@ internal sealed class IltProgression : IIltFeature
// sends edits back as "prog ..." remote commands (HandleRemote). Planner math stays here so
// the Hub and the Skills panel can never disagree. Numbers are preformatted for display.
/// <summary>Appends <c>"aug":{...},"enl":{...}</c> to <paramref name="sb"/>. Pump thread.</summary>
/// <summary>Appends <c>"aug":{...},"enl":{...},"attr":{...}</c> to <paramref name="sb"/>. Pump thread.</summary>
public void AppendSnapshotJson(StringBuilder sb)
{
AppendAugJson(sb);
sb.Append(',');
AppendEnlJson(sb);
sb.Append(',');
Attributes.AppendJson(sb);
}
private void AppendAugJson(StringBuilder sb)
@ -421,7 +437,9 @@ internal sealed class IltProgression : IIltFeature
RynthLog.Trace(LogCat.IltProgression, $"HandleRemote({string.Join(" ", a)})");
string arg1 = a.Length > 1 ? a[1] : string.Empty;
int.TryParse(a.Length > 2 ? a[2] : arg1, out int n);
switch (a[0].ToLowerInvariant())
string verb = a[0].ToLowerInvariant();
if (verb.StartsWith("attr", StringComparison.Ordinal) && Attributes.HandleRemote(verb, a)) return;
switch (verb)
{
case "augload": RequestAugs(); break;
case "augtarget" when a.Length > 2:

View file

@ -3,8 +3,9 @@
// UB gated every Leaftide tool on a single test (WorldName == "InfiniteLeaftide" or a
// Force checkbox). That lies on shards where the operator turned Powerball, /myquests or
// a charm off. This module instead keeps one tri-state bit per feature:
// * World identity: Host.TryGetWorldName (or ForceLeaftideFeatures) decides whether we
// even ASK — it never switches a feature on by itself.
// * World identity: ServerFeatureGate (Settings > Misc server list, or its manual
// override / the Hub's ForceLeaftideFeatures) decides whether we even ASK — it never
// switches a feature on by itself.
// * Preferred source: a structured "/ilt features" dump (ILTFEATURE key=0|1 lines) once
// ACECustom ships it. Today the server prints "Coming Soon", so:
// * Fallback: a one-shot login probe of read-only commands (/bank, /aug, /qb, /pets,
@ -16,6 +17,7 @@
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
namespace RynthCore.Plugin.RynthAi.IltHub;
@ -58,6 +60,7 @@ internal sealed class IltServerOptions
private readonly IltChatCapture _capture;
private readonly IltHubState _state;
private readonly Action<string> _chat;
private readonly Func<LegacyUiSettings?> _settings;
/// <summary>Feeds probe replies to features that can reuse them (e.g. /bank → Banking balances).</summary>
public Action<string, IltChatResult>? ProbeReplyTap;
@ -77,12 +80,14 @@ internal sealed class IltServerOptions
/// </summary>
private const long WorldNameWaitMs = 60000;
public IltServerOptions(RynthCoreHost host, IltChatCapture capture, IltHubState state, Action<string> chat)
public IltServerOptions(RynthCoreHost host, IltChatCapture capture, IltHubState state, Action<string> chat,
Func<LegacyUiSettings?>? settings = null)
{
_host = host;
_capture = capture;
_state = state;
_chat = chat;
_settings = settings ?? (() => null);
}
// ── Identity ────────────────────────────────────────────────────────────
@ -98,15 +103,18 @@ internal sealed class IltServerOptions
}
}
/// <summary>True when the world is (or is declared to be) an ACECustom/ILT shard.</summary>
/// <summary>
/// True when the world is (or is declared to be) an ACECustom/ILT shard: its name is in the
/// Settings > Misc server list, or an override is on (ServerFeatureGate).
/// </summary>
public bool IsIltLikeWorld
{
get
{
if (_state.ForceLeaftideFeatures) return true;
string w = WorldName;
return w.Equals("InfiniteLeaftide", StringComparison.OrdinalIgnoreCase)
|| w.Contains("leaftide", StringComparison.OrdinalIgnoreCase);
LegacyUiSettings? s;
try { s = _settings(); } catch { s = null; }
return ServerFeatureGate.IsEnabled(WorldName, s);
}
}
@ -193,7 +201,7 @@ internal sealed class IltServerOptions
}
if (!IsIltLikeWorld)
{
if (manual) _chat("[ILT Hub] This world is not an ILT/ACECustom shard (enable Force in the Hub to override).");
if (manual) _chat("[ILT Hub] This world is not in the Server Features list (Settings > Misc: add it, or tick the override).");
return;
}

View file

@ -0,0 +1,129 @@
// ServerFeatureGate.cs — Which worlds get the ILT / infinite-attribute features.
//
// One gate for everything ILT-shaped: the ILT Hub and Mini Remote, the Skills panel's
// Progression planners and the attribute raiser. A world is "on" when:
// * its name matches one of the server patterns in Settings > Misc (FeatureServerNames,
// '*' wildcard, case-insensitive; defaults cover InfiniteLeaftide), or
// * the manual override is ticked (Settings > Misc ForceServerFeatures, or the older
// per-character ILT Hub "Treat this world as ILT" / "/ra hub force on").
// The gate only decides whether RynthAi ASKS the server; each feature still follows the
// server's own report (IltServerOptions bits), so a shard with /xp off keeps the raiser off.
using System;
using System.Collections.Generic;
using System.Linq;
using RynthCore.Plugin.RynthAi.LegacyUi;
namespace RynthCore.Plugin.RynthAi.IltHub;
internal static class ServerFeatureGate
{
/// <summary>Patterns a fresh profile starts with (the names the old hard-coded check accepted).</summary>
public static readonly string[] DefaultServerNames = { "InfiniteLeaftide", "*Leaftide*" };
/// <summary>World name of the current session; set by RynthAiPlugin (empty before login).</summary>
public static Func<string>? WorldNameProvider;
/// <summary>The per-character ILT Hub override (ilt-hub.json); set by the Hub while it exists.</summary>
public static Func<bool>? HubForceProvider;
public static string CurrentWorld
{
get
{
try { return (WorldNameProvider?.Invoke() ?? string.Empty).Trim(); }
catch { return string.Empty; }
}
}
/// <summary>The patterns in force: the profile's list, or the defaults when there is no profile yet.</summary>
public static IReadOnlyList<string> Patterns(LegacyUiSettings? settings)
=> settings?.FeatureServerNames ?? (IReadOnlyList<string>)DefaultServerNames;
/// <summary>True when <paramref name="world"/> matches one of <paramref name="patterns"/>.</summary>
public static bool NameMatches(string world, IEnumerable<string>? patterns, out string matched)
{
matched = string.Empty;
if (string.IsNullOrWhiteSpace(world) || patterns == null) return false;
foreach (string p in patterns)
{
if (string.IsNullOrWhiteSpace(p)) continue;
if (!Matches(world.Trim(), p.Trim())) continue;
matched = p.Trim();
return true;
}
return false;
}
/// <summary>Case-insensitive match where '*' stands for any run of characters (anywhere in the pattern).</summary>
public static bool Matches(string text, string pattern)
{
if (pattern.Length == 0) return false;
if (!pattern.Contains('*')) return text.Equals(pattern, StringComparison.OrdinalIgnoreCase);
string[] parts = pattern.Split('*');
int pos = 0;
for (int i = 0; i < parts.Length; i++)
{
string part = parts[i];
if (part.Length == 0) continue;
if (i == 0)
{
if (!text.StartsWith(part, StringComparison.OrdinalIgnoreCase)) return false;
pos = part.Length;
continue;
}
if (i == parts.Length - 1)
return text.Length - pos >= part.Length && text.EndsWith(part, StringComparison.OrdinalIgnoreCase);
int at = text.IndexOf(part, pos, StringComparison.OrdinalIgnoreCase);
if (at < 0) return false;
pos = at + part.Length;
}
return true;
}
/// <summary>Is the override on (Settings > Misc, or the per-character Hub checkbox)?</summary>
public static bool ForceOn(LegacyUiSettings? settings)
{
if (settings?.ForceServerFeatures == true) return true;
try { return HubForceProvider?.Invoke() == true; }
catch { return false; }
}
/// <summary>The gate itself.</summary>
public static bool IsEnabled(string world, LegacyUiSettings? settings)
=> ForceOn(settings) || NameMatches(world, Patterns(settings), out _);
/// <summary>"InfiniteLeaftide, *Leaftide*" → trimmed, de-duplicated list (case-insensitive).</summary>
public static List<string> ParseList(string? text)
{
var list = new List<string>();
if (string.IsNullOrWhiteSpace(text)) return list;
foreach (string raw in text.Split(new[] { ',', ';', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries))
{
string p = raw.Trim();
if (p.Length > 0 && !list.Contains(p, StringComparer.OrdinalIgnoreCase)) list.Add(p);
}
return list;
}
public static string FormatList(IEnumerable<string>? patterns)
=> patterns == null ? string.Empty : string.Join(", ", patterns.Where(p => !string.IsNullOrWhiteSpace(p)));
/// <summary>One status line for Settings > Misc: the world, whether the features are on, and why.</summary>
public static string Describe(LegacyUiSettings? settings)
{
string world = CurrentWorld;
string shown = world.Length > 0 ? $"'{world}'" : "(not logged in)";
if (settings?.ForceServerFeatures == true)
return $"This world {shown}: ON - manual override.";
if (NameMatches(world, Patterns(settings), out string matched))
return $"This world {shown}: ON - matches '{matched}'.";
bool hubForce;
try { hubForce = HubForceProvider?.Invoke() == true; } catch { hubForce = false; }
if (hubForce)
return $"This world {shown}: ON - the ILT Hub's \"Treat this world as ILT\" override.";
return world.Length > 0
? $"This world {shown}: OFF - not in the list. Add it, or tick the override."
: "This world: not logged in yet.";
}
}

View file

@ -11,6 +11,8 @@ internal sealed class LegacyAdvancedSettingsUi
// Scratch buffer for the "never attack" name entry box.
private string _newBlacklistName = "";
// Server Features list being edited (committed on Enter / focus loss); null = show the saved list.
private string? _serverNamesEdit;
private static readonly string[] AttackHeights = { "Low", "Medium", "High" };
private static readonly string[] LootOwnershipModes = { "My Kills Only", "Fellowship Kills", "All Corpses" };
@ -66,6 +68,35 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.End();
}
/// <summary>Settings > Misc "Server Features": the world list and the manual override (ServerFeatureGate).</summary>
private void RenderServerFeatures()
{
ImGui.Text("Server Features (ILT / infinite attributes)");
ImGui.TextDisabled(IltHub.ServerFeatureGate.Describe(_settings));
string text = _serverNamesEdit ?? IltHub.ServerFeatureGate.FormatList(_settings.FeatureServerNames);
ImGui.SetNextItemWidth(320);
bool enter = ImGui.InputTextWithHint("Servers##featureServers", "InfiniteLeaftide, *Leaftide*", ref text, 512,
ImGuiInputTextFlags.EnterReturnsTrue);
if (ImGui.IsItemActive() || enter) _serverNamesEdit = text;
if ((enter || ImGui.IsItemDeactivatedAfterEdit()) && _serverNamesEdit != null)
{
_settings.FeatureServerNames = IltHub.ServerFeatureGate.ParseList(_serverNamesEdit);
_serverNamesEdit = null;
}
else if (!ImGui.IsItemActive()) _serverNamesEdit = null;
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Comma-separated world names that turn on the ILT Hub, the Progression\n" +
"planners and the attribute raiser. * is a wildcard (*Leaftide* matches any\n" +
"name containing Leaftide). Case does not matter.");
ImGui.Checkbox("Force enable on this server (manual override)", ref _settings.ForceServerFeatures);
if (ImGui.IsItemHovered())
ImGui.SetTooltip("Turn the features on for whatever world you are on, even if it is not in the list.\n" +
"Each feature still follows what the server reports (for example /xp off keeps\n" +
"the attribute raiser off).");
}
private void RenderVendoring()
{
ImGui.Text("AutoVendor (UtilityBelt)");
@ -266,6 +297,10 @@ internal sealed class LegacyAdvancedSettingsUi
ImGui.SetTooltip("Automatically starts dungeon patrol when RynthAi loads.");
ImGui.Checkbox("Enable Raycasting", ref _settings.EnableRaycasting);
ImGui.Separator();
ImGui.Spacing();
RenderServerFeatures();
ImGui.Separator();
ImGui.Spacing();
ImGui.Text("Missile Arc Velocities (m/s)");

View file

@ -934,6 +934,9 @@ internal sealed partial class LegacyDashboardRenderer
StartMacroOnLogin = s.StartMacroOnLogin,
PatrolOnLogin = s.PatrolOnLogin,
YieldToVTank = s.YieldToVTank,
FeatureServerNames = IltHub.ServerFeatureGate.FormatList(s.FeatureServerNames),
ForceServerFeatures = s.ForceServerFeatures,
ServerFeaturesStatus = IltHub.ServerFeatureGate.Describe(s),
EnableRaycasting = s.EnableRaycasting,
UseArcs = s.UseArcs,
BowArcVelocity = s.BowArcVelocity,
@ -1142,6 +1145,9 @@ internal sealed partial class LegacyDashboardRenderer
s.StartMacroOnLogin = p.StartMacroOnLogin;
s.PatrolOnLogin = p.PatrolOnLogin;
s.YieldToVTank = p.YieldToVTank;
if (p.FeatureServerNames != null)
s.FeatureServerNames = IltHub.ServerFeatureGate.ParseList(p.FeatureServerNames);
s.ForceServerFeatures = p.ForceServerFeatures;
s.EnableRaycasting = p.EnableRaycasting;
s.UseArcs = p.UseArcs;
s.BowArcVelocity = p.BowArcVelocity;
@ -1771,6 +1777,8 @@ internal sealed partial class LegacyDashboardRenderer
dst.StartMacroOnLogin = tmp.StartMacroOnLogin;
dst.PatrolOnLogin = tmp.PatrolOnLogin;
dst.YieldToVTank = tmp.YieldToVTank;
dst.FeatureServerNames = tmp.FeatureServerNames ?? new(IltHub.ServerFeatureGate.DefaultServerNames);
dst.ForceServerFeatures = tmp.ForceServerFeatures;
dst.ShowTerrainPassability = tmp.ShowTerrainPassability;
dst.GiveQueueIntervalMs = tmp.GiveQueueIntervalMs;
dst.SpellCastIntervalMs = tmp.SpellCastIntervalMs;

View file

@ -241,6 +241,15 @@ public sealed class LegacyUiSettings
/// </summary>
public bool YieldToVTank = true;
/// <summary>
/// Server Features (Settings > Misc): world names that turn on the ILT Hub, the Skills
/// panel's Progression planners and the attribute raiser ('*' wildcard, case-insensitive).
/// See IltHub/ServerFeatureGate. A profile saved before this existed loads the defaults.
/// </summary>
public List<string> FeatureServerNames { get; set; } = new(IltHub.ServerFeatureGate.DefaultServerNames);
/// <summary>Manual override: treat the current world as feature-enabled whatever its name.</summary>
public bool ForceServerFeatures;
public int BlacklistAttempts = 3;
public int BlacklistTimeoutSec = 30;
/// <summary>
@ -794,6 +803,11 @@ public sealed class SettingsBridgePayload
public bool PatrolOnLogin { get; set; }
// Absent from an older engine's payload: must not read as off.
public bool YieldToVTank { get; set; } = true;
// Server Features: the list travels as one comma-separated string (the engine's text row).
public string FeatureServerNames { get; set; } = string.Join(", ", IltHub.ServerFeatureGate.DefaultServerNames);
public bool ForceServerFeatures { get; set; }
// Read-only status line for Settings > Misc (ignored when the engine sends it back).
public string ServerFeaturesStatus { get; set; } = string.Empty;
public bool EnableRaycasting { get; set; }
public bool UseArcs { get; set; }
public float BowArcVelocity { get; set; }

View file

@ -101,6 +101,9 @@ public sealed partial class RynthAiPlugin
return;
var dash = _dashboard;
// Settings > Misc "Server Features" status line names the current world.
IltHub.ServerFeatureGate.WorldNameProvider ??=
() => Host.HasGetWorldName && Host.TryGetWorldName(out string w) ? w ?? string.Empty : string.Empty;
_iltHub = new IltHub.IltHubController(Host, dash.CharFolder,
() => _objectCache, () => dash.Settings, () => _questTracker,
() => dash.SaveSettings());
@ -153,6 +156,7 @@ public sealed partial class RynthAiPlugin
try { _iltHub?.OnLogout(); }
catch (Exception ex) { RynthLog.Exception(LogCat.IltHub, ex, "logout"); }
_iltHub = null;
IltHub.ServerFeatureGate.HubForceProvider = null;
try { _huds?.OnLogout(); }
catch (Exception ex) { RynthLog.Exception(LogCat.Huds, ex, "logout"); }
_huds = null;

View file

@ -64,6 +64,7 @@ internal static class Program
LootAddItemTests.Register(runner);
GiveTests.Register(runner);
DungeonMapBakeTests.Register(runner);
AttributeRaiserTests.Register(runner);
return runner.Run("RynthAi host tests", args.Length > 0 ? args[0] : null);
}
}

View file

@ -0,0 +1,289 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using RynthCore.Plugin.RynthAi.IltHub;
using RynthCore.Plugin.RynthAi.LegacyUi;
using RynthCore.PluginSdk;
using RynthCore.RynthAiHostTests.Fakes;
using RynthCore.RynthAiTests.Harness;
namespace RynthCore.RynthAiHostTests.Tests;
// Server Features gate + the infinite-attribute raiser (2026-10-06). The gate decides from
// Settings > Misc (world-name patterns, manual override) whether the ILT features ask the
// server at all; the raiser reads "/xp all" costs and spends unassigned XP with "/attr <abbr> 1"
// on the ticked stats, in the chosen order, never below the reserve.
internal static class AttributeRaiserTests
{
private const uint Player = 0x50000C01;
public static void Register(Runner r)
{
r.Add("server features: name patterns (exact, wildcards, case)", Patterns);
r.Add("server features: list parsing and the override", ListAndOverride);
r.Add("attr raiser: pick by mode (priority, round robin, cheapest)", PickModes);
r.Add("attr raiser: pick respects ticks, reserve and unknown costs", PickLimits);
r.Add("attr raiser: order repair and stat names from server lines", OrderAndNames);
r.Add("attr raiser: a run reads costs, raises in order, stops when nothing is affordable", FullRun);
r.Add("attr raiser: off when the world is not in the Server Features list", GatedOff);
r.Add("attr raiser: safety (stale costs, another stat's reply, gate off mid-run, held off)", Safety);
}
private static void Patterns()
{
Check.True(ServerFeatureGate.Matches("InfiniteLeaftide", "InfiniteLeaftide"), "exact");
Check.True(ServerFeatureGate.Matches("infiniteleaftide", "InfiniteLeaftide"), "exact ignores case");
Check.False(ServerFeatureGate.Matches("InfiniteLeaftide2", "InfiniteLeaftide"), "exact means the whole name");
Check.True(ServerFeatureGate.Matches("Leaftide Test", "*Leaftide*"), "contains");
Check.True(ServerFeatureGate.Matches("MyLeaftide", "*tide"), "ends with");
Check.True(ServerFeatureGate.Matches("Leaftide-PTR", "Leaf*"), "starts with");
Check.True(ServerFeatureGate.Matches("Aelrynth Infinite", "Ael*Inf*"), "two wildcards");
Check.False(ServerFeatureGate.Matches("Aelrynth", "*Leaftide*"), "no match");
Check.False(ServerFeatureGate.Matches("ab", "a*bb"), "the end part must fit after the start");
Check.True(ServerFeatureGate.NameMatches("Aelrynth", new[] { "", "InfiniteLeaftide", "aelrynth" }, out string m) && m == "aelrynth",
"NameMatches reports the pattern that matched");
Check.False(ServerFeatureGate.NameMatches("", ServerFeatureGate.DefaultServerNames, out _), "an unknown world never matches");
}
private static void ListAndOverride()
{
var list = ServerFeatureGate.ParseList(" InfiniteLeaftide , *Leaftide*;Aelrynth,,aelrynth ");
Check.Eq(string.Join("|", list), "InfiniteLeaftide|*Leaftide*|Aelrynth", "trimmed, split on , and ;, de-duplicated ignoring case");
Check.Eq(ServerFeatureGate.FormatList(list), "InfiniteLeaftide, *Leaftide*, Aelrynth", "formatted back for the text box");
var s = new LegacyUiSettings();
Check.True(s.FeatureServerNames.Contains("InfiniteLeaftide"), "a fresh profile starts with the defaults");
Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s), "the default list covers InfiniteLeaftide");
Check.False(ServerFeatureGate.IsEnabled("Aelrynth", s), "another world is off by default");
s.ForceServerFeatures = true;
Check.True(ServerFeatureGate.IsEnabled("Aelrynth", s), "the manual override turns it on anywhere");
s.ForceServerFeatures = false;
s.FeatureServerNames = new List<string> { "Aelrynth" };
Check.True(ServerFeatureGate.IsEnabled("aelrynth", s), "a world added to the list is on");
Check.False(ServerFeatureGate.IsEnabled("InfiniteLeaftide", s), "a world removed from the list is off");
Check.True(ServerFeatureGate.IsEnabled("InfiniteLeaftide", null), "no profile yet: the defaults apply");
}
private static readonly string[] Order = { "coo", "qui", "str", "end", "foc", "sel", "hea", "sta", "man" };
private static void PickModes()
{
var cost = new Dictionary<string, long> { ["coo"] = 500, ["qui"] = 300, ["str"] = 100 };
var ticked = new HashSet<string> { "coo", "qui", "str" };
int rr = 0;
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, ticked, cost, 1000, ref rr), "coo",
"priority: the first affordable stat in the order");
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, ticked, cost, 400, ref rr), "qui",
"priority: skips a stat it can't afford");
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, ticked, cost, 1000, ref rr), "str",
"cheapest: the lowest next-level cost");
var tie = new Dictionary<string, long> { ["coo"] = 100, ["str"] = 100 };
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, ticked, tie, 1000, ref rr), "coo",
"cheapest: a tie goes to the higher-priority stat");
rr = 0;
var picks = new List<string?>();
for (int i = 0; i < 4; i++) picks.Add(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 1000, ref rr));
Check.Eq(string.Join(",", picks), "coo,qui,str,coo", "round robin: one each in order, then around again");
rr = 0;
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 400, ref rr), "qui",
"round robin: an unaffordable stat is passed over");
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.RoundRobin, Order, ticked, cost, 400, ref rr), "str",
"round robin: carries on from the last pick");
}
private static void PickLimits()
{
var cost = new Dictionary<string, long> { ["coo"] = 500, ["qui"] = 300 };
int rr = 0;
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string>(), cost, 10_000, ref rr),
"nothing ticked: nothing raised");
Check.Eq(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string> { "qui" }, cost, 10_000, ref rr), "qui",
"an unticked stat is never spent on, even at the top of the order");
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string> { "coo", "qui" }, cost, 0, ref rr),
"no budget (XP at or below the reserve): nothing raised");
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Priority, Order, new HashSet<string> { "str" }, cost, 10_000, ref rr),
"a stat whose cost wasn't read is not raised blind");
var zero = new Dictionary<string, long> { ["coo"] = 0 };
Check.Null(IltAttributeRaiser.Pick(IltAttributeRaiser.Mode.Cheapest, Order, new HashSet<string> { "coo" }, zero, 10_000, ref rr),
"a zero cost (unparsed) is not raised");
}
private static void OrderAndNames()
{
var repaired = IltAttributeRaiser.RepairOrder(new List<string> { "sel", "bogus", "Self", "Strength", "hea" });
Check.Eq(string.Join(",", repaired), "sel,str,hea,coo,qui,end,foc,sta,man",
"saved order kept, duplicates/junk dropped, missing stats appended in the default order");
Check.Eq(IltAttributeRaiser.RepairOrder(null).Count, 9, "a missing order becomes the default");
Check.Eq(string.Join(",", IltAttributeRaiser.RepairSelection(new List<string> { "Coordination", "coo", "x" })), "coo",
"selection: names map to abbreviations, duplicates and junk dropped");
Check.Eq(IltAttributeRaiser.Find("MaxHealth")?.Abbr, "hea", "cost line 'MaxHealth'");
Check.Eq(IltAttributeRaiser.Find("Maximum Stamina")?.Abbr, "sta", "'Maximum Stamina'");
Check.Eq(IltAttributeRaiser.Find("Self")?.Abbr, "sel", "Self");
Check.Eq(IltAttributeRaiser.Find("qui")?.Abbr, "qui", "abbreviation");
Check.Null(IltAttributeRaiser.Find("Luck"), "unknown names are rejected");
var cost = IltParse.XpCost.Match("[XP] Your XP cost for next 1 Coordination level is: 12,345,678");
Check.True(cost.Success && cost.Groups[1].Value == "Coordination" && IltParse.ParseLeadingLong(cost.Groups[2].Value) == 12_345_678,
"the /xp all cost line parses");
var raised = IltParse.AttrRaised.Match("[ATTR] Quickness attribute raised by 1, costing 9,876!");
Check.True(raised.Success && raised.Groups[1].Value == "Quickness" && raised.Groups[2].Value == "1"
&& IltParse.ParseLeadingLong(raised.Groups[3].Value) == 9876, "the /attr success line parses");
}
// ── The loop on the fake host ─────────────────────────────────────────────
private static IltHubController NewHub(string world, LegacyUiSettings settings, string folder, out RynthCoreHost host)
{
FakeHost.Reset();
FakeHost.WorldName = world;
host = FakeHost.Create(Player);
string dir = Path.Combine(Program.TempRoot, folder);
Directory.CreateDirectory(dir);
return new IltHubController(host, dir, () => null, () => settings, () => null, () => { });
}
/// <summary>Ticks the hub until <paramref name="done"/> or the timeout (the chat queue spaces sends by real time).</summary>
private static bool TickUntil(IltHubController hub, Func<bool> done, int timeoutMs = 6000)
{
var until = DateTime.UtcNow.AddMilliseconds(timeoutMs);
while (DateTime.UtcNow < until)
{
hub.Tick();
if (done()) return true;
Thread.Sleep(25);
}
return false;
}
private static void Reply(IltHubController hub, params string[] lines)
{
foreach (string l in lines) hub.OnChat(l);
}
private static void FullRun()
{
var settings = new LegacyUiSettings();
var hub = NewHub("InfiniteLeaftide", settings, "attr-run", out _);
var c = hub.State.Character;
c.AttrRaiseStats = new List<string> { "coo", "qui" };
c.AttrRaiseMode = (int)IltAttributeRaiser.Mode.Priority;
c.AttrKeepXp = 200;
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 2_500;
var raiser = hub.Progression.Attributes;
Check.Null(raiser.Blocker(), "an ILT world with /xp not reported off: the raiser can run");
raiser.Start(auto: false);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "a run starts by reading the costs");
Reply(hub, "[XP] Your XP cost for next 1 Strength level is: 50",
"[XP] Your XP cost for next 1 Coordination level is: 1,000",
"[XP] Your XP cost for next 1 Quickness level is: 1,200");
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr coo 1")),
"priority: Coordination first (Strength is cheaper but not ticked)");
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 1_500;
Reply(hub, "[ATTR] Coordination attribute raised by 1, costing 1,000!");
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Count(x => x == "/xp all") >= 2), "costs are read again after each raise");
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 2,000",
"[XP] Your XP cost for next 1 Quickness level is: 1,200");
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr qui 1")),
"Coordination now costs more than the spendable 1,300: Quickness next");
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 300;
Reply(hub, "[ATTR] Quickness attribute raised by 1, costing 1,200!");
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Count(x => x == "/xp all") >= 3), "third cost read");
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 2,000",
"[XP] Your XP cost for next 1 Quickness level is: 1,500");
Check.True(TickUntil(hub, () => !raiser.Running), "nothing affordable above the reserve: the run ends");
Check.Eq(FakeHost.ChatCommands.Count(x => x.StartsWith("/attr", StringComparison.Ordinal)), 2, "exactly two raises sent");
string summary = FakeHost.Chat.LastOrDefault(x => x.Contains("Attribute raise")) ?? "";
Check.True(summary.Contains("Coordination +1") && summary.Contains("Quickness +1") && summary.Contains("2.2K"),
$"the run reports what it raised and spent (got '{summary}')");
var sb = new System.Text.StringBuilder();
raiser.AppendJson(sb);
string json = sb.ToString();
Check.True(json.StartsWith("\"attr\":{\"off\":false", StringComparison.Ordinal), "the Progression snapshot carries the raiser");
Check.True(json.Contains("\"key\":\"coo\"") && json.Contains("\"cost\":\"2.0K\""), "rows carry the last read costs");
System.Text.Json.JsonDocument.Parse("{" + json + "}").Dispose(); // throws if the JSON is malformed
// Panel commands: order, ticks, mode, reserve, a manual +10.
raiser.HandleRemote("attrmove", new[] { "attrmove", "qui", "up" });
Check.Eq(c.AttrOrder[0], "qui", "attrmove up");
raiser.HandleRemote("attron", new[] { "attron", "str", "on" });
Check.True(c.AttrRaiseStats.Contains("str"), "attron");
raiser.HandleRemote("attrmode", new[] { "attrmode", "2" });
Check.Eq(c.AttrRaiseMode, 2, "attrmode");
raiser.HandleRemote("attrkeep", new[] { "attrkeep", "1.5b" });
Check.Eq(c.AttrKeepXp, 1_500_000_000L, "attrkeep takes k/m/b suffixes");
raiser.HandleRemote("attrraise", new[] { "attrraise", "foc", "10" });
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/attr foc 10")), "a manual +10 sends /attr foc 10");
}
private static void Safety()
{
var settings = new LegacyUiSettings();
var hub = NewHub("InfiniteLeaftide", settings, "attr-safety", out _);
var c = hub.State.Character;
var raiser = hub.Progression.Attributes;
c.AttrRaiseStats = new List<string> { "coo", "qui" };
FakeHost.Quads[(Player, IltInventory.QuadAvailableXp)] = 10_000;
// A cost seen earlier (passively, here by a hand-typed /xp all) is not trusted by a run:
// only the costs in the run's own read count.
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 100");
raiser.Start(auto: false);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "run reads costs");
Reply(hub, "[XP] Your XP cost for next 1 Quickness level is: 500"); // Coordination missing this time
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Any(x => x.StartsWith("/attr", StringComparison.Ordinal))), "a raise is sent");
Check.Eq(FakeHost.ChatCommands.First(x => x.StartsWith("/attr", StringComparison.Ordinal)), "/attr qui 1",
"Coordination's older cost is not used when this read left it out");
// A reply about another stat (some other /attr sender) is not taken as our success.
Reply(hub, "[ATTR] Strength attribute raised by 1, costing 50!");
Check.True(TickUntil(hub, () => !raiser.Running), "a reply about another stat ends the run");
Check.Eq(FakeHost.ChatCommands.Count(x => x.StartsWith("/attr", StringComparison.Ordinal)), 1, "and nothing more is raised");
Check.False(FakeHost.Chat.Any(x => x.Contains("Attribute raise")), "and no raise is reported");
// The world leaves Server Features mid-run: the next step stops.
FakeHost.ChatCommands.Clear();
raiser.Start(auto: false);
Check.True(TickUntil(hub, () => FakeHost.ChatCommands.Contains("/xp all")), "second run reads costs");
settings.FeatureServerNames = new List<string> { "SomewhereElse" };
Reply(hub, "[XP] Your XP cost for next 1 Coordination level is: 100");
Check.True(TickUntil(hub, () => !raiser.Running), "the run stops once the world is off");
Check.False(FakeHost.ChatCommands.Any(x => x.StartsWith("/attr", StringComparison.Ordinal)), "no raise after the gate closed");
settings.FeatureServerNames = new List<string>(ServerFeatureGate.DefaultServerNames);
// Another XP spender running: neither Raise now nor +N starts.
bool spending = true;
raiser.HoldOff = () => spending;
FakeHost.ChatCommands.Clear();
raiser.Start(auto: false);
raiser.RaiseManual("coo", 1);
TickUntil(hub, () => false, 600);
Check.False(raiser.Running, "held off: Raise now doesn't start");
Check.False(FakeHost.ChatCommands.Any(), "held off: nothing is sent");
}
private static void GatedOff()
{
var settings = new LegacyUiSettings();
var hub = NewHub("Aelrynth", settings, "attr-gated", out _);
var raiser = hub.Progression.Attributes;
hub.State.Character.AttrRaiseStats = new List<string> { "coo" };
Check.NotNull(raiser.Blocker(), "a world not in the list: blocked");
raiser.Start(auto: false);
TickUntil(hub, () => false, 600);
Check.False(FakeHost.ChatCommands.Any(), "nothing is sent off a feature world");
settings.FeatureServerNames.Add("Aelrynth");
Check.Null(raiser.Blocker(), "adding the world to Server Features unblocks it");
settings.FeatureServerNames.Remove("Aelrynth");
settings.ForceServerFeatures = true;
Check.Null(raiser.Blocker(), "so does the manual override");
}
}