A programming framework for agentic AI
WIP, moved to base namespace
Jack Gerritsb16b94feb8bd
diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentExceptions.cs b/dotnet/src/Microsoft.AutoGen/Contracts/AgentExceptions.cssimilarity index 98%rename from dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentExceptions.csrename to dotnet/src/Microsoft.AutoGen/Contracts/AgentExceptions.csindex 9b58ed6d0..9147e47fb 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentExceptions.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/AgentExceptions.cs@@ -1,7 +1,7 @@// Copyright (c) Microsoft Corporation. All rights reserved.// AgentExceptions.cs-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>/// Exception thrown when a handler cannot process the given message.diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/AgentId.cs b/dotnet/src/Microsoft.AutoGen/Contracts/AgentId.csindex 49c26a8c8..28d4a8af4 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/AgentId.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/AgentId.cs@@ -1,13 +1,106 @@// Copyright (c) Microsoft Corporation. All rights reserved.// AgentId.cs+using System.Diagnostics;+using System.Diagnostics.CodeAnalysis;+namespace Microsoft.AutoGen.Contracts;-public partial class AgentId+/// <summary>+/// Agent ID uniquely identifies an agent instance within an agent runtime, including a distributed runtime.+/// It serves as the "address" of the agent instance for receiving messages.+/// </summary>+/// See the Python equivalent:+/// <see href="https://microsoft.github.io/autogen/stable/reference/python/autogen_core.html#autogen_core.AgentId">AgentId in AutoGen (Python)</see>.+/// </remarks>+[DebuggerDisplay($"AgentId(type=\"{nameof(Type)}\", key=\"{nameof(Key)}\")")]+public struct AgentId{+ /// <summary>+ /// An identifier that associates an agent with a specific factory function.+ /// Strings may only be composed of alphanumeric letters (a-z) and (0-9), or underscores (_).+ /// </summary>+ public string Type;++ /// <summary>+ /// Agent instance identifier.+ /// Strings may only be composed of alphanumeric letters (a-z) and (0-9), or underscores (_).+ /// </summary>+ public string Key;++ /// <summary>+ /// Initializes a new instance of the <see cref="AgentId"/> struct.+ /// </summary>+ /// <param name="type">The agent type.</param>+ /// <param name="key">Agent instance identifier.</param>public AgentId(string type, string key){Type = type;Key = key;}++ /// <summary>+ /// Initializes a new instance of the <see cref="AgentId"/> struct from a tuple.+ /// </summary>+ /// <param name="kvPair">A tuple containing the agent type and key.</param>+ public AgentId((string Type, string Key) kvPair) : this(kvPair.Type, kvPair.Key)+ {+ }++ /// <summary>+ /// Initializes a new instance of the <see cref="AgentId"/> struct from an <see cref="AgentType"/>.+ /// </summary>+ /// <param name="type">The agent type.</param>+ /// <param name="key">Agent instance identifier.</param>+ public AgentId(AgentType type, string key) : this(type.Name, key)+ {+ }++ /// <summary>+ /// Convert a string of the format "type/key" into an <see cref="AgentId"/>.+ /// </summary>+ /// <param name="maybeAgentId">The agent ID string.</param>+ /// <returns>An instance of <see cref="AgentId"/>.</returns>+ public static AgentId FromStr(string maybeAgentId) => new AgentId(maybeAgentId.ToKVPair(nameof(Type), nameof(Key)));++ /// <summary>+ /// Returns the string representation of the <see cref="AgentId"/>.+ /// </summary>+ /// <returns>A string in the format "type/key".</returns>+ public override string ToString() => $"{Type}/{Key}";++ /// <summary>+ /// Determines whether the specified object is equal to the current <see cref="AgentId"/>.+ /// </summary>+ /// <param name="obj">The object to compare with the current instance.</param>+ /// <returns><c>true</c> if the specified object is equal to the current <see cref="AgentId"/>; otherwise, <c>false</c>.</returns>+ public override bool Equals([NotNullWhen(true)] object? obj)+ {+ if (obj is AgentId other)+ {+ return Type == other.Type && Key == other.Key;+ }++ return false;+ }++ /// <summary>+ /// Returns a hash code for this <see cref="AgentId"/>.+ /// </summary>+ /// <returns>A hash code for the current instance.</returns>+ public override int GetHashCode()+ {+ return HashCode.Combine(Type, Key);+ }++ /// <summary>+ /// Explicitly converts a string to an <see cref="AgentId"/>.+ /// </summary>+ /// <param name="id">The string representation of an agent ID.</param>+ /// <returns>An instance of <see cref="AgentId"/>.</returns>+ public static explicit operator AgentId(string id) => FromStr(id);++ public static bool operator ==(AgentId left, AgentId right) => left.Equals(right);+ public static bool operator !=(AgentId left, AgentId right) => !left.Equals(right);}+diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentMetadata.cs b/dotnet/src/Microsoft.AutoGen/Contracts/AgentMetadata.cssimilarity index 93%rename from dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentMetadata.csrename to dotnet/src/Microsoft.AutoGen/Contracts/AgentMetadata.csindex fe9bbf6fd..961ba3094 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentMetadata.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/AgentMetadata.cs@@ -1,7 +1,7 @@// Copyright (c) Microsoft Corporation. All rights reserved.// AgentMetadata.cs-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>/// Represents metadata associated with an agent, including its type, unique key, and description.@@ -22,7 +22,7 @@ public struct AgentMetadata(string type, string key, string description)/// <summary>/// A brief description of the agent's purpose or functionality.- /// </summary>+ /// </summary>public string Description { get; set; } = description;}diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentProxy.cs b/dotnet/src/Microsoft.AutoGen/Contracts/AgentProxy.cssimilarity index 97%rename from dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentProxy.csrename to dotnet/src/Microsoft.AutoGen/Contracts/AgentProxy.csindex 06182d086..7efff53f6 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentProxy.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/AgentProxy.cs@@ -1,7 +1,7 @@// Copyright (c) Microsoft Corporation. All rights reserved.// AgentProxy.cs-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>/// A helper class that allows you to use an <see cref="AgentId"/> in place of its associated <see cref="IAgent"/>.@@ -38,7 +38,7 @@ public class AgentProxy(AgentId agentId, IAgentRuntime runtime)/// <param name="message">The message to send to the agent.</param>/// <param name="sender">The agent that is sending the message.</param>/// <param name="messageId">- /// The message ID. If <c>null</c>, a new message ID will be generated.+ /// The message ID. If <c>null</c>, a new message ID will be generated./// This message ID must be unique and is recommended to be a UUID./// </param>/// <param name="cancellationToken">diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentType.cs b/dotnet/src/Microsoft.AutoGen/Contracts/AgentType.cssimilarity index 94%rename from dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentType.csrename to dotnet/src/Microsoft.AutoGen/Contracts/AgentType.csindex 2b7fd66f2..e05d4735a 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentType.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/AgentType.cs@@ -1,10 +1,10 @@// Copyright (c) Microsoft Corporation. All rights reserved.// AgentType.cs-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>-/// Represents the type of an agent as a string.+/// Represents the type of an agent as a string./// This is a strongly-typed wrapper around a string, ensuring type safety when working with agent types./// </summary>/// <remarks>diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/AgentsRegistryState.cs b/dotnet/src/Microsoft.AutoGen/Contracts/AgentsRegistryState.csdeleted file mode 100644index 836d4699c..000000000--- a/dotnet/src/Microsoft.AutoGen/Contracts/AgentsRegistryState.cs+++ /dev/null@@ -1,15 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// AgentsRegistryState.cs-using System.Collections.Concurrent;--namespace Microsoft.AutoGen.Contracts;-public class AgentsRegistryState-{- public ConcurrentDictionary<string, HashSet<string>> AgentsToEventsMap { get; set; } = new ConcurrentDictionary<string, HashSet<string>>();- public ConcurrentDictionary<string, HashSet<string>> AgentsToTopicsMap { get; set; } = [];- public ConcurrentDictionary<string, HashSet<string>> TopicToAgentTypesMap { get; set; } = [];- public ConcurrentDictionary<string, HashSet<string>> EventsToAgentTypesMap { get; set; } = [];- public ConcurrentDictionary<string, HashSet<Subscription>> GuidSubscriptionsMap { get; set; } = [];- public ConcurrentDictionary<string, AgentId> AgentTypes { get; set; } = [];- public string Etag { get; set; } = Guid.NewGuid().ToString();-}diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/ChatHistoryItem.cs b/dotnet/src/Microsoft.AutoGen/Contracts/ChatHistoryItem.csdeleted file mode 100644index 77491bdb8..000000000--- a/dotnet/src/Microsoft.AutoGen/Contracts/ChatHistoryItem.cs+++ /dev/null@@ -1,12 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// ChatHistoryItem.cs--namespace Microsoft.AutoGen.Contracts;--[Serializable]-public class ChatHistoryItem-{- public required string Message { get; set; }- public ChatUserType UserType { get; set; }- public int Order { get; set; }-}diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/ChatState.cs b/dotnet/src/Microsoft.AutoGen/Contracts/ChatState.csdeleted file mode 100644index 6e41b644b..000000000--- a/dotnet/src/Microsoft.AutoGen/Contracts/ChatState.cs+++ /dev/null@@ -1,13 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// ChatState.cs--using Google.Protobuf;--namespace Microsoft.AutoGen.Contracts;--public class ChatState- <T> where T : IMessage, new()-{- public List<ChatHistoryItem> History { get; set; } = new();- public T Data { get; set; } = new();-}diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/ChatUserType.cs b/dotnet/src/Microsoft.AutoGen/Contracts/ChatUserType.csdeleted file mode 100644index 3bfcbb376..000000000--- a/dotnet/src/Microsoft.AutoGen/Contracts/ChatUserType.cs+++ /dev/null@@ -1,11 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// ChatUserType.cs--namespace Microsoft.AutoGen.Contracts;--public enum ChatUserType-{- System,- User,- Agent-}diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/IAgent.cs b/dotnet/src/Microsoft.AutoGen/Contracts/IAgent.csindex 01a3624cf..ceb738a08 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/IAgent.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/IAgent.cs@@ -1,24 +1,46 @@// Copyright (c) Microsoft Corporation. All rights reserved.// IAgent.cs-using Google.Protobuf;-namespace Microsoft.AutoGen.Contracts;-public interface IAgent+/// <summary>+/// Represents an agent within the runtime that can process messages, maintain state, and be closed when no longer needed.+/// </summary>+public interface IAgent : ISaveState<IAgent>+{+ /// <summary>+ /// Gets the unique identifier of the agent.+ /// </summary>+ public AgentId Id { get; }++ /// <summary>+ /// Gets metadata associated with the agent.+ /// </summary>+ public AgentMetadata Metadata { get; }++ /// <summary>+ /// Handles an incoming message for the agent.+ /// This should only be called by the runtime, not by other agents.+ /// </summary>+ /// <param name="message">The received message. The type should match one of the expected subscription types.</param>+ /// <param name="messageContext">The context of the message, providing additional metadata.</param>+ /// <returns>+ /// A task representing the asynchronous operation, returning a response to the message.+ /// The response can be <c>null</c> if no reply is necessary.+ /// </returns>+ /// <exception cref="OperationCanceledException">Thrown if the message was cancelled.</exception>+ /// <exception cref="CantHandleException">Thrown if the agent cannot handle the message.</exception>+ public ValueTask<object?> OnMessageAsync(object message, MessageContext messageContext); // TODO: How do we express this properly in .NET?+}+/// <summary>+/// Represents an agent that can be explicitly hosted and closed when the runtime shuts down.+/// </summary>+public interface IHostableAgent : IAgent{- AgentId AgentId { get; }- IAgentRuntime Worker { get; }- ValueTask<List<Subscription>> GetSubscriptionsAsync();- ValueTask<AddSubscriptionResponse> SubscribeAsync(string topic);- ValueTask<RemoveSubscriptionResponse> UnsubscribeAsync(Guid id);- ValueTask<RemoveSubscriptionResponse> UnsubscribeAsync(string topic);- Task StoreAsync(AgentState state, CancellationToken cancellationToken = default);- Task<T> ReadAsync<T>(AgentId agentId, CancellationToken cancellationToken = default) where T : IMessage, new();- ValueTask PublishMessageAsync(IMessage message, string topic, string source, string key, CancellationToken token = default);- ValueTask PublishMessageAsync<T>(T message, string topic, string source, CancellationToken token = default) where T : IMessage;- ValueTask PublishMessageAsync<T>(T message, string topic, CancellationToken token = default) where T : IMessage;- ValueTask PublishMessageAsync<T>(T message, CancellationToken token = default) where T : IMessage;- Task<RpcResponse> HandleRequestAsync(RpcRequest request);- Task HandleObjectAsync(object item, CancellationToken cancellationToken = default);+ /// <summary>+ /// Called when the runtime is closing.+ /// </summary>+ /// <returns>A task representing the asynchronous operation.</returns>+ public ValueTask CloseAsync() => ValueTask.CompletedTask;}+diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/IAgentRuntime.cs b/dotnet/src/Microsoft.AutoGen/Contracts/IAgentRuntime.csindex aab5f90ff..bc461e74a 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/IAgentRuntime.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/IAgentRuntime.cs@@ -1,103 +1,127 @@// Copyright (c) Microsoft Corporation. All rights reserved.// IAgentRuntime.cs-using Google.Protobuf;+using StateDict = System.Collections.Generic.IDictionary<string, object>;+namespace Microsoft.AutoGen.Contracts;/// <summary>-/// Defines the common surface for agent runtime implementations.+/// Defines the runtime environment for agents, managing message sending, subscriptions, agent resolution, and state persistence./// </summary>-public interface IAgentRuntime+public interface IAgentRuntime : ISaveState<IAgentRuntime>{/// <summary>- /// Gets the dependency injection service provider for the runtime.+ /// Sends a message to an agent and gets a response.+ /// This method should be used to communicate directly with an agent./// </summary>- IServiceProvider RuntimeServiceProvider { get; }+ /// <param name="message">The message to send.</param>+ /// <param name="recepient">The agent to send the message to.</param>+ /// <param name="sender">The agent sending the message. Should be <c>null</c> if sent from an external source.</param>+ /// <param name="messageId">A unique identifier for the message. If <c>null</c>, a new ID will be generated.</param>+ /// <param name="cancellationToken">A token to cancel the operation if needed.</param>+ /// <returns>A task representing the asynchronous operation, returning the response from the agent.</returns>+ /// <exception cref="CantHandleException">Thrown if the recipient cannot handle the message.</exception>+ /// <exception cref="UndeliverableException">Thrown if the message cannot be delivered.</exception>+ public ValueTask<object?> SendMessageAsync(object message, AgentId recepient, AgentId? sender = null, string? messageId = null, CancellationToken? cancellationToken = default);/// <summary>- /// Registers a new agent type asynchronously.+ /// Publishes a message to all agents subscribed to the given topic.+ /// No responses are expected from publishing./// </summary>- /// <param name="request">The request containing the agent type details.</param>- /// <param name="cancellationToken">A token to cancel the operation.</param>- /// <returns>A task that represents the asynchronous operation.</returns>- ValueTask RegisterAgentTypeAsync(RegisterAgentTypeRequest request, CancellationToken cancellationToken = default);+ /// <param name="message">The message to publish.</param>+ /// <param name="topic">The topic to publish the message to.</param>+ /// <param name="sender">The agent sending the message. Defaults to <c>null</c>.</param>+ /// <param name="messageId">A unique message ID. If <c>null</c>, a new one will be generated.</param>+ /// <param name="cancellationToken">A token to cancel the operation if needed.</param>+ /// <returns>A task representing the asynchronous operation.</returns>+ /// <exception cref="UndeliverableException">Thrown if the message cannot be delivered.</exception>+ public ValueTask PublishMessageAsync(object message, TopicId topic, AgentId? sender = null, string? messageId = null, CancellationToken? cancellationToken = default);+ // TODO: Can we call this Resolve?/// <summary>- /// to be removed in favor of send_message- /// Sends a request to and agent.+ /// Retrieves an agent by its unique identifier./// </summary>- /// <param name="agent">The agent sending the request.</param>- /// <param name="request">The request to be sent.</param>- /// <param name="cancellationToken">A token to cancel the operation.</param>- /// <returns>A task that represents the asynchronous operation.</returns>- ValueTask RuntimeSendRequestAsync(IAgent agent, RpcRequest request, CancellationToken cancellationToken = default);+ /// <param name="agentId">The unique identifier of the agent.</param>+ /// <param name="lazy">If <c>true</c>, the agent is fetched lazily.</param>+ /// <returns>A task representing the asynchronous operation, returning the agent's ID.</returns>+ public ValueTask<AgentId> GetAgentAsync(AgentId agentId, bool lazy = true/*, CancellationToken? = default*/);/// <summary>- /// Sends a response to the above request.- /// /// to be removed in favor of send_message+ /// Retrieves an agent by its type./// </summary>- /// <param name="response">The response to be sent.</param>- /// <param name="cancellationToken">A token to cancel the operation.</param>- /// <returns>A task that represents the asynchronous operation.</returns>- ValueTask RuntimeSendResponseAsync(RpcResponse response, CancellationToken cancellationToken = default);+ /// <param name="agentType">The type of the agent.</param>+ /// <param name="key">An optional key to specify variations of the agent. Defaults to "default".</param>+ /// <param name="lazy">If <c>true</c>, the agent is fetched lazily.</param>+ /// <returns>A task representing the asynchronous operation, returning the agent's ID.</returns>+ public ValueTask<AgentId> GetAgentAsync(AgentType agentType, string key = "default", bool lazy = true/*, CancellationToken? = default*/);/// <summary>- /// Sends a message directly to another agent.+ /// Retrieves an agent by its string representation./// </summary>- /// <param name="message">The message to be sent.</param>- /// <param name="recipient">The recipient of the message.</param>- /// <param name="sender">The agent sending the message.</param>- /// <param name="cancellationToken">A token to cancel the operation.</param>- /// <returns>A task that represents the response to th message.</returns>- ValueTask<RpcResponse> SendMessageAsync(IMessage message, AgentId recipient, AgentId? sender, CancellationToken? cancellationToken = default);+ /// <param name="agent">The string representation of the agent.</param>+ /// <param name="key">An optional key to specify variations of the agent. Defaults to "default".</param>+ /// <param name="lazy">If <c>true</c>, the agent is fetched lazily.</param>+ /// <returns>A task representing the asynchronous operation, returning the agent's ID.</returns>+ public ValueTask<AgentId> GetAgentAsync(string agent, string key = "default", bool lazy = true/*, CancellationToken? = default*/);/// <summary>- /// Publishes a message to a topic.+ /// Saves the state of an agent.+ /// The result must be JSON serializable./// </summary>- /// <param name="message">The message to be published.</param>- /// <param name="topic">The topic to publish the message to.</param>- /// <param name="sender">The agent sending the message.</param>- /// <param name="cancellationToken">A token to cancel the operation.</param>- /// <returns>A task that represents the asynchronous operation.</returns>- ValueTask PublishMessageAsync(IMessage message, TopicId topic, IAgent? sender, CancellationToken? cancellationToken = default);+ /// <param name="agentId">The ID of the agent whose state is being saved.</param>+ /// <returns>A task representing the asynchronous operation, returning a dictionary of the saved state.</returns>+ public ValueTask<StateDict> SaveAgentStateAsync(AgentId agentId/*, CancellationToken? cancellationToken = default*/);++ /// <summary>+ /// Loads the saved state into an agent.+ /// </summary>+ /// <param name="agentId">The ID of the agent whose state is being restored.</param>+ /// <param name="state">The state dictionary to restore.</param>+ /// <returns>A task representing the asynchronous operation.</returns>+ public ValueTask LoadAgentStateAsync(AgentId agentId, StateDict state/*, CancellationToken? cancellationToken = default*/);/// <summary>- /// Saves the state of an agent asynchronously.+ /// Retrieves metadata for an agent./// </summary>- /// <param name="value">The state to be saved.</param>- /// <param name="cancellationToken">A token to cancel the operation.</param>- /// <returns>A task that represents the asynchronous operation.</returns>- ValueTask SaveStateAsync(AgentState value, CancellationToken cancellationToken = default);+ /// <param name="agentId">The ID of the agent.</param>+ /// <returns>A task representing the asynchronous operation, returning the agent's metadata.</returns>+ public ValueTask<AgentMetadata> GetAgentMetadataAsync(AgentId agentId/*, CancellationToken? cancellationToken = default*/);/// <summary>- /// Loads the state of an agent asynchronously.+ /// Adds a new subscription for the runtime to handle when processing published messages./// </summary>- /// <param name="agentId">The ID of the agent whose state is to be loaded.</param>- /// <param name="cancellationToken">A token to cancel the operation.</param>- /// <returns>A task that represents the asynchronous operation, containing the agent state.</returns>- ValueTask<AgentState> LoadStateAsync(AgentId agentId, CancellationToken cancellationToken = default);+ /// <param name="subscription">The subscription to add.</param>+ /// <returns>A task representing the asynchronous operation.</returns>+ public ValueTask AddSubscriptionAsync(ISubscriptionDefinition subscription/*, CancellationToken? cancellationToken = default*/);/// <summary>- /// Adds a subscription to a topic.+ /// Removes a subscription from the runtime./// </summary>- /// <param name="request">The request containing the subscription types.</param>- /// <param name="cancellationToken">A token to cancel the operation.</param>- /// <returns>A task that represents the asynchronous operation, containing the response.</returns>- ValueTask<AddSubscriptionResponse> AddSubscriptionAsync(AddSubscriptionRequest request, CancellationToken cancellationToken = default);+ /// <param name="subscriptionId">The unique identifier of the subscription to remove.</param>+ /// <returns>A task representing the asynchronous operation.</returns>+ /// <exception cref="KeyNotFoundException">Thrown if the subscription does not exist.</exception>+ public ValueTask RemoveSubscriptionAsync(string subscriptionId/*, CancellationToken? cancellationToken = default*/);/// <summary>- /// Removes a subscription.+ /// Registers an agent factory with the runtime, associating it with a specific agent type.+ /// The type must be unique./// </summary>- /// <param name="request">The request containing the subscription id.</param>- /// <param name="cancellationToken">A token to cancel the operation.</param>- /// <returns>A task that represents the asynchronous operation, containing the response.</returns>- ValueTask<RemoveSubscriptionResponse> RemoveSubscriptionAsync(RemoveSubscriptionRequest request, CancellationToken cancellationToken = default);+ /// <typeparam name="TAgent">The agent type being registered.</typeparam>+ /// <param name="type">The agent type to associate with the factory.</param>+ /// <param name="factoryFunc">A function that asynchronously creates the agent instance.</param>+ /// <returns>A task representing the asynchronous operation, returning the registered <see cref="AgentType"/>.</returns>+ public ValueTask<AgentType> RegisterAgentFactoryAsync<TAgent>(AgentType type, Func<AgentId, IAgentRuntime, ValueTask<TAgent>> factoryFunc) where TAgent : IHostableAgent;+ // TODO:+ //public ValueTask<TAgent> TryGetUnderlyingAgentInstanceAsync<TAgent>(AgentId agentId) where TAgent : IHostableAgent;+ //public void AddMessageSerializer(params object[] serializers);++ // Extras/// <summary>- /// Gets the list of subscriptions.+ /// Attempts to retrieve an <see cref="AgentProxy"/> for the specified agent./// </summary>- /// <param name="request">The request containing the subscription query details.</param>- /// <param name="cancellationToken">A token to cancel the operation.</param>- /// <returns>A task that represents the asynchronous operation, containing the list of subscriptions.</returns>- ValueTask<List<Subscription>> GetSubscriptionsAsync(GetSubscriptionsRequest request, CancellationToken cancellationToken = default);+ /// <param name="agentId">The ID of the agent.</param>+ /// <returns>A task representing the asynchronous operation, returning an <see cref="AgentProxy"/> if successful.</returns>+ public ValueTask<AgentProxy> TryGetAgentProxyAsync(AgentId agentId);}+diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/IAgentState.cs b/dotnet/src/Microsoft.AutoGen/Contracts/IAgentState.csdeleted file mode 100644index 0b3491dfb..000000000--- a/dotnet/src/Microsoft.AutoGen/Contracts/IAgentState.cs+++ /dev/null@@ -1,26 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// IAgentState.cs--namespace Microsoft.AutoGen.Contracts;--/// <summary>-/// Interface for managing the state of an agent.-/// </summary>-public interface IAgentState-{- /// <summary>- /// Reads the current state of the agent asynchronously.- /// </summary>- /// <param name="cancellationToken">A token to cancel the operation.</param>- /// <returns>A task that represents the asynchronous read operation. The task result contains the current state of the agent.</returns>- ValueTask<AgentState> ReadStateAsync(CancellationToken cancellationToken = default);-- /// <summary>- /// Writes the specified state of the agent asynchronously.- /// </summary>- /// <param name="state">The state to write.</param>- /// <param name="eTag">The ETag for concurrency control.</param>- /// <param name="cancellationToken">A token to cancel the operation.</param>- /// <returns>A task that represents the asynchronous write operation. The task result contains the ETag of the written state.</returns>- ValueTask<string> WriteStateAsync(AgentState state, string eTag, CancellationToken cancellationToken = default);-}diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/IConnection.cs b/dotnet/src/Microsoft.AutoGen/Contracts/IConnection.csdeleted file mode 100644index 3e7484c5d..000000000--- a/dotnet/src/Microsoft.AutoGen/Contracts/IConnection.cs+++ /dev/null@@ -1,7 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// IConnection.cs--namespace Microsoft.AutoGen.Contracts;-public interface IConnection-{-}diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/IRegistry.cs b/dotnet/src/Microsoft.AutoGen/Contracts/IRegistry.csdeleted file mode 100644index bea5f657d..000000000--- a/dotnet/src/Microsoft.AutoGen/Contracts/IRegistry.cs+++ /dev/null@@ -1,55 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// IRegistry.cs-namespace Microsoft.AutoGen.Contracts;--public interface IRegistry-{- //AgentsRegistryState State { get; set; }- /// <summary>- /// Registers a new agent type with the specified worker.- /// </summary>- /// <param name="request">The request containing agent type details.</param>- /// <param name="worker">The worker to register the agent type with.</param>- /// <returns>A task representing the asynchronous operation.</returns>- /// <remarks>removing CancellationToken from here as it is not compatible with Orleans Serialization</remarks>- ValueTask RegisterAgentTypeAsync(RegisterAgentTypeRequest request, IAgentRuntime worker);-- /// <summary>- /// Unregisters an agent type from the specified worker.- /// </summary>- /// <param name="type">The type of the agent to unregister.</param>- /// <param name="worker">The worker to unregister the agent type from.</param>- /// <returns>A task representing the asynchronous operation.</returns>- /// <remarks>removing CancellationToken from here as it is not compatible with Orleans Serialization</remarks>- ValueTask UnregisterAgentTypeAsync(string type, IAgentRuntime worker);-- /// <summary>- /// Gets a list of agents subscribed to and handling the specified topic and event type.- /// </summary>- /// <param name="topic">The topic to check subscriptions for.</param>- /// <param name="eventType">The event type to check subscriptions for.</param>- /// <returns>A task representing the asynchronous operation, with the list of agent IDs as the result.</returns>- ValueTask<List<string>> GetSubscribedAndHandlingAgentsAsync(string topic, string eventType);-- /// <summary>- /// Subscribes an agent to a topic.- /// </summary>- /// <param name="request">The subscription request.</param>- /// <returns>A task representing the asynchronous operation.</returns>- /// <remarks>removing CancellationToken from here as it is not compatible with Orleans Serialization</remarks>- ValueTask SubscribeAsync(AddSubscriptionRequest request);-- /// <summary>- /// Unsubscribes an agent from a topic.- /// </summary>- /// <param name="request">The unsubscription request.</param>- /// <returns>A task representing the asynchronous operation.</returns>- /// <remarks>removing CancellationToken from here as it is not compatible with Orleans Serialization</remarks>- ValueTask UnsubscribeAsync(RemoveSubscriptionRequest request); // TODO: This should have its own request type.-- /// <summary>- /// Gets the subscriptions for a specified agent type.- /// </summary>- /// <returns>A task representing the asynchronous operation, with the subscriptions as the result.</returns>- ValueTask<List<Subscription>> GetSubscriptionsAsync(GetSubscriptionsRequest request);-}diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/IRegistryStorage.cs b/dotnet/src/Microsoft.AutoGen/Contracts/IRegistryStorage.csdeleted file mode 100644index 499fc9147..000000000--- a/dotnet/src/Microsoft.AutoGen/Contracts/IRegistryStorage.cs+++ /dev/null@@ -1,20 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// IRegistryStorage.cs--namespace Microsoft.AutoGen.Contracts;--public interface IRegistryStorage-{- /// <summary>- /// Populates the Registry state from the storage.- /// </summary>- /// <param name="cancellationToken"></param>- Task<AgentsRegistryState> ReadStateAsync(CancellationToken cancellationToken = default);- /// <summary>- /// Writes the Registry state to the storage.- /// </summary>- /// <param name="state"></param>- /// <param name="cancellationToken"></param>- /// <returns>the etag that was written</returns>- ValueTask<string> WriteStateAsync(AgentsRegistryState state, CancellationToken cancellationToken = default);-}diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/ISaveState.cs b/dotnet/src/Microsoft.AutoGen/Contracts/ISaveState.cssimilarity index 95%rename from dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/ISaveState.csrename to dotnet/src/Microsoft.AutoGen/Contracts/ISaveState.csindex dafdfb5d6..4d8a8ac11 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/ISaveState.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/ISaveState.cs@@ -3,7 +3,7 @@using StateDict = System.Collections.Generic.IDictionary<string, object>;-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>/// Defines a contract for saving and loading the state of an object.@@ -11,7 +11,7 @@ namespace Microsoft.AutoGen.Contracts.Python;/// </summary>/// <typeparam name="T">The type of the object implementing this interface.</typeparam>public interface ISaveState<T>-{+{/// <summary>/// Saves the current state of the object./// </summary>diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/ISubscriptionDefinition.cs b/dotnet/src/Microsoft.AutoGen/Contracts/ISubscriptionDefinition.cssimilarity index 97%rename from dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/ISubscriptionDefinition.csrename to dotnet/src/Microsoft.AutoGen/Contracts/ISubscriptionDefinition.csindex da78c7656..1c23c7e77 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/ISubscriptionDefinition.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/ISubscriptionDefinition.cs@@ -3,7 +3,7 @@using System.Diagnostics.CodeAnalysis;-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>/// Defines a subscription that matches topics and maps them to agents.@@ -21,7 +21,7 @@ public interface ISubscriptionDefinition/// <param name="obj">The object to compare with the current instance.</param>/// <returns><c>true</c> if the specified object is equal to this instance; otherwise, <c>false</c>.</returns>public bool Equals([NotNullWhen(true)] object? obj) => obj is ISubscriptionDefinition other && Equals(other);-+/// <summary>/// Determines whether the specified subscription is equal to the current subscription./// </summary>diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/IUnboundSubscriptionDefinition.cs b/dotnet/src/Microsoft.AutoGen/Contracts/IUnboundSubscriptionDefinition.cssimilarity index 94%rename from dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/IUnboundSubscriptionDefinition.csrename to dotnet/src/Microsoft.AutoGen/Contracts/IUnboundSubscriptionDefinition.csindex b4ca23f5b..3dcf8ce3b 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/IUnboundSubscriptionDefinition.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/IUnboundSubscriptionDefinition.cs@@ -1,7 +1,7 @@// Copyright (c) Microsoft Corporation. All rights reserved.// IUnboundSubscriptionDefinition.cs-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>/// Defines a subscription that is not yet bound to a specific agent type.diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/KVStringParseHelper.cs b/dotnet/src/Microsoft.AutoGen/Contracts/KVStringParseHelper.cssimilarity index 97%rename from dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/KVStringParseHelper.csrename to dotnet/src/Microsoft.AutoGen/Contracts/KVStringParseHelper.csindex 21b03c362..993470d88 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/KVStringParseHelper.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/KVStringParseHelper.cs@@ -3,7 +3,7 @@using System.Text.RegularExpressions;-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>/// Provides helper methods for parsing key-value string representations.diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/MessageContext.cs b/dotnet/src/Microsoft.AutoGen/Contracts/MessageContext.cssimilarity index 96%rename from dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/MessageContext.csrename to dotnet/src/Microsoft.AutoGen/Contracts/MessageContext.csindex 04d91c4c9..367beff58 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/MessageContext.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/MessageContext.cs@@ -1,7 +1,7 @@// Copyright (c) Microsoft Corporation. All rights reserved.// MessageContext.cs-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>/// Represents the context of a message being sent within the agent runtime.diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/Microsoft.AutoGen.Contracts.csproj b/dotnet/src/Microsoft.AutoGen/Contracts/Microsoft.AutoGen.Contracts.csprojindex 6a8f6bbf2..74b8d70a5 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/Microsoft.AutoGen.Contracts.csproj+++ b/dotnet/src/Microsoft.AutoGen/Contracts/Microsoft.AutoGen.Contracts.csproj@@ -7,16 +7,4 @@</PropertyGroup><Import Project="$(RepoRoot)/nuget/nuget-package.props" />-- <ItemGroup>- <Protobuf Include="..\..\..\..\protos\agent_worker.proto" GrpcServices="Client;Server" Link="Protos\agent_worker.proto" />- <Protobuf Include="..\..\..\..\protos\cloudevent.proto" GrpcServices="Client;Server" Link="Protos\cloudevent.proto" />- <Protobuf Include="..\..\..\..\protos\agent_events.proto" GrpcServices="Client;Server" Link="Protos\agent_events.proto" />- </ItemGroup>-- <ItemGroup>- <PackageReference Include="Grpc.AspNetCore" />- <PackageReference Include="Grpc.Net.ClientFactory" />- <PackageReference Include="Grpc.Tools" PrivateAssets="All" />- </ItemGroup></Project>diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentId.cs b/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentId.csdeleted file mode 100644index a85a21686..000000000--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/AgentId.cs+++ /dev/null@@ -1,106 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// AgentId.cs--using System.Diagnostics;-using System.Diagnostics.CodeAnalysis;--namespace Microsoft.AutoGen.Contracts.Python;--/// <summary>-/// Agent ID uniquely identifies an agent instance within an agent runtime, including a distributed runtime.-/// It serves as the "address" of the agent instance for receiving messages.-/// </summary>-/// See the Python equivalent:-/// <see href="https://microsoft.github.io/autogen/stable/reference/python/autogen_core.html#autogen_core.AgentId">AgentId in AutoGen (Python)</see>.-/// </remarks>-[DebuggerDisplay($"AgentId(type=\"{nameof(Type)}\", key=\"{nameof(Key)}\")")]-public struct AgentId-{- /// <summary>- /// An identifier that associates an agent with a specific factory function.- /// Strings may only be composed of alphanumeric letters (a-z) and (0-9), or underscores (_).- /// </summary>- public string Type;-- /// <summary>- /// Agent instance identifier.- /// Strings may only be composed of alphanumeric letters (a-z) and (0-9), or underscores (_).- /// </summary>- public string Key;-- /// <summary>- /// Initializes a new instance of the <see cref="AgentId"/> struct.- /// </summary>- /// <param name="type">The agent type.</param>- /// <param name="key">Agent instance identifier.</param>- public AgentId(string type, string key)- {- Type = type;- Key = key;- }-- /// <summary>- /// Initializes a new instance of the <see cref="AgentId"/> struct from a tuple.- /// </summary>- /// <param name="kvPair">A tuple containing the agent type and key.</param>- public AgentId((string Type, string Key) kvPair) : this(kvPair.Type, kvPair.Key)- {- }-- /// <summary>- /// Initializes a new instance of the <see cref="AgentId"/> struct from an <see cref="AgentType"/>.- /// </summary>- /// <param name="type">The agent type.</param>- /// <param name="key">Agent instance identifier.</param>- public AgentId(AgentType type, string key) : this(type.Name, key)- {- }-- /// <summary>- /// Convert a string of the format "type/key" into an <see cref="AgentId"/>.- /// </summary>- /// <param name="maybeAgentId">The agent ID string.</param>- /// <returns>An instance of <see cref="AgentId"/>.</returns>- public static AgentId FromStr(string maybeAgentId) => new AgentId(maybeAgentId.ToKVPair(nameof(Type), nameof(Key)));-- /// <summary>- /// Returns the string representation of the <see cref="AgentId"/>.- /// </summary>- /// <returns>A string in the format "type/key".</returns>- public override string ToString() => $"{Type}/{Key}";-- /// <summary>- /// Determines whether the specified object is equal to the current <see cref="AgentId"/>.- /// </summary>- /// <param name="obj">The object to compare with the current instance.</param>- /// <returns><c>true</c> if the specified object is equal to the current <see cref="AgentId"/>; otherwise, <c>false</c>.</returns>- public override bool Equals([NotNullWhen(true)] object? obj)- {- if (obj is AgentId other)- {- return Type == other.Type && Key == other.Key;- }-- return false;- }-- /// <summary>- /// Returns a hash code for this <see cref="AgentId"/>.- /// </summary>- /// <returns>A hash code for the current instance.</returns>- public override int GetHashCode()- {- return HashCode.Combine(Type, Key);- }-- /// <summary>- /// Explicitly converts a string to an <see cref="AgentId"/>.- /// </summary>- /// <param name="id">The string representation of an agent ID.</param>- /// <returns>An instance of <see cref="AgentId"/>.</returns>- public static explicit operator AgentId(string id) => FromStr(id);-- public static bool operator ==(AgentId left, AgentId right) => left.Equals(right);- public static bool operator !=(AgentId left, AgentId right) => !left.Equals(right);-}-diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/IAgent.cs b/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/IAgent.csdeleted file mode 100644index e3ecfe7d0..000000000--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/IAgent.cs+++ /dev/null@@ -1,46 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// IAgent.cs--namespace Microsoft.AutoGen.Contracts.Python;--/// <summary>-/// Represents an agent within the runtime that can process messages, maintain state, and be closed when no longer needed.-/// </summary>-public interface IAgent : ISaveState<IAgent>-{- /// <summary>- /// Gets the unique identifier of the agent.- /// </summary>- public AgentId Id { get; }-- /// <summary>- /// Gets metadata associated with the agent.- /// </summary>- public AgentMetadata Metadata { get; }-- /// <summary>- /// Handles an incoming message for the agent.- /// This should only be called by the runtime, not by other agents.- /// </summary>- /// <param name="message">The received message. The type should match one of the expected subscription types.</param>- /// <param name="messageContext">The context of the message, providing additional metadata.</param>- /// <returns>- /// A task representing the asynchronous operation, returning a response to the message.- /// The response can be <c>null</c> if no reply is necessary.- /// </returns>- /// <exception cref="OperationCanceledException">Thrown if the message was cancelled.</exception>- /// <exception cref="CantHandleException">Thrown if the agent cannot handle the message.</exception>- public ValueTask<object?> OnMessageAsync(object message, MessageContext messageContext); // TODO: How do we express this properly in .NET?-}-/// <summary>-/// Represents an agent that can be explicitly hosted and closed when the runtime shuts down.-/// </summary>-public interface IHostableAgent : IAgent-{- /// <summary>- /// Called when the runtime is closing.- /// </summary>- /// <returns>A task representing the asynchronous operation.</returns>- public ValueTask CloseAsync() => ValueTask.CompletedTask;-}-diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/IAgentRuntime.cs b/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/IAgentRuntime.csdeleted file mode 100644index 1a9bf6b45..000000000--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/IAgentRuntime.cs+++ /dev/null@@ -1,127 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// IAgentRuntime.cs--using StateDict = System.Collections.Generic.IDictionary<string, object>;--namespace Microsoft.AutoGen.Contracts.Python;--/// <summary>-/// Defines the runtime environment for agents, managing message sending, subscriptions, agent resolution, and state persistence.-/// </summary>-public interface IAgentRuntime : ISaveState<IAgentRuntime>-{- /// <summary>- /// Sends a message to an agent and gets a response.- /// This method should be used to communicate directly with an agent.- /// </summary>- /// <param name="message">The message to send.</param>- /// <param name="recepient">The agent to send the message to.</param>- /// <param name="sender">The agent sending the message. Should be <c>null</c> if sent from an external source.</param>- /// <param name="messageId">A unique identifier for the message. If <c>null</c>, a new ID will be generated.</param>- /// <param name="cancellationToken">A token to cancel the operation if needed.</param>- /// <returns>A task representing the asynchronous operation, returning the response from the agent.</returns>- /// <exception cref="CantHandleException">Thrown if the recipient cannot handle the message.</exception>- /// <exception cref="UndeliverableException">Thrown if the message cannot be delivered.</exception>- public ValueTask<object?> SendMessageAsync(object message, AgentId recepient, AgentId? sender = null, string? messageId = null, CancellationToken? cancellationToken = default);-- /// <summary>- /// Publishes a message to all agents subscribed to the given topic.- /// No responses are expected from publishing.- /// </summary>- /// <param name="message">The message to publish.</param>- /// <param name="topic">The topic to publish the message to.</param>- /// <param name="sender">The agent sending the message. Defaults to <c>null</c>.</param>- /// <param name="messageId">A unique message ID. If <c>null</c>, a new one will be generated.</param>- /// <param name="cancellationToken">A token to cancel the operation if needed.</param>- /// <returns>A task representing the asynchronous operation.</returns>- /// <exception cref="UndeliverableException">Thrown if the message cannot be delivered.</exception>- public ValueTask PublishMessageAsync(object message, TopicId topic, AgentId? sender = null, string? messageId = null, CancellationToken? cancellationToken = default);-- // TODO: Can we call this Resolve?- /// <summary>- /// Retrieves an agent by its unique identifier.- /// </summary>- /// <param name="agentId">The unique identifier of the agent.</param>- /// <param name="lazy">If <c>true</c>, the agent is fetched lazily.</param>- /// <returns>A task representing the asynchronous operation, returning the agent's ID.</returns>- public ValueTask<AgentId> GetAgentAsync(AgentId agentId, bool lazy = true/*, CancellationToken? = default*/);-- /// <summary>- /// Retrieves an agent by its type.- /// </summary>- /// <param name="agentType">The type of the agent.</param>- /// <param name="key">An optional key to specify variations of the agent. Defaults to "default".</param>- /// <param name="lazy">If <c>true</c>, the agent is fetched lazily.</param>- /// <returns>A task representing the asynchronous operation, returning the agent's ID.</returns>- public ValueTask<AgentId> GetAgentAsync(AgentType agentType, string key = "default", bool lazy = true/*, CancellationToken? = default*/);-- /// <summary>- /// Retrieves an agent by its string representation.- /// </summary>- /// <param name="agent">The string representation of the agent.</param>- /// <param name="key">An optional key to specify variations of the agent. Defaults to "default".</param>- /// <param name="lazy">If <c>true</c>, the agent is fetched lazily.</param>- /// <returns>A task representing the asynchronous operation, returning the agent's ID.</returns>- public ValueTask<AgentId> GetAgentAsync(string agent, string key = "default", bool lazy = true/*, CancellationToken? = default*/);-- /// <summary>- /// Saves the state of an agent.- /// The result must be JSON serializable.- /// </summary>- /// <param name="agentId">The ID of the agent whose state is being saved.</param>- /// <returns>A task representing the asynchronous operation, returning a dictionary of the saved state.</returns>- public ValueTask<StateDict> SaveAgentStateAsync(AgentId agentId/*, CancellationToken? cancellationToken = default*/);-- /// <summary>- /// Loads the saved state into an agent.- /// </summary>- /// <param name="agentId">The ID of the agent whose state is being restored.</param>- /// <param name="state">The state dictionary to restore.</param>- /// <returns>A task representing the asynchronous operation.</returns>- public ValueTask LoadAgentStateAsync(AgentId agentId, StateDict state/*, CancellationToken? cancellationToken = default*/);-- /// <summary>- /// Retrieves metadata for an agent.- /// </summary>- /// <param name="agentId">The ID of the agent.</param>- /// <returns>A task representing the asynchronous operation, returning the agent's metadata.</returns>- public ValueTask<AgentMetadata> GetAgentMetadataAsync(AgentId agentId/*, CancellationToken? cancellationToken = default*/);-- /// <summary>- /// Adds a new subscription for the runtime to handle when processing published messages.- /// </summary>- /// <param name="subscription">The subscription to add.</param>- /// <returns>A task representing the asynchronous operation.</returns>- public ValueTask AddSubscriptionAsync(ISubscriptionDefinition subscription/*, CancellationToken? cancellationToken = default*/);-- /// <summary>- /// Removes a subscription from the runtime.- /// </summary>- /// <param name="subscriptionId">The unique identifier of the subscription to remove.</param>- /// <returns>A task representing the asynchronous operation.</returns>- /// <exception cref="KeyNotFoundException">Thrown if the subscription does not exist.</exception>- public ValueTask RemoveSubscriptionAsync(string subscriptionId/*, CancellationToken? cancellationToken = default*/);-- /// <summary>- /// Registers an agent factory with the runtime, associating it with a specific agent type.- /// The type must be unique.- /// </summary>- /// <typeparam name="TAgent">The agent type being registered.</typeparam>- /// <param name="type">The agent type to associate with the factory.</param>- /// <param name="factoryFunc">A function that asynchronously creates the agent instance.</param>- /// <returns>A task representing the asynchronous operation, returning the registered <see cref="AgentType"/>.</returns>- public ValueTask<AgentType> RegisterAgentFactoryAsync<TAgent>(AgentType type, Func<AgentId, IAgentRuntime, ValueTask<TAgent>> factoryFunc) where TAgent : IHostableAgent;-- // TODO:- //public ValueTask<TAgent> TryGetUnderlyingAgentInstanceAsync<TAgent>(AgentId agentId) where TAgent : IHostableAgent;- //public void AddMessageSerializer(params object[] serializers);-- // Extras- /// <summary>- /// Attempts to retrieve an <see cref="AgentProxy"/> for the specified agent.- /// </summary>- /// <param name="agentId">The ID of the agent.</param>- /// <returns>A task representing the asynchronous operation, returning an <see cref="AgentProxy"/> if successful.</returns>- public ValueTask<AgentProxy> TryGetAgentProxyAsync(AgentId agentId);-}-diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/TopicId.cs b/dotnet/src/Microsoft.AutoGen/Contracts/TopicId.cssimilarity index 99%rename from dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/TopicId.csrename to dotnet/src/Microsoft.AutoGen/Contracts/TopicId.csindex caa410a60..899ae2a4e 100644--- a/dotnet/src/Microsoft.AutoGen/Contracts/PythonEquiv/TopicId.cs+++ b/dotnet/src/Microsoft.AutoGen/Contracts/TopicId.cs@@ -3,7 +3,7 @@using System.Diagnostics.CodeAnalysis;-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>/// Represents a topic identifier that defines the scope of a broadcast message.diff --git a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs b/dotnet/src/Microsoft.AutoGen/Core/Agent.csdeleted file mode 100644index d9c2f3fea..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs+++ /dev/null@@ -1,448 +0,0 @@--// Copyright (c) Microsoft Corporation. All rights reserved.-// Agent.cs--using System.Collections.Concurrent;-using System.Diagnostics;-using System.Reflection;-using System.Text;-using System.Text.Json;-using System.Threading.Channels;-using Google.Protobuf;-using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.Logging;--namespace Microsoft.AutoGen.Core;-/// <summary>-/// Represents the base class for an agent in the AutoGen system.-/// </summary>-public abstract class Agent : IAgent-{- private readonly object _lock = new();- private readonly ConcurrentDictionary<string, TaskCompletionSource<RpcResponse>> _pendingRequests = [];-- /// <summary>- /// The activity source for tracing.- /// </summary>- public static readonly ActivitySource s_source = new("Microsoft.AutoGen.Core.Agent");-- /// <summary>- /// Gets the unique identifier of the agent.- /// </summary>- public AgentId AgentId { get; private set; }- private readonly Channel<object> _mailbox = Channel.CreateUnbounded<object>();- protected internal ILogger<Agent> _logger;- public IAgentRuntime Worker { get; private set; }- private readonly ConcurrentDictionary<Type, MethodInfo> _handlersByMessageType;- protected readonly AgentsMetadata EventTypes;-- protected Agent(- AgentsMetadata eventTypes,- ILogger<Agent>? logger = null)- {- EventTypes = eventTypes;- AgentId = new AgentId(this.GetType().Name, Guid.NewGuid().ToString());- _logger = logger ?? LoggerFactory.Create(builder => { }).CreateLogger<Agent>();- _handlersByMessageType = new(GetType().GetHandlersLookupTable());- Worker = new UninitializedAgentWorker();- }- public static void Initialize(IAgentRuntime worker, Agent agent)- {- agent.Worker = worker;- agent.Start();- agent.AddImplicitSubscriptionsAsync().AsTask().Wait();- }-- private async ValueTask AddImplicitSubscriptionsAsync()- {- var topicTypes = new List<string>- {- this.AgentId.Type + ":" + this.AgentId.Key,- this.AgentId.Type- };-- foreach (var topicType in topicTypes)- {- var subscriptionRequest = new AddSubscriptionRequest- {- RequestId = Guid.NewGuid().ToString(),- Subscription = new Subscription- {- TypeSubscription = new TypeSubscription- {- AgentType = this.AgentId.Type,- TopicType = topicType- }- }- };- // explicitly wait for this to complete- Worker.AddSubscriptionAsync(subscriptionRequest).AsTask().Wait();- }-- // using reflection, find all methods that Handle<T> and subscribe to the topic T- var handleMethods = this.GetType().GetMethods().Where(m => m.Name == "Handle").ToList();- foreach (var method in handleMethods)- {- var eventType = method.GetParameters()[0].ParameterType;- var topics = EventTypes.GetTopicsForAgent(GetType());- if (topics != null)- {- foreach (var topic in topics)- {- await SubscribeAsync(topic).ConfigureAwait(true);- }- }- }- }-- /// <summary>- /// Starts the message pump for the agent.- /// </summary>- /// <returns>A task representing the asynchronous operation.</returns>- internal Task Start()- {- var didSuppress = false;- if (!ExecutionContext.IsFlowSuppressed())- {- didSuppress = true;- ExecutionContext.SuppressFlow();- }-- try- {- return Task.Run(RunMessagePump);- }- finally- {- if (didSuppress)- {- ExecutionContext.RestoreFlow();- }- }- }- public void ReceiveMessage(Message message) => _mailbox.Writer.TryWrite(message);-- private async Task RunMessagePump()- {- await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding);- await foreach (var message in _mailbox.Reader.ReadAllAsync())- {- try- {- switch (message)- {- case Message msg:- await HandleRpcMessage(msg, new CancellationToken()).ConfigureAwait(false);- break;- default:- throw new InvalidOperationException($"Unexpected message '{message}'.");- }- }- catch (Exception ex)- {- _logger.LogError(ex, "Error processing message.");- }- }- }- protected internal async Task HandleRpcMessage(Message msg, CancellationToken cancellationToken = default)- {- switch (msg.MessageCase)- {- case Message.MessageOneofCase.CloudEvent:- {- var activity = this.ExtractActivity(msg.CloudEvent.Type, msg.CloudEvent.Attributes);- await this.InvokeWithActivityAsync(- static ((Agent Agent, CloudEvent Item) state, CancellationToken ct) => state.Agent.CallHandlerAsync(state.Item, ct),- (this, msg.CloudEvent),- activity,- msg.CloudEvent.Type, cancellationToken).ConfigureAwait(false);- }- break;- case Message.MessageOneofCase.Request:- {- var activity = this.ExtractActivity(msg.Request.Method, msg.Request.Metadata);- await this.InvokeWithActivityAsync(- static ((Agent Agent, RpcRequest Request) state, CancellationToken ct) => state.Agent.OnRequestCoreAsync(state.Request, ct),- (this, msg.Request),- activity,- msg.Request.Method, cancellationToken).ConfigureAwait(false);- }- break;- case Message.MessageOneofCase.Response:- OnResponseCore(msg.Response);- break;- }- }- public async ValueTask<List<Subscription>> GetSubscriptionsAsync()- {- GetSubscriptionsRequest request = new();- return await Worker.GetSubscriptionsAsync(request).ConfigureAwait(false);- }- public async ValueTask<AddSubscriptionResponse> SubscribeAsync(string topic)- {- AddSubscriptionRequest subscriptionRequest = new()- {- RequestId = Guid.NewGuid().ToString(),- Subscription = new Subscription- {- TypeSubscription = new TypeSubscription- {- TopicType = topic,- AgentType = this.AgentId.Type- }- }- };- var subscriptionResponse = await Worker.AddSubscriptionAsync(subscriptionRequest).ConfigureAwait(true);- if (!subscriptionResponse.Success)- {- _logger.LogError($"{GetType}{AgentId.Key}: Failed to unsubscribe from topic {topic}");- }- return subscriptionResponse;- }- public async ValueTask<RemoveSubscriptionResponse> UnsubscribeAsync(Guid id)- {- RemoveSubscriptionRequest subscriptionRequest = new()- {- Id = id.ToString()- };- var subscriptionResponse = await Worker.RemoveSubscriptionAsync(subscriptionRequest).ConfigureAwait(true);- if (!subscriptionResponse.Success)- {- _logger.LogError($"{GetType}{AgentId.Key}: Failed to unsubscribe from Subscription {id}");- }- return subscriptionResponse;- }- public async ValueTask<RemoveSubscriptionResponse> UnsubscribeAsync(string topic)- {- var subscriptions = await GetSubscriptionsAsync().ConfigureAwait(false);- var subscription = subscriptions.FirstOrDefault(s => s.TypeSubscription.TopicType == topic);- if (subscription == null)- {- var error = $"{GetType}{AgentId.Key}: Subscription not found for topic {topic}";- _logger.LogError(error);- return new RemoveSubscriptionResponse { Success = false, Error = error };- }- var id = Guid.Parse(subscription.Id);- return await UnsubscribeAsync(id).ConfigureAwait(true);- }- public async Task StoreAsync(AgentState state, CancellationToken cancellationToken = default)- {- await Worker.SaveStateAsync(state, cancellationToken).ConfigureAwait(false);- return;- }- public async Task<T> ReadAsync<T>(AgentId agentId, CancellationToken cancellationToken = default) where T : IMessage, new()- {- var agentstate = await Worker.LoadStateAsync(agentId, cancellationToken).ConfigureAwait(false);- return agentstate.FromAgentState<T>();- }- private void OnResponseCore(RpcResponse response)- {- var requestId = response.RequestId;- TaskCompletionSource<RpcResponse>? completion;- lock (_lock)- {- if (!_pendingRequests.Remove(requestId, out completion))- {- throw new InvalidOperationException($"Unknown request id '{requestId}'.");- }- }-- completion.SetResult(response);- }- private async Task OnRequestCoreAsync(RpcRequest request, CancellationToken cancellationToken = default)- {- RpcResponse response;-- try- {- response = await HandleRequestAsync(request).ConfigureAwait(false);- }- catch (Exception ex)- {- response = new RpcResponse { Error = ex.Message };- }- response.RequestId = request.RequestId;-- await Worker.RuntimeSendResponseAsync(response, cancellationToken).ConfigureAwait(false);- }-- protected async Task<RpcResponse> RequestAsync(AgentId target, string method, Dictionary<string, string> parameters)- {- var requestId = Guid.NewGuid().ToString();- var request = new RpcRequest- {- Target = target,- RequestId = requestId,- Method = method,- Payload = new Payload- {- DataType = "application/json",- Data = ByteString.CopyFrom(JsonSerializer.Serialize(parameters), Encoding.UTF8),- DataContentType = "application/json"-- }- };-- var activity = s_source.StartActivity($"Call '{method}'", ActivityKind.Client, Activity.Current?.Context ?? default);- activity?.SetTag("peer.service", target.ToString());-- var completion = new TaskCompletionSource<RpcResponse>(TaskCreationOptions.RunContinuationsAsynchronously);- IAgentRuntimeExtensions.Update(this.Worker, request, activity);- await this.InvokeWithActivityAsync(- static async (state, ct) =>- {- var (self, request, completion) = state;-- self._pendingRequests.AddOrUpdate(request.RequestId, _ => completion, (_, __) => completion);-- await state.Item1.Worker!.RuntimeSendRequestAsync(state.Item1, state.request, ct).ConfigureAwait(false);-- await completion.Task.ConfigureAwait(false);- },- (this, request, completion),- activity,- method).ConfigureAwait(false);-- // Return the result from the already-completed task- return await completion.Task.ConfigureAwait(false);- }-- private string SetTopic(string? topic = null, string? source = null, string? key = null)- {- if (string.IsNullOrWhiteSpace(topic))- {- topic = this.AgentId.Type + "." + this.AgentId.Key;- }- else- {- topic = topic + "." + source + "." + key;- }- return topic;- }-- /// <summary>- /// Publishes a message to the agent runtime.- /// </summary>- /// <param name="message">The message to publish.</param>- /// <param name="topic">The topic to which we publish the message</param>- /// <param name="source">The source of the message.</param>- /// <param name="key">The key of the message.</param>- /// <param name="token">A token to cancel the operation.</param>- /// <returns>A task representing the asynchronous operation.</returns>- public async ValueTask PublishMessageAsync(IMessage message, string topic, string source, string key, CancellationToken token = default)- {- var taskList = new List<Task>();- var topicTypes = new List<string>();- // if there are no topic types, use the agent's default topic subscription attribute and the agent's type and key- if (string.IsNullOrWhiteSpace(topic))- {- topic = this.AgentId.Type;- var topicAttributes = this.GetType().GetCustomAttributes<TopicSubscriptionAttribute>().Select(t => t.Topic);- if (topicAttributes.Any())- {- topicTypes.AddRange(topicAttributes);- }- if (topicTypes.Count == 0)- {- topicTypes.Add(- string.IsNullOrWhiteSpace(source) ? this.AgentId.Type + "." + (string.IsNullOrEmpty(key) ? this.AgentId.Key : key) : source- );- }- topicTypes.Add(SetTopic(topic, source, key));- }- if (string.IsNullOrWhiteSpace(source) && string.IsNullOrWhiteSpace(key)) { source = this.AgentId.Key; }- if (!String.IsNullOrWhiteSpace(key)) { source = source + "." + key; }- var topicIds = new List<TopicId>();- foreach (var t in topicTypes) { topicIds.Add(new TopicId() { Type = t, Source = source }); }- topicIds.Add(new TopicId() { Type = topic, Source = source });- foreach (var topicId in topicIds)- {- taskList.Add(Task.Run(async () =>- {- await Worker.PublishMessageAsync(message, topicId, this, token);- }));- }- await Task.WhenAll(taskList).ConfigureAwait(false);- }- public async ValueTask PublishMessageAsync<T>(T message, string topic, string source, CancellationToken token = default) where T : IMessage- {- var key = this.AgentId.Key;- await PublishMessageAsync(message, topic, source, key, token).ConfigureAwait(false);- }- public async ValueTask PublishMessageAsync<T>(T message, string topic, CancellationToken token = default) where T : IMessage- {- var source = this.AgentId.Type;- var key = this.AgentId.Key;- await PublishMessageAsync(message, topic, source, key, token).ConfigureAwait(false);- }- public async ValueTask PublishMessageAsync<T>(T message, CancellationToken token = default) where T : IMessage- {- var topic = "";- var source = this.AgentId.Type;- var key = this.AgentId.Key;- await PublishMessageAsync(message, topic, source, key, token).ConfigureAwait(false);- }- private Task CallHandlerAsync(CloudEvent item, CancellationToken cancellationToken = default)- {- // Only send the event to the handler if the agent type is handling that type- if (EventTypes.CheckIfTypeHandles(GetType(), eventName: item.Type))- {- var payload = item.ProtoData.Unpack(EventTypes.TypeRegistry);- var eventType = EventTypes.GetEventTypeByName(item.Type);- if (eventType == null)- {- _logger.LogError($"Event type {item.Type} not found in the registry");- return Task.CompletedTask;- }- var convertedPayload = Convert.ChangeType(payload, eventType);- var genericInterfaceType = typeof(IHandle<>).MakeGenericType(eventType);-- MethodInfo methodInfo;- try- {- // check that our target actually implements this interface, otherwise call the default static- if (genericInterfaceType.IsAssignableFrom(this.GetType()))- {- methodInfo = genericInterfaceType.GetMethod(nameof(IHandle<IMessage>.Handle), BindingFlags.Public | BindingFlags.Instance)- ?? throw new InvalidOperationException($"Method not found on type {genericInterfaceType.FullName}");- return methodInfo.Invoke(this, new object[] { convertedPayload, cancellationToken }) as Task ?? Task.CompletedTask;- }- else- {- // The error here is we have registered for an event that we do not have code to listen to- throw new InvalidOperationException($"Agent Type '{GetType()}' is registered to handle this type but no handler found for event '{item.Type}'; expecting IHandle<{item.Type}> implementation.");- }- }- catch (Exception ex)- {- _logger.LogError(ex, $"Error invoking method {nameof(IHandle<IMessage>.Handle)}");- throw; // TODO: ?- }- }- return Task.CompletedTask;- }-- public virtual Task<RpcResponse> HandleRequestAsync(RpcRequest request) => Task.FromResult(new RpcResponse { Error = "Not implemented" });-- /// <summary>- /// Handles a generic object- /// </summary>- /// <param name="item">The object to handle</param>- /// <param name="cancellationToken">The cancellation token</param>- /// <returns>A task representing the asynchronous operation.</returns>- /// TODO: this is only called from tests, should we remove it?- public virtual async Task HandleObjectAsync(object item, CancellationToken cancellationToken = default)- {- // get all Handle<T> methods- var handleTMethods = this.GetType().GetMethods().Where(m => m.Name == "Handle" && m.GetParameters().Length == 1).ToList();- // get the one that matches the type of the item- var handleTMethod = handleTMethods.FirstOrDefault(m => m.GetParameters()[0].ParameterType == item.GetType());- // if we found one, invoke it- if (handleTMethod != null)- {- await (Task)handleTMethod.Invoke(this, [item])!;- }- // otherwise, complain- _logger.LogError($"No handler found for type {item.GetType().FullName}");- }-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentExtensions.csdeleted file mode 100644index d2fc801ac..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/AgentExtensions.cs+++ /dev/null@@ -1,122 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// AgentExtensions.cs--using System.Diagnostics;-using Google.Protobuf.Collections;-using static Microsoft.AutoGen.Contracts.CloudEvent.Types;--namespace Microsoft.AutoGen.Core;--/// <summary>-/// Provides extension methods for the <see cref="Agent"/> class.-/// </summary>-public static class AgentExtensions-{- /// <summary>- /// Extracts an <see cref="Activity"/> from the given agent and metadata.- /// </summary>- /// <param name="agent">The agent from which to extract the activity.</param>- /// <param name="activityName">The name of the activity.</param>- /// <param name="metadata">The metadata containing trace information.</param>- /// <returns>The extracted <see cref="Activity"/> or null if extraction fails.</returns>- public static Activity? ExtractActivity(this Agent agent, string activityName, IDictionary<string, string> metadata)- {- Activity? activity;- (string? traceParent, string? traceState) = IAgentRuntimeExtensions.GetTraceIdAndState(agent.Worker, metadata);- if (!string.IsNullOrEmpty(traceParent))- {- if (ActivityContext.TryParse(traceParent, traceState, isRemote: true, out var parentContext))- {- // traceParent is a W3CId- activity = Agent.s_source.CreateActivity(activityName, ActivityKind.Server, parentContext);- }- else- {- // Most likely, traceParent uses ActivityIdFormat.Hierarchical- activity = Agent.s_source.CreateActivity(activityName, ActivityKind.Server, traceParent);- }-- if (activity is not null)- {- if (!string.IsNullOrEmpty(traceState))- {- activity.TraceStateString = traceState;- }-- var baggage = IAgentRuntimeExtensions.ExtractMetadata(agent.Worker, metadata);-- foreach (var baggageItem in baggage)- {- activity.AddBaggage(baggageItem.Key, baggageItem.Value);- }- }- }- else- {- activity = Agent.s_source.CreateActivity(activityName, ActivityKind.Server);- }-- return activity;- }-- public static Activity? ExtractActivity(this Agent agent, string activityName, MapField<string, CloudEventAttributeValue> metadata)- {- return ExtractActivity(agent, activityName, metadata.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.CeString));- }-- /// <summary>- /// Invokes a function asynchronously within the context of an <see cref="Activity"/>.- /// </summary>- /// <typeparam name="TState">The type of the state parameter.</typeparam>- /// <param name="agent">The agent invoking the function.</param>- /// <param name="func">The function to invoke.</param>- /// <param name="state">The state parameter to pass to the function.</param>- /// <param name="activity">The activity within which to invoke the function.</param>- /// <param name="methodName">The name of the method being invoked.</param>- /// <param name="cancellationToken">A token to monitor for cancellation requests.</param>- /// <returns>A task representing the asynchronous operation.</returns>- public static async Task InvokeWithActivityAsync<TState>(this Agent agent, Func<TState, CancellationToken, Task> func, TState state, Activity? activity, string methodName, CancellationToken cancellationToken = default)- {- if (activity is not null && activity.StartTimeUtc == default)- {- activity.Start();-- // rpc attributes from https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/rpc.md- activity.SetTag("rpc.system", "autogen");- activity.SetTag("rpc.service", agent.AgentId.ToString());- activity.SetTag("rpc.method", methodName);- }-- try- {- await func(state, cancellationToken).ConfigureAwait(false);- if (activity is not null && activity.IsAllDataRequested)- {- activity.SetStatus(ActivityStatusCode.Ok);- }- }- catch (Exception e)- {- if (activity is not null && activity.IsAllDataRequested)- {- activity.SetStatus(ActivityStatusCode.Error);-- // exception attributes from https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/trace/semantic_conventions/exceptions.md- activity.SetTag("exception.type", e.GetType().FullName);- activity.SetTag("exception.message", e.Message);-- // Note that "exception.stacktrace" is the full exception detail, not just the StackTrace property.- // See https://opentelemetry.io/docs/specs/semconv/attributes-registry/exception/- // and https://github.com/open-telemetry/opentelemetry-specification/pull/697#discussion_r453662519- activity.SetTag("exception.stacktrace", e.ToString());- activity.SetTag("exception.escaped", true);- }-- throw;- }- finally- {- activity?.Stop();- }- }-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentRuntime.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentRuntime.csdeleted file mode 100644index 7da485fa8..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/AgentRuntime.cs+++ /dev/null@@ -1,236 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// AgentRuntime.cs-using System.Collections.Concurrent;-using System.Threading.Channels;-using Google.Protobuf;-using Google.Protobuf.WellKnownTypes;-using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.DependencyInjection;-using Microsoft.Extensions.Hosting;-using Microsoft.Extensions.Logging;--namespace Microsoft.AutoGen.Core;--/// <summary>-/// An InMemory single-process implementation of <see cref="IAgentRuntime"/>.-/// </summary>-/// <remarks>-/// Responsible for message routing and delivery.-/// </remarks>-/// <param name="hostApplicationLifetime">The application lifetime.</param>-/// <param name="serviceProvider">The service provider.</param>-/// <param name="configuredAgentTypes">The configured agent types.</param>-public class AgentRuntime(- IHostApplicationLifetime hostApplicationLifetime,- IServiceProvider serviceProvider,- [FromKeyedServices("AgentTypes")] IEnumerable<Tuple<string, System.Type>> configuredAgentTypes,- ILogger<AgentRuntime> logger) :- AgentRuntimeBase(- hostApplicationLifetime,- serviceProvider,- configuredAgentTypes,- logger)-{- private readonly ConcurrentDictionary<string, AgentState> _agentStates = new();- private readonly ConcurrentDictionary<string, List<Subscription>> _subscriptionsByAgentType = new();- private readonly ConcurrentDictionary<string, List<string>> _subscriptionsByTopic = new();- private readonly ConcurrentDictionary<Guid, IDictionary<string, string>> _subscriptionsByGuid = new();- private readonly IRegistry _registry = serviceProvider.GetRequiredService<IRegistry>();- private readonly ConcurrentDictionary<string, TaskCompletionSource<RpcResponse>> _pendingRequests = new();- private static readonly TimeSpan s_agentResponseTimeout = TimeSpan.FromSeconds(300);- private new readonly ILogger<AgentRuntime> _logger = logger;-- /// <inheritdoc />- public override async ValueTask RegisterAgentTypeAsync(RegisterAgentTypeRequest request, CancellationToken cancellationToken = default)- {- await _registry.RegisterAgentTypeAsync(request, this);- }- /// <inheritdoc />- public override async ValueTask<RpcResponse> SendMessageAsync(IMessage message, AgentId agentId, AgentId? agent = null, CancellationToken? cancellationToken = default)- {- var request = new RpcRequest- {- RequestId = Guid.NewGuid().ToString(),- Source = agent,- Target = agentId,- Payload = new Payload { Data = Any.Pack(message).ToByteString() }- };- var response = await InvokeRequestAsync(request).ConfigureAwait(false);- return response;- }- /// <inheritdoc />- public override ValueTask SaveStateAsync(AgentState value, CancellationToken cancellationToken = default)- {- var agentId = value.AgentId ?? throw new InvalidOperationException("AgentId is required when saving AgentState.");- var response = _agentStates.AddOrUpdate(agentId.ToString(), value, (key, oldValue) => value);- return ValueTask.CompletedTask;- }-- /// <inheritdoc />- public override ValueTask<AgentState> LoadStateAsync(AgentId agentId, CancellationToken cancellationToken = default)- {- _agentStates.TryGetValue(agentId.ToString(), out var state);- if (state is not null && state.AgentId is not null)- {- return new ValueTask<AgentState>(state);- }- else- {- throw new KeyNotFoundException($"Failed to read AgentState for {agentId}.");- }- }- /// <inheritdoc />- public override async ValueTask RuntimeSendRequestAsync(IAgent agent, RpcRequest request, CancellationToken cancellationToken = default)- {- var requestId = Guid.NewGuid().ToString();- _pendingClientRequests[requestId] = ((Agent)agent, request.RequestId);- request.RequestId = requestId;- await _mailbox.Writer.WriteAsync(request, cancellationToken).ConfigureAwait(false);- }-- /// <inheritdoc />- public override ValueTask RuntimeSendResponseAsync(RpcResponse response, CancellationToken cancellationToken = default)- {- return _mailbox.Writer.WriteAsync(new Message { Response = response }, cancellationToken);- }- /// <inheritdoc />- public ValueTask RuntimeWriteMessage(Message message, CancellationToken cancellationToken = default)- {- return _mailbox.Writer.WriteAsync(message, cancellationToken);- }- public override async ValueTask<AddSubscriptionResponse> AddSubscriptionAsync(AddSubscriptionRequest subscription, CancellationToken cancellationToken = default)- {- var topic = subscription.Subscription.TypeSubscription.TopicType;- var agentType = subscription.Subscription.TypeSubscription.AgentType;- var id = Guid.NewGuid();- subscription.Subscription.Id = id.ToString();- var sub = new Dictionary<string, string> { { topic, agentType } };- _subscriptionsByGuid.GetOrAdd(id, static _ => new Dictionary<string, string>()).Add(topic, agentType);- _subscriptionsByAgentType.GetOrAdd(key: agentType, _ => []).Add(subscription.Subscription);- _subscriptionsByTopic.GetOrAdd(topic, _ => []).Add(agentType);- var response = new AddSubscriptionResponse- {- RequestId = subscription.RequestId,- Error = "",- Success = true- };- return response;- }- public override async ValueTask<RemoveSubscriptionResponse> RemoveSubscriptionAsync(RemoveSubscriptionRequest request, CancellationToken cancellationToken = default)- {- if (!Guid.TryParse(request.Id, out var id))- {- var removeSubscriptionResponse = new RemoveSubscriptionResponse- {- Error = "Invalid subscription ID",- Success = false- };- return removeSubscriptionResponse;- }- if (_subscriptionsByGuid.TryGetValue(id, out var sub))- {- foreach (var (topic, agentType) in sub)- {- if (_subscriptionsByTopic.TryGetValue(topic, out var innerAgentTypes))- {- while (innerAgentTypes.Remove(agentType))- {- //ensures all instances are removed- }- _subscriptionsByTopic.AddOrUpdate(topic, innerAgentTypes, (_, _) => innerAgentTypes);- }- var toRemove = new List<Subscription>();- if (_subscriptionsByAgentType.TryGetValue(agentType, out var innerSubscriptions))- {- foreach (var subscription in innerSubscriptions)- {- if (subscription.Id == id.ToString())- {- toRemove.Add(subscription);- }- }- foreach (var subscription in toRemove) { innerSubscriptions.Remove(subscription); }- _subscriptionsByAgentType.AddOrUpdate(agentType, innerSubscriptions, (_, _) => innerSubscriptions);- }- }- _subscriptionsByGuid.TryRemove(id, out _);- }- var response = new RemoveSubscriptionResponse- {- Error = "",- Success = true- };- return response;- }-- public ValueTask<List<Subscription>> GetSubscriptionsAsync(System.Type type)- {- if (_subscriptionsByAgentType.TryGetValue(type.Name, out var subscriptions))- {- return new ValueTask<List<Subscription>>(subscriptions);- }- return new ValueTask<List<Subscription>>([]);- }- public override ValueTask<List<Subscription>> GetSubscriptionsAsync(GetSubscriptionsRequest request, CancellationToken cancellationToken = default)- {- var subscriptions = new List<Subscription>();- foreach (var (_, value) in _subscriptionsByAgentType)- {- subscriptions.AddRange(value);- }- return new ValueTask<List<Subscription>>(subscriptions);- }- public override async ValueTask DispatchRequestAsync(RpcRequest request)- {- var requestId = request.RequestId;- if (request.Target is null)- {- throw new InvalidOperationException($"Request message is missing a target. Message: '{request}'.");- }- var agentId = request.Target;- await InvokeRequestDelegate(_mailbox, request, async request =>- {- return await InvokeRequestAsync(request).ConfigureAwait(true);- }).ConfigureAwait(false);- }- public override void DispatchResponse(RpcResponse response)- {- if (!_pendingRequests.TryRemove(response.RequestId, out var completion))- {- _logger.LogWarning("Received response for unknown request id: {RequestId}.", response.RequestId);- return;- }- // Complete the request.- completion.SetResult(response);- }- public async ValueTask<RpcResponse> InvokeRequestAsync(RpcRequest request, CancellationToken cancellationToken = default)- {- var agentId = request.Target;- // get the agent- var agent = GetOrActivateAgent(agentId);-- // Proxy the request to the agent.- var originalRequestId = request.RequestId;- var completion = new TaskCompletionSource<RpcResponse>(TaskCreationOptions.RunContinuationsAsynchronously);- _pendingRequests.TryAdd(request.RequestId, completion);- //request.RequestId = Guid.NewGuid().ToString();- agent.ReceiveMessage(new Message() { Request = request });- // Wait for the response and send it back to the caller.- var response = await completion.Task.WaitAsync(s_agentResponseTimeout);- response.RequestId = originalRequestId;- return response;- }- private static async Task InvokeRequestDelegate(Channel<object> mailbox, RpcRequest request, Func<RpcRequest, Task<RpcResponse>> func)- {- try- {- var response = await func(request);- response.RequestId = request.RequestId;- await mailbox.Writer.WriteAsync(new Message { Response = response }).ConfigureAwait(false);- }- catch (Exception ex)- {- await mailbox.Writer.WriteAsync(new Message { Response = new RpcResponse { RequestId = request.RequestId, Error = ex.Message } }).ConfigureAwait(false);- }- }-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentRuntimeBase.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentRuntimeBase.csdeleted file mode 100644index 81ce47933..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/AgentRuntimeBase.cs+++ /dev/null@@ -1,222 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// AgentRuntimeBase.cs--using System.Collections.Concurrent;-using System.Diagnostics;-using System.Threading.Channels;-using Google.Protobuf;-using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.DependencyInjection;-using Microsoft.Extensions.Hosting;-using Microsoft.Extensions.Logging;--namespace Microsoft.AutoGen.Core;-/// <summary>-/// Base class for agent runtime.-/// </summary>-/// <param name="hostApplicationLifetime">used for shutdown</param>-/// <param name="serviceProvider">the service host for DI container</param>-/// <param name="configuredAgentTypes">the agent types this runtime can host</param>-public abstract class AgentRuntimeBase(- IHostApplicationLifetime hostApplicationLifetime,- IServiceProvider serviceProvider,- [FromKeyedServices("AgentTypes")] IEnumerable<Tuple<string, Type>> configuredAgentTypes,- ILogger<AgentRuntimeBase> logger) : IHostedService, IAgentRuntime-{- public IServiceProvider RuntimeServiceProvider { get; } = serviceProvider;- protected readonly ConcurrentDictionary<string, (Agent Agent, string OriginalRequestId)> _pendingClientRequests = new();- protected readonly Channel<object> _mailbox = Channel.CreateUnbounded<object>();- private readonly ConcurrentDictionary<(string Type, string Key), Agent> _agents = new();- private readonly ConcurrentDictionary<string, Type> _agentTypes = new();- private readonly CancellationTokenSource _shutdownCts = CancellationTokenSource.CreateLinkedTokenSource(hostApplicationLifetime.ApplicationStopping);- private readonly CancellationTokenSource _shutdownCancellationToken = new();- private readonly IEnumerable<Tuple<string, Type>> _configuredAgentTypes = configuredAgentTypes;- private Task? _mailboxTask;- private readonly object _channelLock = new();- protected readonly ILogger<AgentRuntimeBase> _logger = logger;-- /// <summary>- /// Starts the agent runtime.- /// Required to implement IHostedService- /// </summary>- /// <param name="cancellationToken"></param>- /// <returns>Task</returns>- public async Task StartAsync(CancellationToken cancellationToken)- {- _logger.LogInformation("Starting AgentRuntimeBase...");- StartCore();-- foreach (var (typeName, type) in _configuredAgentTypes)- {- _agentTypes.TryAdd(typeName, type);- }- void StartCore()- {- var didSuppress = false;- if (!ExecutionContext.IsFlowSuppressed())- {- didSuppress = true;- ExecutionContext.SuppressFlow();- }-- try- {- _mailboxTask = Task.Run(RunMessagePump, CancellationToken.None);- }- finally- {- if (didSuppress)- {- ExecutionContext.RestoreFlow();- }- }- }- }- /// <summary>- /// Stops the agent runtime.- /// Required to implement IHostedService.- /// </summary>- /// <param name="cancellationToken"></param>- /// <returns>Task</returns>- public async Task StopAsync(CancellationToken cancellationToken)- {- _shutdownCts.Cancel();-- _mailbox.Writer.TryComplete();-- if (_mailboxTask is { } readTask)- {- await readTask.ConfigureAwait(false);- }- lock (_channelLock)- {- }- }-- /// <summary>- /// Runs the message pump.- /// </summary>- public async Task RunMessagePump()- {- await Task.CompletedTask.ConfigureAwait(ConfigureAwaitOptions.ForceYielding);- await foreach (var message in _mailbox.Reader.ReadAllAsync())- {- try- {- if (message == null) { continue; }- switch (message)- {- case Message msg when msg.Request != null:- await DispatchRequestAsync(msg.Request).ConfigureAwait(true);- break;- case Message msg when msg.Response != null:- DispatchResponse(msg.Response);- break;- case Message msg when msg.CloudEvent != null:-- var item = msg.CloudEvent;-- foreach (var (typeName, _) in _agentTypes)- {- var agentToInvoke = GetOrActivateAgent(new AgentId(typeName, item.Source));- agentToInvoke.ReceiveMessage(msg);- }- break;- case Message msg when msg.AddSubscriptionRequest != null:- await AddSubscriptionAsync(msg.AddSubscriptionRequest).ConfigureAwait(true);- break;- case Message msg when msg.AddSubscriptionResponse != null:- break;- case Message msg when msg.RegisterAgentTypeResponse != null:- break;- default:- throw new InvalidOperationException($"Unexpected message '{message}'.");- }- }- catch (OperationCanceledException)- {- }- finally- {- _shutdownCancellationToken.Cancel();- }- }- }- public abstract void DispatchResponse(RpcResponse response);- public abstract ValueTask DispatchRequestAsync(RpcRequest request);- public abstract ValueTask RegisterAgentTypeAsync(RegisterAgentTypeRequest request, CancellationToken cancellationToken = default);- public async ValueTask PublishMessageAsync(IMessage message, TopicId topic, IAgent? sender, CancellationToken? cancellationToken = default)- {- var topicString = topic.Type + "." + topic.Source;- sender ??= RuntimeServiceProvider.GetRequiredService<Client>();- await PublishEventAsync(message.ToCloudEvent(key: sender.GetType().Name, topic: topicString), (Agent)sender, cancellationToken.GetValueOrDefault()).ConfigureAwait(false);- }- public abstract ValueTask SaveStateAsync(AgentState value, CancellationToken cancellationToken = default);- public abstract ValueTask<AgentState> LoadStateAsync(AgentId agentId, CancellationToken cancellationToken = default);- public abstract ValueTask<AddSubscriptionResponse> AddSubscriptionAsync(AddSubscriptionRequest request, CancellationToken cancellationToken = default);- public abstract ValueTask<RemoveSubscriptionResponse> RemoveSubscriptionAsync(RemoveSubscriptionRequest request, CancellationToken cancellationToken = default);- public abstract ValueTask<List<Subscription>> GetSubscriptionsAsync(GetSubscriptionsRequest request, CancellationToken cancellationToken = default);-- protected Agent GetOrActivateAgent(AgentId agentId)- {- if (!_agents.TryGetValue((agentId.Type, agentId.Key), out var agent))- {- if (_agentTypes.TryGetValue(agentId.Type, out var agentType))- {- using (var scope = RuntimeServiceProvider.CreateScope())- {- var scopedProvider = scope.ServiceProvider;- agent = (Agent)ActivatorUtilities.CreateInstance(scopedProvider, agentType);- Agent.Initialize(this, agent);- _agents.TryAdd((agentId.Type, agentId.Key), agent);- }- }- else- {- throw new InvalidOperationException($"Agent type '{agentId.Type}' is unknown.");- }- }- return agent;- }- private async ValueTask PublishEventAsync(CloudEvent item, Agent sender, CancellationToken cancellationToken = default)- {- var activity = Agent.s_source.StartActivity($"PublishEventAsync '{item.Type}'", ActivityKind.Client, Activity.Current?.Context ?? default);- activity?.SetTag("peer.service", $"{item.Type}/{item.Source}");-- IAgentRuntimeExtensions.Update(this, item, activity);- await sender.InvokeWithActivityAsync<(IAgentRuntime Worker, CloudEvent Event)>(- async (state, ct) =>- {- await DispatchEventsToAgentsAsync(state.Event, cancellationToken).ConfigureAwait(false);- },- (this, item),- activity,- item.Type, cancellationToken).ConfigureAwait(false);- }-- /// <summary>- /// DispatchEventsToAgentsAsync- /// writes CloudEvent to Agents- /// </summary>- /// <param name="cloudEvent">The CloudEvent to dispatch.</param>- /// <param name="cancellationToken">The cancellation token.</param>- private async ValueTask DispatchEventsToAgentsAsync(CloudEvent cloudEvent, CancellationToken cancellationToken = default)- {- var taskList = new List<Task>(capacity: _agentTypes.Count);- foreach (var (typeName, _) in _agentTypes)- {- if (typeName == nameof(Client)) { continue; }- var task = Task.Run(async () =>- {- var agent = GetOrActivateAgent(new AgentId { Type = typeName, Key = cloudEvent.GetSubject() });- agent.ReceiveMessage(new Message { CloudEvent = cloudEvent });- }, cancellationToken);- taskList.Add(task);- }- await Task.WhenAll(taskList).ConfigureAwait(false);- }- public abstract ValueTask RuntimeSendRequestAsync(IAgent agent, RpcRequest request, CancellationToken cancellationToken = default);-- public abstract ValueTask RuntimeSendResponseAsync(RpcResponse response, CancellationToken cancellationToken = default);- public abstract ValueTask<RpcResponse> SendMessageAsync(IMessage message, AgentId recipient, AgentId? sender, CancellationToken? cancellationToken = default);-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/AgentRuntimeExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentRuntimeExtensions.cssimilarity index 98%rename from dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/AgentRuntimeExtensions.csrename to dotnet/src/Microsoft.AutoGen/Core/AgentRuntimeExtensions.csindex 4b3858c78..bf75a6faa 100644--- a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/AgentRuntimeExtensions.cs+++ b/dotnet/src/Microsoft.AutoGen/Core/AgentRuntimeExtensions.cs@@ -1,11 +1,11 @@// Copyright (c) Microsoft Corporation. All rights reserved.// AgentRuntimeExtensions.cs-using Microsoft.AutoGen.Core.Python;+using Microsoft.AutoGen.Core;using Microsoft.Extensions.DependencyInjection;using System.Reflection;-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>/// Provides extension methods for managing and registering agents within an <see cref="IAgentRuntime"/>.diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentTypes.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentTypes.csdeleted file mode 100644index d1a67678c..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/AgentTypes.cs+++ /dev/null@@ -1,20 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// AgentTypes.cs--namespace Microsoft.AutoGen.Core-;-public sealed class AgentTypes(Dictionary<string, Type> types)-{- public Dictionary<string, Type> Types { get; } = types;- public static AgentTypes? GetAgentTypesFromAssembly()- {- var agents = AppDomain.CurrentDomain.GetAssemblies()- .SelectMany(assembly => assembly.GetTypes())- .Where(type => ReflectionHelper.IsSubclassOfGeneric(type, typeof(Agent))- && !type.IsAbstract- && !type.Name.Equals(nameof(Client)))- .ToDictionary(type => type.Name, type => type);-- return new AgentTypes(agents);- }-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/AgentsApp.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentsApp.cssimilarity index 96%rename from dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/AgentsApp.csrename to dotnet/src/Microsoft.AutoGen/Core/AgentsApp.csindex 1a383e3df..e092f9793 100644--- a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/AgentsApp.cs+++ b/dotnet/src/Microsoft.AutoGen/Core/AgentsApp.cs@@ -1,11 +1,11 @@// Copyright (c) Microsoft Corporation. All rights reserved.// AgentsApp.cs-using Microsoft.AutoGen.Contracts.Python;+using Microsoft.AutoGen.Contracts;using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Hosting;-namespace Microsoft.AutoGen.Core.PythonEquiv;+namespace Microsoft.AutoGen.CoreEquiv;public class AgentsAppBuilder{diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentsMetadata.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentsMetadata.csdeleted file mode 100644index b3812d2e4..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/AgentsMetadata.cs+++ /dev/null@@ -1,85 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// AgentsMetadata.cs--using System.Collections.Concurrent;-using Google.Protobuf.Reflection;--namespace Microsoft.AutoGen.Core;--/// <summary>-/// Represents a collection of event types and their associated metadata.-/// </summary>-public sealed class AgentsMetadata-{- /// <summary>- /// Initializes a new instance of the <see cref="AgentsMetadata"/> class.- /// </summary>- /// <param name="typeRegistry">The type registry containing protobuf type information.</param>- /// <param name="types">A dictionary mapping event names to their corresponding types.</param>- /// <param name="eventsMap">A dictionary mapping types to a set of event names associated with those types.</param>- public AgentsMetadata(TypeRegistry typeRegistry, Dictionary<string, Type> types, Dictionary<Type, HashSet<string>> eventsMap, Dictionary<Type, HashSet<string>> topicsMap)- {- TypeRegistry = typeRegistry;- _types = new(types);- _eventsMap = new(eventsMap);- _topicsMap = new(topicsMap);- }-- /// <summary>- /// Gets the type registry containing protobuf type information.- /// </summary>- public TypeRegistry TypeRegistry { get; }-- private ConcurrentDictionary<string, Type> _types;-- private ConcurrentDictionary<Type, HashSet<string>> _eventsMap;- private ConcurrentDictionary<Type, HashSet<string>> _topicsMap;-- /// <summary>- /// Checks if a given type handles a specific event name.- /// </summary>- /// <param name="type">The type to check.</param>- /// <param name="eventName">The event name to check.</param>- /// <returns><c>true</c> if the type handles the event name; otherwise, <c>false</c>.</returns>- public bool CheckIfTypeHandles(Type type, string eventName)- {- if (_eventsMap.TryGetValue(type, out var events))- {- return events.Contains(eventName);- }- return false;- }-- /// <summary>- /// Gets the event type by its name.- /// </summary>- /// <param name="type">The name of the event type.</param>- /// <returns>The event type if found; otherwise, <c>null</c>.</returns>- public Type? GetEventTypeByName(string type)- {- if (_types.TryGetValue(type, out var eventType))- {- return eventType;- }- return null;- }-- public HashSet<string>? GetEventsForAgent(Type agent)- {- if (_eventsMap.TryGetValue(agent, out var events))- {- return events;- }- return null;- }-- public HashSet<string>? GetTopicsForAgent(Type agent)- {- if (_topicsMap.TryGetValue(agent, out var topics))- {- return topics;- }- return null;- }-}-diff --git a/dotnet/src/Microsoft.AutoGen/Core/App.cs b/dotnet/src/Microsoft.AutoGen/Core/App.csdeleted file mode 100644index d13bd5a5f..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/App.cs+++ /dev/null@@ -1,64 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// App.cs-using System.Diagnostics;-using System.Diagnostics.CodeAnalysis;-using Google.Protobuf;-using Microsoft.Extensions.DependencyInjection;-using Microsoft.Extensions.DependencyInjection.Extensions;-using Microsoft.Extensions.Hosting;--namespace Microsoft.AutoGen.Core;--public static class AgentsApp-{- // need a variable to store the runtime instance- public static IHost? Host { get; private set; }-- [MemberNotNull(nameof(Host))]- public static async ValueTask<IHost> StartAsync(HostApplicationBuilder? builder = null, AgentTypes? agentTypes = null)- {- builder ??= new HostApplicationBuilder();- builder.Services.TryAddSingleton(DistributedContextPropagator.Current);- builder.AddAgentWorker()- .AddAgents(agentTypes);- var app = builder.Build();-- Host = app;- await app.StartAsync().ConfigureAwait(false);- return Host;- }- public static async ValueTask<IHost> PublishMessageAsync(- string topic,- IMessage message,- HostApplicationBuilder? builder = null,- AgentTypes? agents = null,- bool local = false)- {- if (Host == null)- {- await StartAsync(builder, agents).ConfigureAwait(false);- }- var client = Host.Services.GetRequiredService<Client>() ?? throw new InvalidOperationException("Host not started");- await client.PublishMessageAsync(message, topic, token: new CancellationToken()).ConfigureAwait(true);- return Host;- }- public static async ValueTask ShutdownAsync()- {- if (Host == null)- {- throw new InvalidOperationException("Host not started");- }- await Host.StopAsync().ConfigureAwait(true);- }-- private static IHostApplicationBuilder AddAgents(this IHostApplicationBuilder builder, AgentTypes? agentTypes)- {- agentTypes ??= AgentTypes.GetAgentTypesFromAssembly()- ?? throw new InvalidOperationException("No agent types found in the assembly");- foreach (var type in agentTypes.Types)- {- builder.AddAgent(type.Key, type.Value);- }- return builder;- }-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/BaseAgent.cs b/dotnet/src/Microsoft.AutoGen/Core/BaseAgent.cssimilarity index 82%rename from dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/BaseAgent.csrename to dotnet/src/Microsoft.AutoGen/Core/BaseAgent.csindex c3a3f8080..3ba1b52cd 100644--- a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/BaseAgent.cs+++ b/dotnet/src/Microsoft.AutoGen/Core/BaseAgent.cs@@ -4,10 +4,10 @@using System.Diagnostics;using System.Reflection;-using Microsoft.AutoGen.Contracts.Python;+using Microsoft.AutoGen.Contracts;using Microsoft.Extensions.Logging;-namespace Microsoft.AutoGen.Core.Python;+namespace Microsoft.AutoGen.Core;/// <summary>/// Represents the base class for an agent in the AutoGen system./// </summary>@@ -64,7 +64,7 @@ public abstract class BaseAgent : IAgent, IHostableAgent_handlersByMessageType = new(GetType().GetHandlersLookupTable());}- public ValueTask<object?> OnMessageAsync(object message, MessageContext messageContext)+ public async ValueTask<object?> OnMessageAsync(object message, MessageContext messageContext){// Determine type of message, then get handler method and invoke itvar messageType = message.GetType();@@ -76,7 +76,10 @@ public abstract class BaseAgent : IAgent, IHostableAgent{// This is a IHandle<T> methodvar return_value = handlerMethod.Invoke(this, new object[] { message, messageContext });- return ValueTask.FromResult(return_value);+ if (return_value != null){+ await (ValueTask)return_value;+ }+ return ValueTask.CompletedTask;}else if (genericArguments.Length == 2)@@ -85,17 +88,20 @@ public abstract class BaseAgent : IAgent, IHostableAgent// var _messageType = genericArguments[0];// var _returnType = genericArguments[1];var result = handlerMethod.Invoke(this, new object[] { message, messageContext });+ if (result != null){+ return await (ValueTask<object?>)result;+ }- return ValueTask.FromResult(result);+ throw new InvalidOperationException($"Got null result from handler method {handlerMethod.Name}");}else{- return ValueTask.FromException<object?>(new InvalidOperationException($"Unexpected number of generic arguments in handler method {handlerMethod.Name}"));+ throw new InvalidOperationException($"Unexpected number of generic arguments in handler method {handlerMethod.Name}");}}else{- return ValueTask.FromException<object?>(new InvalidOperationException($"No handler found for message type {messageType.FullName}"));+ throw new InvalidOperationException($"No handler found for message type {messageType.FullName}");}}diff --git a/dotnet/src/Microsoft.AutoGen/Core/Client.cs b/dotnet/src/Microsoft.AutoGen/Core/Client.csdeleted file mode 100644index 132dcd998..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/Client.cs+++ /dev/null@@ -1,9 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// Client.cs-using Microsoft.Extensions.DependencyInjection;--namespace Microsoft.AutoGen.Core;-public sealed class Client([FromKeyedServices("AgentsMetadata")] AgentsMetadata eventTypes)- : Agent(eventTypes)-{-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/EventTypes.cs b/dotnet/src/Microsoft.AutoGen/Core/EventTypes.csdeleted file mode 100644index 7b99f4ef8..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/EventTypes.cs+++ /dev/null@@ -1,11 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// EventTypes.cs-using Google.Protobuf.Reflection;--namespace Microsoft.AutoGen.Core;-public sealed class EventTypes(TypeRegistry typeRegistry, Dictionary<string, Type> types, Dictionary<Type, HashSet<string>> eventsMap)-{- public TypeRegistry TypeRegistry { get; } = typeRegistry;- public Dictionary<string, Type> Types { get; } = types;- public Dictionary<Type, HashSet<string>> EventsMap { get; } = eventsMap;-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/HostBuilderExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/HostBuilderExtensions.csdeleted file mode 100644index 7df12c12f..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/HostBuilderExtensions.cs+++ /dev/null@@ -1,67 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// HostBuilderExtensions.cs--using System.Diagnostics;-using System.Diagnostics.CodeAnalysis;-using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.DependencyInjection;-using Microsoft.Extensions.DependencyInjection.Extensions;-using Microsoft.Extensions.Hosting;--namespace Microsoft.AutoGen.Core;--public static class HostBuilderExtensions-{- public static IHostApplicationBuilder AddAgent<- [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TAgent>(this IHostApplicationBuilder builder, string typeName) where TAgent : Agent- {- builder.Services.AddKeyedSingleton("AgentTypes", (sp, key) => Tuple.Create(typeName, typeof(TAgent)));-- return builder;- }-- public static IHostApplicationBuilder AddAgent(this IHostApplicationBuilder builder, string typeName, Type agentType)- {- builder.Services.AddKeyedSingleton("AgentTypes", (sp, key) => Tuple.Create(typeName, agentType));- return builder;- }-- public static IHostApplicationBuilder AddAgentWorker(this IHostApplicationBuilder builder)- {- var assemblies = AppDomain.CurrentDomain.GetAssemblies();- builder.Services.TryAddSingleton(DistributedContextPropagator.Current);- builder.Services.AddSingleton<IRegistryStorage, RegistryStorage>();- builder.Services.AddSingleton<IRegistry, Registry>();- builder.Services.AddSingleton<IAgentRuntime, AgentRuntime>();- builder.Services.AddSingleton<IHostedService>(sp => (IHostedService)sp.GetRequiredService<IAgentRuntime>());- builder.Services.AddKeyedSingleton("AgentsMetadata", (sp, key) =>- {- return ReflectionHelper.GetAgentsMetadata(assemblies);- });- builder.Services.AddSingleton((s) =>- {- var worker = s.GetRequiredService<IAgentRuntime>();- var client = ActivatorUtilities.CreateInstance<Client>(s);- Agent.Initialize(worker, client);- return client;- });- builder.Services.AddSingleton(new AgentApplicationBuilder(builder));-- return builder;- }-}-public sealed class AgentApplicationBuilder(IHostApplicationBuilder builder)-{- public AgentApplicationBuilder AddAgent<- [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TAgent>(string typeName) where TAgent : Agent- {- builder.Services.AddKeyedSingleton("AgentTypes", (sp, key) => Tuple.Create(typeName, typeof(TAgent)));- return this;- }- public AgentApplicationBuilder AddAgent(string typeName, Type agentType)- {- builder.Services.AddKeyedSingleton("AgentTypes", (sp, key) => Tuple.Create(typeName, agentType));- return this;- }-}-diff --git a/dotnet/src/Microsoft.AutoGen/Core/IAgentRuntimeExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/IAgentRuntimeExtensions.csdeleted file mode 100644index 479ba06f5..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/IAgentRuntimeExtensions.cs+++ /dev/null@@ -1,101 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// IAgentRuntimeExtensions.cs--using System.Diagnostics;-using Google.Protobuf.Collections;-using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.DependencyInjection;-using static Microsoft.AutoGen.Contracts.CloudEvent.Types;--namespace Microsoft.AutoGen.Core;--public static class IAgentRuntimeExtensions-{- public static (string?, string?) GetTraceIdAndState(IAgentRuntime worker, IDictionary<string, string> metadata)- {- var dcp = worker.RuntimeServiceProvider.GetRequiredService<DistributedContextPropagator>();- dcp.ExtractTraceIdAndState(metadata,- static (object? carrier, string fieldName, out string? fieldValue, out IEnumerable<string>? fieldValues) =>- {- var metadata = (IDictionary<string, string>)carrier!;- fieldValues = null;- metadata.TryGetValue(fieldName, out fieldValue);- },- out var traceParent,- out var traceState);- return (traceParent, traceState);- }- public static (string?, string?) GetTraceIdAndState(IAgentRuntime worker, MapField<string, CloudEventAttributeValue> metadata)- {- var dcp = worker.RuntimeServiceProvider.GetRequiredService<DistributedContextPropagator>();- dcp.ExtractTraceIdAndState(metadata,- static (object? carrier, string fieldName, out string? fieldValue, out IEnumerable<string>? fieldValues) =>- {- var metadata = (MapField<string, CloudEventAttributeValue>)carrier!;- fieldValues = null;- metadata.TryGetValue(fieldName, out var ceValue);- fieldValue = ceValue?.CeString;- },- out var traceParent,- out var traceState);- return (traceParent, traceState);- }- public static void Update(IAgentRuntime worker, RpcRequest request, Activity? activity = null)- {- var dcp = worker.RuntimeServiceProvider.GetRequiredService<DistributedContextPropagator>();- dcp.Inject(activity, request.Metadata, static (carrier, key, value) =>- {- var metadata = (IDictionary<string, string>)carrier!;- if (metadata.TryGetValue(key, out _))- {- metadata[key] = value;- }- else- {- metadata.Add(key, value);- }- });- }- public static void Update(IAgentRuntime worker, CloudEvent cloudEvent, Activity? activity = null)- {- var dcp = worker.RuntimeServiceProvider.GetRequiredService<DistributedContextPropagator>();- dcp.Inject(activity, cloudEvent.Attributes, static (carrier, key, value) =>- {- var mapField = (MapField<string, CloudEventAttributeValue>)carrier!;- if (mapField.TryGetValue(key, out var ceValue))- {- mapField[key] = new CloudEventAttributeValue { CeString = value };- }- else- {- mapField.Add(key, new CloudEventAttributeValue { CeString = value });- }- });- }-- public static IDictionary<string, string> ExtractMetadata(IAgentRuntime worker, IDictionary<string, string> metadata)- {- var dcp = worker.RuntimeServiceProvider.GetRequiredService<DistributedContextPropagator>();- var baggage = dcp.ExtractBaggage(metadata, static (object? carrier, string fieldName, out string? fieldValue, out IEnumerable<string>? fieldValues) =>- {- var metadata = (IDictionary<string, string>)carrier!;- fieldValues = null;- metadata.TryGetValue(fieldName, out fieldValue);- });-- return baggage as IDictionary<string, string> ?? new Dictionary<string, string>();- }- public static IDictionary<string, string> ExtractMetadata(IAgentRuntime worker, MapField<string, CloudEventAttributeValue> metadata)- {- var dcp = worker.RuntimeServiceProvider.GetRequiredService<DistributedContextPropagator>();- var baggage = dcp.ExtractBaggage(metadata, static (object? carrier, string fieldName, out string? fieldValue, out IEnumerable<string>? fieldValues) =>- {- var metadata = (MapField<string, CloudEventAttributeValue>)carrier!;- fieldValues = null;- metadata.TryGetValue(fieldName, out var ceValue);- fieldValue = ceValue?.CeString;- });-- return baggage as IDictionary<string, string> ?? new Dictionary<string, string>();- }-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/IHandle.cs b/dotnet/src/Microsoft.AutoGen/Core/IHandle.csindex cb1dd62de..dbf4a9636 100644--- a/dotnet/src/Microsoft.AutoGen/Core/IHandle.cs+++ b/dotnet/src/Microsoft.AutoGen/Core/IHandle.cs@@ -2,6 +2,7 @@// IHandle.csusing Google.Protobuf;+using Microsoft.AutoGen.Contracts;namespace Microsoft.AutoGen.Core;@@ -9,12 +10,22 @@ namespace Microsoft.AutoGen.Core;/// Defines a handler interface for processing items of type <typeparamref name="T"/>./// </summary>/// <typeparam name="T">The type of item to be handled, which must implement <see cref="IMessage"/>.</typeparam>-public interface IHandle<in T> where T : IMessage+public interface IHandle<in T>{/// <summary>/// Handles the specified item asynchronously./// </summary>/// <param name="item">The item to be handled.</param>/// <returns>A task that represents the asynchronous operation.</returns>- Task Handle(T item, CancellationToken cancellationToken = default);+ ValueTask Handle(T item, MessageContext messageContext);+}++public interface IHandle<in InT, OutT>+{+ /// <summary>+ /// Handles the specified item asynchronously.+ /// </summary>+ /// <param name="item">The item to be handled.</param>+ /// <returns>A task that represents the asynchronous operation.</returns>+ ValueTask<OutT> Handle(InT item, MessageContext messageContext);}diff --git a/dotnet/src/Microsoft.AutoGen/Core/IHandleExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/IHandleExtensions.csindex 44014a4ab..9c5b64b95 100644--- a/dotnet/src/Microsoft.AutoGen/Core/IHandleExtensions.cs+++ b/dotnet/src/Microsoft.AutoGen/Core/IHandleExtensions.cs@@ -17,7 +17,7 @@ public static class IHandleExtensions/// <returns>An array of MethodInfo objects representing the handler methods.</returns>public static MethodInfo[] GetHandlers(this Type type){- var handlers = type.GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IHandle<>));+ var handlers = type.GetInterfaces().Where(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IHandle<>) || i.GetGenericTypeDefinition() == typeof(IHandle<,>)));return handlers.SelectMany(h => h.GetMethods().Where(m => m.Name == "Handle")).ToArray();}diff --git a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/InProcessRuntime.cs b/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cssimilarity index 98%rename from dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/InProcessRuntime.csrename to dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.csindex cbc6187b4..32920f686 100644--- a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/InProcessRuntime.cs+++ b/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs@@ -1,9 +1,9 @@// Copyright (c) Microsoft Corporation. All rights reserved.// InProcessRuntime.cs-using Microsoft.AutoGen.Contracts.Python;+using Microsoft.AutoGen.Contracts;-namespace Microsoft.AutoGen.Core.Python;+namespace Microsoft.AutoGen.Core;public sealed class InProcessRuntime : IAgentRuntime{diff --git a/dotnet/src/Microsoft.AutoGen/Core/MessageExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/MessageExtensions.csdeleted file mode 100644index 7e2260d31..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/MessageExtensions.cs+++ /dev/null@@ -1,103 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// MessageExtensions.cs--using Google.Protobuf;-using Google.Protobuf.WellKnownTypes;-using Microsoft.AutoGen.Contracts;--namespace Microsoft.AutoGen.Core;--/// <summary>-/// Provides extension methods for converting messages to and from various formats.-/// </summary>-public static class MessageExtensions-{- private const string PROTO_DATA_CONTENT_TYPE = "application/x-protobuf";-- /// <summary>- /// Converts a message to a CloudEvent.- /// </summary>- /// <typeparam name="T">The type of the message.</typeparam>- /// <param name="message">The message to convert.</param>- /// <param name="key">The key of the event, maps to the Topic Type</param>- /// <param name="topic">The topic of the event, </param>- /// <returns>A CloudEvent representing the message.</returns>- public static CloudEvent ToCloudEvent<T>(this T message, string key, string topic) where T : IMessage- {- return new CloudEvent- {- ProtoData = Any.Pack(message),- Type = message.Descriptor.FullName,- Source = topic,- Id = Guid.NewGuid().ToString(),- Attributes = {- {- "datacontenttype", new CloudEvent.Types.CloudEventAttributeValue { CeString = PROTO_DATA_CONTENT_TYPE }- },- {- "subject", new CloudEvent.Types.CloudEventAttributeValue { CeString = key }- }- }- };- }-- /// <summary>- /// Converts a CloudEvent back to a message.- /// </summary>- /// <typeparam name="T">The type of the message.</typeparam>- /// <param name="cloudEvent">The CloudEvent to convert.</param>- /// <returns>The message represented by the CloudEvent.</returns>- public static T FromCloudEvent<T>(this CloudEvent cloudEvent) where T : IMessage, new()- {- return cloudEvent.ProtoData.Unpack<T>();- }-- /// <summary>- public static string GetSubject(this CloudEvent cloudEvent)- {- if (cloudEvent.Attributes.TryGetValue("subject", out var value))- {- return value.CeString;- }- else- {- return string.Empty;- }- }-- /// <summary>- /// Converts a state to an AgentState.- /// </summary>- /// <typeparam name="T">The type of the state.</typeparam>- /// <param name="state">The state to convert.</param>- /// <param name="agentId">The ID of the agent.</param>- /// <param name="eTag">The ETag of the state.</param>- /// <returns>An AgentState representing the state.</returns>- public static AgentState ToAgentState<T>(this T state, AgentId agentId, string eTag) where T : IMessage- {- return new AgentState- {- ProtoData = Any.Pack(state),- AgentId = agentId,- ETag = eTag- };- }-- /// <summary>- /// Converts an AgentState back to a state.- /// </summary>- /// <typeparam name="T">The type of the state.</typeparam>- /// <param name="state">The AgentState to convert.</param>- /// <returns>The state represented by the AgentState.</returns>- public static T FromAgentState<T>(this AgentState state) where T : IMessage, new()- {- if (state.HasTextData == true)- {- if (typeof(T) == typeof(AgentState))- {- return (T)(IMessage)state;- }- }- return state.ProtoData.Unpack<T>();- }-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/IHandle.cs b/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/IHandle.csdeleted file mode 100644index bd37618dd..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/IHandle.cs+++ /dev/null@@ -1,31 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// IHandle.cs--using Google.Protobuf;-using Microsoft.AutoGen.Contracts.Python;--namespace Microsoft.AutoGen.Core.Python;--/// <summary>-/// Defines a handler interface for processing items of type <typeparamref name="T"/>.-/// </summary>-/// <typeparam name="T">The type of item to be handled, which must implement <see cref="IMessage"/>.</typeparam>-public interface IHandle<in T>-{- /// <summary>- /// Handles the specified item asynchronously.- /// </summary>- /// <param name="item">The item to be handled.</param>- /// <returns>A task that represents the asynchronous operation.</returns>- Task Handle(T item, MessageContext messageContext);-}--public interface IHandle<in InT, OutT>-{- /// <summary>- /// Handles the specified item asynchronously.- /// </summary>- /// <param name="item">The item to be handled.</param>- /// <returns>A task that represents the asynchronous operation.</returns>- Task<OutT> Handle(InT item, MessageContext messageContext);-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/IHandleExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/IHandleExtensions.csdeleted file mode 100644index 5053e5965..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/IHandleExtensions.cs+++ /dev/null@@ -1,38 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// IHandleExtensions.cs--using System.Reflection;--namespace Microsoft.AutoGen.Core.Python;--/// <summary>-/// Provides extension methods for types implementing the IHandle interface.-/// </summary>-public static class IHandleExtensions-{- /// <summary>- /// Gets all the handler methods from the interfaces implemented by the specified type.- /// </summary>- /// <param name="type">The type to get the handler methods from.</param>- /// <returns>An array of MethodInfo objects representing the handler methods.</returns>- public static MethodInfo[] GetHandlers(this Type type)- {- var handlers = type.GetInterfaces().Where(i => i.IsGenericType && (i.GetGenericTypeDefinition() == typeof(IHandle<>) || i.GetGenericTypeDefinition() == typeof(IHandle<,>)));- return handlers.SelectMany(h => h.GetMethods().Where(m => m.Name == "Handle")).ToArray();- }-- /// <summary>- /// Gets a lookup table of handler methods from the interfaces implemented by the specified type.- /// </summary>- /// <param name="type">The type to get the handler methods from.</param>- /// <returns>A dictionary where the key is the generic type and the value is the MethodInfo of the handler method.</returns>- public static Dictionary<Type, MethodInfo> GetHandlersLookupTable(this Type type)- {- var handlers = type.GetHandlers();- return handlers.ToDictionary(h =>- {- var generic = h.DeclaringType!.GetGenericArguments();- return generic[0];- });- }-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/ReflectionHelper.cs b/dotnet/src/Microsoft.AutoGen/Core/ReflectionHelper.csdeleted file mode 100644index a977af69e..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/ReflectionHelper.cs+++ /dev/null@@ -1,63 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// ReflectionHelper.cs-using System.Reflection;-using Google.Protobuf;-using Google.Protobuf.Reflection;--namespace Microsoft.AutoGen.Core;-public sealed class ReflectionHelper-{- public static bool IsSubclassOfGeneric(Type type, Type genericBaseType)- {- while (type != null && type != typeof(object))- {- if (genericBaseType == (type.IsGenericType ? type.GetGenericTypeDefinition() : type))- {- return true;- }- if (type.BaseType == null)- {- return false;- }- type = type.BaseType;- }- return false;- }- public static AgentsMetadata GetAgentsMetadata(params Assembly[] assemblies)- {- var interfaceType = typeof(IMessage);- var pairs = assemblies- .SelectMany(assembly => assembly.GetTypes())- .Where(type => interfaceType.IsAssignableFrom(type) && type.IsClass && !type.IsAbstract)- .Select(t => (t, GetMessageDescriptor(t)));-- var descriptors = pairs.Select(t => t.Item2);- var typeRegistry = TypeRegistry.FromMessages(descriptors);- var types = pairs.ToDictionary(item => item.Item2?.FullName ?? "", item => item.t);-- var eventsMap = assemblies- .SelectMany(assembly => assembly.GetTypes())- .Where(type => IsSubclassOfGeneric(type, typeof(Agent)) && !type.IsAbstract)- .Select(t => (t, t.GetInterfaces()- .Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IHandle<>))- .Select(i => GetMessageDescriptor(i.GetGenericArguments().First())?.FullName ?? "").ToHashSet()))- .ToDictionary(item => item.t, item => item.Item2);- var topicsMap = assemblies- .SelectMany(assembly => assembly.GetTypes())- .Where(type => IsSubclassOfGeneric(type, typeof(Agent)) && !type.IsAbstract)- .Select(t => (t, t.GetCustomAttributes<TopicSubscriptionAttribute>().Select(a => a.Topic).ToHashSet()))- .ToDictionary(item => item.t, item => item.Item2);- return new AgentsMetadata(typeRegistry, types, eventsMap, topicsMap);- }-- /// <summary>- /// Gets the message descriptor for the specified type.- /// </summary>- /// <param name="type">The type to get the message descriptor for.</param>- /// <returns>The message descriptor if found; otherwise, <c>null</c>.</returns>- public static MessageDescriptor? GetMessageDescriptor(Type type)- {- var property = type.GetProperty("Descriptor", BindingFlags.Static | BindingFlags.Public);- return property?.GetValue(null) as MessageDescriptor;- }-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/Registry.cs b/dotnet/src/Microsoft.AutoGen/Core/Registry.csdeleted file mode 100644index 543784421..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/Registry.cs+++ /dev/null@@ -1,268 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// Registry.cs-using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.DependencyInjection;-using Microsoft.Extensions.Logging;--namespace Microsoft.AutoGen.Core;-public class Registry : IRegistry-{- public AgentsRegistryState State { get; set; }- private readonly IRegistryStorage Storage;- private readonly ILogger<Registry> _logger;- private string _registryEtag;- private const int _retries = 5;-- public Registry(IRegistryStorage storage, ILogger<Registry> logger)- {- _logger = logger;- Storage = storage;- State = Storage.ReadStateAsync().ConfigureAwait(true).GetAwaiter().GetResult();- _registryEtag = State.Etag;- _logger.LogInformation("Registry initialized.");- }-- public ValueTask<List<string>> GetSubscribedAndHandlingAgentsAsync(string topic, string eventType)- {- UpdateStateIfStale();- List<string> agents = [];- // get all agent types that are subscribed to the topic- if (State.TopicToAgentTypesMap.TryGetValue(topic, out var subscribedAgentTypes))- {- /*// get all agent types that are handling the event- if (State.EventsToAgentTypesMap.TryGetValue(eventType, out var handlingAgents))- {- agents.AddRange(subscribedAgentTypes.Intersect(handlingAgents).ToList());- }*/- agents.AddRange(subscribedAgentTypes.ToList());- }- if (State.TopicToAgentTypesMap.TryGetValue(eventType, out var eventHandlingAgents))- {- agents.AddRange(eventHandlingAgents.ToList());- }- if (State.TopicToAgentTypesMap.TryGetValue(topic + "." + eventType, out var combo))- {- agents.AddRange(combo.ToList());- }- // instead of an exact match, we can also check for a prefix match where key starts with the eventType- if (State.TopicToAgentTypesMap.Keys.Any(key => key.StartsWith(eventType)))- {- State.TopicToAgentTypesMap.Where(- kvp => kvp.Key.StartsWith(eventType))- .SelectMany(kvp => kvp.Value)- .Distinct()- .ToList()- .ForEach(async agentType =>- {- agents.Add(agentType);- });- }- agents = agents.Distinct().ToList();-- return new ValueTask<List<string>>(agents);- }- public async ValueTask RegisterAgentTypeAsync(RegisterAgentTypeRequest registration, IAgentRuntime runtime)- {- var retries = _retries;- while (!await RegisterAgentTypeWriteAsync(registration, runtime))- {- if (retries == 0)- {- throw new IOException($"Failed to register agent type after {_retries} retries.");- }- _logger.LogWarning("Failed to register agent type, retrying...");- retries--;- }- }-- private async ValueTask<bool> RegisterAgentTypeWriteAsync(RegisterAgentTypeRequest registration, IAgentRuntime runtime, CancellationToken cancellationToken = default)- {- UpdateStateIfStale();- if (registration.Type is null)- {- throw new InvalidOperationException("RegisterAgentType: Agent type is required.");- }- var agentTypes = AgentTypes.GetAgentTypesFromAssembly()- ?? throw new InvalidOperationException("No agent types found in the assembly");-- if (!agentTypes.Types.TryGetValue(registration.Type, out var value))- {- throw new InvalidOperationException($"RegisterAgentType: Invalid agent type {registration.Type}.");- }- try- {- var agentInstance = (Agent)runtime.RuntimeServiceProvider.GetRequiredService(value);- _logger.LogWarning("Agent type {agentType} is already registered.", registration.Type);- State.AgentTypes.TryAdd(registration.Type, agentInstance.AgentId);- }- catch (InvalidOperationException)- {- // Agent type was not yet in the registry - it won't be available in DI- _logger.LogInformation("Agent type {agentType} is not yet registered, activating", registration.Type);- var agent = (Agent)ActivatorUtilities.CreateInstance(runtime.RuntimeServiceProvider, instanceType: value);- Agent.Initialize(runtime, agent);- State.AgentTypes.TryAdd(registration.Type, agent.AgentId);- }- return await WriteStateAsync(State, cancellationToken).ConfigureAwait(false);- }- public async ValueTask SubscribeAsync(AddSubscriptionRequest subscription)- {- var retries = _retries;- while (!await SubscribeWriteAsync(subscription))- {- if (retries == 0)- {- throw new IOException($"Failed to subscribe after {_retries} retries.");- }- _logger.LogWarning("Failed to subscribe, retrying...");- retries--;- }- }- private async ValueTask<bool> SubscribeWriteAsync(AddSubscriptionRequest subscription, CancellationToken cancellationToken = default)- {- UpdateStateIfStale();- var guid = Guid.NewGuid().ToString();- subscription.Subscription.Id = guid;- switch (subscription.Subscription.SubscriptionCase)- {- //TODO: this doesnt look right- case Subscription.SubscriptionOneofCase.TypePrefixSubscription:- break;- case Subscription.SubscriptionOneofCase.TypeSubscription:- {- // add the topic to the set of topics for the agent type- State.AgentsToTopicsMap.TryGetValue(subscription.Subscription.TypeSubscription.AgentType, out var topics);- if (topics is null)- {- topics = new HashSet<string>();- State.AgentsToTopicsMap[subscription.Subscription.TypeSubscription.AgentType] = topics;- }- topics.Add(subscription.Subscription.TypeSubscription.TopicType);-- // add the agent type to the set of agent types for the topic- State.TopicToAgentTypesMap.TryGetValue(subscription.Subscription.TypeSubscription.TopicType, out var agents);- if (agents is null)- {- agents = new HashSet<string>();- State.TopicToAgentTypesMap[subscription.Subscription.TypeSubscription.TopicType] = agents;- }- agents.Add(subscription.Subscription.TypeSubscription.AgentType);-- // add the subscription by Guid- State.GuidSubscriptionsMap.TryGetValue(guid, out var existingSubscriptions);- if (existingSubscriptions is null)- {- existingSubscriptions = new HashSet<Subscription>();- State.GuidSubscriptionsMap[guid] = existingSubscriptions;- }- existingSubscriptions.Add(subscription.Subscription);- break;- }- default:- throw new InvalidOperationException("Invalid subscription type");- }- return await WriteStateAsync(State, cancellationToken).ConfigureAwait(false);- }- public async ValueTask UnsubscribeAsync(RemoveSubscriptionRequest request)- {- var retries = _retries;- while (!await UnsubscribeWriteAsync(request))- {- if (retries == 0)- {- throw new IOException($"Failed to unsubscribe after {_retries} retries.");- }- _logger.LogWarning("Failed to unsubscribe, retrying...");- retries--;- }- }- private async ValueTask<bool> UnsubscribeWriteAsync(RemoveSubscriptionRequest request, CancellationToken cancellationToken = default)- {- UpdateStateIfStale();- var guid = request.Id;- // does the guid parse?- if (!Guid.TryParse(guid, out var _))- {- throw new InvalidOperationException("Invalid subscription id");- }- if (State.GuidSubscriptionsMap.TryGetValue(guid, out var subscriptions))- {- foreach (var subscription in subscriptions)- {- switch (subscription.SubscriptionCase)- {- case Subscription.SubscriptionOneofCase.TypeSubscription:- {- // remove the topic from the set of topics for the agent type- State.AgentsToTopicsMap.TryGetValue(subscription.TypeSubscription.AgentType, out var topics);- topics?.Remove(subscription.TypeSubscription.TopicType);-- // remove the agent type from the set of agent types for the topic- State.TopicToAgentTypesMap.TryGetValue(subscription.TypeSubscription.TopicType, out var agents);- agents?.Remove(subscription.TypeSubscription.AgentType);-- //remove the subscription by Guid- State.GuidSubscriptionsMap.TryGetValue(guid, out var existingSubscriptions);- existingSubscriptions?.Remove(subscription);- break;- }- case Subscription.SubscriptionOneofCase.TypePrefixSubscription:- break;- default:- throw new InvalidOperationException("Invalid subscription type");- }- }- State.GuidSubscriptionsMap.Remove(guid, out _);- return await WriteStateAsync(State, cancellationToken).ConfigureAwait(false);- }- return true;- }- public ValueTask<List<Subscription>> GetSubscriptionsAsync(GetSubscriptionsRequest request)- {- var _ = request;- UpdateStateIfStale();- var subscriptions = new List<Subscription>();- foreach (var kvp in State.GuidSubscriptionsMap)- {- subscriptions.AddRange(kvp.Value);- }- return new(subscriptions);- }- /// <summary>- /// in case there is a write in between our last read and now...- /// </summary>- private void UpdateStateIfStale()- {- if (State.Etag != _registryEtag)- {- State = Storage.ReadStateAsync().ConfigureAwait(true).GetAwaiter().GetResult();- _registryEtag = State.Etag;- }- }- /// <summary>- /// Writes the state to the storage.- /// </summary>- /// <param name="state"></param>- /// <returns>bool true on success, false on failure</returns>- private async ValueTask<bool> WriteStateAsync(AgentsRegistryState state, CancellationToken cancellationToken = default)- {- try- {- await Storage.WriteStateAsync(state, cancellationToken).ConfigureAwait(false);- _registryEtag = state.Etag;- State = state;- return true;- }- catch (Exception e)- {- _logger.LogError(e, "Failed to write state to storage.");- return false;- }- }-- public ValueTask UnregisterAgentTypeAsync(string type, IAgentRuntime worker)- {- throw new NotImplementedException();- }-}-diff --git a/dotnet/src/Microsoft.AutoGen/Core/RegistryStorage.cs b/dotnet/src/Microsoft.AutoGen/Core/RegistryStorage.csdeleted file mode 100644index aab624ec8..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/RegistryStorage.cs+++ /dev/null@@ -1,77 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// RegistryStorage.cs--using System.Text.Json;-using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.Logging;--namespace Microsoft.AutoGen.Core;-/// <summary>-/// Storage implementation for the RegistryState-/// Note: if you really care about the performance and resilience of this you should probably use the distributed runtime and persistent storage through Orleans-/// </summary>-public class RegistryStorage(ILogger<IRegistryStorage> logger) : IRegistryStorage-{- /// a property representing the file path to the state file read from configuration- public string FilePath { get; set; } = Environment.GetEnvironmentVariable("AGENTS_REGISTRY") ?? "registry.json";- protected internal ILogger<IRegistryStorage> _logger = logger;- private readonly object _lock = new();-- public async Task<AgentsRegistryState> ReadStateAsync(CancellationToken cancellationToken = default)- {- string json;- var state = new AgentsRegistryState();- if (File.Exists(FilePath)) { json = await File.ReadAllTextAsync(FilePath, cancellationToken).ConfigureAwait(false); }- else- {- _logger.LogWarning("Registry file {FilePath} does not exist, starting with an empty Registry", FilePath);- await WriteStateAsync(state, cancellationToken, true).ConfigureAwait(false);- return state;- }- try- {- state = JsonSerializer.Deserialize<AgentsRegistryState>(json) ?? new AgentsRegistryState();- }- catch (Exception e)- {- _logger.LogWarning(e, "Failed to read the Registry from {FilePath}, starting with an empty Registry", FilePath);- await WriteStateAsync(state, cancellationToken, true).ConfigureAwait(false);- }- return state;- }- public async ValueTask<string> WriteStateAsync(AgentsRegistryState state, CancellationToken cancellationToken = default)- {- return await WriteStateAsync(state, cancellationToken, false).ConfigureAwait(false);- }-- private async ValueTask<string> WriteStateAsync(AgentsRegistryState state, CancellationToken cancellationToken = default, bool noRead = false)- {- lock (_lock)- {- var eTag = "";- // etags for optimistic concurrency control- if (!noRead)- {- // read the current state to get the current ETag- eTag = ReadStateAsync().ConfigureAwait(false).GetAwaiter().GetResult().Etag;- }- else { eTag = state.Etag; }- // if the Etag is null, its a new state- // if both etags are set, they should match or it means that the state has changed since the last read.- if (string.IsNullOrEmpty(state.Etag) || (string.IsNullOrEmpty(eTag)) || (string.Equals(state.Etag, eTag, StringComparison.Ordinal)))- {- state.Etag = Guid.NewGuid().ToString();- // serialize to JSON and write to file- var json = JsonSerializer.Serialize(state);- File.WriteAllTextAsync(FilePath, json, cancellationToken).ConfigureAwait(false);- return state.Etag;- }- else- {- //TODO - this is probably not the correct behavior to just throw - I presume we want to somehow let the caller know that the state has changed and they need to re-read it- throw new ArgumentException(- "The provided ETag does not match the current ETag. The state has been modified by another request.");- }- }- }-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/TopicSubscriptionAttribute.cs b/dotnet/src/Microsoft.AutoGen/Core/TopicSubscriptionAttribute.csdeleted file mode 100644index 8c1e93e2f..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/TopicSubscriptionAttribute.cs+++ /dev/null@@ -1,10 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// TopicSubscriptionAttribute.cs--namespace Microsoft.AutoGen.Core;--[AttributeUsage(AttributeTargets.All)]-public class TopicSubscriptionAttribute(string topic) : Attribute-{- public string Topic { get; } = topic;-}diff --git a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/TypePrefixSubscription.cs b/dotnet/src/Microsoft.AutoGen/Core/TypePrefixSubscription.cssimilarity index 98%rename from dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/TypePrefixSubscription.csrename to dotnet/src/Microsoft.AutoGen/Core/TypePrefixSubscription.csindex b4a8422f4..a4e1ea1b5 100644--- a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/TypePrefixSubscription.cs+++ b/dotnet/src/Microsoft.AutoGen/Core/TypePrefixSubscription.cs@@ -3,7 +3,7 @@using System.Diagnostics.CodeAnalysis;-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>/// This subscription matches on topics based on a prefix of the type and maps to agents using the source of the topic as the agent key.diff --git a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/TypePrefixSubscriptionAttribute.cs b/dotnet/src/Microsoft.AutoGen/Core/TypePrefixSubscriptionAttribute.cssimilarity index 83%rename from dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/TypePrefixSubscriptionAttribute.csrename to dotnet/src/Microsoft.AutoGen/Core/TypePrefixSubscriptionAttribute.csindex 161c97a28..57105c8b9 100644--- a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/TypePrefixSubscriptionAttribute.cs+++ b/dotnet/src/Microsoft.AutoGen/Core/TypePrefixSubscriptionAttribute.cs@@ -1,9 +1,9 @@// Copyright (c) Microsoft Corporation. All rights reserved.// TypePrefixSubscriptionAttribute.cs-using Microsoft.AutoGen.Contracts.Python;+using Microsoft.AutoGen.Contracts;-namespace Microsoft.AutoGen.Core.Python;+namespace Microsoft.AutoGen.Core;[AttributeUsage(AttributeTargets.All)]public class TopicPrefixSubscriptionAttribute(string topic) : Attribute, IUnboundSubscriptionDefinitiondiff --git a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/TypeSubscription.cs b/dotnet/src/Microsoft.AutoGen/Core/TypeSubscription.cssimilarity index 97%rename from dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/TypeSubscription.csrename to dotnet/src/Microsoft.AutoGen/Core/TypeSubscription.csindex 84a8f83f4..54c903125 100644--- a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/TypeSubscription.cs+++ b/dotnet/src/Microsoft.AutoGen/Core/TypeSubscription.cs@@ -3,7 +3,7 @@using System.Diagnostics.CodeAnalysis;-namespace Microsoft.AutoGen.Contracts.Python;+namespace Microsoft.AutoGen.Contracts;/// <summary>/// This subscription matches on topics based on the exact type and maps to agents using the source of the topic as the agent key.@@ -86,7 +86,7 @@ public class TypeSubscription : ISubscriptionDefinitionpublic override bool Equals([NotNullWhen(true)] object? obj){return obj is TypeSubscription other &&- (Id == other.Id ||+ (Id == other.Id ||(AgentType == other.AgentType && TopicType == other.TopicType));}diff --git a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/TypeSubscriptionAttribute.cs b/dotnet/src/Microsoft.AutoGen/Core/TypeSubscriptionAttribute.cssimilarity index 83%rename from dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/TypeSubscriptionAttribute.csrename to dotnet/src/Microsoft.AutoGen/Core/TypeSubscriptionAttribute.csindex 11c391889..11cd32732 100644--- a/dotnet/src/Microsoft.AutoGen/Core/PythonEquiv/TypeSubscriptionAttribute.cs+++ b/dotnet/src/Microsoft.AutoGen/Core/TypeSubscriptionAttribute.cs@@ -1,9 +1,9 @@// Copyright (c) Microsoft Corporation. All rights reserved.// TypeSubscriptionAttribute.cs-using Microsoft.AutoGen.Contracts.Python;+using Microsoft.AutoGen.Contracts;-namespace Microsoft.AutoGen.Core.Python;+namespace Microsoft.AutoGen.Core;[AttributeUsage(AttributeTargets.All)]public class TypeSubscriptionAttribute(string topic) : Attribute, IUnboundSubscriptionDefinitiondiff --git a/dotnet/src/Microsoft.AutoGen/Core/UninitializedAgentWorker.cs b/dotnet/src/Microsoft.AutoGen/Core/UninitializedAgentWorker.csdeleted file mode 100644index 5eb3c418b..000000000--- a/dotnet/src/Microsoft.AutoGen/Core/UninitializedAgentWorker.cs+++ /dev/null@@ -1,25 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// UninitializedAgentWorker.cs--using Google.Protobuf;-using Microsoft.AutoGen.Contracts;--namespace Microsoft.AutoGen.Core;-public class UninitializedAgentWorker() : IAgentRuntime-{- public IServiceProvider RuntimeServiceProvider => throw new AgentInitalizedIncorrectlyException(AgentNotInitializedMessage);- internal const string AgentNotInitializedMessage = "Agent not initialized correctly. An Agent should never be directly intialized - it is always started by the AgentWorker from the Runtime (using the static Initialize() method).";- public ValueTask<AgentState> LoadStateAsync(AgentId agentId, CancellationToken cancellationToken = default) => throw new AgentInitalizedIncorrectlyException(AgentNotInitializedMessage);- public ValueTask RuntimeSendRequestAsync(IAgent agent, RpcRequest request, CancellationToken cancellationToken = default) => throw new AgentInitalizedIncorrectlyException(AgentNotInitializedMessage);- public ValueTask RuntimeSendResponseAsync(RpcResponse response, CancellationToken cancellationToken = default) => throw new AgentInitalizedIncorrectlyException(AgentNotInitializedMessage);- public ValueTask SaveStateAsync(AgentState value, CancellationToken cancellationToken = default) => throw new AgentInitalizedIncorrectlyException(AgentNotInitializedMessage);- public ValueTask<List<Subscription>> GetSubscriptionsAsync(GetSubscriptionsRequest request, CancellationToken cancellationToken = default) => throw new AgentInitalizedIncorrectlyException(AgentNotInitializedMessage);- public ValueTask<AddSubscriptionResponse> AddSubscriptionAsync(AddSubscriptionRequest request, CancellationToken cancellationToken = default) => throw new AgentInitalizedIncorrectlyException(AgentNotInitializedMessage);- public ValueTask<RemoveSubscriptionResponse> RemoveSubscriptionAsync(RemoveSubscriptionRequest request, CancellationToken cancellationToken = default) => throw new AgentInitalizedIncorrectlyException(AgentNotInitializedMessage);- public ValueTask PublishMessageAsync(IMessage message, TopicId topic, IAgent? sender, CancellationToken? cancellationToken = null) => throw new AgentInitalizedIncorrectlyException(AgentNotInitializedMessage);- public ValueTask RegisterAgentTypeAsync(RegisterAgentTypeRequest request, CancellationToken cancellationToken = default) => throw new AgentInitalizedIncorrectlyException(AgentNotInitializedMessage);- public ValueTask<RpcResponse> SendMessageAsync(IMessage message, AgentId recipient, AgentId? sender, CancellationToken? cancellationToken = null) => throw new AgentInitalizedIncorrectlyException(AgentNotInitializedMessage);- public class AgentInitalizedIncorrectlyException(string message) : Exception(message)- {- }-}diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentRuntimeTests.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentRuntimeTests.csdeleted file mode 100644index df3de5680..000000000--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentRuntimeTests.cs+++ /dev/null@@ -1,74 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// AgentRuntimeTests.cs--using Google.Protobuf;-using Google.Protobuf.Reflection;-using Google.Protobuf.WellKnownTypes;-using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.Hosting;-using Microsoft.Extensions.Logging;-using Moq;-using Xunit;--namespace Microsoft.AutoGen.Core.Tests;--public class AgentRuntimeTests-{- private readonly Mock<IHostApplicationLifetime> _hostApplicationLifetimeMock;- private readonly Mock<IServiceProvider> _serviceProviderMock;- private readonly Mock<ILogger<AgentRuntime>> _loggerMock;- private readonly Mock<IRegistry> _registryMock;- private readonly AgentRuntime _agentRuntime;-- public AgentRuntimeTests()- {- _hostApplicationLifetimeMock = new Mock<IHostApplicationLifetime>();- _serviceProviderMock = new Mock<IServiceProvider>();- _loggerMock = new Mock<ILogger<AgentRuntime>>();- _registryMock = new Mock<IRegistry>();-- _serviceProviderMock.Setup(sp => sp.GetService(typeof(IRegistry))).Returns(_registryMock.Object);-- var configuredAgentTypes = new List<Tuple<string, System.Type>>- {- new Tuple<string, System.Type>("TestAgent", typeof(TestAgent))- };-- _agentRuntime = new AgentRuntime(- _hostApplicationLifetimeMock.Object,- _serviceProviderMock.Object,- configuredAgentTypes,- _loggerMock.Object);- }-- [Fact]- public async Task SendMessageAsync_ShouldReturnResponse()- {- // Arrange- var fixture = new InMemoryAgentRuntimeFixture();- var (runtime, agent) = fixture.Start();- var agentId = new AgentId { Type = "TestAgent", Key = "test-key" };- var message = new TextMessage { TextMessage_ = "Hello, World!" };- var agentMock = new Mock<TestAgent>(MockBehavior.Loose, new AgentsMetadata(TypeRegistry.Empty, new Dictionary<string, System.Type>(), new Dictionary<System.Type, HashSet<string>>(), new Dictionary<System.Type, HashSet<string>>()), new Logger<Agent>(new LoggerFactory()));- agentMock.CallBase = true; // Enable calling the base class methods- agentMock.Setup(a => a.HandleObjectAsync(It.IsAny<object>(), It.IsAny<CancellationToken>())).Callback<object, CancellationToken>((msg, ct) =>- {- var response = new RpcResponse- {- RequestId = "test-request-id",- Payload = new Payload { Data = Any.Pack(new TextMessage { TextMessage_ = "Response" }).ToByteString() }- };- _agentRuntime.DispatchResponse(response);- });-- // Act- var response = await runtime.SendMessageAsync(message, agentId, agent.AgentId);-- // Assert- Assert.NotNull(response);- var any = Any.Parser.ParseFrom(response.Payload.Data);- var unpackedMessage = any.Unpack<TextMessage>();- Assert.Equal("Response", unpackedMessage.TextMessage_);- fixture.Stop();- }-}diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.csindex 712d09fe9..32db2beea 100644--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.cs+++ b/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.cs@@ -1,10 +1,7 @@// Copyright (c) Microsoft Corporation. All rights reserved.// AgentTests.cs-using System.Text.Json;using FluentAssertions;-using Google.Protobuf.Reflection;using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;using Xunit;@@ -16,15 +13,15 @@ public class AgentTests()[Fact]public async Task Agent_ShouldNotReceiveMessages_WhenNotSubscribed(){- var fixture = new InMemoryAgentRuntimeFixture();- var (_, agent) = fixture.Start();+ var runtime = new InProcessRuntime();- var topicType = "TestTopic";+ Logger<BaseAgent> logger = new(new LoggerFactory());+ await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) => ValueTask.FromResult(new TestAgent(id, runtime, logger)));+ await runtime.RegisterImplicitAgentSubscriptionsAsync<TestAgent>("MyAgent");- var subscriptions = await agent.GetSubscriptionsAsync().ConfigureAwait(true);- subscriptions.Any(s => s.TypeSubscription.TopicType == topicType).Should().BeFalse("Agent should not be subscribed to the topic by default.");+ var topicType = "TestTopic";- await agent.PublishMessageAsync(new TextMessage { Source = topicType, TextMessage_ = "test" }, topicType).ConfigureAwait(true);+ await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId("TestTopic")).ConfigureAwait(true);//await Task.Yield();await Task.Delay(100);@@ -32,164 +29,203 @@ public class AgentTests()TestAgent.ReceivedMessages.Any().Should().BeFalse("Agent should not receive messages when not subscribed.");}- /// <summary>- /// Verify that if the agent is not initialized via AgentWorker, it should throw the correct exception.- /// </summary>- /// <returns>void</returns>- [Fact]- public async Task Agent_ShouldThrowException_WhenNotInitialized()- {- using var fixture = new InMemoryAgentRuntimeFixture();- var agent = ActivatorUtilities.CreateInstance<TestAgent>(fixture.AppHost.Services);- await Assert.ThrowsAsync<UninitializedAgentWorker.AgentInitalizedIncorrectlyException>(- async () =>- {- await agent.SubscribeAsync("TestEvent");- }- );- }-- /// <summary>- /// validate that the agent is initialized correctly with implicit subs- /// </summary>- /// <returns>void</returns>- [Fact]- public async Task Agent_ShouldInitializeCorrectly()- {- var fixture = new InMemoryAgentRuntimeFixture();- var (runtime, agent) = fixture.Start();- Assert.Equal(nameof(AgentRuntime), runtime.GetType().Name);- var subscriptions = await agent.GetSubscriptionsAsync();- Assert.Equal(2, subscriptions.Count);- fixture.Stop();- }- /// <summary>- /// Test SubscribeAsync method- /// </summary>- /// <returns>void</returns>[Fact]- public async Task SubscribeAsync_UnsubscribeAsync_and_GetSubscriptionsTest()+ public async Task Agent_ShoulReceiveMessages_WhenSubscribed(){- var fixture = new InMemoryAgentRuntimeFixture();- var (_, agent) = fixture.Start();- await agent.SubscribeAsync("TestEvent");- await Task.Delay(100);- var subscriptions = await agent.GetSubscriptionsAsync().ConfigureAwait(true);- var found = false;- foreach (var subscription in subscriptions)- {- if (subscription.TypeSubscription.TopicType == "TestEvent")- {- found = true;- }- }- Assert.True(found);- await agent.UnsubscribeAsync("TestEvent").ConfigureAwait(true);- await Task.Delay(500);- subscriptions = await agent.GetSubscriptionsAsync().ConfigureAwait(true);- found = false;- foreach (var subscription in subscriptions)- {- if (subscription.TypeSubscription.TopicType == "TestEvent")- {- found = true;- }- }- Assert.False(found);- fixture.Stop();- }+ var runtime = new InProcessRuntime();- /// <summary>- /// Test StoreAsync and ReadAsync methods- /// </summary>- /// <returns>void</returns>- [Fact]- public async Task StoreAsync_and_ReadAsyncTest()- {- var fixture = new InMemoryAgentRuntimeFixture();- var (_, agent) = fixture.Start();- Dictionary<string, string> state = new()- {- { "testdata", "Active" }- };- await agent.StoreAsync(new AgentState- {- AgentId = agent.AgentId,- TextData = JsonSerializer.Serialize(state)- }).ConfigureAwait(true);- var readState = await agent.ReadAsync<AgentState>(agent.AgentId).ConfigureAwait(true);- var read = JsonSerializer.Deserialize<Dictionary<string, string>>(readState.TextData) ?? new Dictionary<string, string> { { "data", "No state data found" } };- read.TryGetValue("testdata", out var value);- Assert.Equal("Active", value);- fixture.Stop();- }+ Logger<BaseAgent> logger = new(new LoggerFactory());+ await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) => ValueTask.FromResult(new SubscribedAgent(id, runtime, logger)));+ await runtime.RegisterImplicitAgentSubscriptionsAsync<SubscribedAgent>("MyAgent");- /// <summary>- /// Test PublishMessageAsync method and ReceiveMessage method- /// </summary>- /// <returns>void</returns>- [Fact]- public async Task PublishMessageAsync_and_ReceiveMessageTest()- {- var fixture = new InMemoryAgentRuntimeFixture();- var (_, agent) = fixture.Start();var topicType = "TestTopic";- await agent.SubscribeAsync(topicType).ConfigureAwait(true);- var subscriptions = await agent.GetSubscriptionsAsync().ConfigureAwait(true);- var found = false;- foreach (var subscription in subscriptions)- {- if (subscription.TypeSubscription.TopicType == topicType)- {- found = true;- }- }- Assert.True(found);- await agent.PublishMessageAsync(new TextMessage()- {- Source = topicType,- TextMessage_ = "buffer"- }, topicType).ConfigureAwait(true);++ await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId("TestTopic")).ConfigureAwait(true);++ //await Task.Yield();await Task.Delay(100);- Assert.True(TestAgent.ReceivedMessages.ContainsKey(topicType));- fixture.Stop();- }- [Fact]- public async Task InvokeCorrectHandler()- {- var agent = new TestAgent(new AgentsMetadata(TypeRegistry.Empty, new Dictionary<string, Type>(), new Dictionary<Type, HashSet<string>>(), new Dictionary<Type, HashSet<string>>()), new Logger<Agent>(new LoggerFactory()));- await agent.HandleObjectAsync("hello world");- await agent.HandleObjectAsync(42);- agent.ReceivedItems.Should().HaveCount(2);- agent.ReceivedItems[0].Should().Be("hello world");- agent.ReceivedItems[1].Should().Be(42);+ TestAgent.ReceivedMessages.Any().Should().BeTrue("Agent should receive messages when subscribed.");}[Fact]- public async Task DelegateMessageToTestAgentAsync()+ public async Task SendMessageAsync_ShouldReturnResponse(){- var runtime = new InMemoryAgentRuntimeFixture();- var client = runtime.AppHost.Services.GetRequiredService<Client>();- await client.PublishMessageAsync(new TextMessage()- {- Source = nameof(DelegateMessageToTestAgentAsync),- TextMessage_ = "buffer"- }, token: CancellationToken.None);-- // wait for 10 seconds- var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));- while (!TestAgent.ReceivedMessages.ContainsKey(nameof(DelegateMessageToTestAgentAsync)) && !cts.Token.IsCancellationRequested)- {- await Task.Delay(100);+ // Arrange+ var runtime = new InProcessRuntime();+ Logger<BaseAgent> logger = new(new LoggerFactory());+ await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) => ValueTask.FromResult(new TestAgent(id, runtime, logger)));+ await runtime.RegisterImplicitAgentSubscriptionsAsync<TestAgent>("MyAgent");++ var agentId = new AgentId("MyAgent", "TestAgent");+ var response = await runtime.SendMessageAsync(new RpcTextMessage { Source = "TestTopic", Content = "Request" }, agentId);++ // Assert+ Assert.NotNull(response);+ Assert.IsType<string>(response);+ if (response is string responseString) {+ Assert.Equal("Request", responseString);}-- TestAgent.ReceivedMessages[nameof(DelegateMessageToTestAgentAsync)].Should().NotBeNull();}- [CollectionDefinition(Name)]- public sealed class ClusterFixtureCollection : ICollectionFixture<InMemoryAgentRuntimeFixture>- {- public const string Name = nameof(ClusterFixtureCollection);- }+ // / <summary>+ // / Verify that if the agent is not initialized via AgentWorker, it should throw the correct exception.+ // / </summary>+ // / <returns>void</returns>+ // [Fact]+ // public async Task Agent_ShouldThrowException_WhenNotInitialized()+ // {+ // using var fixture = new InMemoryAgentRuntimeFixture();+ // var agent = ActivatorUtilities.CreateInstance<TestAgent>(fixture.AppHost.Services);+ // await Assert.ThrowsAsync<UninitializedAgentWorker.AgentInitalizedIncorrectlyException>(+ // async () =>+ // {+ // await agent.SubscribeAsync("TestEvent");+ // }+ // );+ // }++ // /// <summary>+ // /// validate that the agent is initialized correctly with implicit subs+ // /// </summary>+ // /// <returns>void</returns>+ // [Fact]+ // public async Task Agent_ShouldInitializeCorrectly()+ // {+ // var fixture = new InMemoryAgentRuntimeFixture();+ // var (runtime, agent) = fixture.Start();+ // Assert.Equal(nameof(AgentRuntime), runtime.GetType().Name);+ // var subscriptions = await agent.GetSubscriptionsAsync();+ // Assert.Equal(2, subscriptions.Count);+ // fixture.Stop();+ // }+ // /// <summary>+ // /// Test SubscribeAsync method+ // /// </summary>+ // /// <returns>void</returns>+ // [Fact]+ // public async Task SubscribeAsync_UnsubscribeAsync_and_GetSubscriptionsTest()+ // {+ // var fixture = new InMemoryAgentRuntimeFixture();+ // var (_, agent) = fixture.Start();+ // await agent.SubscribeAsync("TestEvent");+ // await Task.Delay(100);+ // var subscriptions = await agent.GetSubscriptionsAsync().ConfigureAwait(true);+ // var found = false;+ // foreach (var subscription in subscriptions)+ // {+ // if (subscription.TypeSubscription.TopicType == "TestEvent")+ // {+ // found = true;+ // }+ // }+ // Assert.True(found);+ // await agent.UnsubscribeAsync("TestEvent").ConfigureAwait(true);+ // await Task.Delay(500);+ // subscriptions = await agent.GetSubscriptionsAsync().ConfigureAwait(true);+ // found = false;+ // foreach (var subscription in subscriptions)+ // {+ // if (subscription.TypeSubscription.TopicType == "TestEvent")+ // {+ // found = true;+ // }+ // }+ // Assert.False(found);+ // fixture.Stop();+ // }++ // /// <summary>+ // /// Test StoreAsync and ReadAsync methods+ // /// </summary>+ // /// <returns>void</returns>+ // [Fact]+ // public async Task StoreAsync_and_ReadAsyncTest()+ // {+ // var fixture = new InMemoryAgentRuntimeFixture();+ // var (_, agent) = fixture.Start();+ // Dictionary<string, string> state = new()+ // {+ // { "testdata", "Active" }+ // };+ // await agent.StoreAsync(new AgentState+ // {+ // AgentId = agent.AgentId,+ // TextData = JsonSerializer.Serialize(state)+ // }).ConfigureAwait(true);+ // var readState = await agent.ReadAsync<AgentState>(agent.AgentId).ConfigureAwait(true);+ // var read = JsonSerializer.Deserialize<Dictionary<string, string>>(readState.TextData) ?? new Dictionary<string, string> { { "data", "No state data found" } };+ // read.TryGetValue("testdata", out var value);+ // Assert.Equal("Active", value);+ // fixture.Stop();+ // }++ // /// <summary>+ // /// Test PublishMessageAsync method and ReceiveMessage method+ // /// </summary>+ // /// <returns>void</returns>+ // [Fact]+ // public async Task PublishMessageAsync_and_ReceiveMessageTest()+ // {+ // var fixture = new InMemoryAgentRuntimeFixture();+ // var (_, agent) = fixture.Start();+ // var topicType = "TestTopic";+ // await agent.SubscribeAsync(topicType).ConfigureAwait(true);+ // var subscriptions = await agent.GetSubscriptionsAsync().ConfigureAwait(true);+ // var found = false;+ // foreach (var subscription in subscriptions)+ // {+ // if (subscription.TypeSubscription.TopicType == topicType)+ // {+ // found = true;+ // }+ // }+ // Assert.True(found);+ // await agent.PublishMessageAsync(new TextMessage()+ // {+ // Source = topicType,+ // TextMessage_ = "buffer"+ // }, topicType).ConfigureAwait(true);+ // await Task.Delay(100);+ // Assert.True(TestAgent.ReceivedMessages.ContainsKey(topicType));+ // fixture.Stop();+ // }++ // [Fact]+ // public async Task InvokeCorrectHandler()+ // {+ // var agent = new TestAgent(new AgentsMetadata(TypeRegistry.Empty, new Dictionary<string, Type>(), new Dictionary<Type, HashSet<string>>(), new Dictionary<Type, HashSet<string>>()), new Logger<Agent>(new LoggerFactory()));+ // await agent.HandleObjectAsync("hello world");+ // await agent.HandleObjectAsync(42);+ // agent.ReceivedItems.Should().HaveCount(2);+ // agent.ReceivedItems[0].Should().Be("hello world");+ // agent.ReceivedItems[1].Should().Be(42);+ // }++ // [Fact]+ // public async Task DelegateMessageToTestAgentAsync()+ // {+ // var runtime = new InMemoryAgentRuntimeFixture();+ // var client = runtime.AppHost.Services.GetRequiredService<Client>();+ // await client.PublishMessageAsync(new TextMessage()+ // {+ // Source = nameof(DelegateMessageToTestAgentAsync),+ // TextMessage_ = "buffer"+ // }, token: CancellationToken.None);++ // // wait for 10 seconds+ // var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));+ // while (!TestAgent.ReceivedMessages.ContainsKey(nameof(DelegateMessageToTestAgentAsync)) && !cts.Token.IsCancellationRequested)+ // {+ // await Task.Delay(100);+ // }++ // TestAgent.ReceivedMessages[nameof(DelegateMessageToTestAgentAsync)].Should().NotBeNull();+ // }++ // [CollectionDefinition(Name)]+ // public sealed class ClusterFixtureCollection : ICollectionFixture<InMemoryAgentRuntimeFixture>+ // {+ // public const string Name = nameof(ClusterFixtureCollection);+ // }}diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/InMemoryAgentRuntimeFixture.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/InMemoryAgentRuntimeFixture.csdeleted file mode 100644index 002efc0f3..000000000--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/InMemoryAgentRuntimeFixture.cs+++ /dev/null@@ -1,74 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// InMemoryAgentRuntimeFixture.cs-using System.Diagnostics;-using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.DependencyInjection;-using Microsoft.Extensions.DependencyInjection.Extensions;-using Microsoft.Extensions.Hosting;--using AgentRegistration = (string Name, System.Type Type);--namespace Microsoft.AutoGen.Core.Tests;--/// <summary>-/// InMemoryAgentRuntimeFixture - provides a fixture for the agent runtime.-/// </summary>-/// <remarks>-/// This fixture is used to provide a runtime for the agent tests.-/// However, it is shared between tests. So operations from one test can affect another.-/// </remarks>-public sealed class InMemoryAgentRuntimeFixture : IDisposable-{- private static IEnumerable<AgentRegistration> DefaultAgents = [(nameof(TestAgent), typeof(TestAgent))];-- public InMemoryAgentRuntimeFixture() : this(null, null)- {- }-- public InMemoryAgentRuntimeFixture(HostApplicationBuilder? hostBuilder = null, IEnumerable<AgentRegistration>? agentTypes = null)- {- var builder = hostBuilder ?? new HostApplicationBuilder();- builder.Services.TryAddSingleton(DistributedContextPropagator.Current);- builder.AddAgentWorker();-- foreach (var agentType in agentTypes ?? DefaultAgents)- {- builder.AddAgent(agentType.Name, agentType.Type);- }-- AppHost = builder.Build();- AppHost.StartAsync().Wait();- }-- public IHost AppHost { get; }-- /// <summary>- /// Start - starts the agent- /// </summary>- /// <returns>IAgentWorker, TestAgent</returns>- public (IAgentRuntime, TestAgent) Start() => Start<TestAgent>();-- public (IAgentRuntime, TAgent) Start<TAgent>() where TAgent : Agent- {- var agent = ActivatorUtilities.CreateInstance<TAgent>(AppHost.Services);- var worker = AppHost.Services.GetRequiredService<IAgentRuntime>();- Agent.Initialize(worker, agent);- return (worker, agent);- }-- /// <summary>- /// Stop - stops the agent and ensures cleanup- /// </summary>- public void Stop()- {- AppHost?.StopAsync().GetAwaiter().GetResult();- }-- /// <summary>- /// Dispose - Ensures cleanup after each test- /// </summary>- public void Dispose()- {- Stop();- }-}diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/PythonEquiv/AgentTests.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/PythonEquiv/AgentTests.csdeleted file mode 100644index 98cace67b..000000000--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/PythonEquiv/AgentTests.cs+++ /dev/null@@ -1,212 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// AgentTests.cs-using FluentAssertions;-using Microsoft.AutoGen.Contracts.Python;-using Microsoft.AutoGen.Core.Python;-using Microsoft.Extensions.Logging;-using Xunit;--namespace Microsoft.AutoGen.Core.Tests.Python;--//[Collection(ClusterFixtureCollection.Name)]-public class AgentTests()-{- [Fact]- public async Task Agent_ShouldNotReceiveMessages_WhenNotSubscribed()- {- var runtime = new Core.Python.InProcessRuntime();-- Logger<BaseAgent> logger = new(new LoggerFactory());- await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) => ValueTask.FromResult(new TestAgent(id, runtime, logger)));- await runtime.RegisterImplicitAgentSubscriptionsAsync<TestAgent>("MyAgent");-- var topicType = "TestTopic";-- await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId("TestTopic")).ConfigureAwait(true);-- //await Task.Yield();- await Task.Delay(100);-- TestAgent.ReceivedMessages.Any().Should().BeFalse("Agent should not receive messages when not subscribed.");- }-- [Fact]- public async Task Agent_ShoulReceiveMessages_WhenSubscribed()- {- var runtime = new Core.Python.InProcessRuntime();-- Logger<BaseAgent> logger = new(new LoggerFactory());- await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) => ValueTask.FromResult(new SubscribedAgent(id, runtime, logger)));- await runtime.RegisterImplicitAgentSubscriptionsAsync<SubscribedAgent>("MyAgent");-- var topicType = "TestTopic";-- await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId("TestTopic")).ConfigureAwait(true);-- //await Task.Yield();- await Task.Delay(100);-- TestAgent.ReceivedMessages.Any().Should().BeTrue("Agent should receive messages when subscribed.");- }-- // / <summary>- // / Verify that if the agent is not initialized via AgentWorker, it should throw the correct exception.- // / </summary>- // / <returns>void</returns>- // [Fact]- // public async Task Agent_ShouldThrowException_WhenNotInitialized()- // {- // using var fixture = new InMemoryAgentRuntimeFixture();- // var agent = ActivatorUtilities.CreateInstance<TestAgent>(fixture.AppHost.Services);- // await Assert.ThrowsAsync<UninitializedAgentWorker.AgentInitalizedIncorrectlyException>(- // async () =>- // {- // await agent.SubscribeAsync("TestEvent");- // }- // );- // }-- // /// <summary>- // /// validate that the agent is initialized correctly with implicit subs- // /// </summary>- // /// <returns>void</returns>- // [Fact]- // public async Task Agent_ShouldInitializeCorrectly()- // {- // var fixture = new InMemoryAgentRuntimeFixture();- // var (runtime, agent) = fixture.Start();- // Assert.Equal(nameof(AgentRuntime), runtime.GetType().Name);- // var subscriptions = await agent.GetSubscriptionsAsync();- // Assert.Equal(2, subscriptions.Count);- // fixture.Stop();- // }- // /// <summary>- // /// Test SubscribeAsync method- // /// </summary>- // /// <returns>void</returns>- // [Fact]- // public async Task SubscribeAsync_UnsubscribeAsync_and_GetSubscriptionsTest()- // {- // var fixture = new InMemoryAgentRuntimeFixture();- // var (_, agent) = fixture.Start();- // await agent.SubscribeAsync("TestEvent");- // await Task.Delay(100);- // var subscriptions = await agent.GetSubscriptionsAsync().ConfigureAwait(true);- // var found = false;- // foreach (var subscription in subscriptions)- // {- // if (subscription.TypeSubscription.TopicType == "TestEvent")- // {- // found = true;- // }- // }- // Assert.True(found);- // await agent.UnsubscribeAsync("TestEvent").ConfigureAwait(true);- // await Task.Delay(500);- // subscriptions = await agent.GetSubscriptionsAsync().ConfigureAwait(true);- // found = false;- // foreach (var subscription in subscriptions)- // {- // if (subscription.TypeSubscription.TopicType == "TestEvent")- // {- // found = true;- // }- // }- // Assert.False(found);- // fixture.Stop();- // }-- // /// <summary>- // /// Test StoreAsync and ReadAsync methods- // /// </summary>- // /// <returns>void</returns>- // [Fact]- // public async Task StoreAsync_and_ReadAsyncTest()- // {- // var fixture = new InMemoryAgentRuntimeFixture();- // var (_, agent) = fixture.Start();- // Dictionary<string, string> state = new()- // {- // { "testdata", "Active" }- // };- // await agent.StoreAsync(new AgentState- // {- // AgentId = agent.AgentId,- // TextData = JsonSerializer.Serialize(state)- // }).ConfigureAwait(true);- // var readState = await agent.ReadAsync<AgentState>(agent.AgentId).ConfigureAwait(true);- // var read = JsonSerializer.Deserialize<Dictionary<string, string>>(readState.TextData) ?? new Dictionary<string, string> { { "data", "No state data found" } };- // read.TryGetValue("testdata", out var value);- // Assert.Equal("Active", value);- // fixture.Stop();- // }-- // /// <summary>- // /// Test PublishMessageAsync method and ReceiveMessage method- // /// </summary>- // /// <returns>void</returns>- // [Fact]- // public async Task PublishMessageAsync_and_ReceiveMessageTest()- // {- // var fixture = new InMemoryAgentRuntimeFixture();- // var (_, agent) = fixture.Start();- // var topicType = "TestTopic";- // await agent.SubscribeAsync(topicType).ConfigureAwait(true);- // var subscriptions = await agent.GetSubscriptionsAsync().ConfigureAwait(true);- // var found = false;- // foreach (var subscription in subscriptions)- // {- // if (subscription.TypeSubscription.TopicType == topicType)- // {- // found = true;- // }- // }- // Assert.True(found);- // await agent.PublishMessageAsync(new TextMessage()- // {- // Source = topicType,- // TextMessage_ = "buffer"- // }, topicType).ConfigureAwait(true);- // await Task.Delay(100);- // Assert.True(TestAgent.ReceivedMessages.ContainsKey(topicType));- // fixture.Stop();- // }-- // [Fact]- // public async Task InvokeCorrectHandler()- // {- // var agent = new TestAgent(new AgentsMetadata(TypeRegistry.Empty, new Dictionary<string, Type>(), new Dictionary<Type, HashSet<string>>(), new Dictionary<Type, HashSet<string>>()), new Logger<Agent>(new LoggerFactory()));- // await agent.HandleObjectAsync("hello world");- // await agent.HandleObjectAsync(42);- // agent.ReceivedItems.Should().HaveCount(2);- // agent.ReceivedItems[0].Should().Be("hello world");- // agent.ReceivedItems[1].Should().Be(42);- // }-- // [Fact]- // public async Task DelegateMessageToTestAgentAsync()- // {- // var runtime = new InMemoryAgentRuntimeFixture();- // var client = runtime.AppHost.Services.GetRequiredService<Client>();- // await client.PublishMessageAsync(new TextMessage()- // {- // Source = nameof(DelegateMessageToTestAgentAsync),- // TextMessage_ = "buffer"- // }, token: CancellationToken.None);-- // // wait for 10 seconds- // var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));- // while (!TestAgent.ReceivedMessages.ContainsKey(nameof(DelegateMessageToTestAgentAsync)) && !cts.Token.IsCancellationRequested)- // {- // await Task.Delay(100);- // }-- // TestAgent.ReceivedMessages[nameof(DelegateMessageToTestAgentAsync)].Should().NotBeNull();- // }-- // [CollectionDefinition(Name)]- // public sealed class ClusterFixtureCollection : ICollectionFixture<InMemoryAgentRuntimeFixture>- // {- // public const string Name = nameof(ClusterFixtureCollection);- // }-}diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/PythonEquiv/TestAgent.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/PythonEquiv/TestAgent.csdeleted file mode 100644index ffbedd706..000000000--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/PythonEquiv/TestAgent.cs+++ /dev/null@@ -1,61 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// TestAgent.cs--using Microsoft.AutoGen.Contracts.Python;-using Microsoft.AutoGen.Core.Python;-using Microsoft.Extensions.Logging;--namespace Microsoft.AutoGen.Core.Tests.Python;--public class TextMessage-{- public string Source { get; set; } = "";- public string Content { get; set; } = "";-}--/// <summary>-/// The test agent is a simple agent that is used for testing purposes.-/// </summary>-public class TestAgent(AgentId id,- IAgentRuntime runtime,- Logger<BaseAgent>? logger = null) : BaseAgent(id, runtime, "Test Agent", logger),- Core.Python.IHandle<TextMessage>,- Core.Python.IHandle<string>,- Core.Python.IHandle<int>-{- public Task Handle(TextMessage item, MessageContext messageContext)- {- ReceivedMessages[item.Source] = item.Content;- return Task.CompletedTask;- }-- public Task Handle(string item, MessageContext messageContext)- {- ReceivedItems.Add(item);- return Task.CompletedTask;- }-- public Task Handle(int item, MessageContext messageContext)- {- ReceivedItems.Add(item);- return Task.CompletedTask;- }-- public List<object> ReceivedItems { get; private set; } = [];-- /// <summary>- /// Key: source- /// Value: message- /// </summary>- public static Dictionary<string, object> ReceivedMessages { get; private set; } = new();-}--[TypeSubscription("TestTopic")]-public class SubscribedAgent : TestAgent-{- public SubscribedAgent(AgentId id,- IAgentRuntime runtime,- Logger<BaseAgent>? logger = null) : base(id, runtime, logger)- {- }-}diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/RegistryStorageTests.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/RegistryStorageTests.csdeleted file mode 100644index f1024cefc..000000000--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/RegistryStorageTests.cs+++ /dev/null@@ -1,111 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// RegistryStorageTests.cs-using System.Collections.Concurrent;-using System.Text.Json;-using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.Logging;-using Moq;-using Xunit;--namespace Microsoft.AutoGen.Core.Tests;--public class RegistryStorageTests-{- private readonly Mock<ILogger<IRegistryStorage>> _loggerMock;- private readonly RegistryStorage _registryStorage;-- public RegistryStorageTests()- {- _loggerMock = new Mock<ILogger<IRegistryStorage>>();- _registryStorage = new RegistryStorage(_loggerMock.Object)- {- FilePath = "test_registry.json"- };- }-- [Fact]- public async Task ReadStateAsync_ShouldReturnEmptyState_WhenFileDoesNotExist()- {- // Arrange- if (File.Exists(_registryStorage.FilePath))- {- File.Delete(_registryStorage.FilePath);- }-- // Act- var state = await _registryStorage.ReadStateAsync();-- // Assert- Assert.NotNull(state);- Assert.Empty(state.AgentTypes);- }-- [Fact]- public async Task ReadStateAsync_ShouldReturnState_WhenFileExists()- {- // Arrange- if (File.Exists(_registryStorage.FilePath))- {- File.Delete(_registryStorage.FilePath);- }- var agentType = "agent1";- var expectedState = new AgentsRegistryState- {- Etag = Guid.NewGuid().ToString(),- AgentTypes = new ConcurrentDictionary<string, AgentId>- {- [agentType] = new AgentId() { Type = agentType, Key = Guid.NewGuid().ToString() }- }- };- var json = JsonSerializer.Serialize(expectedState);- await File.WriteAllTextAsync(_registryStorage.FilePath, json);-- // Act- var state = await _registryStorage.ReadStateAsync();-- // Assert- Assert.NotNull(state);- Assert.Single(state.AgentTypes);- Assert.Equal(agentType, state.AgentTypes.Keys.First());- }-- [Fact]- public async Task WriteStateAsync_ShouldWriteStateToFile()- {- // Arrange- if (File.Exists(_registryStorage.FilePath))- {- File.Delete(_registryStorage.FilePath);- }- var agentType = "agent1";- var state = await _registryStorage.ReadStateAsync();- state.AgentTypes.TryAdd(agentType, new AgentId() { Type = agentType, Key = Guid.NewGuid().ToString() });-- // Act- await _registryStorage.WriteStateAsync(state);-- // Assert- var json = await File.ReadAllTextAsync(_registryStorage.FilePath);- var writtenState = JsonSerializer.Deserialize<AgentsRegistryState>(json);- Assert.NotNull(writtenState);- Assert.Single(writtenState.AgentTypes);- Assert.Equal(agentType, writtenState.AgentTypes.Keys.First());- }-- [Fact]- public async Task WriteStateAsync_ShouldThrowException_WhenETagMismatch()- {- // Arrange- // Arrange- if (File.Exists(_registryStorage.FilePath))- {- File.Delete(_registryStorage.FilePath);- }- var initialState = await _registryStorage.ReadStateAsync();-- var newState = new AgentsRegistryState { Etag = "mismatch" };-- // Act & Assert- await Assert.ThrowsAsync<ArgumentException>(async () => await _registryStorage.WriteStateAsync(newState));- }-}diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/RegistryTests.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/RegistryTests.csdeleted file mode 100644index a6938b342..000000000--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/RegistryTests.cs+++ /dev/null@@ -1,160 +0,0 @@-// Copyright (c) Microsoft Corporation. All rights reserved.-// RegistryTests.cs--using System.Collections.Concurrent;-using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.Logging;-using Moq;-using Xunit;--namespace Microsoft.AutoGen.Core.Tests;--public class RegistryTests-{- private readonly Mock<IRegistryStorage> _storageMock;- private readonly Mock<ILogger<Registry>> _loggerMock;- private readonly Registry _registry;-- public RegistryTests()- {- _storageMock = new Mock<IRegistryStorage>();- _loggerMock = new Mock<ILogger<Registry>>();- _storageMock.Setup(s => s.ReadStateAsync(It.IsAny<CancellationToken>())).ReturnsAsync(new AgentsRegistryState());- _registry = new Registry(_storageMock.Object, _loggerMock.Object);- }-- [Fact]- public async Task GetSubscribedAndHandlingAgentsAsync_ShouldReturnEmptyList_WhenNoAgentsSubscribed()- {- // Arrange- var state = new AgentsRegistryState- {- TopicToAgentTypesMap = new ConcurrentDictionary<string, HashSet<string>>()- };- _storageMock.Setup(s => s.ReadStateAsync(CancellationToken.None)).ReturnsAsync(state);-- // Act- var agents = await _registry.GetSubscribedAndHandlingAgentsAsync("topic", "eventType");-- // Assert- Assert.Empty(agents);- }-- [Fact]- public async Task GetSubscribedAndHandlingAgentsAsync_ShouldReturnAgents_WhenAgentsSubscribed()- {- // Arrange- var agent1 = "agent1";- var agent2 = "agent2";- var topic = "topic";- var request = new AddSubscriptionRequest- {- Subscription = new Subscription- {- TypeSubscription = new TypeSubscription- {- AgentType = agent1,- TopicType = topic- }- }- };- await _registry.SubscribeAsync(request);- request.Subscription.TypeSubscription.AgentType = agent2;- await _registry.SubscribeAsync(request);-- // Act- var agents = await _registry.GetSubscribedAndHandlingAgentsAsync(topic, "eventType");-- // Assert- Assert.Equal(2, agents.Count);- Assert.Contains(agent1, agents);- Assert.Contains(agent2, agents);- }-- [Fact]- public async Task RegisterAgentTypeAsync_ShouldAddAgentType()- {- // Arrange- var agentTypeName = "TestAgent";- var agentType = Type.GetType(agentTypeName);-- var request = new RegisterAgentTypeRequest { Type = agentTypeName };- var fixture = new InMemoryAgentRuntimeFixture();- var (runtime, agent) = fixture.Start();-- // Act- await _registry.RegisterAgentTypeAsync(request, runtime);-- // Assert- _storageMock.Verify(s => s.WriteStateAsync(It.IsAny<AgentsRegistryState>(), It.IsAny<CancellationToken>()), Times.Once);- Assert.Contains(agentTypeName, _registry.State.AgentTypes.Keys);- fixture.Stop();- }-- [Fact]- public async Task SubscribeAsync_ShouldAddSubscription()- {- // Arrange- var request = new AddSubscriptionRequest- {- Subscription = new Subscription- {- TypeSubscription = new TypeSubscription- {- AgentType = "TestAgent",- TopicType = "TestTopic"- }- }- };-- // Act- await _registry.SubscribeAsync(request);-- // Assert- _storageMock.Verify(s => s.WriteStateAsync(It.IsAny<AgentsRegistryState>(), It.IsAny<CancellationToken>()), Times.Once);- Assert.Contains("TestAgent", _registry.State.AgentsToTopicsMap.Keys);- Assert.Contains("TestTopic", _registry.State.TopicToAgentTypesMap.Keys);- }-- [Fact]- public async Task UnsubscribeAsync_ShouldFail_WhenRequestIsInvalid()- {- // Arrange- var request = new RemoveSubscriptionRequest { Id = "invalid-guid" };-- // Act- var exception = await Assert.ThrowsAsync<InvalidOperationException>(async () => await _registry.UnsubscribeAsync(request).AsTask());- }-- [Fact]- public async Task UnsubscribeAsync_ShouldRemoveSubscription()- {- // Arrange- var topic = "TestTopic1";- var agent = "TestAgent1";- var request = new AddSubscriptionRequest- {- Subscription = new Subscription- {- TypeSubscription = new TypeSubscription- {- AgentType = agent,- TopicType = topic- }- }- };- await _registry.SubscribeAsync(request);- var subscriptions = await _registry.GetSubscriptionsAsync(new GetSubscriptionsRequest());- var subscriptionId = subscriptions.Where(- s => s.TypeSubscription.AgentType == agent && s.TypeSubscription.TopicType == topic- ).Select(s => s.Id).FirstOrDefault();- var removeRequest = new RemoveSubscriptionRequest { Id = subscriptionId };-- //Act- await _registry.UnsubscribeAsync(removeRequest);- subscriptions = await _registry.GetSubscriptionsAsync(new GetSubscriptionsRequest());-- // Assert subscriptions doesn't match for id- Assert.DoesNotContain(subscriptionId, subscriptions.Select(s => s.Id));- }-}diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgent.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgent.csindex 974e8a23b..8bdc18ea4 100644--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgent.cs+++ b/dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgent.cs@@ -1,61 +1,73 @@// Copyright (c) Microsoft Corporation. All rights reserved.// TestAgent.cs-using System.Collections.Concurrent;-using Google.Protobuf;-using Google.Protobuf.WellKnownTypes;using Microsoft.AutoGen.Contracts;-using Microsoft.Extensions.DependencyInjection;using Microsoft.Extensions.Logging;+namespace Microsoft.AutoGen.Core.Tests;++public class TextMessage+{+ public string Source { get; set; } = "";+ public string Content { get; set; } = "";+}++public class RpcTextMessage+{+ public string Source { get; set; } = "";+ public string Content { get; set; } = "";+}+/// <summary>/// The test agent is a simple agent that is used for testing purposes./// </summary>-public class TestAgent(- [FromKeyedServices("AgentsMetadata")] AgentsMetadata eventTypes,- Logger<Agent>? logger = null) : Agent(eventTypes, logger), IHandle<TextMessage>+public class TestAgent(AgentId id,+ IAgentRuntime runtime,+ Logger<BaseAgent>? logger = null) : BaseAgent(id, runtime, "Test Agent", logger),+ IHandle<TextMessage>,+ IHandle<string>,+ IHandle<RpcTextMessage, string>+{- public Task Handle(TextMessage item, CancellationToken cancellationToken = default)+ public Task Handle(TextMessage item, MessageContext messageContext){- ReceivedMessages[item.Source] = item.TextMessage_;+ ReceivedMessages[item.Source] = item.Content;return Task.CompletedTask;}- public Task Handle(string item)+ public Task Handle(string item, MessageContext messageContext){ReceivedItems.Add(item);return Task.CompletedTask;}- public Task Handle(int item)+ public Task Handle(int item, MessageContext messageContext){ReceivedItems.Add(item);return Task.CompletedTask;}- public override Task<RpcResponse> HandleRequestAsync(RpcRequest request)++ public Task<string> Handle(RpcTextMessage item, MessageContext messageContext){- var response = new RpcResponse- {- RequestId = request.RequestId,- Payload = new Payload { Data = Any.Pack(new TextMessage { TextMessage_ = "Response" }).ToByteString() }- };- return Task.FromResult(response);+ ReceivedMessages[item.Source] = item.Content;+ return Task.FromResult(item.Content);}+public List<object> ReceivedItems { get; private set; } = [];/// <summary>/// Key: source/// Value: message/// </summary>- public static ConcurrentDictionary<string, object> ReceivedMessages { get; private set; } = new();+ public static Dictionary<string, object> ReceivedMessages { get; private set; } = new();}-[TopicSubscription("TestEvent")]+[TypeSubscription("TestTopic")]public class SubscribedAgent : TestAgent{- public SubscribedAgent(- [FromKeyedServices("AgentsMetadata")] AgentsMetadata eventTypes,- Logger<Agent>? logger = null) : base(eventTypes, logger)+ public SubscribedAgent(AgentId id,+ IAgentRuntime runtime,+ Logger<BaseAgent>? logger = null) : base(id, runtime, logger){}}