Files
Beyhan Oğur d5f52cc3d3 first commit
2026-09-03 04:45:36 +03:00

23 KiB
Raw Permalink Blame History

Agent Architecture & Base Classes

**Referenced Files in This Document** - [Engine.cs](file://ClassicAssist.Shared/Engine.cs) - [IncomingPacketHandlers.cs](file://ClassicAssist.Shared/UO/Network/IncomingPacketHandlers.cs) - [OutgoingPacketHandlers.cs](file://ClassicAssist.Shared/UO/Network/OutgoingPacketHandlers.cs) - [PacketHandler.cs](file://ClassicAssist.Shared/UO/Network/PacketHandler.cs) - [ActionPacketQueue.cs](file://ClassicAssist.Shared/UO/Network/ActionPacketQueue.cs) - [IncomingPacketFilters.cs](file://ClassicAssist.Shared/UO/Network/IncomingPacketFilters.cs) - [ThreadQueue.cs](file://ClassicAssist.Shared/Misc/ThreadQueue.cs) - [ThreadPriorityQueue.cs](file://ClassicAssist.Shared/Misc/ThreadPriorityQueue.cs) - [MacroManager.cs](file://ClassicAssist.Shared/Data/Macros/MacroManager.cs) - [HotkeyManager.cs](file://ClassicAssist.Shared/Data/Hotkeys/HotkeyManager.cs) - [AutolootManager.cs](file://ClassicAssist.Shared/Data/Autoloot/AutolootManager.cs) - [DressManager.cs](file://ClassicAssist.Shared/Data/Dress/DressManager.cs) - [ScavengerManager.cs](file://ClassicAssist.Shared/Data/Scavenger/ScavengerManager.cs) - [VendorBuyAgentEntry.cs](file://ClassicAssist.Shared/Data/Vendors/VendorBuyAgentEntry.cs) - [VendorSellAgentEntry.cs](file://ClassicAssist.Shared/Data/Vendors/VendorSellAgentEntry.cs) - [AgentsTabControl.axaml.cs](file://ClassicAssist.Avalonia/Views/AgentsTabControl.axaml.cs) - [AvaloniaDispatcher.cs](file://ClassicAssist.Avalonia/AvaloniaDispatcher.cs) - [AvaloniaUIInvoker.cs](file://ClassicAssist.Avalonia/AvaloniaUIInvoker.cs)

Table of Contents

  1. Introduction
  2. Project Structure
  3. Core Components
  4. Architecture Overview
  5. Detailed Component Analysis
  6. Dependency Analysis
  7. Performance Considerations
  8. Troubleshooting Guide
  9. Conclusion

Introduction

This document explains the agent framework architecture used by ClassicAssist.Avalonia. It focuses on base manager classes, agent lifecycle management, registration and discovery patterns, event handling, state management, integration with the game engine, network packet processing, and rule evaluation for condition matching and action execution. It also covers threading models, performance considerations, memory management for long-running agents, and practical guidance for extending base classes and implementing custom agent logic.

Project Structure

The agent framework spans shared networking, data managers, UI integration, and platform dispatchers:

  • Shared core provides the engine entry point, packet handlers, queues, and manager abstractions.
  • Avalonia-specific code integrates UI threads and dispatcher invokers.
  • Managers implement concrete agent behaviors (e.g., autoloot, dress, scavenger, vendor buy/sell).
graph TB
subgraph "Shared Core"
Engine["Engine"]
InPktHdlrs["IncomingPacketHandlers"]
OutPktHdlrs["OutgoingPacketHandlers"]
PktHandler["PacketHandler"]
InPktFilters["IncomingPacketFilters"]
ActionQ["ActionPacketQueue"]
TQ["ThreadQueue"]
TPQ["ThreadPriorityQueue"]
MacroMgr["MacroManager"]
HotkeyMgr["HotkeyManager"]
AutolootMgr["AutolootManager"]
DressMgr["DressManager"]
ScavengerMgr["ScavengerManager"]
VendorBuy["VendorBuyAgentEntry"]
VendorSell["VendorSellAgentEntry"]
end
subgraph "Avalonia UI"
AgentsTab["AgentsTabControl"]
Dispatcher["AvaloniaDispatcher"]
UIInvoker["AvaloniaUIInvoker"]
end
Engine --> InPktHdlrs
Engine --> OutPktHdlrs
InPktHdlrs --> PktHandler
OutPktHdlrs --> PktHandler
InPktHdlrs --> InPktFilters
InPktHdlrs --> ActionQ
ActionQ --> TQ
ActionQ --> TPQ
MacroMgr --> Engine
HotkeyMgr --> Engine
AutolootMgr --> Engine
DressMgr --> Engine
ScavengerMgr --> Engine
VendorBuy --> Engine
VendorSell --> Engine
AgentsTab --> Dispatcher
Dispatcher --> UIInvoker

Diagram sources

Section sources

Core Components

  • Engine: Central orchestrator that initializes subsystems, wires up packet handlers, and coordinates managers.
  • Packet Handlers: Incoming and outgoing packet routing to registered handlers and filters.
  • Queues: Thread-safe queues for deferring actions across threads.
  • Managers: Feature-specific agents (autoloot, dress, scavenger, vendor buy/sell) that encapsulate rules and state.
  • UI Integration: Avalonia dispatcher and UI invoker bridge background work to UI safely.

Key responsibilities:

  • Registration and discovery of packet handlers and managers.
  • Event-driven updates from packets and timers.
  • Rule evaluation pipelines for conditions and actions.
  • Threading model ensuring safe cross-thread operations.

Section sources

Architecture Overview

The agent framework follows an event-driven architecture:

  • The game engine receives network packets and routes them through incoming/outgoing handlers.
  • Filters can inspect or block packets before they reach handlers.
  • Handlers update shared state and enqueue actions via thread-safe queues.
  • Managers subscribe to events and process queued actions, applying rules and performing actions.
  • UI components observe state changes and are updated via the Avalonia dispatcher.
sequenceDiagram
participant Game as "Game Engine"
participant InPkt as "IncomingPacketHandlers"
participant Filter as "IncomingPacketFilters"
participant Handler as "PacketHandler"
participant Queue as "ActionPacketQueue"
participant Manager as "Agent Manager"
participant UI as "AvaloniaDispatcher/UIInvoker"
Game->>InPkt : "Receive packet"
InPkt->>Filter : "Apply filters"
Filter-->>InPkt : "Allow/Deny"
InPkt->>Handler : "Dispatch to handler"
Handler->>Manager : "Update state / raise events"
Handler->>Queue : "Enqueue action"
Queue-->>Manager : "Dequeue and execute"
Manager->>UI : "Invoke UI updates"

Diagram sources

Detailed Component Analysis

Base Manager Pattern and Lifecycle

Managers encapsulate agent behavior and configuration. Typical lifecycle:

  • Initialization: Register handlers, load configuration, initialize state.
  • Runtime: Subscribe to engine events, evaluate rules, perform actions.
  • Cleanup: Unsubscribe, release resources, persist state.

Common patterns:

  • Configuration entries per agent type (e.g., vendor buy/sell entries).
  • State held in collections and caches for fast lookup.
  • Event-driven updates triggered by packet handlers or timers.

Examples:

  • Autoloot manager maintains lists of constraints and properties to match items.
  • Dress manager tracks desired equipment sets and applies them based on conditions.
  • Scavenger manager defines loot priorities and filtering rules.
  • Vendor buy/sell managers manage shop lists and transaction logic.

Section sources

Agent Registration System

Registration typically occurs during engine initialization:

  • Managers register themselves with the engine.
  • Packet handlers are discovered and bound to specific packet types.
  • UI tabs bind to manager view models for display and control.

Patterns:

  • Centralized registry in the engine.
  • Attribute-based or convention-based discovery for handlers and commands.
  • Tabbed UI surfaces each agent’s configuration and status.

Section sources

Event Handling Mechanisms

Event flow:

  • Network packets arrive and are filtered.
  • Handlers update shared state and raise domain events.
  • Managers listen to these events and react accordingly.
  • Actions may be enqueued for asynchronous execution.

Best practices:

  • Keep handlers lightweight; offload heavy work to queues.
  • Use immutable snapshots where possible to reduce contention.
  • Ensure thread safety when updating shared collections.

Section sources

State Management Patterns

State is managed centrally and accessed by multiple managers:

  • Entity collections and caches provide fast lookups.
  • Managers maintain local state derived from global state.
  • Changes are propagated via events and queues.

Guidelines:

  • Prefer read-only views for UI-bound data.
  • Batch updates to minimize churn.
  • Persist configuration separately from runtime state.

Section sources

Network Packet Integration

Integration points:

  • IncomingPacketHandlers route packets to specific handlers.
  • IncomingPacketFilters allow pre-processing and blocking.
  • OutgoingPacketHandlers intercept outgoing actions for logging or modification.
  • PacketHandler centralizes dispatch logic.

Considerations:

  • Avoid blocking in handlers; use queues for deferred work.
  • Validate packet payloads before processing.
  • Maintain compatibility across client/server protocol versions.

Section sources

Rule Evaluation System: Conditions and Actions

Rule evaluation pipeline:

  • Collect candidate entities or events.
  • Apply filter conditions (e.g., item properties, light level, cliloc text).
  • Compute priority or score.
  • Execute actions (e.g., pick up, equip, sell/buy).

Flowchart:

flowchart TD
Start(["Start Rule Evaluation"]) --> Gather["Gather Candidates"]
Gather --> ApplyFilters["Apply Filter Conditions"]
ApplyFilters --> Matched{"Any Matches?"}
Matched --> |No| End(["End"])
Matched --> |Yes| Score["Compute Priority/Score"]
Score --> SelectTop["Select Top Candidate(s)"]
SelectTop --> ExecuteActions["Execute Actions"]
ExecuteActions --> UpdateState["Update State"]
UpdateState --> End

Diagram sources

Extending Base Classes and Implementing Custom Logic

To extend the framework:

  • Create a new manager class following existing patterns.
  • Initialize configuration entries and subscribe to relevant events.
  • Implement rule evaluation methods and action execution.
  • Integrate with UI via a tab control if needed.

Example references:

  • Autoloot manager demonstrates property-based filtering and selection.
  • Dress manager shows conditional application of equipment sets.
  • Vendor buy/sell entries define structured configurations for transactions.

Section sources

Managing Agent Configuration

Configuration is typically stored in structured entries:

  • Each agent has dedicated entry types (e.g., vendor buy/sell entries).
  • Managers load and apply configurations at startup.
  • UI exposes configuration editors bound to view models.

Recommendations:

  • Validate configuration on load.
  • Provide defaults for missing fields.
  • Persist changes atomically to avoid corruption.

Section sources

Threading Models and Cross-Thread Operations

Threading model:

  • Packet processing runs on network threads.
  • Managers may run on background threads.
  • UI updates must be marshaled to the UI thread using the dispatcher.

Queues:

  • ActionPacketQueue provides a unified queue for actions.
  • ThreadQueue and ThreadPriorityQueue support prioritized scheduling.

Cross-thread best practices:

  • Enqueue work instead of direct UI calls.
  • Use the Avalonia dispatcher to marshal UI updates.
  • Avoid long-running operations on UI threads.

Section sources

Performance Considerations

  • Minimize allocations in hot paths (packet handlers, rule evaluation).
  • Use efficient data structures for entity lookups and filtering.
  • Batch UI updates to reduce redraw overhead.
  • Leverage priority queues for time-sensitive actions.
  • Profile memory usage for long-running sessions and clear caches when appropriate.

[No sources needed since this section provides general guidance]

Memory Management for Long-Running Agents

  • Release subscriptions and timers on cleanup.
  • Avoid retaining large object graphs in static caches.
  • Periodically compact or rebuild indexes if necessary.
  • Monitor GC pressure and adjust batching strategies.

[No sources needed since this section provides general guidance]

Dependency Analysis

High-level dependencies among core components:

  • Engine depends on packet handlers and managers.
  • Packet handlers depend on filters and queues.
  • Managers depend on shared data and configuration entries.
  • UI depends on dispatcher and invoker for cross-thread updates.
graph LR
Engine --> InPktHdlrs
Engine --> OutPktHdlrs
InPktHdlrs --> InPktFilters
InPktHdlrs --> ActionQ
ActionQ --> TQ
ActionQ --> TPQ
Managers["Managers (Autoloot, Dress, Scavenger, Vendor)"] --> Engine
UI["Avalonia UI"] --> Dispatcher
Dispatcher --> UIInvoker

Diagram sources

Section sources

Performance Considerations

  • Favor lightweight handlers and defer heavy computations to queues.
  • Use efficient filtering and early exits in rule evaluation.
  • Reduce UI churn by batching updates and avoiding frequent rebinds.
  • Monitor queue depths and backpressure to prevent memory growth.
  • Profile critical paths under realistic loads to identify bottlenecks.

[No sources needed since this section provides general guidance]

Troubleshooting Guide

Common issues and resolutions:

  • Packets not processed: Verify filters are not blocking; check handler registrations.
  • UI not updating: Ensure actions are dispatched via Avalonia dispatcher.
  • High CPU usage: Inspect tight loops in rule evaluation; add throttling or batching.
  • Memory leaks: Confirm unsubscription from events and disposal of timers.

Diagnostic utilities:

  • Logging in packet handlers and managers.
  • Queue depth monitoring.
  • UI thread invocation failures captured by dispatcher.

Section sources

Conclusion

The ClassicAssist.Avalonia agent framework is built around a robust event-driven architecture with clear separation between networking, rule evaluation, and UI concerns. Managers encapsulate agent logic and configuration, while queues and dispatchers ensure safe, performant operation across threads. By following the patterns outlined here—registration, event handling, rule evaluation, and cross-thread updates—you can extend the system with custom agents that integrate seamlessly with the game engine and UI.