diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
index 487d8d6..38bc605 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/BuffManager.cs
@@ -390,71 +390,55 @@ public partial class BuffManager : IDisposable
return _healthFellAt != DateTime.MinValue && (now - _healthFellAt).TotalMilliseconds < HealthFellCountsMs;
}
- // ── Buffs wait for the fight (2026-11-07, every buff since 2026-11-20) ──
+ // ── Buffs in a fight (2026-11-07; 2026-11-20; the rule since 2026-12-01) ──
// 2026-11-07: a character cast four weapon auras (2.4 s each) one after another with a golem's Force Bolts
// hitting him and his health under Heal At; the emergency heal then waited for the last aura's cast and
- // he died. Then only health under Heal At held the buffs back.
- // 2026-11-20, DreamWeave Thread 0x5C47: a Virindi dispelled Robustify and Executor's Blessing in the
- // middle of a fight. RynthAi put his hand wraps away for the staff and cast them with a Rager on him and
- // five monsters in range, and he died 4 s later. The owner: "dispel makes sense... but i think we should
- // clear the mobs nearby before we rebuff". So in a fight (a monster within Monster Range, or health
- // falling: InCombatNow) no new buff cast starts, whatever the health; one already sent finishes. The
- // arbiter doesn't give Buffing the tick for buffs, so combat goes first, and the heals (a vital recharge
- // keeps its slot). A rebuff run under way stops between two casts and carries on once the fight is over.
- // The same for a dispelled buff and one at Rebuff With. A Force Rebuff the player asked for still goes in a
- // fight (their own ask), except under Heal At, as before.
+ // he died. Since then no buff cast starts in a fight while health is under Heal At: the heals go first.
+ // 2026-11-20 (DreamWeave Thread 0x5C47, two buffs dispelled mid-fight and recast with a Rager on him):
+ // every buff waited for the fight's end. At a spot that never empties that never came (2026-11-25,
+ // R-20261125-130039-e3bc: buffs waited almost 7 hours, ran out, the character died); a 2-minute cap
+ // followed. Since 2026-12-01: once a buff is under the set timer, the rebuff starts regardless; the idle
+ // rebuff is the higher timer and picks quiet moments, and when a monster comes the fight goes on until a
+ // buff reaches the regular timer.
+ // So: a buff at or under Rebuff With (RebuffSecondsRemaining), or gone, is rebuffed now, fight or not;
+ // a run it starts carries on in a fight. Only health under Heal At in a fight holds a cast back. The
+ // earlier line (Rebuff When Idle's margin) is used only while idle (IdleTopOffNow); an early run stops
+ // when a monster comes (EndIdleTopOffRun), and in a fight a buff is due only at Rebuff With again.
+ // Dispels (2026-12-01, an option): with Recast dispelled buffs in a fight
+ // (RecastDispelledInFight) off, a fight with only gone buffs due (none present and at Rebuff With) waits
+ // for its end, as 2026-11-20; a run under way, or one a buff at Rebuff With starts, still goes.
private bool _buffFightWaitOn; // a wait with buffs to cast was logged
private DateTime _buffFightWaitSince = DateTime.MinValue;
private DateTime _buffFightNeedCheckedAt = DateTime.MinValue;
+ private bool _buffFightRunLogged; // "rebuffing in the fight" logged for this fight
- // ── A fight that never ends (2026-11-25, R-20261125-130039-e3bc) ──
- // Conquest, a spot that respawns constantly with Monster Range 10: never more than ~15 s without a
- // monster in range, so the wait above never ended. Buffs waited 24,811 s (almost 7 hours), ran out,
- // and the character died several times; Force Rebuff (cast in the fight) worked. Now once buffs
- // have waited BuffFightWaitMaxSec through one unbroken fight, a full pass goes in it, the way a Force
- // Rebuff does: never while health is under Heal At, and it stops once nothing is due. A short fight
- // (the 11-20 Thread dispel case) is over long before that and still waits.
- internal const int BuffFightWaitMaxSec = 120;
- private bool _buffFightPass; // a pass let through a fight that doesn't end
- private bool _buffFightPassNeed; // NeedsAnyBuff, asked at most once a second during a pass
- private DateTime _buffFightPassCheckedAt = DateTime.MinValue;
-
- /// True in a fight: no new buff cast. A Force Rebuff the player asked for waits only while health
- /// is under Heal At. Logs the start (when there are buffs to cast) and the end of each wait.
+ /// True when no new buff cast may start: in a fight with health under Heal At. Logs the start
+ /// (when there are buffs to cast) and the end of each wait, and once per fight a rebuff that goes in it.
public bool BuffsWaitForFight()
{
bool fight = InCombatNow();
bool hurt = _settings.HealAt > 0 && _vitals.HealthPct > 0 && _vitals.HealthPct < _settings.HealAt;
- bool playersOwn = _isForceRebuffing && !_isAutoBatchRebuff;
DateTime now = RynthClock.Now;
- if (_buffFightPass)
- {
- // The pass ends with the fight or once nothing is due.
- if ((now - _buffFightPassCheckedAt).TotalMilliseconds >= 1000)
- {
- _buffFightPassCheckedAt = now;
- _buffFightPassNeed = NeedsAnyBuff();
- }
- if (!fight || !_buffFightPassNeed)
- {
- _buffFightPass = false;
- _host.Log($"[Buff] the rebuff pass in the fight is done ({(fight ? "nothing left to cast" : "the fight is over")}).");
- }
- }
- else if (fight && _buffFightWaitOn && (now - _buffFightWaitSince).TotalSeconds >= BuffFightWaitMaxSec)
- {
- _buffFightPass = true;
- _buffFightPassNeed = true;
- _buffFightPassCheckedAt = now;
- _host.Log($"[Buff] buffs have waited {(now - _buffFightWaitSince).TotalSeconds:0} s for a fight that doesn't end (a monster always within range): " +
- "a full rebuff pass goes now, in the fight, as Force Rebuff does (never under Heal At).");
- }
- bool wait = fight && (!(playersOwn || _buffFightPass) || hurt);
+ if (!fight) _buffFightRunLogged = false;
+ bool dispelWait = fight && !hurt && !_settings.RecastDispelledInFight && !_isForceRebuffing
+ && NeedsAnyBuff() && !AnyBuffOnTimer(BuildDynamicBuffList(), _settings.RebuffSecondsRemaining);
+ bool wait = fight && (hurt || dispelWait);
if (!wait)
{
if (_buffFightWaitOn)
- _host.Log($"[Buff] buffs go on: {(!fight ? "the fight is over" : _buffFightPass ? "the fight doesn't end, so they go in it" : $"health {_vitals.HealthPct}%, back over Heal At, for the Force Rebuff you asked for")} (they waited {(now - _buffFightWaitSince).TotalSeconds:0} s).");
+ _host.Log($"[Buff] buffs go on: {(!fight ? "the fight is over" : $"health {_vitals.HealthPct}%, back over Heal At")} (they waited {(now - _buffFightWaitSince).TotalSeconds:0} s).");
_buffFightWaitOn = false;
+ if (fight && !_buffFightRunLogged && (_isForceRebuffing || (now - _buffFightNeedCheckedAt).TotalMilliseconds >= 1000))
+ {
+ _buffFightNeedCheckedAt = now;
+ if (_isForceRebuffing || NeedsAnyBuff())
+ {
+ _buffFightRunLogged = true;
+ _host.Log(_isForceRebuffing && !_isAutoBatchRebuff
+ ? $"[Buff] rebuffing in the fight ({FightWhy(false)}): the Force Rebuff you asked for."
+ : $"[Buff] rebuffing in the fight ({FightWhy(false)}): a buff is at or under Rebuff With ({_settings.RebuffSecondsRemaining} s) or gone, so it goes now.");
+ }
+ }
return false;
}
// Logged only when something is held back (a fight with every buff up isn't a wait); asked once a second.
@@ -465,7 +449,9 @@ public partial class BuffManager : IDisposable
{
_buffFightWaitOn = true;
_buffFightWaitSince = now;
- _host.Log($"[Buff] buffs wait: {FightWhy(hurt)}; they go on once the fight is over (combat and the heals first).");
+ _host.Log(dispelWait
+ ? $"[Buff] buffs wait: {FightWhy(false)}; a dispelled buff waits for the fight's end (Recast dispelled buffs in a fight is off)."
+ : $"[Buff] buffs wait: {FightWhy(hurt)}; the heals first, the buffs once health is back over Heal At or the fight is over.");
}
}
return true;
@@ -484,8 +470,8 @@ public partial class BuffManager : IDisposable
// The checkbox was saved and shown since the first version but nothing read it (a player asked,
// 2026-10-30, whether "buff only when idle" was implemented). What it means (the owner): an earlier
// timer for idle moments. The regular rebuff is unchanged: a buff at or under Rebuff With
- // (RebuffSecondsRemaining), or dispelled, is recast as always, once a fight is over (BuffsWaitForFight,
- // since 2026-11-20; before that in a fight too). With the option
+ // (RebuffSecondsRemaining), or dispelled, is recast at once, fight or not (2026-11-20 to 12-01 it waited
+ // for the fight's end; now only health under Heal At in a fight holds it, BuffsWaitForFight). With the option
// on and the bot idle (IdleForTopOff: no fight target, no monster within Monster Range, no corpse
// to loot, no salvage), a rebuff run also starts once a buff is at or under Rebuff With plus the
// margin (default 2 minutes). Such an early run never starts in a fight, and one under way stops
@@ -3356,6 +3342,27 @@ public partial class BuffManager : IDisposable
// Families currently parked in _buffFailCooldownUntil are skipped so a parked
// family can't keep retriggering the batch (which would otherwise loop:
// batch starts → clears cooldown → cast again → silent no-show → re-park).
+ /// A buff that is on but at or under (a gone one doesn't count): due
+ /// by its timer, not by a dispel. The shield's count when all of them are on and one is under the line.
+ private bool AnyBuffOnTimer(List desiredBuffs, int thresholdSec)
+ {
+ DateTime now = RynthClock.Now;
+ foreach (string buffBaseName in desiredBuffs)
+ {
+ AcSkillType castSkill = SkillFor(buffBaseName);
+ if (!IsSkillUsable(castSkill)) continue;
+ int spellId = FindBestSpellId(buffBaseName, castSkill);
+ if (spellId == 0) continue;
+ int family = SpellTableStub.GetById(spellId)?.Family ?? 0;
+ if (family != 0
+ && _buffFailCooldownUntil.TryGetValue(family, out DateTime coolUntil)
+ && now < coolUntil)
+ continue;
+ if (IsBuffActive(spellId, 0) && !IsBuffActive(spellId, thresholdSec)) return true;
+ }
+ return ShieldBuffBelowThreshold(desiredBuffs, thresholdSec) && !ShieldBuffBelowThreshold(desiredBuffs, 0);
+ }
+
private bool AnyBuffBelowThreshold(List desiredBuffs, int thresholdSec)
{
DateTime now = RynthClock.Now;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
index 5982fcd..b255708 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Combat/CombatManager.cs
@@ -8300,6 +8300,12 @@ public partial class CombatManager : IDisposable
_scriptHeld = false;
_equipGateHeld = false;
if (_spellManager == null || target == null) return;
+ // The target was dropped earlier this tick (JudgePendingOffensiveCast read an answer: out of range, a
+ // ghost) after Think had picked it up. R-20261201-190034-03c5 (Conquest): the debuff went out at it
+ // anyway, as target 0: the client cast at its own selection ("You must select a suitable target before
+ // casting this spell", "This spell cannot be cast on Corpse of ..."), sent nothing, and combat waited
+ // for a server answer that never came: 7 s, a jump, Peace mode, about 13 s stood still each time.
+ if (activeTargetId == 0) return;
// Hard safety veto: never cast offensive magic at something AC's combat
// system says is not attackable. AC NPCs/vendors are ItemType=Creature,
@@ -8633,6 +8639,7 @@ public partial class CombatManager : IDisposable
/// One debuff cast at ; its result is read from chat (HandleChatForDebuffs).
private bool CastDebuffAt(int targetId, string targetName, string debuffKey, int spellId, int castTier, bool renewal)
{
+ if (targetId == 0) return false; // target 0 = the client's own selection: never (R-20261201-190034-03c5)
try
{
_host.CastSpellFor((uint)targetId, spellId, "Combat", SpellTableStub.GetById(spellId)?.Name ?? $"spell {spellId}");
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs b/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs
index 13d1dc8..72cfd7a 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Dashboard/InstrumentDashboard.cs
@@ -1783,7 +1783,7 @@ internal sealed unsafe class InstrumentDashboard
// The Loaded files drawer: label, picker, the Loot Editor and Spells buttons, and each row's
// "..." key: that file's buttons (Save, Save As, New, Rename, Move to Deleted, Open folder).
- private float FilesHeight() => 5 * Px(22) + 4 * Px(4);
+ private float FilesHeight() => 6 * Px(22) + 5 * Px(4);
private float FilesBody(ImDrawListPtr dl, float x0, float y, float w)
{
@@ -1801,7 +1801,9 @@ internal sealed unsafe class InstrumentDashboard
"Loot Editor: the loot profile in use.", () => _d.Host.SetPanelOpen("Loot Editor", RynthPanelOpen.Toggle), f.LootMode) + Px(4);
y = PickerRow(dl, x0, y, w, "META", f.MetaName, f.Metas, f.MetaIdx, 2, null, null, null) + Px(4);
y = PickerRow(dl, x0, y, w, "BUFFS", f.BuffName, f.Buffs, f.BuffIdx, 4, RynthIcons.Sparkle,
- "RynthAi Spells: the spell list and buff profiles.", _d.ToggleSpells);
+ "RynthAi Spells: the spell list and buff profiles.", _d.ToggleSpells) + Px(4);
+ // Named window layouts (2026-12-01): pick one to put this character's windows that way.
+ y = PickerRow(dl, x0, y, w, "LAYOUT", f.LayoutName, f.Layouts ?? Array.Empty(), f.LayoutIdx, 5, null, null, null);
return y;
}
@@ -1910,12 +1912,13 @@ internal sealed unsafe class InstrumentDashboard
0 => "Nav: Save, Save As, New, Rename, Move to Deleted, Open folder.",
2 => "Meta: Save, Save As, New, Rename, Move to Deleted, Open folder.",
1 => "Loot profile: Loot Editor, Save As (a copy), New, Rename, Move to Deleted, Open folder.",
+ 5 => "Window layout: Save your windows to it, Save As a new layout, Rename, Move to Deleted, Open folder.\nPick a layout in the list to load it on this character.",
_ => "Buff profiles: the Spells window, Open folder.",
};
private static string KindTitle(int kind) => kind switch
{
- 3 => "SETTINGS PROFILE", 0 => "NAV", 2 => "META", 1 => "LOOT PROFILE", _ => "BUFF PROFILE",
+ 3 => "SETTINGS PROFILE", 0 => "NAV", 2 => "META", 1 => "LOOT PROFILE", 5 => "WINDOW LAYOUT", _ => "BUFF PROFILE",
};
private void OpenFilesMenu(int kind, Vector2 anchor)
@@ -2002,7 +2005,7 @@ internal sealed unsafe class InstrumentDashboard
}
p.Y += Px(4);
- bool settings = kind == 3, nav = kind == 0, loot = kind == 1, buffs = kind == 4;
+ bool settings = kind == 3, nav = kind == 0, loot = kind == 1, buffs = kind == 4, layout = kind == 5;
bool isDefault = settings && string.Equals(info.Name, "Default", StringComparison.OrdinalIgnoreCase);
bool idle = !_filesBusy;
@@ -2029,7 +2032,8 @@ internal sealed unsafe class InstrumentDashboard
else
{
bool canSave = idle && (settings || (nav ? info.Name != "None" : info.HasFile)); // a nav: a file, a meta's nav or an unsaved route
- string saveTip = settings ? "Save the settings profile now (it also saves every change on its own)."
+ string saveTip = layout ? (info.HasFile ? $"Save your windows as they are now into '{info.Name}'." : "No layout in use yet: type a name below and use Save As.")
+ : settings ? "Save the settings profile now (it also saves every change on its own)."
: nav ? (info.HasFile ? "Save the route to its file now." : "Save the route (an unsaved route gets a new file, Route N).")
: info.HasFile ? "Save the meta to its file now." : "This meta has no file yet: type a name below and use Save As.";
if (FilesKey(dl, ref x, p.Y, h, "Save", "##f_save", canSave, saveTip)) RunFiles(ProfileVerb.Save, string.Empty);
@@ -2088,7 +2092,8 @@ internal sealed unsafe class InstrumentDashboard
p.Y += h + gap;
x = p.X;
}
- string asTip = loot ? "Copy the loot profile in use to this name; RynthAi loots with the copy."
+ string asTip = layout ? "Save your windows as they are now as a layout with this name (any character on this PC can load it)."
+ : loot ? "Copy the loot profile in use to this name; RynthAi loots with the copy."
: settings ? $"Save these settings as a new profile with this name, a copy of '{info.Name}' (its Monsters list too); it becomes the one in use."
: $"Save the {(nav ? "route" : "meta")} under this name; it becomes the one in use.";
if (settings && _filesFresh)
@@ -2102,7 +2107,7 @@ internal sealed unsafe class InstrumentDashboard
bool saveAs = FilesKey(dl, ref x, p.Y, h, "Save As", "##f_saveas", named && (!loot || info.HasFile), asTip);
if (saveAs || (enter && named && (!loot || info.HasFile))) RunFiles(ProfileVerb.SaveAs, name);
}
- if (!settings)
+ if (!settings && !layout)
{
string newTip = loot ? "A new, empty loot profile with this name, opened in the Loot Editor (its Save creates the file)."
: nav ? "A new, empty route with this name (Circular), loaded." : "A new meta with this name (one state, Default), loaded.";
@@ -2171,7 +2176,7 @@ internal sealed unsafe class InstrumentDashboard
private static string NameHint(int kind) => kind switch
{
- 3 => "Profile name...", 0 => "Nav name...", 2 => "Meta name...", _ => "Loot profile name...",
+ 3 => "Profile name...", 0 => "Nav name...", 2 => "Meta name...", 5 => "Layout name...", _ => "Loot profile name...",
};
/// The faint line under the name: where it lives, and how it is saved.
@@ -2181,6 +2186,7 @@ internal sealed unsafe class InstrumentDashboard
0 => info.Unsaved ? "Not saved to a file yet." : info.HasFile ? "NavProfiles; edits save on their own." : string.Empty,
2 => info.Unsaved ? "Not saved to a file yet (Save As names one)." : info.HasFile ? "MetaFiles; every change saves on its own." : string.Empty,
1 => info.Unsaved ? "The Loot Editor has changes not saved yet." : info.HasFile ? "LootProfiles" : string.Empty,
+ 5 => "For every character on this PC; pick one to load it. /rc layout save|load ",
_ => info.Unsaved ? "The Spells window has changes not saved yet." : string.Empty,
};
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
index 6a82995..2628d3c 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyAdvancedSettingsUi.cs
@@ -1039,6 +1039,13 @@ internal sealed class LegacyAdvancedSettingsUi
"without waiting for the cast's recoil animation to end.\n" +
"A refused cast turns it off for the rest of that buff pass.\n" +
"On by default. Off = every buff waits for the animation.");
+ ImGui.Checkbox("Recast dispelled buffs in a fight", ref _settings.RecastDispelledInFight);
+ if (ImGui.IsItemHovered())
+ ImGui.SetTooltip(
+ "On: a buff a monster dispels is recast at once, fight or not.\n" +
+ "Off: it waits until no monster is within Monster Range (a melee character\n" +
+ "doesn't put its weapon away mid-fight for it). A buff at 'Rebuff With'\n" +
+ "still goes in the fight, and takes the dispelled one along. On by default.");
ImGui.Checkbox("Skip buffs this character can't use", ref _settings.SkipUnusableBuffs);
if (ImGui.IsItemHovered())
ImGui.SetTooltip(
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Instrument.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Instrument.cs
index 82dc49f..6e7e53e 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Instrument.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Instrument.cs
@@ -45,7 +45,8 @@ internal sealed record DashboardFiles(
string[] Metas, int MetaIdx,
string[] Buffs, int BuffIdx,
string ProfileName, string NavName, string LootName, string MetaName, string BuffName,
- int LootMode = 0);
+ int LootMode = 0,
+ string[]? Layouts = null, int LayoutIdx = -1, string LayoutName = "None");
internal sealed partial class LegacyDashboardRenderer
{
@@ -76,7 +77,7 @@ internal sealed partial class LegacyDashboardRenderer
/// The five pickers' lists (copied under the lists' lock) and the entry in use. Any thread.
internal DashboardFiles ReadDashboardFiles()
{
- string[] profiles, navs, loots, metas, buffs;
+ string[] profiles, navs, loots, metas, buffs, layouts;
lock (_profileListsLock)
{
profiles = _profiles.ToArray();
@@ -84,7 +85,10 @@ internal sealed partial class LegacyDashboardRenderer
loots = _lootFiles.ToArray();
metas = _metaFiles.ToArray();
buffs = _buffFiles.ToArray();
+ layouts = _layoutFiles.ToArray();
}
+ string layoutName = _layoutName;
+ int layoutIdx = layoutName.Length > 0 ? Array.FindIndex(layouts, n => n.Equals(layoutName, StringComparison.OrdinalIgnoreCase)) : -1;
string profile = _settings.SelectedProfile ?? "Default";
return new DashboardFiles(
profiles, Math.Max(0, Array.IndexOf(profiles, profile)),
@@ -97,7 +101,8 @@ internal sealed partial class LegacyDashboardRenderer
LootLineName(),
string.IsNullOrEmpty(_settings.CurrentMetaPath) ? "None" : Path.GetFileNameWithoutExtension(_settings.CurrentMetaPath),
string.IsNullOrEmpty(_settings.CurrentBuffProfilePath) ? BuiltInBuffProfileLabel : Path.GetFileNameWithoutExtension(_settings.CurrentBuffProfilePath),
- Loot.LootModes.Clamp(_settings.LootMode));
+ Loot.LootModes.Clamp(_settings.LootMode),
+ layouts, layoutIdx, layoutName.Length > 0 ? layoutName : "None");
}
///
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Layouts.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Layouts.cs
new file mode 100644
index 0000000..4dee0c0
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.Layouts.cs
@@ -0,0 +1,167 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+
+namespace RynthCore.Plugin.RynthAi.LegacyUi;
+
+// Named window layouts in the Loaded files drawer (2026-12-01, report R-20261127-150927-7938: "save your
+// screen layout and load it on others via chat commands"; named layouts belong in the files drawer, easy
+// to reach and change). The engine keeps them
+// (/rc layout save|load|list|delete , %LOCALAPPDATA%\RynthCore\layouts\_saved\); this is the
+// LAYOUT row: its list is that folder, picking one loads it on this character, and the row's "..." saves,
+// saves as, renames, moves to Deleted and opens the folder. Which one this character last loaded or saved
+// is kept beside its settings profiles (layout.txt), for the row to show.
+internal sealed partial class LegacyDashboardRenderer
+{
+ /// Where the engine keeps named layouts (PanelLayoutPolicy.NamedFolder).
+ internal static string LayoutsFolder => LayoutsFolderForTests ??
+ Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "RynthCore", "layouts", "_saved");
+
+ /// Tests: their own folder, never the PC's real layouts.
+ internal static string? LayoutsFolderForTests;
+
+ private const string LayoutNameFile = "layout.txt";
+ private readonly List _layoutFiles = new();
+ private string _layoutName = string.Empty;
+ private DateTime _layoutFolderStamp;
+
+ /// The named layout this character last loaded or saved ("" none).
+ internal string LayoutName => _layoutName;
+
+ /// Why can't name a layout, or null (the engine's own rule: PanelLayoutPolicy.LayoutNameProblem).
+ internal static string? LayoutNameProblem(string? name)
+ {
+ string n = (name ?? string.Empty).Trim();
+ if (n.Length == 0) return "Type a name for the layout first.";
+ if (n.Length > 40) return "A layout name is at most 40 characters.";
+ if (n.StartsWith('_')) return "A layout name can't start with _.";
+ foreach (char ch in n)
+ if (!(char.IsLetterOrDigit(ch) || ch is ' ' or '-' or '_' or '(' or ')' or '.' or '\''))
+ return $"'{ch}' can't be in a layout name (letters, digits, spaces and - _ ( ) . ' can).";
+ if (n.EndsWith('.')) return "A layout name can't end with a dot.";
+ return null;
+ }
+
+ /// The named layouts in the folder (those with a panel_state.txt), sorted. Plugin tick.
+ internal void RefreshLayoutFiles()
+ {
+ var names = new List();
+ try
+ {
+ if (Directory.Exists(LayoutsFolder))
+ foreach (string dir in Directory.GetDirectories(LayoutsFolder))
+ {
+ string n = Path.GetFileName(dir);
+ if (!n.StartsWith('_') && File.Exists(Path.Combine(dir, "panel_state.txt"))) names.Add(n);
+ }
+ }
+ catch { }
+ names.Sort(StringComparer.OrdinalIgnoreCase);
+ lock (_profileListsLock) { _layoutFiles.Clear(); _layoutFiles.AddRange(names); }
+ }
+
+ /// The layout this character last loaded or saved, from its folder (at login).
+ private void ReadLayoutName()
+ {
+ _layoutName = string.Empty;
+ try
+ {
+ string path = string.IsNullOrEmpty(_charFolder) ? string.Empty : Path.Combine(_charFolder, LayoutNameFile);
+ if (path.Length > 0 && File.Exists(path)) _layoutName = File.ReadAllText(path).Trim();
+ }
+ catch { }
+ RefreshLayoutFiles();
+ }
+
+ private void SetLayoutName(string name)
+ {
+ _layoutName = name.Trim();
+ try
+ {
+ if (!string.IsNullOrEmpty(_charFolder))
+ {
+ Directory.CreateDirectory(_charFolder);
+ File.WriteAllText(Path.Combine(_charFolder, LayoutNameFile), _layoutName);
+ }
+ }
+ catch { }
+ }
+
+ /// The folder changed (a layout saved, renamed or deleted, here or by another client): list it again. Plugin tick.
+ private void TickLayoutFolder()
+ {
+ if (FolderChanged(LayoutsFolder, ref _layoutFolderStamp)) RefreshLayoutFiles();
+ }
+
+ /// An engine command (/rc layout ...), as typed in chat. False when the engine can't take it.
+ private bool LayoutCommand(string args)
+ {
+ try { return _host.HasInvokeChatParser && _host.InvokeChatParser("/rc layout " + args); }
+ catch { return false; }
+ }
+
+ private bool LayoutExists(string name) => File.Exists(Path.Combine(LayoutsFolder, name.Trim(), "panel_state.txt"));
+
+ /// Picked in the LAYOUT row: this character's windows become that layout. Plugin tick.
+ internal ProfileResult LoadLayout(string name)
+ {
+ if (!LayoutExists(name)) { RefreshLayoutFiles(); return ProfileResult.Failed($"There's no saved layout '{name}' any more."); }
+ if (!LayoutCommand("load " + name)) return ProfileResult.Failed("This RynthCore can't load layouts: update the core.");
+ SetLayoutName(name);
+ return ProfileResult.Done($"Loading the layout '{name}': your windows move to it in a moment.");
+ }
+
+ /// The LAYOUT row's "..." buttons. Plugin tick (RynthAiPlugin.RunProfileAction).
+ internal ProfileResult LayoutAction(ProfileVerb verb, string? raw, bool replace)
+ {
+ string name = (raw ?? string.Empty).Trim();
+ switch (verb)
+ {
+ case ProfileVerb.Save:
+ if (_layoutName.Length == 0) return ProfileResult.Failed("No layout in use yet: type a name and use Save As.");
+ return SaveLayout(_layoutName);
+ case ProfileVerb.SaveAs:
+ case ProfileVerb.New:
+ {
+ if (LayoutNameProblem(name) is string bad) return ProfileResult.Failed(bad);
+ if (LayoutExists(name) && !replace && !name.Equals(_layoutName, StringComparison.OrdinalIgnoreCase))
+ return new ProfileResult(false, $"[RynthAi] There's a layout '{name}' already.", NeedsReplace: true);
+ return SaveLayout(name);
+ }
+ case ProfileVerb.Rename:
+ {
+ if (_layoutName.Length == 0 || !LayoutExists(_layoutName)) return ProfileResult.Failed("No saved layout in use to rename.");
+ if (LayoutNameProblem(name) is string bad) return ProfileResult.Failed(bad);
+ if (LayoutExists(name)) return ProfileResult.Failed($"There's a layout '{name}' already.");
+ try
+ {
+ Directory.Move(Path.Combine(LayoutsFolder, _layoutName), Path.Combine(LayoutsFolder, name));
+ }
+ catch (Exception ex) { return ProfileResult.Failed($"Couldn't rename the layout: {ex.Message}"); }
+ string was = _layoutName;
+ SetLayoutName(name);
+ RefreshLayoutFiles();
+ return ProfileResult.Done($"Renamed the layout '{was}' to '{name}'.");
+ }
+ case ProfileVerb.Delete:
+ {
+ if (_layoutName.Length == 0 || !LayoutExists(_layoutName)) return ProfileResult.Failed("No saved layout in use to delete.");
+ string was = _layoutName;
+ if (!LayoutCommand("delete " + was)) return ProfileResult.Failed("This RynthCore can't delete layouts: update the core.");
+ SetLayoutName(string.Empty);
+ return ProfileResult.Done($"Moved the layout '{was}' to {Path.Combine(LayoutsFolder, "_deleted")} (nothing is erased).");
+ }
+ case ProfileVerb.Folder:
+ return OpenProfileFolder(ProfileKind.Layout);
+ default:
+ return ProfileResult.Failed("Layouts have Save, Save As, Rename, Delete and Open folder.");
+ }
+ }
+
+ private ProfileResult SaveLayout(string name)
+ {
+ if (!LayoutCommand("save " + name)) return ProfileResult.Failed("This RynthCore can't save layouts: update the core.");
+ SetLayoutName(name);
+ return ProfileResult.Done($"Saved your windows as the layout '{name}'. Any character on this PC can load it from the LAYOUT row, or with /rc layout load {name}.");
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.NavEdit.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.NavEdit.cs
index 643faf4..c0f2f84 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.NavEdit.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.NavEdit.cs
@@ -267,23 +267,43 @@ internal sealed partial class LegacyDashboardRenderer
break;
case "trailToRoute":
- {
- NavCrumb[] trail = NavBreadcrumbs?.Trail ?? Array.Empty();
- List pts = NavBreadcrumbTracker.TrailToPoints(trail, _settings.NavOverlay.RecordSpacingYards, cmd.Reverse);
- if (pts.Count < 2) { SetNavEditStatus("The trail is too short to make a route."); return; }
- _settings.IsRecordingNav = false;
- // A new unsaved route: the loaded file on disk is not changed (Save As keeps it).
- _settings.CurrentRoute = new NavRouteParser { RouteType = NavRouteType.Once, Points = pts };
- _settings.CurrentNavPath = string.Empty;
- _settings.ActiveNavIndex = 0;
- RefreshNavFiles();
- SaveSettings();
- SetNavEditStatus($"{(cmd.Reverse ? "Backtrack" : "Trail")} route created: {pts.Count} points (unsaved).");
+ SetNavEditStatus(TrailToRoute(cmd.Reverse, null, out _));
break;
- }
}
}
+ ///
+ /// The breadcrumb trail (its newest unbroken stretch) becomes the current route, walked again or
+ /// backwards (), and with it is saved as
+ /// NavProfiles\<name>.nav (report R-20261129-210845-0574: "a nav route made from your
+ /// breadcrumbs"; the Nav panel's Tools menu had it, /ra navtrail route|back gives it a name too).
+ /// Returns the line to show; is false when no route was made.
+ ///
+ internal string TrailToRoute(bool reverse, string? saveAs, out bool made)
+ {
+ made = false;
+ NavCrumb[] trail = NavBreadcrumbs?.Trail ?? Array.Empty();
+ List pts = NavBreadcrumbTracker.TrailToPoints(trail, _settings.NavOverlay.RecordSpacingYards, reverse);
+ if (pts.Count < 2)
+ return _settings.NavOverlay.TrackBreadcrumbs
+ ? "The trail is too short to make a route: walk a while first."
+ : "No trail to make a route from: turn Breadcrumbs on (/ra navtrail on) and walk a while.";
+ _settings.IsRecordingNav = false;
+ // A new unsaved route: the loaded file on disk is not changed (Save As keeps it).
+ _settings.CurrentRoute = new NavRouteParser { RouteType = NavRouteType.Once, Points = pts };
+ _settings.CurrentNavPath = string.Empty;
+ _settings.ActiveNavIndex = 0;
+ made = true;
+ string what = $"{(reverse ? "Backtrack" : "Trail")} route created: {pts.Count} points";
+ if (string.IsNullOrWhiteSpace(saveAs))
+ {
+ RefreshNavFiles();
+ SaveSettings();
+ return what + " (unsaved).";
+ }
+ return what + ". " + SaveRoute(saveAs).Replace("[RynthAi] ", "");
+ }
+
/// Copy-on-write route edit, then the route file autosave.
private void EditRoute(Func, List> edit)
{
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.ProfileFiles.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.ProfileFiles.cs
index 90e2437..e9e3ba4 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.ProfileFiles.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.ProfileFiles.cs
@@ -7,7 +7,7 @@ using RynthCore.Plugin.Shared;
namespace RynthCore.Plugin.RynthAi.LegacyUi;
/// The kinds of profile the Loaded files drawer lists (the numbers of ).
-internal enum ProfileKind { Nav = 0, Loot = 1, Meta = 2, Settings = 3, Buffs = 4 }
+internal enum ProfileKind { Nav = 0, Loot = 1, Meta = 2, Settings = 3, Buffs = 4, Layout = 5 }
/// What a profile button or its /ra verb does.
internal enum ProfileVerb { Save, SaveAs, New, Rename, Delete, Folder, Edit, ClearMonsters }
@@ -58,6 +58,7 @@ internal sealed partial class LegacyDashboardRenderer
ProfileKind.Loot => "loot profile",
ProfileKind.Meta => "meta",
ProfileKind.Settings => "settings profile",
+ ProfileKind.Layout => "layout",
_ => "buff profile",
};
@@ -76,6 +77,7 @@ internal sealed partial class LegacyDashboardRenderer
ProfileKind.Loot => _lootFolder,
ProfileKind.Meta => _metaFolder,
ProfileKind.Settings => _charFolder ?? string.Empty,
+ ProfileKind.Layout => LayoutsFolder,
_ => BuffProfileStore.Folder,
};
@@ -89,6 +91,7 @@ internal sealed partial class LegacyDashboardRenderer
ProfileKind.Loot => _settings.CurrentLootPath ?? string.Empty,
ProfileKind.Meta => _settings.CurrentMetaPath ?? string.Empty,
ProfileKind.Settings => _settingsFilePath ?? string.Empty,
+ ProfileKind.Layout => _layoutName.Length > 0 ? Path.Combine(LayoutsFolder, _layoutName, "panel_state.txt") : string.Empty,
_ => _settings.CurrentBuffProfilePath ?? string.Empty,
};
@@ -133,6 +136,9 @@ internal sealed partial class LegacyDashboardRenderer
case ProfileKind.Buffs:
if (path.Length == 0) name = BuiltInBuffProfileLabel;
break;
+ case ProfileKind.Layout:
+ name = _layoutName.Length > 0 ? _layoutName : "None";
+ break;
}
return new ProfileFileInfo(name, path, hasFile, unsaved, ProfileFolder(k), monsterRules);
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
index a0aeaa7..b2b8e7a 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyDashboardRenderer.cs
@@ -386,6 +386,7 @@ internal sealed partial class LegacyDashboardRenderer
_serverFolder = ResolveServerFolder();
_charFolder = Path.Combine(_settingsRoot, safeChar);
MigrateToServerFolder(safeChar);
+ ReadLayoutName(); // the named layout this character last loaded or saved (the LAYOUT row)
// Migrate legacy settings.json → Default.json if needed
string legacyPath = Path.Combine(_charFolder, "settings.json");
@@ -600,6 +601,7 @@ internal sealed partial class LegacyDashboardRenderer
_host.Log($"[RynthAi] Meta ({when}): {path} differs from the copy kept with these settings ({mine} rules); running the file's {loaded.Rules.Count} rules.");
}
_metaUi.NoteCallStates(path, loaded.Rules); // CallState rules that call nothing: say so
+ _metaUi.EmbedFileRoutes(when); // routes still read from NavProfiles go into the meta
}
catch (Exception ex)
{
@@ -1485,6 +1487,7 @@ internal sealed partial class LegacyDashboardRenderer
RebuffIdleMarginMinutes = s.RebuffIdleMarginMinutes,
CastBuffsOverItemBuffs = s.CastBuffsOverItemBuffs,
SkipUnusableBuffs = s.SkipUnusableBuffs,
+ RecastDispelledInFight = s.RecastDispelledInFight,
UseFellowshipBuffs = s.UseFellowshipBuffs,
DisabledBuffs = new List(s.DisabledBuffs),
BlockedBuffItems = new List(s.BlockedBuffItems),
@@ -1786,6 +1789,7 @@ internal sealed partial class LegacyDashboardRenderer
if (p.RebuffIdleMarginMinutes is int idleMargin) s.RebuffIdleMarginMinutes = Math.Max(0, idleMargin); // absent = unchanged
if (p.CastBuffsOverItemBuffs is bool castOverItems) s.CastBuffsOverItemBuffs = castOverItems; // absent = unchanged
if (p.SkipUnusableBuffs is bool skipUnusable) s.SkipUnusableBuffs = skipUnusable; // absent = unchanged
+ if (p.RecastDispelledInFight is bool recastDispelled) s.RecastDispelledInFight = recastDispelled; // absent = unchanged
if (p.UseFellowshipBuffs is bool fellowBuffs) s.UseFellowshipBuffs = fellowBuffs; // absent = unchanged
if (p.DisabledBuffs is { } disabledBuffs) s.DisabledBuffs = new List(disabledBuffs); // absent = unchanged
if (p.BlockedBuffItems is { } blockedItems) s.BlockedBuffItems = new List(blockedItems); // absent = unchanged
@@ -2178,6 +2182,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.OutdoorHuntRange = tmp.OutdoorHuntRange;
dst.OutdoorHuntRadius = tmp.OutdoorHuntRadius;
dst.OutdoorHuntPick = Math.Clamp(tmp.OutdoorHuntPick, 0, 2);
+ dst.OutdoorHuntRoam = tmp.OutdoorHuntRoam;
dst.T2Speed = tmp.T2Speed;
dst.T2DistanceTo = tmp.T2DistanceTo;
dst.T2ReissueMs = tmp.T2ReissueMs;
@@ -2333,6 +2338,7 @@ internal sealed partial class LegacyDashboardRenderer
dst.CastBuffsOverItemBuffs = tmp.CastBuffsOverItemBuffs;
dst.FastBuffChain = tmp.FastBuffChain;
dst.SkipUnusableBuffs = tmp.SkipUnusableBuffs;
+ dst.RecastDispelledInFight = tmp.RecastDispelledInFight;
dst.UseFellowshipBuffs = tmp.UseFellowshipBuffs;
dst.DisabledBuffs = tmp.DisabledBuffs;
dst.BlockedBuffItems = tmp.BlockedBuffItems;
@@ -2938,6 +2944,7 @@ internal sealed partial class LegacyDashboardRenderer
if (FolderChanged(_lootFolder, ref _lootFolderStamp)) RefreshLootFiles();
if (FolderChanged(_metaFolder, ref _metaFolderStamp)) RefreshMetaFiles();
if (FolderChanged(_charFolder, ref _profileFolderStamp)) RefreshProfilesList();
+ TickLayoutFolder();
}
/// True when 's write time moved since the last call (never on
@@ -3733,7 +3740,7 @@ internal sealed partial class LegacyDashboardRenderer
// AddRange() on the pump thread — a torn read or
// ArgumentOutOfRangeException. Snapshot the one list this call needs
// under _profileListsLock first, mirroring BuildSnapshotJson.
- string? navFile = null, lootFile = null, metaFile = null, profileName = null, buffFile = null;
+ string? navFile = null, lootFile = null, metaFile = null, profileName = null, buffFile = null, layoutFile = null;
lock (_profileListsLock)
{
switch (kind)
@@ -3743,6 +3750,7 @@ internal sealed partial class LegacyDashboardRenderer
case 2: if (index >= 0 && index < _metaFiles.Count) metaFile = _metaFiles[index]; break;
case 3: if (index >= 0 && index < _profiles.Count) profileName = _profiles[index]; break;
case 4: if (index >= 0 && index < _buffFiles.Count) buffFile = _buffFiles[index]; break;
+ case 5: if (index >= 0 && index < _layoutFiles.Count) layoutFile = _layoutFiles[index]; break;
}
}
@@ -3780,6 +3788,13 @@ internal sealed partial class LegacyDashboardRenderer
if (buffFile != null)
SetActiveBuffProfile(index == 0 ? string.Empty : Path.Combine(BuffProfileStore.Folder, buffFile));
break;
+ case 5:
+ if (layoutFile != null)
+ {
+ ProfileResult r = LoadLayout(layoutFile);
+ _host.WriteToChat(r.Text, r.Ok ? 1 : 0x1A);
+ }
+ break;
}
}
@@ -3900,6 +3915,18 @@ internal sealed partial class LegacyDashboardRenderer
AppendStringArray(sb, "navFiles", _navFiles); sb.Append(',');
AppendStringArray(sb, "embeddedNavKeys", _settings.EmbeddedNavs.Keys); sb.Append(',');
+ // The loaded nav route, for the Embedded Nav Route's "Embed loaded" button (MetaNavEmbedding):
+ // the name it is embedded under, its points, and why it can't be (empty note: it can).
+ {
+ var loadedRoute = MetaNavEmbedding.DescribeLoaded(_settings.CurrentRoute, _settings.CurrentNavPath,
+ _metaSaver.NavFolder(), _settings.EmbeddedNavs);
+ sb.Append("\"loadedRoute\":{");
+ AppendString(sb, "name", loadedRoute.Name); sb.Append(',');
+ sb.Append("\"points\":").Append(loadedRoute.Points).Append(',');
+ AppendString(sb, "note", loadedRoute.Note);
+ sb.Append("},");
+ }
+
string sourceText = "";
try { sourceText = AfFileWriter.SaveToString(_settings.MetaRules, _settings.EmbeddedNavs); } catch { }
AppendString(sb, "sourceText", sourceText);
@@ -4121,7 +4148,11 @@ internal sealed partial class LegacyDashboardRenderer
case "add_rule":
if (cmd.Rule == null) { RefuseEdit(op, "the command carried no rule"); break; }
- _settings.MetaRules.Add(DtoToMetaRule(cmd.Rule));
+ {
+ var added = DtoToMetaRule(cmd.Rule);
+ EmbedPickedRoutes(added, null);
+ _settings.MetaRules.Add(added);
+ }
TryAutoSaveMetaCmd($"add_rule (now {_settings.MetaRules.Count} rules)");
break;
@@ -4129,10 +4160,15 @@ internal sealed partial class LegacyDashboardRenderer
// The engine's editor saves every change (2026-10-05): keep the running rule's
// latch (no re-fire) and the fields the panel can't send (MetaRuleEdits).
if (cmd.Rule == null) { RefuseEdit(op, "the command carried no rule"); break; }
- if (!MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, DtoToMetaRule(cmd.Rule), keepName: cmd.Rule.Name == null))
{
- RefuseEdit(op, NoSuchRule(cmd.Index));
- break;
+ var edited = DtoToMetaRule(cmd.Rule);
+ MetaRule? was = HasRule(cmd.Index) ? _settings.MetaRules[cmd.Index] : null;
+ if (!MetaRuleEdits.Replace(_settings.MetaRules, cmd.Index, edited, keepName: cmd.Rule.Name == null))
+ {
+ RefuseEdit(op, NoSuchRule(cmd.Index));
+ break;
+ }
+ if (was != null) EmbedPickedRoutes(edited, was);
}
TryAutoSaveMetaCmd($"update_rule {cmd.Index + 1}");
break;
@@ -4168,6 +4204,7 @@ internal sealed partial class LegacyDashboardRenderer
if (!HasRule(cmd.Index)) { RefuseEdit(op, NoSuchRule(cmd.Index)); break; }
{
var copy = DtoToMetaRule(cmd.Rule);
+ EmbedPickedRoutes(copy, _settings.MetaRules[cmd.Index]); // the same route: nothing to copy
MetaRuleEdits.KeepHidden(_settings.MetaRules[cmd.Index], copy); // CallState return / ChatCapture colours
if (cmd.Rule.Name == null) copy.Name = _settings.MetaRules[cmd.Index].Name;
_settings.MetaRules.Insert(cmd.Index + 1, copy);
@@ -4214,6 +4251,35 @@ internal sealed partial class LegacyDashboardRenderer
return -1;
}
+ /// A route picked for an Embedded Nav Route (a new rule, or a changed route) is copied
+ /// into the meta from its NavProfiles file (MetaNavEmbedding); the save below writes it. A route the
+ /// panel's "Embed loaded" named (MetaNavEmbedding.LoadedMarker) is the loaded route, copied from memory:
+ /// one never saved to a file becomes the meta's route (nav edits then go to the meta's copy).
+ private void EmbedPickedRoutes(MetaRule after, MetaRule? before)
+ {
+ string folder = _metaSaver.NavFolder();
+ lock (_settings.MetaRulesLock)
+ {
+ HashSet? fromMemory = null;
+ foreach (string name in MetaNavEmbedding.TakeLoadedMarkers(after))
+ {
+ string? why = MetaNavEmbedding.EmbedLoaded(name, _settings.CurrentRoute, _settings.CurrentNavPath, folder,
+ _settings.EmbeddedNavs, line => _host.Log(line));
+ if (why == null)
+ {
+ (fromMemory ??= new HashSet(System.StringComparer.OrdinalIgnoreCase)).Add(name);
+ if (string.IsNullOrEmpty(_settings.CurrentNavPath)) _settings.CurrentNavPath = $"";
+ }
+ else
+ {
+ _host.Log($"[RynthAi] Meta: the loaded route wasn't embedded as '{name}': {why}");
+ _host.WriteToChat($"[RynthAi] Meta: the loaded route wasn't embedded: {why}", 1);
+ }
+ }
+ MetaNavEmbedding.EmbedPicked(after, before, _settings.EmbeddedNavs, folder, line => _host.Log(line), fromMemory);
+ }
+ }
+
/// Writes the meta file after a rule command changed the rules (MetaSaver: logged, and the
/// result goes to the panel in the snapshot's saveResult).
private void TryAutoSaveMetaCmd(string change)
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs
index f713e27..08b18d0 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyMetaUi.cs
@@ -1262,6 +1262,7 @@ internal sealed class LegacyMetaUi
: $"Loaded {loaded.Rules.Count} rules / {stateCount} states from {name} — {loaded.Warnings.Count} warning(s): {loaded.Warnings[0]}";
_statusTime = RynthClock.Now;
NoteCallStates(filePath, loaded.Rules);
+ EmbedFileRoutes("load");
return true;
}
catch (Exception ex)
@@ -1272,6 +1273,29 @@ internal sealed class LegacyMetaUi
}
}
+ ///
+ /// The loaded meta's Embedded Nav Routes that it doesn't carry (it named a NavProfiles file) are
+ /// copied in, and a .af is written with them once, so the meta stops needing the files
+ /// (MetaNavEmbedding). A .met keeps them in memory (its first edit saves the .af); a read-only
+ /// file isn't written. names the load for the log.
+ ///
+ internal void EmbedFileRoutes(string when)
+ {
+ string path = _settings.CurrentMetaPath ?? string.Empty;
+ List added;
+ lock (_settings.MetaRulesLock)
+ added = MetaNavEmbedding.EmbedMissing(_settings.MetaRules, _settings.EmbeddedNavs, Saver.NavFolder(), Log);
+ if (added.Count == 0 || path.Length == 0) return;
+ if (!Path.GetExtension(path).Equals(".af", StringComparison.OrdinalIgnoreCase)) return;
+ try
+ {
+ if (!File.Exists(path) || (File.GetAttributes(path) & FileAttributes.ReadOnly) != 0) return;
+ }
+ catch { return; }
+ Saver.SaveTo(path, $"{when}: routes embedded from NavProfiles",
+ $"; route{(added.Count == 1 ? "" : "s")} {string.Join(", ", added)} now inside the meta");
+ }
+
/// The status line of the last load (why it failed, or what it loaded).
internal string LastLoadStatus => _statusMessage ?? string.Empty;
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
index 0d462cb..94cad07 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/LegacyUiSettings.cs
@@ -148,6 +148,8 @@ public sealed class LegacyUiSettings
// What the next monster is chosen by (2026-11-08, OutdoorHunt.PickMode): 0 the nearest (the hunt as
// it was), 1 the biggest pack, 2 the pack worth the most experience (learned XP per kill).
public int OutdoorHuntPick = 0;
+ /// With nothing in range, walk round the parts of Hunt Radius not looked at lately (2026-12-01; on by default).
+ public bool OutdoorHuntRoam = true;
// On: macro start, loading a Circular or Linear route, and nav taking over again after a
// pause that moved the character (combat, looting, buffing, doors) all head for the closest
// waypoint on the route. Off: a pause carries on to the waypoint it was heading for, a macro
@@ -617,6 +619,14 @@ public sealed class LegacyUiSettings
///
public bool SkipUnusableBuffs = true;
///
+ /// Buffing > Recast dispelled buffs in a fight (on by default; 2026-12-01: recasting dispels is
+ /// an option). On: a buff a monster dispels is recast at once, fight or not, like any buff at Rebuff With.
+ /// Off: in a fight a dispelled (gone) buff waits until no monster is within Monster Range; a buff at or
+ /// under Rebuff With still goes in the fight, and the run it starts takes the dispelled one along.
+ /// A profile saved before the setting loads it on. Read by BuffManager.BuffsWaitForFight.
+ ///
+ public bool RecastDispelledInFight = true;
+ ///
/// Buffing > Use fellowship buffs in a fellowship (off by default): in a fellowship, a buff with a
/// fellowship version (the Conclave attributes, the Clutch defenses, the Chants masteries, the Wards
/// protections, the Winds, the Endless Well) casts that version instead, at the same level rules and
@@ -1726,6 +1736,7 @@ public sealed class SettingsBridgePayload
// Settings face must leave the setting alone rather than force it either way.
public bool? CastBuffsOverItemBuffs { get; set; }
public bool? SkipUnusableBuffs { get; set; }
+ public bool? RecastDispelledInFight { get; set; } // Recast dispelled buffs in a fight (2026-12-01); absent = unchanged
public bool? UseFellowshipBuffs { get; set; } // Use fellowship buffs in a fellowship (2026-11-27); absent = unchanged
// Null (absent) likewise leaves the unticked prots/banes alone; an empty list ticks them all.
public List? DisabledBuffs { get; set; }
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/MetaSaver.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/MetaSaver.cs
index 3c26f1c..63b065c 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/MetaSaver.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/MetaSaver.cs
@@ -35,6 +35,9 @@ internal sealed class MetaSaver
_log = log;
}
+ /// Where an Embedded Nav Route's file is read from when the meta doesn't carry the route yet.
+ public Func NavFolder { get; set; } = () => LegacyNavigationUi.NavFolder;
+
/// Counts results (0 = nothing tried yet this session).
public long Seq { get; private set; }
public bool LastOk { get; private set; } = true;
@@ -72,6 +75,11 @@ internal sealed class MetaSaver
string why;
lock (_settings.MetaRulesLock)
{
+ // Every route a rule names goes into the file (MetaNavEmbedding): a route still read
+ // from NavProfiles is copied in now, so the meta runs without the .nav file.
+ List embedded = MetaNavEmbedding.EmbedMissing(_settings.MetaRules, _settings.EmbeddedNavs, NavFolder(), _log);
+ if (embedded.Count > 0)
+ note += $"; route{(embedded.Count == 1 ? "" : "s")} {string.Join(", ", embedded)} now inside the meta";
rules = _settings.MetaRules.Count;
states = _settings.MetaRules.Select(r => r.State ?? "Default").Distinct(StringComparer.OrdinalIgnoreCase).Count();
ok = DataWriteGuard.TrySave("the meta", path,
diff --git a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs
index 2647b2d..322c23e 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/LegacyUi/NavRouteParser.cs
@@ -123,6 +123,14 @@ public sealed class NavRouteParser
///
public bool NavmeshCorners { get; set; }
+ ///
+ /// What built this route in memory when no one recorded or loaded it (the dungeon patrol, a hunt's
+ /// walk, Camp, a go-to...): the Meta panel's "Embed loaded" refuses it, so a meta never freezes a
+ /// generated path (MetaNavEmbedding.DescribeLoaded, 2026-11-30). Empty for files, metas, the nav
+ /// editor and recording. Never saved with the route.
+ ///
+ public string MadeBy { get; set; } = string.Empty;
+
///
/// Non-null if the last load hit an unknown waypoint type or a malformed
/// line. The route still holds whatever points parsed cleanly before that.
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryRules.cs b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryRules.cs
new file mode 100644
index 0000000..d30b5e8
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/Loot/InventoryRules.cs
@@ -0,0 +1,102 @@
+using System;
+using System.IO;
+using RynthCore.Loot;
+using RynthCore.Loot.VTank;
+
+namespace RynthCore.Plugin.RynthAi.Loot;
+
+/// What the rule that takes an item says to do with it, for the inventory commands.
+internal enum InventoryRuleKind { None, Keep, Salvage, Other }
+
+///
+/// A loot profile read for a command that judges what the character carries (2026-12-01 command
+/// audit: /ub equip load|test and /ub autosalvage), not for looting: a VTank .utl or RynthAi's own
+/// .json, read once for the command. Loading one never changes the loot profile in use.
+///
+internal sealed class InventoryRules
+{
+ private readonly VTankLootProfile? _utl;
+ private readonly LootProfile? _json;
+
+ /// The file it came from.
+ public string Path { get; }
+
+ public string FileName => System.IO.Path.GetFileName(Path);
+
+ public int RuleCount => _utl?.Rules.Count ?? _json?.Rules.Count ?? 0;
+
+ private InventoryRules(string path, VTankLootProfile? utl, LootProfile? json)
+ {
+ Path = path;
+ _utl = utl;
+ _json = json;
+ }
+
+ /// The profile at , or null with why not.
+ public static InventoryRules? Load(string path, out string error)
+ {
+ error = string.Empty;
+ if (string.IsNullOrWhiteSpace(path) || !File.Exists(path))
+ {
+ error = "not found";
+ return null;
+ }
+ try
+ {
+ return path.EndsWith(".json", StringComparison.OrdinalIgnoreCase)
+ ? new InventoryRules(path, null, LootProfile.Load(path))
+ : new InventoryRules(path, VTankLootParser.Load(path), null);
+ }
+ catch (Exception ex)
+ {
+ error = ex.Message;
+ return null;
+ }
+ }
+
+ /// For tests: rules already in memory.
+ internal static InventoryRules From(string path, VTankLootProfile profile) => new(path, profile, null);
+
+ ///
+ /// The first rule that takes , as the looter decides it
+ /// (): when a rule
+ /// that could take it needs the item's identify data and is false.
+ /// A native .json profile needs no ID to decide.
+ ///
+ public VTankLootVerdict Decide(WorldObject item, VTankLootContext? ctx, CharacterSkills? skills, bool hasIdData,
+ out InventoryRuleKind kind, out string ruleName)
+ {
+ kind = InventoryRuleKind.None;
+ ruleName = string.Empty;
+ if (_utl != null)
+ {
+ VTankLootVerdict v = VTankLootEvaluator.Decide(_utl, item, ctx, hasIdData, out int index);
+ if (index >= 0)
+ {
+ VTankLootRule rule = _utl.Rules[index];
+ ruleName = LootWhy.NameOf(rule, index);
+ kind = rule.Action switch
+ {
+ VTankLootAction.Keep or VTankLootAction.KeepUpTo => InventoryRuleKind.Keep,
+ VTankLootAction.Salvage => InventoryRuleKind.Salvage,
+ _ => InventoryRuleKind.Other,
+ };
+ }
+ return v;
+ }
+ if (_json != null)
+ {
+ var (action, rule) = LootEvaluator.Classify(_json, item, skills);
+ if (rule == null) return VTankLootVerdict.NoMatch;
+ ruleName = string.IsNullOrWhiteSpace(rule.Name) ? "rule" : rule.Name.Trim();
+ kind = action switch
+ {
+ LootAction.Keep or LootAction.KeepUpTo => InventoryRuleKind.Keep,
+ LootAction.Salvage => InventoryRuleKind.Salvage,
+ _ => InventoryRuleKind.Other,
+ };
+ return VTankLootVerdict.Match;
+ }
+ return VTankLootVerdict.NoMatch;
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.Extra.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.Extra.cs
index 96910a9..cbb18dd 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.Extra.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.Extra.cs
@@ -106,11 +106,68 @@ public sealed partial class RynthAiPlugin
case "config":
// ub-IT: /mt config = /mt opt (list when bare).
return parts.Length < 3 ? HandleMtOpt(new[] { "/mt", "opt", "list" }) : HandleMtOpt(parts);
+ case "attack_melee": return HandleMtAttackMelee(parts);
default:
return false;
}
}
+ // ── attack_melee (2026-12-01 command audit) ─────────────────────────────────
+
+ internal const string MtAttackMeleeUsage = "[RynthAi] Usage: /mt attack_melee [closest]";
+
+ ///
+ /// /mt attack_melee [closest] (Mag-Tools), one step a call as Mag-Tools does it, so a meta sends it
+ /// again and again: out of melee mode it goes to melee mode; in melee mode it attacks the selected
+ /// monster once (the closest monster when none is selected, or with "closest", which it selects),
+ /// at RynthAi's melee attack height and power. It was "Unknown /mt command" before.
+ ///
+ private bool HandleMtAttackMelee(string[] parts)
+ {
+ bool closest = parts.Length >= 3 && parts[2].Equals("closest", StringComparison.OrdinalIgnoreCase);
+ if (parts.Length >= 3 && !closest) { ReplyFail(MtAttackMeleeUsage); return true; }
+ LegacyUi.LegacyUiSettings? s = _dashboard?.Settings;
+ if (_objectCache == null || _playerId == 0 || s == null) { ReplyFail("[RynthAi] /mt attack_melee: not ready (log in first)."); return true; }
+ if (!Host.HasMeleeAttack || !Host.HasChangeCombatMode) { ReplyFail("[RynthAi] /mt attack_melee: this RynthCore can't attack from a command."); return true; }
+
+ if (!Host.HasGetCurrentCombatMode || Host.GetCurrentCombatMode() != CombatMode.Melee)
+ {
+ Host.ChangeCombatModeFor(CombatMode.Melee, "Command", "/mt attack_melee", force: true);
+ ReplyOk("[RynthAi] /mt attack_melee: going to melee mode (the next one attacks).");
+ return true;
+ }
+
+ WorldObject? target = null;
+ uint sel = Host.GetSelectedItemId();
+ if (!closest && sel != 0 && _objectCache[unchecked((int)sel)] is { ObjectClass: AcObjectClass.Monster } picked)
+ target = picked;
+ if (target == null)
+ {
+ int me = unchecked((int)_playerId);
+ double best = double.MaxValue;
+ foreach (WorldObject wo in _objectCache.GetLandscapeObjects())
+ {
+ if (wo.ObjectClass != AcObjectClass.Monster || _objectCache.GetHealthRatio(wo.Id) == 0f) continue;
+ double d = _objectCache.Distance(me, wo.Id);
+ if (d < best) { best = d; target = wo; }
+ }
+ if (target == null) { ReplyFail("[RynthAi] /mt attack_melee: no monster nearby."); return true; }
+ if (Host.HasSelectItem) ItemInfo.SelfSelect.SelectAsBot(Host, unchecked((uint)target.Id));
+ }
+
+ int acHeight = s.MeleeAttackHeight switch { 0 => 3, 2 => 1, _ => 2 }; // Low=3, Med=2, High=1
+ float power = AttackPowerModes.Resolve(AttackPowerModes.Default, s.MeleeAttackPower, s.UseRecklessness,
+ _charSkills == null || _charSkills[AcSkillType.Recklessness].Training >= 2,
+ s.VariablePowerMin, s.VariablePowerMax, Random.Shared.NextDouble);
+ if (Host.MeleeAttack(unchecked((uint)target.Id), acHeight, power))
+ {
+ RynthCore.Plugin.Shared.ActionPacer.NoteAttackSent();
+ ReplyOk($"[RynthAi] /mt attack_melee: attacking {target.Name}.");
+ }
+ else ReplyFail($"[RynthAi] /mt attack_melee: the attack on {target.Name} wasn't sent.");
+ return true;
+ }
+
// ── send: keys, as Mag-Tools ────────────────────────────────────────────────
///
diff --git a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs
index 2116712..c72842d 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/MagToolsCommands.cs
@@ -179,7 +179,8 @@ public sealed partial class RynthAiPlugin
/// A Mag-Tools / VTank option RynthAi maps, or one a meta has stored (an unknown name reads as 0).
private bool OptionKnown(string optName)
- => MtOptionMap.ContainsKey(optName) || _metaManager?.Expressions?.Options.ContainsKey(optName) == true;
+ => MtOptionMap.ContainsKey(optName) || MtSpecialOptions.Contains(optName)
+ || _metaManager?.Expressions?.Options.ContainsKey(optName) == true;
///
/// After /mt opt set (and /ub opt set): the option's value now. Bools read back as 1/0; asked as
@@ -191,13 +192,13 @@ public sealed partial class RynthAiPlugin
bool askedBool = asked.ToLowerInvariant() is "true" or "false" or "on" or "off";
if (askedBool && now is "1" or "0") now = now == "1" ? "True" : "False";
ReplyOk($"[RynthAi] {optName} = {now}"
- + (MtOptionMap.ContainsKey(optName) ? "" : " (not an option RynthAi maps: kept only for metas to read)"));
+ + (MtOptionMap.ContainsKey(optName) || MtSpecialOptions.Contains(optName) ? "" : " (not an option RynthAi maps: kept only for metas to read)"));
}
/// The /mt verbs RynthAi takes, for the usage line.
private const string MtVerbList = "opt, combatstate, face, cast[p], use[i|l][p], select[p], give[p], loot[p], drop[p], "
+ "equip[p], dequip[p], fellow, logout, quit, send, jump, trade, vendor, autopack, dumpspells, click, get xy, "
- + "cursor, movement, strafe, client, config, test";
+ + "cursor, movement, strafe, client, config, attack_melee, test";
/// How to use a /mt (or, with "/ub", a translated /ub) verb; null when it isn't one.
private static string? MtVerbUsage(string verb, string prefix) => verb switch
@@ -257,8 +258,8 @@ public sealed partial class RynthAiPlugin
["lootnearbychests"] = "LootNearbyChests", // Settings > Looting > Loot Nearby Chests
["dooropenrange"] = "OpenDoorRange",
["autofellowmanagement"] = "AutoFellowMgmt",
- ["switchwandstodebuff"] = "UseDispelItems",
- ["lootonlyrarecorpses"] = "MineOnly",
+ // switchwandstodebuff: not UseDispelItems (it turned dispel items on); kept for metas to read back (2026-12-01).
+ ["lootonlyrarecorpses"] = "LootOnlyRareCorpses", // was MineOnly, which nothing reads (2026-12-01 command audit)
// VTank-meta migration aliases (mirror of MetaManager.VtOptionMap so options
// set via /ub opt / /mt opt resolve the same as /vt opt set).
["autocram"] = "EnableAutocram",
@@ -299,10 +300,45 @@ public sealed partial class RynthAiPlugin
["autotrade.think"] = "AutoTradeThink",
["autotrade.onlyfrommainpack"] = "AutoTradeOnlyFromMainPack",
["autotrade.autoaccept"] = "AutoTradeAutoAccept",
+ // 2026-12-01 command audit: UtilityBelt and Mag-Tools options with the same RynthAi setting, which
+ // were only kept for metas to read.
+ ["inventorymanager.autocram"] = "EnableAutocram", // UB: cram items into side packs
+ ["inventorymanager.autostack"] = "EnableAutostack", // UB: stack items
+ ["autobuysell.enabled"] = "AutoVendorEnabled", // Mag-Tools' vendor buy/sell on open (UB AutoVendor grew from it)
+ ["autobuysell.testmode"] = "AutoVendorTestMode",
+ ["autotradeadd.enabled"] = "AutoTradeEnabled", // Mag-Tools: add a profile's items when a trade opens
+ ["looting.autolootchests"] = "LootChestsMacroOff", // Mag-Tools: a chest you open is looted by the loot profile
+ ["looting.autolootmycorpse"] = "LootOwnCorpse", // Mag-Tools: your own corpse is emptied
+ ["inventorymanagement.aetheriarevealer"] = "UnboxAetheriaWhenIdle", // reveal coalesced aetheria
+ ["iteminfoonident.enabled"] = "ItemInfoOnSelect", // RynthAi's item info is Mag-Tools' (MagItemDescriber)
};
+ ///
+ /// Options set by hand below, not through the settings map: Mag-Tools' Tinkering.AutoClickYes ("Auto Click
+ /// Yes on 100%") is RynthAi's Auto-confirm crafting at 100 percent (2026-12-01 command audit).
+ ///
+ private static readonly HashSet MtSpecialOptions = new(StringComparer.OrdinalIgnoreCase) { "tinkering.autoclickyes" };
+
+ private bool TrySetMtSpecialOption(string optName, string value)
+ {
+ if (!MtSpecialOptions.Contains(optName)) return false;
+ LegacyUiSettings? s = _dashboard?.Settings;
+ if (s == null) return true;
+ bool on = value is "1" || value.Equals("true", StringComparison.OrdinalIgnoreCase);
+ bool off = value is "0" || value.Equals("false", StringComparison.OrdinalIgnoreCase);
+ if (on) { s.AutoConfirmCraft = true; s.AutoConfirmCraftPercent = 100; }
+ else if (off) s.AutoConfirmCraft = false;
+ return true;
+ }
+
+ private string? GetMtSpecialOption(string optName)
+ => MtSpecialOptions.Contains(optName) && _dashboard?.Settings is { } s
+ ? (s.AutoConfirmCraft && s.AutoConfirmCraftPercent >= 100 ? "1" : "0")
+ : null;
+
private string? GetOptionValue(string optName)
{
+ if (GetMtSpecialOption(optName) is string special) return special;
if (MtOptionMap.TryGetValue(optName, out string? raName))
{
var map = _metaManager?.Expressions?.BuildSettingsMapPublic();
@@ -325,6 +361,7 @@ public sealed partial class RynthAiPlugin
_ => optVal
};
+ if (TrySetMtSpecialOption(optName, value)) return;
if (MtOptionMap.TryGetValue(optName, out string? raName))
{
var map = _metaManager?.Expressions?.BuildSettingsMapPublic();
diff --git a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs
index b647633..5b14d5e 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/ManaStoneManager.cs
@@ -85,6 +85,14 @@ internal sealed class ManaStoneManager
// low; no refill for a while instead of a stone every think tick.
private long _refillHoldUntil;
private const long RefillHoldMs = 2 * 60 * 1000;
+
+ // ...and once the hold ran out, the same stale read asked for a stone again: R-20261201-171624-0bcf (Coldeve),
+ // Loafers read 21% from before a refill, a stone every 2 minutes, each answered "Your items are fully
+ // charged" (the re-appraisal of 17 worn items didn't get through while looting was appraising). Now the
+ // server's "fully charged" stands for each worn item until its read changes (a newer appraisal) or the
+ // server says it is low: the read each item had then is kept, and that same read counts as full.
+ private readonly Dictionary _gearFullAtRead = new();
+ private bool _gearFullSnapshotDue;
private long _lastNoStoneDiagAt;
// Worn gear's mana is read from its last appraisal, and ACE never sends a change to it while the
@@ -312,16 +320,22 @@ internal sealed class ManaStoneManager
_host.Log($"[RynthAi] ManaStone: the server says worn gear is low ('{text.Trim()}') - refilling whatever the gear's mana reads say.");
_serverSaidGearLowAt = NowMs;
_refillHoldUntil = 0; // the server's word is newer than "fully charged"
+ _gearFullAtRead.Clear();
+ _gearFullSnapshotDue = false;
return;
}
// The stone-on-player reply's second line; it may arrive as a line of its own.
if (text.Contains("Your items are fully charged"))
{
_serverSaidGearLowAt = 0;
+ _gearFullSnapshotDue = true;
HoldRefills("the server says the worn items are fully charged");
}
if (text.Contains("no items equipped that need mana"))
+ {
_serverSaidGearLowAt = 0;
+ _gearFullSnapshotDue = true;
+ }
if (_state == TapState.TappingItem)
{
@@ -833,6 +847,22 @@ internal sealed class ManaStoneManager
|| item.Name.Contains("Mana Charge", StringComparison.OrdinalIgnoreCase);
}
+ ///
+ /// What the charged-stone search looks at: the pack walk (the client's own pack lists, what
+ /// reads) first, then every object the cache knows. The walk can
+ /// hold an item the cache has no entry for yet: on 11-30 a character's gear sat at 30-46% mana for
+ /// an hour with "eternal=True needs=True" and "no charged stone is known" every minute, because
+ /// the search read the cache alone and the Eternal Mana Charge was only in the walk.
+ ///
+ private IEnumerable RefillCandidates()
+ {
+ var seen = new HashSet();
+ foreach (var item in _objectCache.GetDirectInventory(forceRefresh: false))
+ if (seen.Add(item.Id)) yield return item;
+ foreach (var item in _objectCache.AllKnownObjects())
+ if (seen.Add(item.Id)) yield return item;
+ }
+
// FindChargedStone walks every known object; with tapping off it gates the whole tick, so
// the answer is kept for a few seconds.
private long _chargedCheckAt;
@@ -1014,7 +1044,7 @@ internal sealed class ManaStoneManager
int bestMana = 0;
bool requestedId = false;
- foreach (var item in _objectCache.AllKnownObjects())
+ foreach (var item in RefillCandidates())
{
if (!IsRefillStone(item)) continue;
if (!IsOwnedByPlayer(item, playerId) || !InPack(item.Id)) continue;
@@ -1150,6 +1180,9 @@ internal sealed class ManaStoneManager
string lowestName = "";
bool needs = false;
bool requestedThisPass = false;
+ bool snapshot = _gearFullSnapshotDue; // the server just said full: keep each read it had then
+ _gearFullSnapshotDue = false;
+ int trustedFull = 0;
foreach (var item in _objectCache.AllKnownObjects())
{
@@ -1214,6 +1247,13 @@ internal sealed class ManaStoneManager
requestedThisPass = true;
}
}
+ // The server said the gear is full since this read was taken: the same read counts as full.
+ if (snapshot) _gearFullAtRead[item.Id] = curMana;
+ if (_gearFullAtRead.TryGetValue(item.Id, out int fullRead))
+ {
+ if (fullRead == curMana) { trustedFull++; continue; }
+ _gearFullAtRead.Remove(item.Id); // a newer appraisal: the read is real again
+ }
int p = (int)(curMana * 100L / maxMana);
if (p < lowestPct) { lowestPct = p; lowestName = item.Name ?? ""; }
@@ -1239,6 +1279,7 @@ internal sealed class ManaStoneManager
_lastGearDiagAt = now;
_host.Log($"[RynthAi] ManaStone: gear check - worn={worn} manaReadable={readable} lowest={(readable > 0 ? $"{lowestPct}% ({lowestName})" : "n/a")} " +
$"refillBelow={(int)(pct * 100)}% eternal={eternal} needs={needs} tapping={_settings.EnableManaTapping}" +
+ (trustedFull > 0 ? $" fullPerServer={trustedFull}" : "") +
(serverLow ? $" serverSaidLow={(now - _serverSaidGearLowAt) / 1000}s ago" : "") +
(now < _refillHoldUntil ? $" hold={(_refillHoldUntil - now) / 1000}s" : ""));
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs
index 631b261..62daf44 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileParser.cs
@@ -888,13 +888,21 @@ internal static class AfFileParser
/// Drops empty nav routes (header only, 0 points) from the dict and
/// blanks EmbedNav action data on rules whose referenced nav was empty.
/// Non-empty embedded navs survive in the dict for runtime + save.
+ /// A rule naming a route the file has NO block for keeps its name (2026-11-30): it is a
+ /// NavProfiles route (MetaNavEmbedding copies it in on load). It used to be blanked whenever
+ /// the meta had any block at all, so that rule loaded no route.
///
private static void PruneEmbeddedNavs(List rules,
Dictionary> navRoutes)
{
if (navRoutes.Count == 0) return;
- var toRemove = new List();
+ // AfFileWriter writes an Embedded Nav Route with no route as "EmbedNav empty": no route,
+ // unless the meta carries one of that name (the blanking below used to catch it).
+ if (!navRoutes.ContainsKey(AfFileWriter.EmptyNavName))
+ ClearPlaceholderRefs(rules);
+
+ var toRemove = new HashSet(StringComparer.OrdinalIgnoreCase);
foreach (var kvp in navRoutes)
{
var content = kvp.Value;
@@ -904,23 +912,34 @@ internal static class AfFileParser
foreach (string key in toRemove)
navRoutes.Remove(key);
- ClearMissingEmbedRefs(rules, navRoutes);
+ if (toRemove.Count > 0) ClearEmptyEmbedRefs(rules, toRemove);
}
- private static void ClearMissingEmbedRefs(List rules,
- Dictionary> navRoutes)
+ private static void ClearPlaceholderRefs(List rules)
+ {
+ foreach (var rule in rules)
+ {
+ if (rule.Action == MetaActionType.EmbeddedNavRoute &&
+ string.Equals(rule.ActionData, AfFileWriter.EmptyNavName, StringComparison.Ordinal))
+ rule.ActionData = "";
+ if (rule.ActionChildren != null)
+ ClearPlaceholderRefs(rule.ActionChildren);
+ }
+ }
+
+ private static void ClearEmptyEmbedRefs(List rules, HashSet emptyRoutes)
{
foreach (var rule in rules)
{
if (rule.Action == MetaActionType.EmbeddedNavRoute &&
!string.IsNullOrEmpty(rule.ActionData) &&
- !navRoutes.ContainsKey(rule.ActionData))
+ emptyRoutes.Contains(rule.ActionData))
{
rule.ActionData = "";
}
if (rule.ActionChildren != null)
- ClearMissingEmbedRefs(rule.ActionChildren, navRoutes);
+ ClearEmptyEmbedRefs(rule.ActionChildren, emptyRoutes);
}
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs
index 270a24e..2d31a38 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/AfFileWriter.cs
@@ -43,7 +43,7 @@ internal static class AfFileWriter
.OrderBy(g => g.Key)
.ToList();
- // Collect embedded nav routes referenced by rules
+ // Collect embedded nav routes referenced by rules (cleaned, as the parser and MetaManager read them)
var navNames = new HashSet(StringComparer.OrdinalIgnoreCase);
CollectNavNames(rules, navNames);
@@ -69,6 +69,18 @@ internal static class AfFileWriter
{
if (embeddedNavs.TryGetValue(navName, out var content))
WriteNavSection(writer, navName, content);
+ else
+ {
+ // A key kept in another spelling ("None]" from an old settings file): the route still goes in.
+ foreach (var kv in embeddedNavs)
+ {
+ if (string.Equals(EmbedNavName.Clean(kv.Key), navName, StringComparison.OrdinalIgnoreCase))
+ {
+ WriteNavSection(writer, navName, kv.Value);
+ break;
+ }
+ }
+ }
}
}
@@ -94,6 +106,9 @@ internal static class AfFileWriter
// ── Rule writing ────────────────────────────────────────────────────────
+ /// The name written for an Embedded Nav Route with no route (metaf needs a tag); read back as none.
+ internal const string EmptyNavName = "empty";
+
/// A rule name on one line (it is written as a "~~ @name" comment line).
internal static string OneLine(string? text)
{
@@ -275,7 +290,7 @@ internal static class AfFileWriter
case MetaActionType.EmbeddedNavRoute:
{
- string navName = string.IsNullOrEmpty(data) ? "empty" : data.Split(';')[0];
+ string navName = string.IsNullOrEmpty(data) ? EmptyNavName : data.Split(';')[0];
writer.Write($"{keyword} {navName} {{[none]}}");
break;
}
@@ -354,7 +369,8 @@ internal static class AfFileWriter
if (rule.Action == MetaActionType.EmbeddedNavRoute &&
!string.IsNullOrEmpty(rule.ActionData))
{
- navNames.Add(rule.ActionData.Split(';')[0]);
+ string name = EmbedNavName.Clean(rule.ActionData.Split(';')[0]);
+ if (name.Length > 0) navNames.Add(name);
}
if (rule.ActionChildren != null)
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
index 2d5dc94..7cc027d 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/ExpressionEngine.cs
@@ -387,6 +387,7 @@ internal sealed partial class ExpressionEngine
// ── List functions ────────────────────────────────────────────────
"listcreate" => EvalListCreate(rawArgs),
+ "createlist" => EvalListCreate(rawArgs), // UtilityBelt's own name (R-20261201-211257-d2be)
// These change the list (the reference: "Returns the list object"). A list is text
// here, so the changed list is written back to the variable it came from.
"listadd" => ListOp(rawArgs, A(0), l => EvalListAdd(l, A(1))),
@@ -3728,6 +3729,12 @@ internal sealed partial class ExpressionEngine
["StopMacroWhenPackFull"] = (() => B(s.StopMacroWhenPackFull), v => s.StopMacroWhenPackFull = ToDouble(v) != 0),
["SummonPets"] = (() => B(s.SummonPets), v => s.SummonPets = ToDouble(v) != 0),
["MineOnly"] = (() => B(s.MineOnly), v => s.MineOnly = ToDouble(v) != 0),
+ // 2026-12-01 command audit: settings VTank options map onto (MetaManager.VtOptionMap).
+ ["LootOnlyRareCorpses"] = (() => B(s.LootOnlyRareCorpses), v => s.LootOnlyRareCorpses = ToDouble(v) != 0),
+ ["BlacklistAttempts"] = (() => I(s.BlacklistAttempts), v => { if (double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) && double.IsFinite(d)) s.BlacklistAttempts = Math.Clamp((int)Math.Round(d), 1, 20); }),
+ ["ManaTapMinMana"] = (() => I(s.ManaTapMinMana), v => { if (double.TryParse(v, NumberStyles.Float, CultureInfo.InvariantCulture, out double d) && double.IsFinite(d)) s.ManaTapMinMana = Math.Clamp((int)Math.Round(d), 0, 1_000_000); }),
+ ["RestamOthersAt"] = (() => I(s.RestamOthersAt), v => { if (int.TryParse(v, out int i)) s.RestamOthersAt = Math.Clamp(i, 0, 100); }),
+ ["InfuseOthersAt"] = (() => I(s.InfuseOthersAt), v => { if (int.TryParse(v, out int i)) s.InfuseOthersAt = Math.Clamp(i, 0, 100); }),
["UseDispelItems"] = (() => B(s.UseDispelItems), v => s.UseDispelItems = ToDouble(v) != 0),
["CastDispelSelf"] = (() => B(s.CastDispelSelf), v => s.CastDispelSelf = ToDouble(v) != 0),
["AutoFellowMgmt"] = (() => B(s.AutoFellowMgmt), v => s.AutoFellowMgmt = ToDouble(v) != 0),
@@ -3796,6 +3803,7 @@ internal sealed partial class ExpressionEngine
["CastBuffsOverItemBuffs"] = (() => B(s.CastBuffsOverItemBuffs), v => s.CastBuffsOverItemBuffs = ToDouble(v) != 0),
["FastBuffChain"] = (() => B(s.FastBuffChain), v => s.FastBuffChain = ToDouble(v) != 0),
["SkipUnusableBuffs"] = (() => B(s.SkipUnusableBuffs), v => s.SkipUnusableBuffs = ToDouble(v) != 0),
+ ["RecastDispelledInFight"] = (() => B(s.RecastDispelledInFight), v => s.RecastDispelledInFight = ToDouble(v) != 0),
["UseFellowshipBuffs"] = (() => B(s.UseFellowshipBuffs), v => s.UseFellowshipBuffs = ToDouble(v) != 0),
["BuffShield"] = (() => B(s.BuffShield), v => s.BuffShield = ToDouble(v) != 0),
// AutoVendor (UB names map here through /ub opt: AutoVendor.Enabled -> AutoVendorEnabled, ...)
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.Resume.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.Resume.cs
index 5b60917..f0e95e1 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.Resume.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.Resume.cs
@@ -53,6 +53,7 @@ internal sealed partial class MetaManager
s.RouteLines = _settings.CurrentRoute != null && _settings.CurrentRoute.Points.Count > 0
? new List(_settings.CurrentRoute.ToLines())
: new List();
+ s.RouteMadeBy = _settings.CurrentRoute?.MadeBy ?? "";
s.NavIndex = _settings.ActiveNavIndex;
s.NavEnabled = _settings.EnableNavigation;
}
@@ -107,6 +108,7 @@ internal sealed partial class MetaManager
_settings.CurrentNavPath = s.NavPath;
_settings.CurrentRoute = s.RouteLines.Count > 0 ? NavRouteParser.LoadFromLines(s.RouteLines) : new NavRouteParser();
+ _settings.CurrentRoute.MadeBy = s.RouteMadeBy ?? "";
_settings.ActiveNavIndex = Math.Clamp(s.NavIndex, 0, Math.Max(0, _settings.CurrentRoute.Points.Count));
_settings.EnableNavigation = s.NavEnabled;
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs
index a0aafa8..3c02470 100644
--- a/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs
+++ b/Plugins/RynthCore.Plugin.RynthAi/Meta/MetaManager.cs
@@ -1405,6 +1405,32 @@ internal sealed partial class MetaManager
return true;
}
+ // /vt meta save — the loaded meta saved under that name, which is then its file (2026-12-01
+ // command audit: it answered with the usage). /ra meta saveas: the same file again saves it, another
+ // existing one is refused (a command never replaces a file).
+ if (sub == "meta" && parts.Length >= 4 &&
+ parts[2].Equals("save", StringComparison.OrdinalIgnoreCase))
+ {
+ _raCommandHandler?.Invoke("/ra meta saveas " + string.Join(" ", parts, 3, parts.Length - 3));
+ return true;
+ }
+
+ // /vt loot save — a copy of the loot profile in use under that name, then looted with (as
+ // VTank's save does; 2026-12-01 command audit). The profile in use itself is already saved.
+ if ((sub == "loot" || sub == "lootprofile" || sub == "looting") && parts.Length >= 4 &&
+ parts[2].Equals("save", StringComparison.OrdinalIgnoreCase))
+ {
+ string name = string.Join(" ", parts, 3, parts.Length - 3).Trim().Trim('"');
+ string current = _settings.CurrentLootPath ?? string.Empty;
+ if (current.Length > 0 && IsLootProfileNamed(current, name))
+ {
+ Reply.Ok($"[RynthAi] {Path.GetFileName(current)} is the loot profile in use; it is saved (the Loot Editor saves its changes).");
+ return true;
+ }
+ _raCommandHandler?.Invoke("/ra loot saveas " + name);
+ return true;
+ }
+
// /vt nav load — load a nav route
// It used to store only the bare name as the nav path, so nothing loaded.
// /vt nav save saves the current route under that name.
@@ -1461,15 +1487,20 @@ internal sealed partial class MetaManager
return true;
}
- // /vt settings loadchar|savechar — RynthAi's settings profiles (/ra settings ...);
- // universalremote.met switches profiles this way. Any other /vt settings verb is ignored.
+ // /vt settings loadchar|savechar|load|save — RynthAi's settings profiles (/ra settings ...);
+ // universalremote.met switches profiles this way. VTank's load|save are its shared profiles and
+ // loadchar|savechar this character's; RynthAi's profiles are all the character's, so both pairs are
+ // the same here (load|save answered with the usage until the 2026-12-01 command audit).
if (sub == "settings")
{
- if (parts.Length >= 4 && (parts[2].Equals("loadchar", StringComparison.OrdinalIgnoreCase)
- || parts[2].Equals("savechar", StringComparison.OrdinalIgnoreCase)))
- _raCommandHandler?.Invoke($"/ra settings {parts[2].ToLowerInvariant()} {string.Join(" ", parts, 3, parts.Length - 3)}");
+ string verb = parts.Length >= 4 ? parts[2].ToLowerInvariant() : "";
+ if (verb is "loadchar" or "load") verb = "loadchar";
+ else if (verb is "savechar" or "save") verb = "savechar";
+ else verb = "";
+ if (verb.Length > 0)
+ _raCommandHandler?.Invoke($"/ra settings {verb} {string.Join(" ", parts, 3, parts.Length - 3)}");
else
- Reply.Ignored("[RynthAi] Usage: /vt settings loadchar|savechar (other /vt settings verbs are VTank's own; ignored).");
+ Reply.Ignored("[RynthAi] Usage: /vt settings load|save|loadchar|savechar (other /vt settings verbs are VTank's own; ignored).");
return true;
}
@@ -1515,19 +1546,58 @@ internal sealed partial class MetaManager
return true;
}
- // /vt reverseroute — reverse the active nav route in place (shared settings;
- // the engine re-reads CurrentRoute each tick, so the flip takes effect next tick).
+ // /vt reverseroute [true|false] — the route's direction (shared settings; the engine re-reads
+ // CurrentRoute each tick). VTank sets it from the argument: true = reversed, false = the file's own
+ // order, none = the other way. It flipped on every call before (2026-12-01 command audit: a meta
+ // sending "reverseroute true" on each state entry ran the route the wrong way every other time).
+ // A route newly loaded is the file's way round. /vt reverseroutequery says which way it is.
if (sub == "reverseroute")
{
var route = _settings.CurrentRoute;
- if (route?.Points != null && route.Points.Count > 0)
+ if (route?.Points == null || route.Points.Count == 0)
+ {
+ Reply.Fail("[RynthAi] /vt reverseroute: no route is loaded.");
+ return true;
+ }
+ bool reversedNow = RouteReversed;
+ bool? asked = parts.Length >= 3 ? ParseVtBool(parts[2]) : null;
+ if (parts.Length >= 3 && asked == null)
+ {
+ Reply.Fail("[RynthAi] Usage: /vt reverseroute [true|false]");
+ return true;
+ }
+ bool want = asked ?? !reversedNow;
+ int n = route.Points.Count;
+ if (want != reversedNow)
{
- int n = route.Points.Count;
route.Points.Reverse();
_settings.ActiveNavIndex = Math.Clamp(n - 1 - _settings.ActiveNavIndex, 0, n - 1);
- Reply.Ok($"[RynthAi] Route reversed ({n} pts).");
}
- else Reply.Fail("[RynthAi] /vt reverseroute: no route is loaded.");
+ _reversedRoute = route;
+ _routeReversed = want;
+ Reply.Ok(want == reversedNow
+ ? $"[RynthAi] Route already {(want ? "reversed" : "in its own order")} ({n} pts)."
+ : $"[RynthAi] Route {(want ? "reversed" : "back in its own order")} ({n} pts).");
+ return true;
+ }
+ // /vt addnavjump [...]: a jump step at the end of the route
+ // (VTank's form), as /ra nav addjump does with a given heading (2026-12-01 command audit).
+ if (sub == "addnavjump")
+ {
+ if (parts.Length < 5
+ || !float.TryParse(parts[2], System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out float jh)
+ || ParseVtBool(parts[3]) is not bool jshift
+ || !int.TryParse(parts[4], System.Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.InvariantCulture, out int jms))
+ {
+ Reply.Fail("[RynthAi] Usage: /vt addnavjump ");
+ return true;
+ }
+ _raCommandHandler?.Invoke(FormattableString.Invariant($"/ra nav addjump {Math.Clamp(jms, 0, 1000)}{(jshift ? " shift" : "")} heading {jh}"));
+ return true;
+ }
+ if (sub == "reverseroutequery")
+ {
+ Reply.Ok($"[RynthAi] Route reversed: {(RouteReversed ? "true" : "false")}.");
return true;
}
@@ -1566,8 +1636,8 @@ internal sealed partial class MetaManager
/// The /vt verbs RynthAi takes, for the usage line.
internal const string VtVerbList = "opt set|get|list,
public sealed partial class RynthAiPlugin
{
@@ -29,6 +29,7 @@ public sealed partial class RynthAiPlugin
/// Runs /ub delay commands that are due. Called every tick.
private void TickDelayedCommands()
{
+ TickUbInventoryJobs(); // /ub equip load|test, /ub autosalvage
// Out of world, OnChatBarEnter ignores the line and it went raw to AC's chat
// parser at character select. TeardownSession empties the queue at logout.
if (_delayedCommands.Count == 0 || !_loginComplete) return;
@@ -100,6 +101,11 @@ public sealed partial class RynthAiPlugin
case "dumpskills": UbDumpSkills(); return true;
case "quests": UbQuests(args); return true;
case "translateroute": UbTranslateRoute(args); return true;
+ // Equipment profiles and AutoSalvage by a loot profile (UtilityBeltInventoryCommands.cs,
+ // 2026-12-01 command audit): equip went on to /mt equip ("Item not found: load ..."),
+ // autosalvage was accepted and ignored. "/ub equip " still wields by name (/mt equip).
+ case "equip" when UbEquipOwns(args): UbEquip(args); return true;
+ case "autosalvage": UbAutoSalvage(args); return true;
}
return false;
}
@@ -149,8 +155,16 @@ public sealed partial class RynthAiPlugin
}
case "profile":
{
+ // Read for the count only: TryLoadLootProfile also made it the profile looting uses, so a meta
+ // counting against another profile switched what it looted (2026-12-01 command audit).
string path = ResolveLootProfilePath(what);
- if (path.Length == 0 || !TryLoadLootProfile(path, out VTankLootProfile profile, out _)) { ReplyFail($"[RynthAi] count: loot profile not found: {what}"); return; }
+ VTankLootProfile profile;
+ try
+ {
+ if (path.Length == 0 || !File.Exists(path)) { ReplyFail($"[RynthAi] count: loot profile not found: {what}"); return; }
+ profile = VTankLootParser.Load(path);
+ }
+ catch (Exception ex) { ReplyFail($"[RynthAi] count: couldn't read {Path.GetFileName(path)}: {ex.Message}"); return; }
var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
int n = 0;
foreach (var wo in inv)
@@ -307,7 +321,9 @@ public sealed partial class RynthAiPlugin
case "toggle" when w.Length >= 2:
foreach (string name in w.Skip(1))
{
- if (!map.TryGetValue(name, out var tg)) { ReplyFail($"[RynthAi] No option '{name}'."); continue; }
+ // UtilityBelt's names (InventoryManager.AutoCram ...) through the /ub opt map (2026-12-01 command audit).
+ string key = MtOptionMap.TryGetValue(name, out string? mapped) ? mapped : name;
+ if (!map.TryGetValue(key, out var tg)) { ReplyFail($"[RynthAi] No option '{name}'."); continue; }
tg.Set(tg.Get() is "0" or "" or "False" ? "1" : "0");
ReplyOk($"[RynthAi] {name} = {tg.Get()}");
}
@@ -323,7 +339,7 @@ public sealed partial class RynthAiPlugin
{
ChatLine("[RynthAi] /ub commands: use[i][l][p], give[p], ig[p], select, face, fellow, equip, combatstate, close, quit, logout, " +
"follow[p], mexec, myquests, list[g|p]vars, propertydump, jump[swzxc], simplejump, closestportal, portal[p], " +
- "autovendor, vendor, autotrade, autostack, autocram, delay, count, date[utc], id, pos, vitae, playsound, " +
+ "autovendor, vendor, autotrade, autostack, autocram, autosalvage, delay, count, date[utc], id, pos, vitae, playsound, " +
"setmotion, getmotion, clearmotion, opt, dumpskills, quests, translateroute, clearbugged.");
}
diff --git a/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltInventoryCommands.cs b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltInventoryCommands.cs
new file mode 100644
index 0000000..4d47aac
--- /dev/null
+++ b/Plugins/RynthCore.Plugin.RynthAi/UtilityBeltInventoryCommands.cs
@@ -0,0 +1,512 @@
+// ============================================================================
+// RynthAi - UtilityBeltInventoryCommands.cs
+// UtilityBelt's /ub equip list|load|test|create and /ub autosalvage [force]
+// (2026-12-01 command audit). Both judge what the character carries by a loot
+// profile's rules, so they share one job: read the profile, identify the items
+// whose rule needs it, then act.
+//
+// /ub equip used to fall through to /mt equip, which looked for an item named
+// "load" and failed, so a meta's armor or weapon swap did nothing. /ub autosalvage
+// was accepted and ignored.
+// ============================================================================
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using RynthCore.Loot;
+using RynthCore.Loot.Editing;
+using RynthCore.Loot.VTank;
+using RynthCore.Plugin.RynthAi.Loot;
+using RynthCore.Plugin.Shared;
+
+namespace RynthCore.Plugin.RynthAi;
+
+///
+/// Which items of an equipment profile go on, one per slot (pure, so tests can run it). An item is
+/// placed in the order of its rule (then of the inventory); a slot can only take one item. Rings and
+/// bracelets fit either of their two slots; the weapon slots (melee, missile, wand, two-handed) are
+/// one hand, so one weapon. Items already worn keep their slots.
+///
+internal static class UbEquipPlan
+{
+ // AC's EquipMask bits (ValidLocations / CurrentWieldedLocation).
+ internal const int MeleeWeapon = 0x00100000, MissileWeapon = 0x00400000, Held = 0x01000000, TwoHanded = 0x02000000;
+ internal const int WeaponSlots = MeleeWeapon | MissileWeapon | Held | TwoHanded;
+ internal const int WristPair = 0x00010000 | 0x00020000, FingerPair = 0x00040000 | 0x00080000;
+
+ ///
+ /// A carried item a Keep rule takes. is where it can go (ValidLocations),
+ /// where it is worn now (0 when that isn't known); sorts them.
+ ///
+ public readonly record struct Item(int Id, string Name, int Slots, bool Worn, int WornSlots, int Order);
+
+ public sealed class Result
+ {
+ public List Equip { get; } = new();
+ public List AlreadyWorn { get; } = new();
+ public List<(Item Item, string Why)> Skipped { get; } = new();
+ }
+
+ public static Result Plan(IEnumerable matched)
+ {
+ var result = new Result();
+ var list = matched.OrderBy(i => i.Order).ToList();
+ int taken = 0;
+ foreach (Item worn in list.Where(i => i.Worn))
+ {
+ taken |= Expand(worn.WornSlots);
+ result.AlreadyWorn.Add(worn);
+ }
+ foreach (Item item in list.Where(i => !i.Worn))
+ {
+ if (item.Slots == 0) result.Skipped.Add((item, "it isn't something to wear or wield"));
+ else if (TryClaim(item.Slots, ref taken)) result.Equip.Add(item);
+ else result.Skipped.Add((item, "another item of the profile has its slot"));
+ }
+ return result;
+ }
+
+ private static int Expand(int slots) => (slots & WeaponSlots) != 0 ? slots | WeaponSlots : slots;
+
+ private static bool TryClaim(int slots, ref int taken)
+ {
+ foreach (int pair in new[] { WristPair, FingerPair })
+ {
+ if ((slots & ~pair) != 0 || (slots & pair) != pair) continue;
+ int free = pair & ~taken;
+ if (free == 0) return false;
+ taken |= free & -free; // the lower free one of the two
+ return true;
+ }
+ int need = Expand(slots);
+ if ((need & taken) != 0) return false;
+ taken |= need;
+ return true;
+ }
+}
+
+public sealed partial class RynthAiPlugin
+{
+ /// Where /ub equip finds and makes its profiles: RynthAi's LootProfiles (tests point it elsewhere).
+ internal static string UbEquipFolder { get; set; } = LootEditorBridge.LootFolder;
+
+ internal const string UbEquipUsage = "/ub equip list | load | test | create ";
+ internal const string UbAutoSalvageUsage = "/ub autosalvage [force]";
+
+ // Pacing: one identify every IdSpacingMs, a wait of IdWaitMs for the last one, the whole job at
+ // most JobMaxMs; one wield every EquipSpacingMs, the check EquipSettleMs after the last.
+ internal const long UbIdSpacingMs = 300, UbIdWaitMs = 3000, UbJobMaxMs = 60_000;
+ internal const long UbEquipSpacingMs = 700, UbEquipSettleMs = 2000;
+ internal const int UbMaxIds = 100;
+
+ // STypeInts AutoSalvage reads (UtilityBelt leaves tinkered and imbued items alone).
+ private const uint NumTimesTinkeredInt = 171, ImbuedEffectInt = 179;
+
+ private enum UbInvKind { EquipLoad, EquipTest, Salvage, SalvageForce }
+
+ private sealed class UbInvJob
+ {
+ public UbInvKind Kind;
+ public InventoryRules Rules = null!;
+ public bool FromMeta;
+ public long StartedAt;
+ public long NextIdAt;
+ public long LastIdAt;
+ public readonly Queue IdQueue = new();
+ public readonly List Asked = new();
+ }
+
+ private UbInvJob? _ubInvJob;
+ private readonly Queue<(uint Id, string Name)> _ubEquipSends = new();
+ private readonly List<(uint Id, string Name)> _ubEquipSent = new();
+ private long _ubEquipNextAt, _ubEquipLastAt;
+ private bool _ubEquipFromMeta;
+ private string _ubEquipProfile = string.Empty;
+
+ /// Milliseconds for the job's pacing (tests move it on).
+ internal Func UbInvClock { get; set; } = () => Environment.TickCount64;
+
+ /// The profile a /ub equip or /ub autosalvage line names: a full path, else LootProfiles\name[.utl|.json].
+ internal static string ResolveUbEquipProfile(string name)
+ {
+ string n = name.Trim().Trim('"');
+ if (n.Length == 0) return string.Empty;
+ if (Path.IsPathFullyQualified(n)) return File.Exists(n) ? n : string.Empty;
+ foreach (string cand in new[] { n, n + ".utl", n + ".json" })
+ {
+ string p = Path.Combine(UbEquipFolder, cand);
+ if (File.Exists(p)) return p;
+ }
+ return string.Empty;
+ }
+
+ // ── /ub equip ─────────────────────────────────────────────────────────
+
+ ///
+ /// UtilityBelt's own /ub equip line (list, load, test, create, or nothing). Anything else is an item
+ /// name, as metas wrote for the /mt equip this used to be: that still wields the item.
+ ///
+ internal static bool UbEquipOwns(string args)
+ {
+ string first = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries) is { Length: > 0 } w ? w[0].ToLowerInvariant() : "";
+ return first is "" or "list" or "load" or "test" or "create";
+ }
+
+ private void UbEquip(string args)
+ {
+ string[] w = args.Split(' ', 2, StringSplitOptions.RemoveEmptyEntries);
+ string sub = w.Length > 0 ? w[0].ToLowerInvariant() : "";
+ string name = w.Length > 1 ? w[1].Trim() : "";
+ switch (sub)
+ {
+ case "list":
+ UbEquipList();
+ return;
+ case "load" or "test" when name.Length > 0:
+ {
+ string path = ResolveUbEquipProfile(name);
+ if (path.Length == 0) { ReplyFail($"[RynthAi] /ub equip: no profile '{name}' in {UbEquipFolder}."); return; }
+ InventoryRules? rules = InventoryRules.Load(path, out string why);
+ if (rules == null) { ReplyFail($"[RynthAi] /ub equip: couldn't read {Path.GetFileName(path)}: {why}"); return; }
+ StartUbInvJob(sub == "load" ? UbInvKind.EquipLoad : UbInvKind.EquipTest, rules);
+ return;
+ }
+ case "create" when name.Length > 0:
+ UbEquipCreate(name);
+ return;
+ }
+ ReplyFail("[RynthAi] Usage: " + UbEquipUsage);
+ }
+
+ private void UbEquipList()
+ {
+ var names = new List();
+ try
+ {
+ if (Directory.Exists(UbEquipFolder))
+ foreach (string f in Directory.GetFiles(UbEquipFolder))
+ if (f.EndsWith(".utl", StringComparison.OrdinalIgnoreCase) || f.EndsWith(".json", StringComparison.OrdinalIgnoreCase))
+ names.Add(Path.GetFileName(f));
+ }
+ catch (IOException) { }
+ catch (UnauthorizedAccessException) { }
+ names.Sort(StringComparer.OrdinalIgnoreCase);
+ ChatLine(names.Count == 0
+ ? $"[RynthAi] Equipment profiles: none in {UbEquipFolder}. /ub equip create makes one from what you wear."
+ : $"[RynthAi] Equipment profiles ({names.Count}, the loot profiles in {UbEquipFolder}): {string.Join(", ", names)}");
+ }
+
+ ///
+ /// /ub equip create <name>: LootProfiles\<name>.utl with one Keep rule per worn item (its exact
+ /// name and object class), so /ub equip load puts the same things on again. Never over an existing file:
+ /// the folder holds the loot profiles too.
+ ///
+ private void UbEquipCreate(string raw)
+ {
+ if (_objectCache == null || _playerId == 0) { ReplyFail("[RynthAi] /ub equip create: not ready (log in first)."); return; }
+ string? why = LegacyUi.ProfileFileOps.CleanName(raw, LegacyUi.LegacyDashboardRenderer.LootExtensions, out string name);
+ if (why != null) { ReplyFail($"[RynthAi] /ub equip create: can't use '{name}': {why}."); return; }
+ string path = Path.Combine(UbEquipFolder, name + ".utl");
+ if (File.Exists(path) || File.Exists(Path.Combine(UbEquipFolder, name + ".json")))
+ {
+ ReplyFail($"[RynthAi] /ub equip create: {name} already exists in {UbEquipFolder}; pick another name.");
+ return;
+ }
+
+ var profile = new VTankLootProfile();
+ var seen = new HashSet(StringComparer.OrdinalIgnoreCase);
+ foreach (WorldObject wo in _objectCache.GetDirectInventory(forceRefresh: true))
+ {
+ if (!WorldObjectCache.IsWieldedByPlayer(Host, wo) || string.IsNullOrWhiteSpace(wo.Name)) continue;
+ if (!seen.Add(wo.Name + "|" + (int)wo.ObjectClass)) continue; // two of the same ring: one rule takes both
+ var rule = new VTankLootRule { Name = "Equip " + wo.Name.Trim(), Action = VTankLootAction.Keep, CustomExpression = string.Empty };
+ if (wo.ObjectClass != AcObjectClass.Unknown)
+ rule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.ObjectClass, "0",
+ new[] { ((int)wo.ObjectClass).ToString(System.Globalization.CultureInfo.InvariantCulture) }));
+ rule.Conditions.Add(new VTankLootCondition(VTankNodeTypes.StringValueMatch, "0",
+ new[] { LootItemRules.ExactPattern(wo.Name.Trim()), "1" }));
+ profile.Rules.Add(rule);
+ }
+ if (profile.Rules.Count == 0) { ReplyFail("[RynthAi] /ub equip create: you aren't wearing anything to put in it."); return; }
+ if (!DataWriteGuard.TrySave("the equipment profile", path, () =>
+ {
+ Directory.CreateDirectory(UbEquipFolder);
+ VTankLootWriter.Save(profile, path);
+ }, out string saveWhy, callerShows: true))
+ {
+ ReplyFail($"[RynthAi] /ub equip create: couldn't write {Path.GetFileName(path)}: {saveWhy}");
+ return;
+ }
+ ReplyOk($"[RynthAi] Equipment profile {Path.GetFileName(path)}: {profile.Rules.Count} item(s) you wear. /ub equip load {name} puts them on.");
+ }
+
+ // ── /ub autosalvage ───────────────────────────────────────────────────
+
+ ///
+ /// /ub autosalvage [force] (UtilityBelt): the carried items the loot profile in use says Salvage.
+ /// As UtilityBelt, nothing is salvaged without "force" (UB only fills its salvage window then):
+ /// here that lists them. With "force" they go to RynthAi's salvage queue, which skips what it
+ /// always skips (worn, retained, the Items list, the UST, bags). Tinkered and imbued items are
+ /// left out as UtilityBelt does; AutoSalvage.OnlyFromMainPack (a /ub opt) keeps to the main pack.
+ ///
+ private void UbAutoSalvage(string args)
+ {
+ string a = args.Trim().ToLowerInvariant();
+ if (a.Length > 0 && a != "force") { ReplyFail("[RynthAi] Usage: " + UbAutoSalvageUsage); return; }
+ string path = (_dashboard?.Settings?.CurrentLootPath ?? string.Empty).Trim().Trim('"');
+ if (path.Length == 0) { ReplyFail("[RynthAi] /ub autosalvage: no loot profile in use (pick one under LOOT)."); return; }
+ InventoryRules? rules = InventoryRules.Load(path, out string why);
+ if (rules == null) { ReplyFail($"[RynthAi] /ub autosalvage: couldn't read {Path.GetFileName(path)}: {why}"); return; }
+ if (a == "force" && _salvageManager == null) { ReplyFail("[RynthAi] /ub autosalvage: salvaging isn't ready (log in first)."); return; }
+ StartUbInvJob(a == "force" ? UbInvKind.SalvageForce : UbInvKind.Salvage, rules);
+ }
+
+ // ── The job ───────────────────────────────────────────────────────────
+
+ private bool IsEquipJob(UbInvKind k) => k is UbInvKind.EquipLoad or UbInvKind.EquipTest;
+
+ private string UbVerb(UbInvKind k) => k switch
+ {
+ UbInvKind.EquipLoad => "/ub equip load",
+ UbInvKind.EquipTest => "/ub equip test",
+ UbInvKind.Salvage => "/ub autosalvage",
+ _ => "/ub autosalvage force",
+ };
+
+ /// The items the job judges: wearables for equip (worn ones too), else what is in the packs.
+ private List UbInvCandidates(UbInvKind kind)
+ {
+ var list = new List();
+ if (_objectCache == null) return list;
+ foreach (WorldObject wo in _objectCache.GetDirectInventory(forceRefresh: true))
+ {
+ if (IsEquipJob(kind))
+ {
+ if (wo.Values(LongValueKey.Locations, 0) != 0 || WorldObjectCache.IsWieldedByPlayer(Host, wo)) list.Add(wo);
+ }
+ else if (wo.ObjectClass != AcObjectClass.Container && !WorldObjectCache.IsWieldedByPlayer(Host, wo))
+ list.Add(wo);
+ }
+ return list;
+ }
+
+ private bool HasIdData(uint id) => !Host.HasHasAppraisalData || Host.HasAppraisalData(id);
+
+ private void StartUbInvJob(UbInvKind kind, InventoryRules rules)
+ {
+ if (_objectCache == null || _playerId == 0) { ReplyFail($"[RynthAi] {UbVerb(kind)}: not ready (log in first)."); return; }
+ if (_ubInvJob != null) Log($"[RynthAi] {UbVerb(kind)}: replaces {UbVerb(_ubInvJob.Kind)} ({_ubInvJob.Rules.FileName}), which hadn't finished.");
+ if (kind == UbInvKind.EquipLoad) { _ubEquipSends.Clear(); _ubEquipSent.Clear(); }
+
+ var job = new UbInvJob { Kind = kind, Rules = rules, FromMeta = Reply.FromScript, StartedAt = UbInvClock() };
+ var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
+ bool salvage = !IsEquipJob(kind);
+ foreach (WorldObject wo in UbInvCandidates(kind))
+ {
+ uint id = unchecked((uint)wo.Id);
+ if (HasIdData(id) || !Host.HasRequestId) continue;
+ VTankLootVerdict v = rules.Decide(wo, ctx, _charSkills, hasIdData: false, out InventoryRuleKind k, out _);
+ // Salvage also needs the ID to tell a tinkered or imbued item.
+ if (v == VTankLootVerdict.NeedsId || (salvage && v == VTankLootVerdict.Match && k == InventoryRuleKind.Salvage))
+ if (job.IdQueue.Count < UbMaxIds) job.IdQueue.Enqueue(id);
+ }
+ _ubInvJob = job;
+ if (job.IdQueue.Count == 0) { FinishUbInvJob(job); return; }
+ Log($"[RynthAi] {UbVerb(kind)} {rules.FileName}: identifying {job.IdQueue.Count} item(s) first.");
+ Reply.Ok($"[RynthAi] {UbVerb(kind)} {rules.FileName}: identifying {job.IdQueue.Count} item(s) first.");
+ }
+
+ /// Pump thread, every tick: the job's identifies, then its result; the wields of an equip load.
+ private void TickUbInventoryJobs()
+ {
+ if (!_loginComplete) return;
+ long now = UbInvClock();
+ UbInvJob? job = _ubInvJob;
+ if (job != null)
+ {
+ if (job.IdQueue.Count > 0)
+ {
+ if (now >= job.NextIdAt)
+ {
+ uint id = job.IdQueue.Dequeue();
+ if (!HasIdData(id) && Host.RequestId(id)) job.Asked.Add(id);
+ job.NextIdAt = now + UbIdSpacingMs;
+ job.LastIdAt = now;
+ }
+ }
+ else if (job.Asked.All(HasIdData) || now - job.LastIdAt >= UbIdWaitMs || now - job.StartedAt >= UbJobMaxMs)
+ {
+ FinishUbInvJob(job);
+ }
+ }
+ TickUbEquipSends(now);
+ }
+
+ private void FinishUbInvJob(UbInvJob job)
+ {
+ if (ReferenceEquals(_ubInvJob, job)) _ubInvJob = null;
+ if (IsEquipJob(job.Kind)) FinishUbEquip(job);
+ else FinishUbAutoSalvage(job);
+ }
+
+ /// A job's answer: as its command would have said it (quiet in chat when a meta sent it, except Info).
+ private void UbJobSay(UbInvJob job, string text, bool fail = false, bool info = false)
+ {
+ if (job.FromMeta) RunAsMeta(() => { Say(); return true; });
+ else Say();
+
+ void Say()
+ {
+ if (info) ChatLine(text);
+ else if (fail) ReplyFail(text);
+ else ReplyOk(text);
+ }
+ }
+
+ private static string Names(IEnumerable names, int max = 12)
+ {
+ var l = names.ToList();
+ return l.Count <= max ? string.Join(", ", l) : string.Join(", ", l.Take(max)) + $" and {l.Count - max} more";
+ }
+
+ private void FinishUbEquip(UbInvJob job)
+ {
+ var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
+ var matched = new List();
+ int order = 0, unidentified = 0;
+ var ruleOrder = new Dictionary(StringComparer.Ordinal);
+ foreach (WorldObject wo in UbInvCandidates(job.Kind))
+ {
+ uint id = unchecked((uint)wo.Id);
+ VTankLootVerdict v = job.Rules.Decide(wo, ctx, _charSkills, HasIdData(id), out InventoryRuleKind k, out string rule);
+ if (v == VTankLootVerdict.NeedsId) { unidentified++; continue; }
+ if (v != VTankLootVerdict.Match || k != InventoryRuleKind.Keep) continue;
+ if (!ruleOrder.TryGetValue(rule, out int r)) ruleOrder[rule] = r = ruleOrder.Count;
+ bool worn = WorldObjectCache.IsWieldedByPlayer(Host, wo);
+ int slots = wo.Values(LongValueKey.Locations, 0);
+ int wornAt = 0;
+ if (worn)
+ {
+ wornAt = wo.Values(LongValueKey.CurrentWieldedLocation, 0);
+ if (wornAt <= 0 && Host.HasGetObjectWielderInfo && Host.TryGetObjectWielderInfo(id, out _, out uint loc)) wornAt = unchecked((int)loc);
+ if (wornAt < 0) wornAt = 0;
+ }
+ matched.Add(new UbEquipPlan.Item(wo.Id, wo.Name, slots, worn, wornAt, r * 10_000 + order++));
+ }
+ UbEquipPlan.Result plan = UbEquipPlan.Plan(matched);
+ string profile = job.Rules.FileName;
+ string idNote = unidentified > 0 ? $" {unidentified} item(s) couldn't be identified in time and were left out." : "";
+
+ if (job.Kind == UbInvKind.EquipTest)
+ {
+ UbJobSay(job, $"[RynthAi] /ub equip test {profile}: "
+ + (plan.Equip.Count > 0 ? $"would equip {Names(plan.Equip.Select(i => i.Name))}" : "nothing to equip")
+ + (plan.AlreadyWorn.Count > 0 ? $"; already worn: {Names(plan.AlreadyWorn.Select(i => i.Name))}" : "")
+ + (plan.Skipped.Count > 0 ? $"; left out: {Names(plan.Skipped.Select(s => $"{s.Item.Name} ({s.Why})"))}" : "")
+ + "." + idNote, info: true);
+ return;
+ }
+
+ if (plan.Equip.Count == 0)
+ {
+ UbJobSay(job, matched.Count == 0
+ ? $"[RynthAi] /ub equip load {profile}: nothing you carry matches its rules.{idNote}"
+ : $"[RynthAi] /ub equip load {profile}: nothing to put on ({plan.AlreadyWorn.Count} already worn).{idNote}",
+ fail: matched.Count == 0);
+ return;
+ }
+ if (!Host.HasUseObject) { UbJobSay(job, "[RynthAi] /ub equip load: this RynthCore can't use items.", fail: true); return; }
+ _ubEquipSends.Clear();
+ _ubEquipSent.Clear();
+ foreach (UbEquipPlan.Item i in plan.Equip) _ubEquipSends.Enqueue((unchecked((uint)i.Id), i.Name));
+ _ubEquipFromMeta = job.FromMeta;
+ _ubEquipProfile = profile;
+ _ubEquipNextAt = 0;
+ Log($"[RynthAi] /ub equip load {profile}: equipping {Names(plan.Equip.Select(i => i.Name), 40)}"
+ + (plan.Skipped.Count > 0 ? $"; left out: {Names(plan.Skipped.Select(s => $"{s.Item.Name} ({s.Why})"), 40)}" : "") + "." + idNote);
+ UbJobSay(job, $"[RynthAi] /ub equip load {profile}: equipping {plan.Equip.Count} item(s).{idNote}");
+ TickUbEquipSends(UbInvClock());
+ }
+
+ /// One wield per ; after the last, says how many went on.
+ private void TickUbEquipSends(long now)
+ {
+ if (_ubEquipSends.Count > 0)
+ {
+ if (now < _ubEquipNextAt) return;
+ var (id, name) = _ubEquipSends.Dequeue();
+ WorldObject? wo = _objectCache?[unchecked((int)id)];
+ // Already on (worn since the plan): using it again would take it off.
+ if (wo != null && WorldObjectCache.IsWieldedByPlayer(Host, wo)) { _ubEquipSent.Add((id, name)); return; }
+ Host.UseFor(id, "Command", "/ub equip load", UseKind.Asked);
+ _ubEquipSent.Add((id, name));
+ _ubEquipNextAt = _ubEquipLastAt = now;
+ _ubEquipNextAt += UbEquipSpacingMs;
+ return;
+ }
+ if (_ubEquipSent.Count == 0 || now - _ubEquipLastAt < UbEquipSettleMs) return;
+ var missing = new List();
+ foreach (var (id, name) in _ubEquipSent)
+ {
+ WorldObject? wo = _objectCache?[unchecked((int)id)];
+ if (wo == null || !WorldObjectCache.IsWieldedByPlayer(Host, wo)) missing.Add(name);
+ }
+ int on = _ubEquipSent.Count - missing.Count;
+ string text = missing.Count == 0
+ ? $"[RynthAi] /ub equip load {_ubEquipProfile}: equipped {on} item(s)."
+ : $"[RynthAi] /ub equip load {_ubEquipProfile}: equipped {on} of {_ubEquipSent.Count}; not on: {Names(missing)}.";
+ _ubEquipSent.Clear();
+ var job = new UbInvJob { FromMeta = _ubEquipFromMeta };
+ UbJobSay(job, text, fail: missing.Count > 0);
+ }
+
+ private void FinishUbAutoSalvage(UbInvJob job)
+ {
+ var ctx = new VTankLootContext(Host, _playerId) { Cache = _objectCache };
+ bool mainOnly = _metaManager?.Expressions is { } ex && ex.GetOption("AutoSalvage.OnlyFromMainPack") is string o
+ && (o == "1" || o.Equals("true", StringComparison.OrdinalIgnoreCase));
+ var take = new List();
+ var left = new List();
+ int unidentified = 0;
+ foreach (WorldObject wo in UbInvCandidates(job.Kind))
+ {
+ uint id = unchecked((uint)wo.Id);
+ bool hasId = HasIdData(id);
+ VTankLootVerdict v = job.Rules.Decide(wo, ctx, _charSkills, hasId, out InventoryRuleKind k, out _);
+ if (v == VTankLootVerdict.NeedsId) { unidentified++; continue; }
+ if (v != VTankLootVerdict.Match || k != InventoryRuleKind.Salvage) continue;
+ if (!hasId) { unidentified++; continue; } // tinkered or imbued can't be told without it
+ if (wo.Values(unchecked((int)NumTimesTinkeredInt), 0) > 0) { left.Add(wo.Name + " (tinkered)"); continue; }
+ if (wo.Values(unchecked((int)ImbuedEffectInt), 0) != 0) { left.Add(wo.Name + " (imbued)"); continue; }
+ if (mainOnly && wo.Container != 0 && wo.Container != unchecked((int)_playerId)) continue;
+ take.Add(wo);
+ }
+ string profile = job.Rules.FileName;
+ string notes = (left.Count > 0 ? $" Left alone: {Names(left)}." : "")
+ + (unidentified > 0 ? $" {unidentified} item(s) couldn't be identified in time and were left out." : "");
+ if (take.Count == 0)
+ {
+ UbJobSay(job, $"[RynthAi] /ub autosalvage ({profile}): nothing you carry is marked Salvage.{notes}",
+ info: job.Kind == UbInvKind.Salvage);
+ return;
+ }
+ if (job.Kind == UbInvKind.Salvage)
+ {
+ UbJobSay(job, $"[RynthAi] /ub autosalvage ({profile}): {take.Count} item(s) would be salvaged: {Names(take.Select(t => t.Name))}."
+ + notes + " /ub autosalvage force salvages them.", info: true);
+ return;
+ }
+ if (_salvageManager == null) { UbJobSay(job, "[RynthAi] /ub autosalvage: salvaging isn't ready.", fail: true); return; }
+ foreach (WorldObject wo in take) _salvageManager.EnqueueItem(unchecked((uint)wo.Id));
+ Log($"[RynthAi] /ub autosalvage force ({profile}): queued {Names(take.Select(t => $"{t.Name} 0x{(uint)t.Id:X8}"), 60)}.{notes}");
+ UbJobSay(job, $"[RynthAi] /ub autosalvage force ({profile}): salvaging {take.Count} item(s): {Names(take.Select(t => t.Name))}.{notes}");
+ }
+
+ /// At logout: nothing of a job carries into the next character's session.
+ private void ResetUbInventoryJobs()
+ {
+ _ubInvJob = null;
+ _ubEquipSends.Clear();
+ _ubEquipSent.Clear();
+ }
+}
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Clock/DayNightWindow.cs b/Plugins/RynthCore.Plugin.RynthDefective/Clock/DayNightWindow.cs
index 68329f3..264713c 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/Clock/DayNightWindow.cs
+++ b/Plugins/RynthCore.Plugin.RynthDefective/Clock/DayNightWindow.cs
@@ -7,6 +7,10 @@
// Plugins/Shared/DerethClock.cs has the math; RynthCore hosts the frameless
// window (plugin API v90) and remembers where it is.
//
+// A clear background by default (2026-12-01: no box, the sun or moon and the text shadowed, so it
+// can sit on the radar or under the arrow without taking room); /rdef daynight box brings the
+// dark box back (DefSettings.DayNightBox). While hovered a faint box shows where to grab it.
+//
// anywhere drag to move; Ctrl+wheel: bigger or smaller (30-250%);
// right-click: hide it (/rdef daynight, the bar button, or
// Settings > Interface > In The Retail Toolbar's Place show it again).
@@ -64,10 +68,12 @@ internal sealed class DayNightWindow
private const float Pad = 5, RowH = 16, Mark = 14, Gap = 4, Radius = 4;
private static readonly uint SunColor = Argb(0xFFF2C14E), MoonColor = Argb(0xFFB8C7F0);
+ private static readonly uint ShadowColor = Argb(0xD8000000); // under the text and icon on a clear background
private static uint A(uint c, float alpha) => WithAlpha(c, (uint)Math.Clamp(MathF.Round(alpha * 255f), 0f, 255f));
- /// Draws the timer into the host's window; returns the height it needs (pixels). Render thread.
- public float Draw(DayNightView v)
+ /// Draws the timer into the host's window; returns the height it needs (pixels).
+ /// : the dark box; false = a clear background, the text shadowed. Render thread.
+ public float Draw(DayNightView v, bool box = false)
{
Scale();
uint bg = Color(RynthUiColor.Background), line = Color(RynthUiColor.Hairline);
@@ -81,8 +87,11 @@ internal sealed class DayNightWindow
if (width < 30) return height;
ImDrawListPtr dl = ImGui.GetWindowDrawList();
Vector2 max = origin + new Vector2(width, height);
- dl.AddRectFilled(origin, max, A(bg, 0.94f), Px(Radius));
- dl.AddRect(origin, max, line, Px(Radius));
+ if (box)
+ {
+ dl.AddRectFilled(origin, max, A(bg, 0.94f), Px(Radius));
+ dl.AddRect(origin, max, line, Px(Radius));
+ }
// The whole window is the drag surface.
ImGui.SetCursorScreenPos(origin);
@@ -90,6 +99,8 @@ internal sealed class DayNightWindow
_host.PanelDragWithLastItem();
if (ImGui.IsItemClicked(ImGuiMouseButton.Right)) _host.SetPanelOpen(Title, RynthPanelOpen.Close);
bool hot = ImGui.IsItemHovered();
+ if (!box && hot) dl.AddRectFilled(origin, max, A(bg, 0.45f), Px(Radius)); // where to grab it
+ Vector2 sh = new(MathF.Max(1f, MathF.Round(Px(1))), MathF.Max(1f, MathF.Round(Px(1)))); // the shadow's offset
long nowMs = Environment.TickCount64;
double left = v.Ready ? v.SecondsLeft(nowMs) : 0;
@@ -99,12 +110,15 @@ internal sealed class DayNightWindow
Vector2 at = origin + new Vector2(pad, pad);
string icon = !v.Ready || v.Now.IsDay ? RynthIcons.Sun : HasGlyph(RynthIcons.Moon) ? RynthIcons.Moon : RynthIcons.Star;
uint iconColor = !v.Ready ? faint : v.Now.IsDay ? SunColor : MoonColor;
+ if (!box) PanelButtonsWindow.DrawIcon(dl, icon, at + sh, new Vector2(Px(Mark), rowH), Px(13), ShadowColor);
PanelButtonsWindow.DrawIcon(dl, icon, at, new Vector2(Px(Mark), rowH), Px(13), iconColor);
ImFontPtr nf = Font(RynthUiFont.NarrowBold11), sf = Font(RynthUiFont.Narrow9);
float tx = at.X + Px(Mark) + Px(Gap), right = origin.X + width - pad;
float lw = nf.CalcTextSizeA(Fs(nf), float.MaxValue, 0f, label).X;
- dl.AddText(nf, Fs(nf), new Vector2(MathF.Round(tx), MathF.Round(at.Y + (rowH - Fs(nf)) * 0.5f)), v.Ready ? text : faint, label);
+ Vector2 labelAt = new(MathF.Round(tx), MathF.Round(at.Y + (rowH - Fs(nf)) * 0.5f));
+ if (!box) dl.AddText(nf, Fs(nf), labelAt + sh, ShadowColor, label);
+ dl.AddText(nf, Fs(nf), labelAt, v.Ready ? text : faint, label);
// The hour's name, right-aligned, only when it fits whole.
if (v.Ready)
@@ -112,7 +126,11 @@ internal sealed class DayNightWindow
string hour = v.Now.HourName;
float hw = sf.CalcTextSizeA(Fs(sf), float.MaxValue, 0f, hour).X;
if (tx + lw + Px(8) + hw <= right)
- dl.AddText(sf, Fs(sf), new Vector2(MathF.Round(right - hw), MathF.Round(at.Y + (rowH - Fs(sf)) * 0.5f)), faint, hour);
+ {
+ Vector2 hourAt = new(MathF.Round(right - hw), MathF.Round(at.Y + (rowH - Fs(sf)) * 0.5f));
+ if (!box) dl.AddText(sf, Fs(sf), hourAt + sh, ShadowColor, hour);
+ dl.AddText(sf, Fs(sf), hourAt, box ? faint : A(text, 0.8f), hour);
+ }
}
if (hot) SafeImGui.SetItemTooltip(Tip(v, left));
@@ -139,7 +157,8 @@ internal sealed class DayNightWindow
internal static string Tip(DayNightView v, double left)
{
const string help = "A Dereth day is 2 h 7 min of real time: 63.5 minutes of day, then 63.5 of night.\n"
- + "Drag to move; Ctrl+wheel: bigger or smaller; right-click: hide (/rdef daynight).";
+ + "Drag to move; Ctrl+wheel: bigger or smaller; right-click: hide (/rdef daynight).\n"
+ + "/rdef daynight box: the dark box; /rdef daynight clear: no background.";
if (!v.Ready) return "Day or night in Dereth, and the real minutes until it changes. Shown once you're in the world.\n" + help;
TimeSpan t = TimeSpan.FromSeconds(Math.Ceiling(left));
string until = t.TotalMinutes >= 1 ? $"{(int)t.TotalMinutes} min {t.Seconds} s" : $"{t.Seconds} s";
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs
index 54079d3..cf6c51e 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs
+++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefCommand.cs
@@ -21,9 +21,9 @@ internal static class DefCommandParser
"/rdef [use | set [item name] | spell | clear | bind | unbind | "
+ "weapons [search] | fav | slots | list | status | settings | panels (the game panel buttons) | selection | appraisal [pin|unpin|again|popout|dock] | corpses [clear] | "
+ "bars [add | remove | slots | show ] | shortcuts clearbusy [on|off] | "
- + "qty [number|max|half] | split [number] [into ] | give [number] | buy [number] [item name] | daynight [show|hide]]";
+ + "qty [number|max|half] | split [number] [into ] | give [number] | buy [number] [item name] | daynight [show|hide|clear|box]]";
- public const string DayNightUsage = "Usage: /rdef daynight [show|hide], e.g. /rdef daynight show (the Day/Night timer: real minutes to the next dawn or dusk)";
+ public const string DayNightUsage = "Usage: /rdef daynight [show|hide|clear|box], e.g. /rdef daynight show (the Day/Night timer: real minutes to the next dawn or dusk; clear = no background, box = its dark box)";
public const string ClearBusyUsage =
"Usage: /rdef shortcuts clearbusy on|off, e.g. /rdef shortcuts clearbusy on (a press held only by a stuck busy count clears it first; off by default)";
@@ -59,14 +59,16 @@ internal static class DefCommandParser
case "selection": case "target":
// "/rdef selection 0x80001234": select that object (a test hook for the Selection window).
return new DefCommand(DefVerb.Selection, Text: rest);
- // The Day/Night timer (2026-11-04): Text "show", "hide" or "" (toggle).
+ // The Day/Night timer (2026-11-04): Text "show", "hide" or "" (toggle); "clear" or "box" (2026-12-01) its background.
case "daynight":
return rest.ToLowerInvariant() switch
{
"" or "toggle" => new DefCommand(DefVerb.DayNight),
"show" or "on" or "open" => new DefCommand(DefVerb.DayNight, Text: "show"),
"hide" or "off" or "close" => new DefCommand(DefVerb.DayNight, Text: "hide"),
- _ => Fail($"'{rest}' isn't show or hide. {DayNightUsage}"),
+ "clear" or "transparent" or "nobox" => new DefCommand(DefVerb.DayNight, Text: "clear"),
+ "box" or "background" => new DefCommand(DefVerb.DayNight, Text: "box"),
+ _ => Fail($"'{rest}' isn't show, hide, clear or box. {DayNightUsage}"),
};
case "fav": case "favourite": case "favorite": return new DefCommand(DefVerb.Favourite);
case "weapons": case "weapon": case "picker": return new DefCommand(DefVerb.Weapons, Text: rest);
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs
index b4c734f..7d25d7d 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs
+++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefData.cs
@@ -118,6 +118,13 @@ internal sealed class DefSettings
///
public bool QuantityBox = true;
///
+ /// The Day/Night timer's dark box (2026-12-01: a clear background, so it takes no
+ /// room of its own). Off (the default, and what a file from before reads as): the timer
+ /// is drawn on a clear background, its sun or moon and text shadowed so they read over the radar,
+ /// the arrow or the world. On: the dark box as before. /rdef daynight clear | box.
+ ///
+ public bool DayNightBox;
+ ///
/// Shortcuts clear a stuck busy state (2026-11-04, a player's ask): a press held only by the client's
/// busy count (nothing of ours or RynthAi's in flight, no gesture, no "You're too busy" just now) resets
/// the count as RynthAi's /ra clearbusy does (the engine's ForceResetBusyCount), then goes, once per
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefReplies.cs b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefReplies.cs
index 3cd25c8..4f824ac 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/Model/DefReplies.cs
+++ b/Plugins/RynthCore.Plugin.RynthDefective/Model/DefReplies.cs
@@ -41,6 +41,11 @@ internal static class DefReplies
: (true, CommandReply.Shown("Day/Night timer", state == 1) + time);
}
+ /// /rdef daynight clear | box: the timer's background after it.
+ public static (bool Ok, string Text) DayNightLook(bool box) => (true, box
+ ? "Day/Night timer: on its dark box (/rdef daynight clear for no background)."
+ : "Day/Night timer: on a clear background (/rdef daynight box brings the dark box back).");
+
/// A slot's use started (the result shows on the bar; a problem is said in chat).
public static string UseSlot(DefSlot slot, int number) => slot.IsSpell
? $"Casting {slot.SpellLabel} (slot {number})."
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/README.md b/Plugins/RynthCore.Plugin.RynthDefective/README.md
index 01c38bd..c251010 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/README.md
+++ b/Plugins/RynthCore.Plugin.RynthDefective/README.md
@@ -121,7 +121,9 @@ number (the game gets no keys while the box has the keyboard) or pick 1, 10, 100
## The Day/Night timer
-A one-row window (its RynthCore bar button is the sun; `/rdef daynight [show|hide]`; Settings > Interface > In The Retail Toolbar's Place >
+A one-row window (its RynthCore bar button is the sun; `/rdef daynight [show|hide]`; on a clear background, the text
+shadowed, so it can sit on the radar or under the arrow, and `/rdef daynight box` / `clear` puts its dark box back or
+takes it away (per character, 2026-12-01); Settings > Interface > In The Retail Toolbar's Place >
*Day/Night timer*): a sun by day, a moon at night, and the **real** time until the next change, "Night in 23m",
"Day in 4m 10s" (seconds from 10 minutes down), with the Dereth hour's name when there is room. A Dereth day is
16 hours of 476.25 s, 2 h 7 min of real time: day (Dawnsong to Warmtide-and-Half) and night (Evensong to
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.DayNight.cs b/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.DayNight.cs
index 1078978..396e9ab 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.DayNight.cs
+++ b/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.DayNight.cs
@@ -34,7 +34,7 @@ public sealed partial class RynthDefectivePlugin
try
{
_dayNightWindow ??= new DayNightWindow(Host);
- wantHeight = _dayNightWindow.Draw(_dayNightView);
+ wantHeight = _dayNightWindow.Draw(_dayNightView, _session.Settings.DayNightBox);
_dayNightFailures = 0;
return 1;
}
diff --git a/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.cs b/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.cs
index 2f6b9a8..1a29bc1 100644
--- a/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.cs
+++ b/Plugins/RynthCore.Plugin.RynthDefective/RynthDefectivePlugin.cs
@@ -235,6 +235,14 @@ public sealed partial class RynthDefectivePlugin : RynthPluginBase
break;
case DefVerb.DayNight:
{
+ if (c.Text is "clear" or "box")
+ {
+ // The timer's background (2026-12-01): kept with the character's settings.
+ _session.Settings.DayNightBox = c.Text == "box";
+ RequestSave();
+ Answer(DefReplies.DayNightLook(_session.Settings.DayNightBox));
+ break;
+ }
// The window shown or hidden, and the time now in the reply (an engine without the window: the time only).
RynthPanelOpen mode = c.Text == "show" ? RynthPanelOpen.Open : c.Text == "hide" ? RynthPanelOpen.Close : RynthPanelOpen.Toggle;
int state = UsesShortcutBar ? Host.SetPanelOpen(Clock.DayNightWindow.Title, mode) : -1;
diff --git a/Plugins/RynthCore.Plugin.RynthLua/GameApi.cs b/Plugins/RynthCore.Plugin.RynthLua/GameApi.cs
index 7512328..dd777c4 100644
--- a/Plugins/RynthCore.Plugin.RynthLua/GameApi.cs
+++ b/Plugins/RynthCore.Plugin.RynthLua/GameApi.cs
@@ -139,6 +139,10 @@ public sealed partial class RynthLuaPlugin
/// Test harness only: whether a script's Lua state is still alive.
internal bool ScriptIsLoaded(string name) => _scripts.TryGetValue(name, out var ctx) && ctx.Host.Loaded;
+ /// Test harness only: worker coroutines a running script has made (-1 when it isn't running).
+ internal int ScriptWorkersCreated(string name) =>
+ _scripts.TryGetValue(name, out var ctx) && ctx.Host.Loaded ? ctx.Host.WorkersCreated : -1;
+
private void RegisterGame(Script s, ScriptContext ctx)
{
var game = new Table(s);
diff --git a/Plugins/RynthCore.Plugin.RynthLua/LuaScriptHost.cs b/Plugins/RynthCore.Plugin.RynthLua/LuaScriptHost.cs
index 27b9228..17eaddb 100644
--- a/Plugins/RynthCore.Plugin.RynthLua/LuaScriptHost.cs
+++ b/Plugins/RynthCore.Plugin.RynthLua/LuaScriptHost.cs
@@ -32,15 +32,127 @@ internal sealed class LuaScriptHost
private sealed class LuaThread
{
- public DynValue Co = DynValue.Nil;
+ public DynValue Co = DynValue.Nil; // set when the thread first runs (TakeCoroutine)
+ public DynValue Fn = DynValue.Nil; // the function, until then
public long WakeAt;
public Func? WaitFor; // await: resume only once this is true
public DynValue[] Args = Array.Empty();
public bool Started;
+ /// Runs on a pooled worker coroutine (see ): it ends by yielding the done token.
+ public bool Pooled;
/// Called once when the thread ends: its return values, or the error message.
public Action? OnDone;
}
+ // ── Worker coroutines ───────────────────────────────────────────────────
+ //
+ // MoonSharp 2.0 gives every coroutine two 131,072-slot stacks the moment it is created:
+ // about 1 MB in the 32-bit client (2 MB in a 64-bit process), all on the Large Object Heap,
+ // which only a full collection frees. RynthLua used to make one per event handler call and
+ // per hud pass, so a 194-line /myquests read cost each script with a chat handler ~200 MB and
+ // a 20-per-second window 20 MB/s. The heap figure the memory guard reads then passed 800 MB
+ // and the guard stopped scripts that had done nothing wrong (2026-11-30).
+ // Now a thread runs on a worker: a Lua loop that calls the function it is given, yields the
+ // done token with the results, and waits for the next function. A worker whose function
+ // ended normally goes back to a small pool; one that raised an error, or was aborted or
+ // stopped part-way, is simply dropped (it can't be reused).
+
+ private const string WorkerCode = @"
+local DONE, yield, select, unpack = ...
+local function packn(...) return { n = select('#', ...), ... } end
+return function(fn, args)
+ while true do
+ fn, args = yield(DONE, packn(fn(unpack(args, 1, args.n))))
+ end
+end";
+
+ /// Idle workers kept per script; more than this are left to the GC.
+ internal const int MaxIdleWorkers = 8;
+ private DynValue _workerFn = DynValue.Nil;
+ private Table? _doneToken;
+ private readonly Stack _idleWorkers = new();
+
+ /// Test hook: workers made since the script started (a fresh coroutine each).
+ internal int WorkersCreated { get; private set; }
+
+ ///
+ /// Makes the worker function from the state's own coroutine.yield, select and table.unpack,
+ /// taken before any script code runs (a script that replaces them later doesn't touch workers).
+ ///
+ private void CreateWorkers(Script s)
+ {
+ _idleWorkers.Clear();
+ _workerFn = DynValue.Nil;
+ _doneToken = null;
+ WorkersCreated = 0;
+ try
+ {
+ DynValue co = s.Globals.Get("coroutine");
+ DynValue tbl = s.Globals.Get("table");
+ DynValue yield = co.Type == DataType.Table ? co.Table.Get("yield") : DynValue.Nil;
+ DynValue select = s.Globals.Get("select");
+ DynValue unpack = tbl.Type == DataType.Table ? tbl.Table.Get("unpack") : DynValue.Nil;
+ if (unpack.IsNil()) unpack = s.Globals.Get("unpack");
+ if (yield.IsNil() || select.IsNil() || unpack.IsNil()) return; // old behaviour: a coroutine per thread
+ var token = new Table(s);
+ DynValue factory = s.LoadString(WorkerCode, new Table(s), "rynth worker");
+ DynValue fn = s.Call(factory, DynValue.NewTable(token), yield, select, unpack);
+ if (fn.Type != DataType.Function) return;
+ _doneToken = token;
+ _workerFn = fn;
+ }
+ catch { _workerFn = DynValue.Nil; _doneToken = null; }
+ }
+
+ /// An idle worker, or a new one; null when workers aren't available (a coroutine per thread then).
+ internal DynValue? RentWorker()
+ {
+ if (_script == null || _workerFn.Type != DataType.Function) return null;
+ while (_idleWorkers.Count > 0)
+ {
+ DynValue w = _idleWorkers.Pop();
+ if (w.Coroutine.State is CoroutineState.Suspended or CoroutineState.NotStarted) return w;
+ }
+ WorkersCreated++;
+ return _script.CreateCoroutine(_workerFn);
+ }
+
+ /// Puts a worker that yielded the done token back in the pool.
+ internal void ReturnWorker(DynValue worker)
+ {
+ if (_script == null || worker.Coroutine.State is not (CoroutineState.Suspended or CoroutineState.NotStarted)) return;
+ if (_idleWorkers.Count < MaxIdleWorkers) _idleWorkers.Push(worker);
+ }
+
+ /// What a worker is resumed with to run (...).
+ internal DynValue[] WorkerArgs(DynValue fn, DynValue[] args)
+ {
+ var t = new Table(_script);
+ for (int i = 0; i < args.Length; i++) t.Set(i + 1, args[i]);
+ t.Set("n", DynValue.NewNumber(args.Length));
+ return new[] { fn, DynValue.NewTable(t) };
+ }
+
+ /// True when (a worker's Resume result) says its function returned.
+ internal bool IsWorkerDone(DynValue r) =>
+ _doneToken != null && r.Type == DataType.Tuple && r.Tuple is { Length: 2 } tu
+ && tu[0].Type == DataType.Table && ReferenceEquals(tu[0].Table, _doneToken);
+
+ /// The function's return values from a done worker's result: Void for none, the value for one, else a tuple.
+ internal static DynValue WorkerResults(DynValue r)
+ {
+ DynValue packed = r.Tuple[1];
+ if (packed.Type != DataType.Table) return DynValue.Void;
+ Table t = packed.Table;
+ DynValue nv = t.RawGet("n") ?? DynValue.Nil;
+ int n = nv.Type == DataType.Number ? (int)nv.Number : 0;
+ if (n <= 0) return DynValue.Void;
+ if (n == 1) return t.Get(1);
+ var values = new DynValue[n];
+ for (int i = 0; i < n; i++) values[i] = t.Get(i + 1);
+ return DynValue.NewTuple(values);
+ }
+
private readonly Action _log;
private readonly Action