Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 8 additions & 16 deletions CustomAilments.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,12 +14,9 @@
"puncture_moving"
],
"Burning": [
"demon_righteous_fire_aura",
"fire_damage_and_ignite",
"ground_fire_burn",
"ignited",
"righteous_fire_aura",
"searing_bond_in_beam"
"ignited"
],
"Chilled": [
"chilled",
Expand All @@ -32,17 +29,18 @@
"corrupted_blood_rain"
],
"Cursed": [
"curse_assassins_mark",
"curse_chaos_weakness",
"curse_cold_weakness",
"curse_elemental_weakness",
"curse_enfeeble",
"curse_fire_weakness",
"curse_lightning_weakness",
"curse_newpunishment",
"curse_temporal_chains",
"curse_vulnerability",
"curse_warlords_mark"
"curse_vulnerability"
],
"Electrocuted": [
"electrocute",
"electrocuted"
],
"Exposed": [
"reduced_cold_resistance_from_skill",
Expand All @@ -65,18 +63,12 @@
"caustic_cloud",
"chaos_bond_in_beam",
"ground_desecration",
"poison",
"viper_strike_orb"
"poison"
],
"Shocked": [
"ground_lightning_shock",
"lightning_damage_and_shock",
"seawitch_lightning_beam",
"shocked"
],
"Unable To Recover": [
"atlas_orion_meteor_ground",
"maven_rotating_beam_debuff",
"maven_cutter_beam_debuff"
]
}
}
10 changes: 9 additions & 1 deletion Profile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -252,6 +252,14 @@ public void FocusLost()
_groupImportObject = null;
}

internal void ReleaseCompilationContexts()
{
foreach (var group in Groups)
{
group.ReleaseCompilationContexts();
}
}

private void DrawSettingsHorizontal(RuleState state, ReAgentSettings settings)
{
if (ImGui.BeginTabBar("Rule groups", ImGuiTabBarFlags.AutoSelectNewTabs | ImGuiTabBarFlags.Reorderable | ImGuiTabBarFlags.FittingPolicyScroll))
Expand Down Expand Up @@ -343,4 +351,4 @@ private void MoveGroup(int sourceIndex, int targetIndex)
Groups.RemoveAt(sourceIndex);
Groups.Insert(targetIndex, movedItem);
}
}
}
34 changes: 28 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,33 @@
# ReAgent
# ReAgent — PoE2

If you like it, you can donate via:
Generic user-authored rule engine for ExileCore2. This is an automation
framework, not a passive overlay.

BTC: bc1qke67907s6d5k3cm7lx7m020chyjp9e8ysfwtuz
## Logic

ETH: 0x3A37B3f57453555C2ceabb1a2A4f55E0eB969105
1. Build a read-only `RuleState` snapshot containing player vitals, Life, buffs,
skills, flasks, charges, monsters, map stats, and UI visibility.
2. Compile rules as Dynamic-LINQ v1 or Roslyn C# v2 and group them by area/state
conditions.
3. Evaluate enabled groups each frame behind foreground/escape/dead/grace gates.
4. Apply configured effects: overlays, flags/timers, PluginBridge calls,
keyboard/mouse actions, delayed effects, and optional disconnect actions.
5. Persist profiles/rules locally and isolate compilation/runtime failures per
rule. Detach callbacks and clear state on reload/dispose.

# Docs
PoE2-specific behavior includes the two-flask model and data-driven ailment
names. Review every profile before enabling: user rules can send input.

Some docs: https://excore2.github.io/ReAgent/
Entity projections fail closed when an ExileCore2 `ValidEntitiesByType` bucket is
not present during startup or an area transition. Roslyn v2 rule contexts are
also unloaded when a rule is rebuilt or the plugin is disposed, limiting stale
collectible assembly accumulation during profile editing and hot reload.

## Status

Build: **PASS**. Classification: **CURRENT_WITH_WARNINGS**; runtime semantics
and safety are profile-dependent.

Documentation: [upstream ReAgent docs](https://excore2.github.io/ReAgent/).
Detailed report: [PoE2 plugin catalog](../../README.md) ·
[audit](../../../docs/plugins/ReAgent/AUDIT.md).
33 changes: 32 additions & 1 deletion ReAgent.cs
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,9 @@ private string GetNewProfileName(string prefix)

public override void Render()
{
if (!Settings.Enable)
return;

if (Settings.Profiles.Count == 0)
{
Settings.Profiles.Add(GetNewProfileName("New profile "), Profile.CreateWithDefaultGroup());
Expand Down Expand Up @@ -443,6 +446,34 @@ public override void Render()
}
}

public override void OnPluginDestroyForHotReload()
{
ClearRuntimeState();
base.OnPluginDestroyForHotReload();
}

public override void Dispose()
{
ClearRuntimeState();
base.Dispose();
}

private void ClearRuntimeState()
{
_pendingSideEffects.Clear();
_actionInfo.Clear();
foreach (var profile in Settings.Profiles.Values)
{
profile?.ReleaseCompilationContexts();
}

foreach (var loadedTexture in _loadedTextures)
{
try { Graphics.DisposeTexture(loadedTexture); } catch { }
}
_loadedTextures.Clear();
}

private static Color ColorFromName(string color)
{
return Color.FromName(color);
Expand Down Expand Up @@ -518,4 +549,4 @@ private bool ShouldExecute(out string state)
state = "Ready";
return true;
}
}
}
3 changes: 2 additions & 1 deletion ReAgent.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@
<EmbedAllSources>true</EmbedAllSources>
</PropertyGroup>
<ItemGroup>
<Compile Remove="tests\**\*.cs" />
<Compile Remove="docs\**" />
<EmbeddedResource Remove="docs\**" />
<None Remove="docs\**" />
Expand All @@ -37,6 +38,6 @@
<PackageReference Include="ImGui.NET" Version="1.90.0.1" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="4.11.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.3.7" />
<PackageReference Include="System.Linq.Dynamic.Core" Version="1.7.3" />
</ItemGroup>
</Project>
27 changes: 22 additions & 5 deletions Rule.cs
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,7 @@ public Keys? Key
public HotkeyNodeValue KeyV2 = new HotkeyNodeValue(Keys.D0);
public int SyntaxVersion;
private Lazy<(Func<RuleState, IEnumerable<ISideEffect>> Func, string Exception)> _compilationResult;
private AssemblyLoadContext _assemblyLoadContext;
private string _lastException;
private ulong _exceptionCounter;
private static readonly InteractiveAssemblyLoader loader;
Expand Down Expand Up @@ -145,7 +146,7 @@ public void Display(RuleState state, bool expand)
{
ImGui.TextWrapped("Rule source");
ImGui.SameLine();
var syntaxState = SyntaxVersion switch { 1 => false, 2 => true };
var syntaxState = SyntaxVersion switch { 1 => false, 2 => true, _ => true };
if (ImGui.Checkbox("Use new syntax", ref syntaxState))
{
SyntaxVersion = syntaxState ? 2 : 1;
Expand Down Expand Up @@ -205,8 +206,9 @@ public void Display(RuleState state, bool expand)

private void ResetFunction()
{
ReleaseCompilationContext();
_exceptionCounter = 0;
_compilationResult = new(SyntaxVersion switch { 1 => RebuildFunctionV1, 2 => RebuildFunctionV2 }, LazyThreadSafetyMode.None);
_compilationResult = new(SyntaxVersion switch { 1 => RebuildFunctionV1, 2 => RebuildFunctionV2, _ => RebuildFunctionV2 }, LazyThreadSafetyMode.None);
}

private (Func<RuleState, IEnumerable<ISideEffect>> Func, string LastException) RebuildFunctionV1()
Expand Down Expand Up @@ -263,20 +265,20 @@ private void ResetFunction()
{
case RuleActionType.Key:
{
var @delegate = DelegateCompiler.CompileDelegate<ScriptFunc<bool>>(RuleSource, ScriptOptions, CreateAlc());
var @delegate = DelegateCompiler.CompileDelegate<ScriptFunc<bool>>(RuleSource, ScriptOptions, CreateRuleAlc());
return (s => @delegate(s)
? [new PressKeySideEffect(KeyV2 ?? throw new Exception("Key is not assigned"))]
: [], null);
}
case RuleActionType.SingleSideEffect:
{
var @delegate = DelegateCompiler.CompileDelegate<ScriptFunc<ISideEffect>>(RuleSource, ScriptOptions, CreateAlc());
var @delegate = DelegateCompiler.CompileDelegate<ScriptFunc<ISideEffect>>(RuleSource, ScriptOptions, CreateRuleAlc());
return (s => @delegate(s) switch { { } sideEffect => [sideEffect], _ => Enumerable.Empty<ISideEffect>() },
null);
}
case RuleActionType.MultipleSideEffects:
{
var @delegate = DelegateCompiler.CompileDelegate<ScriptFunc<IEnumerable<ISideEffect>>>(RuleSource, ScriptOptions, CreateAlc());
var @delegate = DelegateCompiler.CompileDelegate<ScriptFunc<IEnumerable<ISideEffect>>>(RuleSource, ScriptOptions, CreateRuleAlc());
return (s => @delegate(s) switch { { } sideEffects => sideEffects, _ => Enumerable.Empty<ISideEffect>() }, null);
}
default:
Expand All @@ -285,10 +287,25 @@ private void ResetFunction()
}
catch (Exception ex)
{
ReleaseCompilationContext();
return (null, $"Expression compilation failed: {ex.Message}");
}
}

internal void ReleaseCompilationContext()
{
var context = Interlocked.Exchange(ref _assemblyLoadContext, null);
context?.Unload();
}

private AssemblyLoadContext CreateRuleAlc()
{
ReleaseCompilationContext();
var context = CreateAlc();
_assemblyLoadContext = context;
return context;
}

private static AssemblyLoadContext CreateAlc()
{
var assemblyLoadContext = new AssemblyLoadContext($"bbb{Guid.NewGuid()}", true);
Expand Down
10 changes: 9 additions & 1 deletion RuleGroup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -218,6 +218,14 @@ public IEnumerable<SideEffectContainer> Evaluate(RuleState state)
}
}

internal void ReleaseCompilationContexts()
{
foreach (var rule in Rules)
{
rule.ReleaseCompilationContext();
}
}

private void RemoveAt(int index)
{
Rules.RemoveAt(index);
Expand All @@ -229,4 +237,4 @@ private void MoveRule(int sourceIndex, int targetIndex)
Rules.RemoveAt(sourceIndex);
Rules.Insert(targetIndex, movedItem);
}
}
}
3 changes: 1 addition & 2 deletions SideEffects/DisconnectSideEffect.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ namespace ReAgent.SideEffects;

[DynamicLinqType]
[Api]
[method: Api]
public record DisconnectSideEffect : ISideEffect
{
public SideEffectApplicationResult Apply(RuleState state)
Expand Down Expand Up @@ -108,4 +107,4 @@ private enum TcpTableClass
TcpTableOwnerModuleConnections,
TcpTableOwnerModuleAll
}
}
}
5 changes: 3 additions & 2 deletions State/CustomDynamicLinqCustomTypeProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@ namespace ReAgent.State;

public sealed class CustomDynamicLinqCustomTypeProvider :
AbstractDynamicLinqCustomTypeProvider,
IDynamicLinkCustomTypeProvider,
IDynamicLinqCustomTypeProvider
{
public CustomDynamicLinqCustomTypeProvider() : base(Array.Empty<Type>()) { }

private HashSet<Type> _cachedCustomTypes;
private Dictionary<Type, List<MethodInfo>> _cachedExtensionMethods;

Expand Down Expand Up @@ -52,4 +53,4 @@ private Dictionary<Type, List<MethodInfo>> GetExtensionMethodsInternal()
.GroupBy(x => x.GetParameters()[0].ParameterType)
.ToDictionary(key => key.Key, methods => methods.ToList());
}
}
}
42 changes: 22 additions & 20 deletions State/FlaskInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,7 @@ public record FlaskInfo(

public static FlaskInfo From(
GameController state,
List<ServerInventory.InventSlotItem> flaskItems,
ServerInventory.InventSlotItem flaskItem,
int index,
RuleInternalState internalState)
ServerInventory.InventSlotItem flaskItem)
{
if (flaskItem?.Address is 0 or null || flaskItem.Item?.Address is null or 0)
{
Expand Down Expand Up @@ -66,25 +63,30 @@ public static FlaskInfo From(
return new FlaskInfo(active, canbeUsed, chargeComponent?.NumCharges ?? 0, chargeComponent?.ChargesMax ?? 1, chargeComponent?.ChargesPerUse ?? 1, className, baseName, uniqueName, canBeUsedIn);
}

private static readonly string[] LifeFlaskBuffs = { "flask_effect_life" };

private static readonly string[] ManaFlaskBuffs =
{
"flask_effect_mana",
"flask_effect_mana_not_removed_when_full",
"flask_instant_mana_recovery_at_end_of_effect"
};
// These are the only host members currently available for distinguishing
// life/mana/hybrid flasks in the pinned PoE2 preview. Keep them named and
// fail closed so a future layout change cannot turn a stale read into a
// false-positive automation trigger.
private const int FlaskTypePointerOffset = 0x28;
private const int FlaskTypeValueOffset = 0x20;
private const int CustomBuffPointerOffset = 0x18;
private const int CustomBuffPointerIndex = 0x0;

private static IEnumerable<string> GetFlaskBuffNames(Flask flask)
{
var type = flask.M.Read<int>(flask.Address + 0x28, 0x20);
return type switch
try
{
1 => LifeFlaskBuffs,
2 => ManaFlaskBuffs,
3 => LifeFlaskBuffs.Concat(ManaFlaskBuffs),
4 when flask.M.ReadStringU(flask.M.Read<long>(flask.Address + 0x28, 0x18, 0x0)) is { } s and not "" => new[] { s },
_ => Enumerable.Empty<string>()
};
var type = flask.M.Read<int>(flask.Address + FlaskTypePointerOffset, FlaskTypeValueOffset);
var customBuff = type == 4
? flask.M.ReadStringU(flask.M.Read<long>(flask.Address + FlaskTypePointerOffset, CustomBuffPointerOffset, CustomBuffPointerIndex))
: null;
return FlaskLayoutClassifier.GetBuffNames(type, customBuff);
}
catch
{
// A stale/unknown memory layout must disable classification, not
// break the rule-state snapshot or execute a wrong flask rule.
return Array.Empty<string>();
}
}
}
Loading