Skip to content

Keymanager

Roll4d4 edited this page Feb 23, 2025 · 1 revision

🔑 SLASHKeyManager: The Key Conductor of KLEP

The SLASHKeyManager is the core component responsible for managing keys within the KLEP system. It handles key creation, cloning, buffering, trading, and lifecycle management. The key manager ensures that keys flow seamlessly between executables, neurons, and the buffer, enabling dynamic AI behavior.


🚦 What Does SLASHKeyManager Do?

  1. Key Management:

    • Creates, clones, trades, and copies keys.
    • Buffers keys to control their lifecycle between frames.
  2. Event Handling:

    • Listens to events from the SLASHBridge, enabling reactive behavior.
    • Handles key requests, such as pushing keys to the buffer or neuron.
  3. Pooling and Reuse:

    • Manages a pool of reusable keys, reducing memory allocation overhead.
    • Prevents memory leaks by resetting keys and returning them to the pool.
  4. Dynamic Property Management:

    • Supports dynamic properties via PropertyDefinition, allowing keys to carry complex data.

🔍 Core Components of SLASHKeyManager:


🧠 1. Initialization (Initialize)

public void Initialize(KLEPNeuron neuron)
{
    parentNeuron = neuron; // Assigns the neuron

    slashKeyLoaders.Clear(); // Clear any existing loaders in case of re-initialization
    SLASHkeyLoader[] loadedKeyLoaders = Resources.LoadAll<SLASHkeyLoader>("KeyLoaders");
    slashKeyLoaders.AddRange(loadedKeyLoaders);

    foreach (KLEPKey k in parentNeuron.ReturnInitialElements())
    {
        bool makeUnique = k.GetProperty<bool>(PropertyNames.MakeUnique.ToString(), "Slash Key Manager Init");
        if (makeUnique)
        {
            keyBuffer.Add(Clone(k)); // Add unique key to buffer
        }
        else
        {
            keyBuffer.Add(k); // Non-unique key is added to buffer
        }
    }
}
  • Assigns the parent neuron, linking the key manager to its neuron.
  • Loads SLASHkeyLoader assets from Unity's Resources folder, allowing modular key configuration.
  • Initializes keys as unique or shared based on their properties.
  • Adds initial keys to the buffer for immediate use.

🔄 2. Key Creation & Cloning (CreateKey, Clone)

public KLEPKey Clone(KLEPKey k)
{
    KLEPKey clone = ScriptableObject.CreateInstance<KLEPKey>();
    clone.KeyName = k.KeyName;
    clone.Attractiveness = k.Attractiveness;

    clone.propertyManager = new PropertyManager();
    clone.propertyManager.properties = new List<PropertyDefinition>();
    clone.keyLoader = k.keyLoader;

    foreach (var prop in k.propertyManager.properties)
    {
        PropertyDefinition copiedProp = new PropertyDefinition()
        {
            propertyNameEnum = prop.propertyNameEnum,
            propertyNameCustom = prop.propertyNameCustom,
            type = prop.type,
            Value = ClonePropertyValue(prop.Value)
        };
        clone.propertyManager.properties.Add(copiedProp);
    }
    return clone;
}
  • Creates unique instances of keys, ensuring safe state management.
  • Clones properties to avoid data leakage between keys.
  • Supports dynamic property definitions, allowing executables to transfer complex data.

💡 3. Key Handling Methods:

📤 Push Key to Buffer:

public void HandleKeyCreationEvent_PushToBuffer(string eventName, object eventData)
{
    if (eventData is KeyCreationData creationData)
    {
        IssueOrUpdateKeyToBuffer(creationData);
    }
    else Debug.LogError("We pushed non key data to push to buffer in keymanager");
}
  • Listens for events to push keys into the buffer.
  • Keys in the buffer are not immediately active, they activate on the next frame.

📥 Push Key to Neuron:

public void HandleKeyCreationEvent_PushToNeuron(string eventName, object eventData)
{
    if (eventData is KeyCreationData creationData)
    {
        KLEPKey key = keyPool.Count > 0 ? keyPool.First() : CreateKey();
        UpdateKeyProperties(key, creationData); 
        parentNeuron.AddKey(key); // Immediate processing
    }
    else Debug.LogError("We pushed non key data to push to neuron in keymanager");
}
  • Keys pushed to the neuron are available immediately, bypassing the buffer.
  • Useful for real-time responses to events.

🔁 4. Key Trading & Copying (TradeKey, CopyKey)

public bool TradeKey(string keyName, KLEPNeuron sourceNeuron, KLEPNeuron targetNeuron)
{
    var keyToTrade = sourceNeuron.keyManager.GetFirstKeyInNeuronByName(keyName);
    if (keyToTrade != null)
    {
        sourceNeuron.RemoveKey(keyToTrade);     
        targetNeuron.AddKey(keyToTrade);        
        return true; 
    }
    return false; 
}
  • TradeKey: Moves a key from one neuron to another, allowing communication between agents.
  • CopyKey: Duplicates a key, useful for propagating data without removing it from the original source.

🚦 5. Key Cleanup & Pooling (Cleanup)

public void Cleanup()
{
    foreach (var key in parentNeuron.heldKeys)
    {
        if (key.GetProperty<bool>(PropertyNames.ImmuneToKeyLifecycle.ToString(), "Cleanup function"))
        {
            key.SetProperty(PropertyNames.IsInUse.ToString(), false, "Cleanup function");
        }
    }

    var keysToRemove = parentNeuron.heldKeys
                     .Where(key => !key.GetProperty<bool>(PropertyNames.ImmuneToKeyLifecycle.ToString(), nameof(Cleanup)))
                     .ToList();

    keysToRemove.ForEach(key =>
    {
        parentNeuron.RemoveKey(key);
        ResetKeyProperties(key);     
        keyPool.Add(key);            
    });
}
  • Cleans up non-immortal keys, resetting them and returning them to the pool.
  • Immortal keys are reset but not removed, supporting persistent state within the neuron.

💡 Example Scenario:

🎮 Scenario: Detecting and Responding to an Enemy:

  1. Sensor detects an enemy, pushing an "EnemyDetected_KEY" into the buffer.
  2. SLASHKeyManager moves the key from the buffer to the neuron at the start of the next frame.
  3. An executable with a validation lock for "EnemyDetected_KEY" activates.
  4. If the enemy is defeated, the key is removed, and the key manager resets it.

Key Takeaways:

  • SLASHKeyManager is the central hub for all key management within KLEP.
  • Handles all aspects of key lifecycle, including creation, cloning, trading, and cleanup.
  • Supports dynamic behavior, allowing keys to adapt in real-time through property updates.
  • Ensures stability through buffering, pooling, and event-driven management.

🧠 How This Fits Into KLEP:

  • Seamlessly integrates with the SLASHBridge for event handling.
  • Enables AI agents to communicate through keys, share state, and adapt to new conditions.
  • Facilitates modular development, allowing designers and developers to add new keys without overhauling existing systems.

Would you like additional insights on how to configure key loaders, optimize key pooling, or handle advanced scenarios like multi-agent communication in KLEP? 😊

KLEP Wiki Navigation

🚀 Getting Started

🧠 Core Concepts

🎮 Examples and Tutorials

🛠️ Scripts and Components

💡 Experimental/Project Projections

🧬 Contributing

Clone this wiki locally