| | | 1 | | // Copyright (c) NexusLabs. All rights reserved. |
| | | 2 | | // Licensed under the MIT License. |
| | | 3 | | |
| | | 4 | | using System.Collections.Generic; |
| | | 5 | | using System.Collections.Immutable; |
| | | 6 | | using System.Linq; |
| | | 7 | | using System.Text; |
| | | 8 | | |
| | | 9 | | namespace NexusLabs.Needlr.AgentFramework.Generators; |
| | | 10 | | |
| | | 11 | | internal static class ExtensionsCodeGenerator |
| | | 12 | | { |
| | | 13 | | public static string GenerateWorkflowFactoryExtensionsSource( |
| | | 14 | | Dictionary<(string InitialAgentTypeName, string InitialAgentClassName), List<(string TargetAgentTypeName, string |
| | | 15 | | Dictionary<string, List<string>> groupChatByGroupName, |
| | | 16 | | Dictionary<string, List<string>> sequenceByPipelineName, |
| | | 17 | | Dictionary<string, List<TerminationConditionEntry>> conditionsByAgentTypeName, |
| | | 18 | | Dictionary<string, GraphData> graphDataByName, |
| | | 19 | | string safeAssemblyName) |
| | | 20 | | { |
| | 101 | 21 | | var sb = new StringBuilder(); |
| | 101 | 22 | | sb.AppendLine("// <auto-generated/>"); |
| | 101 | 23 | | sb.AppendLine("// Needlr AgentFramework IWorkflowFactory Extension Methods"); |
| | 101 | 24 | | sb.AppendLine("#nullable enable"); |
| | 101 | 25 | | sb.AppendLine(); |
| | 101 | 26 | | sb.AppendLine("using Microsoft.Agents.AI.Workflows;"); |
| | 101 | 27 | | sb.AppendLine("using NexusLabs.Needlr.AgentFramework;"); |
| | 101 | 28 | | sb.AppendLine(); |
| | 101 | 29 | | sb.AppendLine($"namespace {safeAssemblyName}.Generated;"); |
| | 101 | 30 | | sb.AppendLine(); |
| | 101 | 31 | | sb.AppendLine("/// <summary>"); |
| | 101 | 32 | | sb.AppendLine("/// Generated strongly-typed extension methods on <see cref=\"IWorkflowFactory\"/>."); |
| | 101 | 33 | | sb.AppendLine("/// Each method encapsulates an agent type or group name so the composition root"); |
| | 101 | 34 | | sb.AppendLine("/// requires no direct agent type references or magic strings."); |
| | 101 | 35 | | sb.AppendLine("/// </summary>"); |
| | 101 | 36 | | sb.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.AgentFramework.Generat |
| | 101 | 37 | | sb.AppendLine("public static partial class WorkflowFactoryExtensions"); |
| | 101 | 38 | | sb.AppendLine("{"); |
| | | 39 | | |
| | 217 | 40 | | foreach (var kvp in handoffByInitialAgent.OrderBy(k => k.Key.InitialAgentClassName)) |
| | | 41 | | { |
| | 5 | 42 | | var className = kvp.Key.InitialAgentClassName; |
| | 5 | 43 | | var typeName = kvp.Key.InitialAgentTypeName; |
| | 5 | 44 | | var methodName = $"Create{AgentDiscoveryHelper.StripAgentSuffix(className)}HandoffWorkflow"; |
| | | 45 | | |
| | 5 | 46 | | sb.AppendLine($" /// <summary>"); |
| | 5 | 47 | | sb.AppendLine($" /// Creates a handoff workflow starting from <see cref=\"{typeName.Replace("global::", " |
| | 5 | 48 | | sb.AppendLine($" /// </summary>"); |
| | 5 | 49 | | sb.AppendLine($" /// <remarks>"); |
| | 5 | 50 | | sb.AppendLine($" /// Handoff targets declared via <see cref=\"global::NexusLabs.Needlr.AgentFramework.Age |
| | 5 | 51 | | sb.AppendLine($" /// <list type=\"bullet\">"); |
| | 20 | 52 | | foreach (var (targetTypeName, reason) in kvp.Value) |
| | | 53 | | { |
| | 5 | 54 | | var cref = targetTypeName.Replace("global::", ""); |
| | 5 | 55 | | if (string.IsNullOrEmpty(reason)) |
| | 4 | 56 | | sb.AppendLine($" /// <item><description><see cref=\"{cref}\"/></description></item>"); |
| | | 57 | | else |
| | 1 | 58 | | sb.AppendLine($" /// <item><description><see cref=\"{cref}\"/> — {reason}</description></item>"); |
| | | 59 | | } |
| | 5 | 60 | | sb.AppendLine($" /// </list>"); |
| | 5 | 61 | | sb.AppendLine($" /// </remarks>"); |
| | 5 | 62 | | sb.AppendLine($" public static Workflow {methodName}(this IWorkflowFactory workflowFactory)"); |
| | 5 | 63 | | sb.AppendLine($" => workflowFactory.CreateHandoffWorkflow<{typeName}>();"); |
| | 5 | 64 | | sb.AppendLine(); |
| | | 65 | | |
| | 5 | 66 | | var allHandoffAgents = new[] { typeName } |
| | 5 | 67 | | .Concat(kvp.Value.Select(v => v.TargetAgentTypeName)) |
| | 5 | 68 | | .ToList(); |
| | 5 | 69 | | var handoffConditions = allHandoffAgents |
| | 10 | 70 | | .SelectMany(t => conditionsByAgentTypeName.TryGetValue(t, out var c) ? c : Enumerable.Empty<TerminationC |
| | 5 | 71 | | .ToList(); |
| | | 72 | | |
| | 5 | 73 | | if (handoffConditions.Count > 0) |
| | | 74 | | { |
| | 1 | 75 | | var runMethodName = $"Run{AgentDiscoveryHelper.StripAgentSuffix(className)}HandoffWorkflowAsync"; |
| | 1 | 76 | | sb.AppendLine($" /// <summary>"); |
| | 1 | 77 | | sb.AppendLine($" /// Creates and runs the handoff workflow starting from <see cref=\"{typeName.Replac |
| | 1 | 78 | | sb.AppendLine($" /// </summary>"); |
| | 1 | 79 | | sb.AppendLine($" /// <remarks>"); |
| | 1 | 80 | | sb.AppendLine($" /// Termination conditions are evaluated after each completed agent turn (Layer 2)." |
| | 1 | 81 | | sb.AppendLine($" /// The workflow stops early when any condition is satisfied."); |
| | 1 | 82 | | sb.AppendLine($" /// </remarks>"); |
| | 1 | 83 | | sb.AppendLine($" /// <param name=\"workflowFactory\">The workflow factory.</param>"); |
| | 1 | 84 | | sb.AppendLine($" /// <param name=\"message\">The input message to start the workflow.</param>"); |
| | 1 | 85 | | sb.AppendLine($" /// <param name=\"cancellationToken\">Optional cancellation token.</param>"); |
| | 1 | 86 | | sb.AppendLine($" /// <returns>A dictionary mapping executor IDs to their response text.</returns>"); |
| | 1 | 87 | | sb.AppendLine($" public static async global::System.Threading.Tasks.Task<global::System.Collections.G |
| | 1 | 88 | | sb.AppendLine($" this IWorkflowFactory workflowFactory,"); |
| | 1 | 89 | | sb.AppendLine($" string message,"); |
| | 1 | 90 | | sb.AppendLine($" global::System.Threading.CancellationToken cancellationToken = default)"); |
| | 1 | 91 | | sb.AppendLine($" {{"); |
| | 1 | 92 | | sb.AppendLine($" var workflow = workflowFactory.{methodName}();"); |
| | 1 | 93 | | sb.AppendLine($" global::System.Collections.Generic.IReadOnlyList<global::NexusLabs.Needlr.AgentF |
| | 1 | 94 | | sb.AppendLine($" new global::System.Collections.Generic.List<global::NexusLabs.Needlr.AgentFr |
| | 1 | 95 | | sb.AppendLine($" {{"); |
| | 4 | 96 | | foreach (var cond in handoffConditions) |
| | | 97 | | { |
| | 1 | 98 | | var args = cond.CtorArgLiterals.IsEmpty ? "" : string.Join(", ", cond.CtorArgLiterals); |
| | 1 | 99 | | sb.AppendLine($" new {cond.ConditionTypeFQN}({args}),"); |
| | | 100 | | } |
| | 1 | 101 | | sb.AppendLine($" }};"); |
| | 1 | 102 | | sb.AppendLine($" return await global::NexusLabs.Needlr.AgentFramework.Workflows.StreamingRunWorkf |
| | 1 | 103 | | sb.AppendLine($" }}"); |
| | 1 | 104 | | sb.AppendLine(); |
| | | 105 | | } |
| | | 106 | | } |
| | | 107 | | |
| | 214 | 108 | | foreach (var kvp in groupChatByGroupName.OrderBy(k => k.Key)) |
| | | 109 | | { |
| | 4 | 110 | | var groupName = kvp.Key; |
| | 4 | 111 | | var methodSuffix = AgentDiscoveryHelper.GroupNameToPascalCase(groupName); |
| | 4 | 112 | | var methodName = $"Create{methodSuffix}GroupChatWorkflow"; |
| | 4 | 113 | | var escapedGroupName = groupName.Replace("\"", "\\\""); |
| | | 114 | | |
| | 4 | 115 | | sb.AppendLine($" /// <summary>"); |
| | 4 | 116 | | sb.AppendLine($" /// Creates a round-robin group chat workflow for the \"{escapedGroupName}\" group."); |
| | 4 | 117 | | sb.AppendLine($" /// </summary>"); |
| | 4 | 118 | | sb.AppendLine($" /// <remarks>"); |
| | 4 | 119 | | sb.AppendLine($" /// Participants declared via <see cref=\"global::NexusLabs.Needlr.AgentFramework.AgentG |
| | 4 | 120 | | sb.AppendLine($" /// <list type=\"bullet\">"); |
| | 24 | 121 | | foreach (var participantTypeName in kvp.Value) |
| | | 122 | | { |
| | 8 | 123 | | var cref = participantTypeName.Replace("global::", ""); |
| | 8 | 124 | | sb.AppendLine($" /// <item><description><see cref=\"{cref}\"/></description></item>"); |
| | | 125 | | } |
| | 4 | 126 | | sb.AppendLine($" /// </list>"); |
| | 4 | 127 | | sb.AppendLine($" /// </remarks>"); |
| | 4 | 128 | | sb.AppendLine($" public static Workflow {methodName}(this IWorkflowFactory workflowFactory, int maxIterat |
| | 4 | 129 | | sb.AppendLine($" => workflowFactory.CreateGroupChatWorkflow(\"{escapedGroupName}\", maxIterations);") |
| | 4 | 130 | | sb.AppendLine(); |
| | | 131 | | |
| | 4 | 132 | | var gcConditions = kvp.Value |
| | 8 | 133 | | .SelectMany(t => conditionsByAgentTypeName.TryGetValue(t, out var c) ? c : Enumerable.Empty<TerminationC |
| | 4 | 134 | | .ToList(); |
| | | 135 | | |
| | 4 | 136 | | if (gcConditions.Count > 0) |
| | | 137 | | { |
| | 1 | 138 | | var runMethodName = $"Run{methodSuffix}GroupChatWorkflowAsync"; |
| | 1 | 139 | | sb.AppendLine($" /// <summary>"); |
| | 1 | 140 | | sb.AppendLine($" /// Creates and runs the \"{escapedGroupName}\" group chat workflow, applying declar |
| | 1 | 141 | | sb.AppendLine($" /// </summary>"); |
| | 1 | 142 | | sb.AppendLine($" /// <remarks>"); |
| | 1 | 143 | | sb.AppendLine($" /// Termination conditions are evaluated after each completed agent turn (Layer 2)." |
| | 1 | 144 | | sb.AppendLine($" /// The workflow stops early when any condition is satisfied."); |
| | 1 | 145 | | sb.AppendLine($" /// </remarks>"); |
| | 1 | 146 | | sb.AppendLine($" /// <param name=\"workflowFactory\">The workflow factory.</param>"); |
| | 1 | 147 | | sb.AppendLine($" /// <param name=\"message\">The input message to start the workflow.</param>"); |
| | 1 | 148 | | sb.AppendLine($" /// <param name=\"maxIterations\">Maximum number of group chat iterations.</param>") |
| | 1 | 149 | | sb.AppendLine($" /// <param name=\"cancellationToken\">Optional cancellation token.</param>"); |
| | 1 | 150 | | sb.AppendLine($" /// <returns>A dictionary mapping executor IDs to their response text.</returns>"); |
| | 1 | 151 | | sb.AppendLine($" public static async global::System.Threading.Tasks.Task<global::System.Collections.G |
| | 1 | 152 | | sb.AppendLine($" this IWorkflowFactory workflowFactory,"); |
| | 1 | 153 | | sb.AppendLine($" string message,"); |
| | 1 | 154 | | sb.AppendLine($" int maxIterations = 10,"); |
| | 1 | 155 | | sb.AppendLine($" global::System.Threading.CancellationToken cancellationToken = default)"); |
| | 1 | 156 | | sb.AppendLine($" {{"); |
| | 1 | 157 | | sb.AppendLine($" var workflow = workflowFactory.{methodName}(maxIterations);"); |
| | 1 | 158 | | sb.AppendLine($" global::System.Collections.Generic.IReadOnlyList<global::NexusLabs.Needlr.AgentF |
| | 1 | 159 | | sb.AppendLine($" new global::System.Collections.Generic.List<global::NexusLabs.Needlr.AgentFr |
| | 1 | 160 | | sb.AppendLine($" {{"); |
| | 4 | 161 | | foreach (var cond in gcConditions) |
| | | 162 | | { |
| | 1 | 163 | | var args = cond.CtorArgLiterals.IsEmpty ? "" : string.Join(", ", cond.CtorArgLiterals); |
| | 1 | 164 | | sb.AppendLine($" new {cond.ConditionTypeFQN}({args}),"); |
| | | 165 | | } |
| | 1 | 166 | | sb.AppendLine($" }};"); |
| | 1 | 167 | | sb.AppendLine($" return await global::NexusLabs.Needlr.AgentFramework.Workflows.StreamingRunWorkf |
| | 1 | 168 | | sb.AppendLine($" }}"); |
| | 1 | 169 | | sb.AppendLine(); |
| | | 170 | | } |
| | | 171 | | } |
| | | 172 | | |
| | 241 | 173 | | foreach (var kvp in sequenceByPipelineName.OrderBy(k => k.Key)) |
| | | 174 | | { |
| | 13 | 175 | | var pipelineName = kvp.Key; |
| | 13 | 176 | | var methodSuffix = AgentDiscoveryHelper.GroupNameToPascalCase(pipelineName); |
| | 13 | 177 | | var methodName = $"Create{methodSuffix}SequentialWorkflow"; |
| | 13 | 178 | | var escapedPipelineName = pipelineName.Replace("\"", "\\\""); |
| | | 179 | | |
| | 13 | 180 | | sb.AppendLine($" /// <summary>"); |
| | 13 | 181 | | sb.AppendLine($" /// Creates a sequential pipeline workflow for the \"{escapedPipelineName}\" pipeline.") |
| | 13 | 182 | | sb.AppendLine($" /// </summary>"); |
| | 13 | 183 | | sb.AppendLine($" /// <remarks>"); |
| | 13 | 184 | | sb.AppendLine($" /// Agents declared via <see cref=\"global::NexusLabs.Needlr.AgentFramework.AgentSequenc |
| | 13 | 185 | | sb.AppendLine($" /// <list type=\"number\">"); |
| | 74 | 186 | | foreach (var memberTypeName in kvp.Value) |
| | | 187 | | { |
| | 24 | 188 | | var cref = memberTypeName.Replace("global::", ""); |
| | 24 | 189 | | sb.AppendLine($" /// <item><description><see cref=\"{cref}\"/></description></item>"); |
| | | 190 | | } |
| | 13 | 191 | | sb.AppendLine($" /// </list>"); |
| | 13 | 192 | | sb.AppendLine($" /// </remarks>"); |
| | 13 | 193 | | sb.AppendLine($" public static Workflow {methodName}(this IWorkflowFactory workflowFactory)"); |
| | 13 | 194 | | sb.AppendLine($" => workflowFactory.CreateSequentialWorkflow(\"{escapedPipelineName}\");"); |
| | 13 | 195 | | sb.AppendLine(); |
| | | 196 | | |
| | 13 | 197 | | var seqConditions = kvp.Value |
| | 24 | 198 | | .SelectMany(t => conditionsByAgentTypeName.TryGetValue(t, out var c) ? c : Enumerable.Empty<TerminationC |
| | 13 | 199 | | .ToList(); |
| | | 200 | | |
| | 13 | 201 | | if (seqConditions.Count > 0) |
| | | 202 | | { |
| | 5 | 203 | | var runMethodName = $"Run{methodSuffix}SequentialWorkflowAsync"; |
| | 5 | 204 | | sb.AppendLine($" /// <summary>"); |
| | 5 | 205 | | sb.AppendLine($" /// Creates and runs the \"{escapedPipelineName}\" sequential workflow, applying dec |
| | 5 | 206 | | sb.AppendLine($" /// </summary>"); |
| | 5 | 207 | | sb.AppendLine($" /// <remarks>"); |
| | 5 | 208 | | sb.AppendLine($" /// Termination conditions are evaluated after each completed agent turn (Layer 2)." |
| | 5 | 209 | | sb.AppendLine($" /// The workflow stops early when any condition is satisfied."); |
| | 5 | 210 | | sb.AppendLine($" /// </remarks>"); |
| | 5 | 211 | | sb.AppendLine($" /// <param name=\"workflowFactory\">The workflow factory.</param>"); |
| | 5 | 212 | | sb.AppendLine($" /// <param name=\"message\">The input message to start the workflow.</param>"); |
| | 5 | 213 | | sb.AppendLine($" /// <param name=\"cancellationToken\">Optional cancellation token.</param>"); |
| | 5 | 214 | | sb.AppendLine($" /// <returns>A dictionary mapping executor IDs to their response text.</returns>"); |
| | 5 | 215 | | sb.AppendLine($" public static async global::System.Threading.Tasks.Task<global::System.Collections.G |
| | 5 | 216 | | sb.AppendLine($" this IWorkflowFactory workflowFactory,"); |
| | 5 | 217 | | sb.AppendLine($" string message,"); |
| | 5 | 218 | | sb.AppendLine($" global::System.Threading.CancellationToken cancellationToken = default)"); |
| | 5 | 219 | | sb.AppendLine($" {{"); |
| | 5 | 220 | | sb.AppendLine($" var workflow = workflowFactory.{methodName}();"); |
| | 5 | 221 | | sb.AppendLine($" global::System.Collections.Generic.IReadOnlyList<global::NexusLabs.Needlr.AgentF |
| | 5 | 222 | | sb.AppendLine($" new global::System.Collections.Generic.List<global::NexusLabs.Needlr.AgentFr |
| | 5 | 223 | | sb.AppendLine($" {{"); |
| | 22 | 224 | | foreach (var cond in seqConditions) |
| | | 225 | | { |
| | 6 | 226 | | var args = cond.CtorArgLiterals.IsEmpty ? "" : string.Join(", ", cond.CtorArgLiterals); |
| | 6 | 227 | | sb.AppendLine($" new {cond.ConditionTypeFQN}({args}),"); |
| | | 228 | | } |
| | 5 | 229 | | sb.AppendLine($" }};"); |
| | 5 | 230 | | sb.AppendLine($" return await global::NexusLabs.Needlr.AgentFramework.Workflows.StreamingRunWorkf |
| | 5 | 231 | | sb.AppendLine($" }}"); |
| | 5 | 232 | | sb.AppendLine(); |
| | | 233 | | } |
| | | 234 | | } |
| | | 235 | | |
| | 265 | 236 | | foreach (var kvp in graphDataByName.OrderBy(k => k.Key)) |
| | | 237 | | { |
| | 21 | 238 | | var graphName = kvp.Key; |
| | 21 | 239 | | var graphData = kvp.Value; |
| | 21 | 240 | | var methodSuffix = AgentDiscoveryHelper.GroupNameToPascalCase(graphName); |
| | 21 | 241 | | var methodName = $"Create{methodSuffix}GraphWorkflow"; |
| | 21 | 242 | | var escapedGraphName = graphName.Replace("\"", "\\\""); |
| | | 243 | | |
| | 21 | 244 | | sb.AppendLine($" /// <summary>"); |
| | 21 | 245 | | sb.AppendLine($" /// Creates a DAG graph workflow for the \"{escapedGraphName}\" graph."); |
| | 21 | 246 | | sb.AppendLine($" /// </summary>"); |
| | 21 | 247 | | sb.AppendLine($" /// <remarks>"); |
| | 21 | 248 | | sb.AppendLine($" /// Topology declared via <see cref=\"global::NexusLabs.Needlr.AgentFramework.AgentGraph |
| | 21 | 249 | | sb.AppendLine($" /// <list type=\"bullet\">"); |
| | 88 | 250 | | foreach (var edge in graphData.Edges) |
| | | 251 | | { |
| | 23 | 252 | | var sourceCref = AgentDiscoveryHelper.GetShortName(edge.SourceAgentTypeName); |
| | 23 | 253 | | var targetCref = AgentDiscoveryHelper.GetShortName(edge.TargetAgentTypeName); |
| | 23 | 254 | | if (string.IsNullOrEmpty(edge.Condition)) |
| | 17 | 255 | | sb.AppendLine($" /// <item><description>{sourceCref} -> {targetCref}</description></item>"); |
| | | 256 | | else |
| | 6 | 257 | | sb.AppendLine($" /// <item><description>{sourceCref} -> {targetCref} (condition: {edge.Condition} |
| | | 258 | | } |
| | 21 | 259 | | sb.AppendLine($" /// </list>"); |
| | 21 | 260 | | sb.AppendLine($" /// </remarks>"); |
| | 21 | 261 | | sb.AppendLine($" public static global::Microsoft.Agents.AI.Workflows.Workflow {methodName}(this global::N |
| | 21 | 262 | | sb.AppendLine($" => workflowFactory.CreateGraphWorkflow(\"{escapedGraphName}\");"); |
| | 21 | 263 | | sb.AppendLine(); |
| | | 264 | | |
| | | 265 | | // Run helper — thin convenience wrapper that bakes in the graph name at compile time |
| | 21 | 266 | | var runMethodName = $"Run{methodSuffix}GraphWorkflowAsync"; |
| | 21 | 267 | | sb.AppendLine($" /// <summary>"); |
| | 21 | 268 | | sb.AppendLine($" /// Runs the \"{escapedGraphName}\" graph workflow via <see cref=\"global::NexusLabs.Nee |
| | 21 | 269 | | sb.AppendLine($" /// The graph name is baked in at compile time — no magic strings required."); |
| | 21 | 270 | | sb.AppendLine($" /// </summary>"); |
| | 21 | 271 | | sb.AppendLine($" /// <param name=\"runner\">The graph workflow runner.</param>"); |
| | 21 | 272 | | sb.AppendLine($" /// <param name=\"input\">The input message to send to the entry node.</param>"); |
| | 21 | 273 | | sb.AppendLine($" /// <param name=\"progress\">Optional progress reporter for real-time execution events.< |
| | 21 | 274 | | sb.AppendLine($" /// <param name=\"cancellationToken\">Cancellation token.</param>"); |
| | 21 | 275 | | sb.AppendLine($" /// <returns>An <see cref=\"global::NexusLabs.Needlr.AgentFramework.Diagnostics.IDagRunR |
| | 21 | 276 | | sb.AppendLine($" public static async global::System.Threading.Tasks.Task<global::NexusLabs.Needlr.AgentFr |
| | 21 | 277 | | sb.AppendLine($" this global::NexusLabs.Needlr.AgentFramework.IGraphWorkflowRunner runner,"); |
| | 21 | 278 | | sb.AppendLine($" string input,"); |
| | 21 | 279 | | sb.AppendLine($" global::NexusLabs.Needlr.AgentFramework.Progress.IProgressReporter? progress = null, |
| | 21 | 280 | | sb.AppendLine($" global::System.Threading.CancellationToken cancellationToken = default)"); |
| | 21 | 281 | | sb.AppendLine($" => await runner.RunGraphAsync(\"{escapedGraphName}\", input, progress, cancellationT |
| | 21 | 282 | | sb.AppendLine(); |
| | | 283 | | } |
| | | 284 | | |
| | 101 | 285 | | sb.AppendLine("}"); |
| | 101 | 286 | | return sb.ToString(); |
| | | 287 | | } |
| | | 288 | | |
| | | 289 | | public static string GenerateAgentFactoryExtensionsSource( |
| | | 290 | | List<NeedlrAiAgentTypeInfo> agents, |
| | | 291 | | Dictionary<string, ImmutableArray<string>> progressSinksByAgent, |
| | | 292 | | string safeAssemblyName) |
| | | 293 | | { |
| | 101 | 294 | | var sb = new StringBuilder(); |
| | 101 | 295 | | sb.AppendLine("// <auto-generated/>"); |
| | 101 | 296 | | sb.AppendLine("// Needlr AgentFramework IAgentFactory Extension Methods"); |
| | 101 | 297 | | sb.AppendLine("#nullable enable"); |
| | 101 | 298 | | sb.AppendLine(); |
| | 101 | 299 | | sb.AppendLine("using Microsoft.Agents.AI;"); |
| | 101 | 300 | | sb.AppendLine("using NexusLabs.Needlr.AgentFramework;"); |
| | 101 | 301 | | sb.AppendLine(); |
| | 101 | 302 | | sb.AppendLine($"namespace {safeAssemblyName}.Generated;"); |
| | 101 | 303 | | sb.AppendLine(); |
| | 101 | 304 | | sb.AppendLine("/// <summary>"); |
| | 101 | 305 | | sb.AppendLine("/// Generated strongly-typed extension methods on <see cref=\"IAgentFactory\"/>."); |
| | 101 | 306 | | sb.AppendLine("/// Each method creates an agent from its <c>[NeedlrAiAgent]</c> declaration,"); |
| | 101 | 307 | | sb.AppendLine("/// eliminating magic strings and direct type references at the composition root."); |
| | 101 | 308 | | sb.AppendLine("/// </summary>"); |
| | 101 | 309 | | sb.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.AgentFramework.Generat |
| | 101 | 310 | | sb.AppendLine("public static class GeneratedAgentFactoryExtensions"); |
| | 101 | 311 | | sb.AppendLine("{"); |
| | | 312 | | |
| | 523 | 313 | | foreach (var agent in agents.OrderBy(a => a.ClassName)) |
| | | 314 | | { |
| | 107 | 315 | | sb.AppendLine($" /// <summary>"); |
| | 107 | 316 | | sb.AppendLine($" /// Creates an <see cref=\"AIAgent\"/> configured for <see cref=\"{agent.TypeName.Replac |
| | 107 | 317 | | sb.AppendLine($" /// </summary>"); |
| | 107 | 318 | | sb.AppendLine($" public static AIAgent Create{agent.ClassName}(this IAgentFactory factory)"); |
| | 107 | 319 | | sb.AppendLine($" => factory.CreateAgent<{agent.TypeName}>();"); |
| | 107 | 320 | | sb.AppendLine(); |
| | | 321 | | |
| | | 322 | | // If this agent has [ProgressSinks], emit a companion method |
| | 107 | 323 | | if (progressSinksByAgent.TryGetValue(agent.ClassName, out var sinkFQNs) && sinkFQNs.Length > 0) |
| | | 324 | | { |
| | 4 | 325 | | sb.AppendLine($" /// <summary>"); |
| | 4 | 326 | | sb.AppendLine($" /// Returns the progress sink types declared via <c>[ProgressSinks]</c> on <see cref |
| | 4 | 327 | | sb.AppendLine($" /// Orchestrators use this to create reporters with the correct sinks for this agent |
| | 4 | 328 | | sb.AppendLine($" /// </summary>"); |
| | 4 | 329 | | sb.AppendLine($" public static global::System.Type[] Get{agent.ClassName}ProgressSinkTypes()"); |
| | 4 | 330 | | sb.AppendLine(" {"); |
| | 4 | 331 | | sb.AppendLine(" return new global::System.Type[]"); |
| | 4 | 332 | | sb.AppendLine(" {"); |
| | 16 | 333 | | foreach (var sinkFQN in sinkFQNs) |
| | | 334 | | { |
| | 4 | 335 | | sb.AppendLine($" typeof({sinkFQN}),"); |
| | | 336 | | } |
| | 4 | 337 | | sb.AppendLine(" };"); |
| | 4 | 338 | | sb.AppendLine(" }"); |
| | 4 | 339 | | sb.AppendLine(); |
| | | 340 | | |
| | | 341 | | // Auto-wiring method: resolves sinks from DI, creates reporter, sets scope. |
| | | 342 | | // The returned IDisposable is a CompositeDisposable that tears down both the |
| | | 343 | | // reporter accessor scope AND any sink instances that implement IDisposable, |
| | | 344 | | // preventing leaks of sinks instantiated via ActivatorUtilities. |
| | 4 | 345 | | sb.AppendLine($" /// <summary>"); |
| | 4 | 346 | | sb.AppendLine($" /// Opens a progress reporting scope for <see cref=\"{agent.TypeName.Replace("global |
| | 4 | 347 | | sb.AppendLine($" /// the sinks declared via <c>[ProgressSinks]</c>. Dispose the returned handle to en |
| | 4 | 348 | | sb.AppendLine($" /// and dispose any sinks that implement <see cref=\"global::System.IDisposable\"/>. |
| | 4 | 349 | | sb.AppendLine($" /// </summary>"); |
| | 4 | 350 | | sb.AppendLine($" public static global::System.IDisposable Begin{agent.ClassName}ProgressScope("); |
| | 4 | 351 | | sb.AppendLine($" this global::System.IServiceProvider sp,"); |
| | 4 | 352 | | sb.AppendLine($" string? workflowId = null)"); |
| | 4 | 353 | | sb.AppendLine(" {"); |
| | | 354 | | // Materialize each sink into its own local so we can pass them both to the |
| | | 355 | | // IProgressSink[] array AND as 'as IDisposable' casts to the composite. |
| | 16 | 356 | | for (int i = 0; i < sinkFQNs.Length; i++) |
| | | 357 | | { |
| | 4 | 358 | | sb.AppendLine($" var sink{i} = global::Microsoft.Extensions.DependencyInjection.ActivatorUtil |
| | | 359 | | } |
| | 4 | 360 | | sb.AppendLine($" var sinks = new global::NexusLabs.Needlr.AgentFramework.Progress.IProgressSink[] |
| | 4 | 361 | | sb.AppendLine(" {"); |
| | 16 | 362 | | for (int i = 0; i < sinkFQNs.Length; i++) |
| | | 363 | | { |
| | 4 | 364 | | sb.AppendLine($" sink{i},"); |
| | | 365 | | } |
| | 4 | 366 | | sb.AppendLine(" };"); |
| | 4 | 367 | | sb.AppendLine($" var factory = global::Microsoft.Extensions.DependencyInjection.ServiceProviderSe |
| | 4 | 368 | | sb.AppendLine($" var accessor = global::Microsoft.Extensions.DependencyInjection.ServiceProviderS |
| | 4 | 369 | | sb.AppendLine(" var reporter = factory.Create(workflowId ?? \"" + agent.ClassName + "-\" + global |
| | 4 | 370 | | sb.AppendLine(" var scopeHandle = accessor.BeginScope(reporter);"); |
| | 4 | 371 | | sb.AppendLine(" return new global::NexusLabs.Needlr.AgentFramework.Progress.CompositeDisposable(" |
| | 4 | 372 | | sb.AppendLine(" new global::System.IDisposable?[]"); |
| | 4 | 373 | | sb.AppendLine(" {"); |
| | 4 | 374 | | sb.AppendLine(" scopeHandle,"); |
| | | 375 | | // Box through object so the 'as IDisposable' cast compiles regardless |
| | | 376 | | // of whether the sealed sink type statically implements IDisposable. |
| | | 377 | | // Sinks that don't implement IDisposable become null and are skipped |
| | | 378 | | // by CompositeDisposable's null-tolerant disposal loop. |
| | 16 | 379 | | for (int i = 0; i < sinkFQNs.Length; i++) |
| | | 380 | | { |
| | 4 | 381 | | sb.AppendLine($" ((object)sink{i}) as global::System.IDisposable,"); |
| | | 382 | | } |
| | 4 | 383 | | sb.AppendLine(" });"); |
| | 4 | 384 | | sb.AppendLine(" }"); |
| | 4 | 385 | | sb.AppendLine(); |
| | | 386 | | } |
| | | 387 | | } |
| | | 388 | | |
| | 101 | 389 | | sb.AppendLine("}"); |
| | 101 | 390 | | return sb.ToString(); |
| | | 391 | | } |
| | | 392 | | |
| | | 393 | | public static string GenerateProgressSinkRegistrationSource( |
| | | 394 | | Dictionary<string, ImmutableArray<string>> progressSinksByAgent, |
| | | 395 | | string safeAssemblyName) |
| | | 396 | | { |
| | | 397 | | // Collect all unique sink types across all agents |
| | 3 | 398 | | var allSinkFQNs = progressSinksByAgent.Values |
| | 4 | 399 | | .SelectMany(v => v) |
| | 3 | 400 | | .Distinct() |
| | 2 | 401 | | .OrderBy(s => s) |
| | 3 | 402 | | .ToList(); |
| | | 403 | | |
| | 3 | 404 | | var sb = new StringBuilder(); |
| | 3 | 405 | | sb.AppendLine("// <auto-generated/>"); |
| | 3 | 406 | | sb.AppendLine("// Needlr AgentFramework Progress Sink DI Registration"); |
| | 3 | 407 | | sb.AppendLine("#nullable enable"); |
| | 3 | 408 | | sb.AppendLine(); |
| | 3 | 409 | | sb.AppendLine("using Microsoft.Extensions.DependencyInjection;"); |
| | 3 | 410 | | sb.AppendLine("using Microsoft.Extensions.DependencyInjection.Extensions;"); |
| | 3 | 411 | | sb.AppendLine(); |
| | 3 | 412 | | sb.AppendLine($"namespace {safeAssemblyName}.Generated;"); |
| | 3 | 413 | | sb.AppendLine(); |
| | 3 | 414 | | sb.AppendLine("/// <summary>"); |
| | 3 | 415 | | sb.AppendLine("/// Registers all progress sink types discovered via <c>[ProgressSinks]</c> attributes."); |
| | 3 | 416 | | sb.AppendLine("/// Call from your composition root to register all agent-declared sinks in DI."); |
| | 3 | 417 | | sb.AppendLine("/// </summary>"); |
| | 3 | 418 | | sb.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.AgentFramework.Generat |
| | 3 | 419 | | sb.AppendLine("public static class GeneratedProgressSinkRegistrations"); |
| | 3 | 420 | | sb.AppendLine("{"); |
| | 3 | 421 | | sb.AppendLine(" /// <summary>"); |
| | 3 | 422 | | sb.AppendLine(" /// Registers all sink types found on [ProgressSinks] agent attributes as singletons."); |
| | 3 | 423 | | sb.AppendLine(" /// </summary>"); |
| | 3 | 424 | | sb.AppendLine(" public static global::Microsoft.Extensions.DependencyInjection.IServiceCollection AddGenerate |
| | 3 | 425 | | sb.AppendLine(" this global::Microsoft.Extensions.DependencyInjection.IServiceCollection services)"); |
| | 3 | 426 | | sb.AppendLine(" {"); |
| | | 427 | | |
| | 3 | 428 | | if (allSinkFQNs.Count == 0) |
| | | 429 | | { |
| | 0 | 430 | | sb.AppendLine(" // No [ProgressSinks] attributes found."); |
| | | 431 | | } |
| | | 432 | | else |
| | | 433 | | { |
| | | 434 | | // Register each concrete sink as a singleton once, then expose it via |
| | | 435 | | // AddSingleton<IProgressSink>(factory) so multiple sinks stack in |
| | | 436 | | // GetServices<IProgressSink>(). TryAddSingleton<IProgressSink, T>() |
| | | 437 | | // would silently drop every sink after the first. |
| | 14 | 438 | | foreach (var sinkFQN in allSinkFQNs) |
| | | 439 | | { |
| | 4 | 440 | | sb.AppendLine($" services.TryAddSingleton<{sinkFQN}>();"); |
| | 4 | 441 | | sb.AppendLine($" services.AddSingleton<global::NexusLabs.Needlr.AgentFramework.Progress.IProgress |
| | | 442 | | } |
| | | 443 | | } |
| | | 444 | | |
| | 3 | 445 | | sb.AppendLine(" return services;"); |
| | 3 | 446 | | sb.AppendLine(" }"); |
| | 3 | 447 | | sb.AppendLine("}"); |
| | 3 | 448 | | return sb.ToString(); |
| | | 449 | | } |
| | | 450 | | |
| | | 451 | | public static string GenerateAgentTopologyConstantsSource( |
| | | 452 | | List<NeedlrAiAgentTypeInfo> agents, |
| | | 453 | | List<AgentFunctionGroupEntry> groupEntries, |
| | | 454 | | Dictionary<string, List<string>> sequenceByPipelineName, |
| | | 455 | | IEnumerable<string> graphNames, |
| | | 456 | | string safeAssemblyName) |
| | | 457 | | { |
| | 101 | 458 | | var sb = new StringBuilder(); |
| | 101 | 459 | | sb.AppendLine("// <auto-generated/>"); |
| | 101 | 460 | | sb.AppendLine("// Needlr AgentFramework Topology Constants"); |
| | 101 | 461 | | sb.AppendLine("#nullable enable"); |
| | 101 | 462 | | sb.AppendLine(); |
| | 101 | 463 | | sb.AppendLine($"namespace {safeAssemblyName}.Generated;"); |
| | 101 | 464 | | sb.AppendLine(); |
| | | 465 | | |
| | 101 | 466 | | sb.AppendLine("/// <summary>String constants for agent type names discovered at compile time.</summary>"); |
| | 101 | 467 | | sb.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.AgentFramework.Generat |
| | 101 | 468 | | sb.AppendLine("public static class AgentNames"); |
| | 101 | 469 | | sb.AppendLine("{"); |
| | 523 | 470 | | foreach (var agent in agents.OrderBy(a => a.ClassName)) |
| | | 471 | | { |
| | 107 | 472 | | var fullName = agent.NamespaceName is not null |
| | 107 | 473 | | ? $"{agent.NamespaceName}.{agent.ClassName}" |
| | 107 | 474 | | : agent.ClassName; |
| | 107 | 475 | | var escapedFullName = fullName.Replace("\"", "\\\""); |
| | 107 | 476 | | sb.AppendLine($" /// <summary>The fully-qualified name of <see cref=\"{agent.TypeName.Replace("global::", |
| | 107 | 477 | | sb.AppendLine($" public const string {agent.ClassName} = \"{escapedFullName}\";"); |
| | | 478 | | } |
| | 101 | 479 | | sb.AppendLine("}"); |
| | 101 | 480 | | sb.AppendLine(); |
| | | 481 | | |
| | 119 | 482 | | var groupNames = groupEntries.Select(e => e.GroupName).Distinct().OrderBy(g => g).ToList(); |
| | 101 | 483 | | sb.AppendLine("/// <summary>String constants for function group names discovered at compile time.</summary>"); |
| | 101 | 484 | | sb.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.AgentFramework.Generat |
| | 101 | 485 | | sb.AppendLine("public static class GroupNames"); |
| | 101 | 486 | | sb.AppendLine("{"); |
| | 228 | 487 | | foreach (var gn in groupNames) |
| | | 488 | | { |
| | 13 | 489 | | var propName = AgentDiscoveryHelper.GroupNameToPascalCase(gn); |
| | 13 | 490 | | var escaped = gn.Replace("\"", "\\\""); |
| | 13 | 491 | | sb.AppendLine($" /// <summary>The group name <c>\"{escaped}\"</c>.</summary>"); |
| | 13 | 492 | | sb.AppendLine($" public const string {propName} = \"{escaped}\";"); |
| | | 493 | | } |
| | 101 | 494 | | sb.AppendLine("}"); |
| | 101 | 495 | | sb.AppendLine(); |
| | | 496 | | |
| | 101 | 497 | | sb.AppendLine("/// <summary>String constants for sequential pipeline names discovered at compile time.</summary> |
| | 101 | 498 | | sb.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.AgentFramework.Generat |
| | 101 | 499 | | sb.AppendLine("public static class PipelineNames"); |
| | 101 | 500 | | sb.AppendLine("{"); |
| | 241 | 501 | | foreach (var pn in sequenceByPipelineName.Keys.OrderBy(k => k)) |
| | | 502 | | { |
| | 13 | 503 | | var propName = AgentDiscoveryHelper.GroupNameToPascalCase(pn); |
| | 13 | 504 | | var escaped = pn.Replace("\"", "\\\""); |
| | 13 | 505 | | sb.AppendLine($" /// <summary>The pipeline name <c>\"{escaped}\"</c>.</summary>"); |
| | 13 | 506 | | sb.AppendLine($" public const string {propName} = \"{escaped}\";"); |
| | | 507 | | } |
| | 101 | 508 | | sb.AppendLine("}"); |
| | 101 | 509 | | sb.AppendLine(); |
| | | 510 | | |
| | 101 | 511 | | sb.AppendLine("/// <summary>String constants for graph names discovered at compile time.</summary>"); |
| | 101 | 512 | | sb.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.AgentFramework.Generat |
| | 101 | 513 | | sb.AppendLine("public static class GraphNames"); |
| | 101 | 514 | | sb.AppendLine("{"); |
| | 265 | 515 | | foreach (var gn in graphNames.OrderBy(k => k)) |
| | | 516 | | { |
| | 21 | 517 | | var propName = AgentDiscoveryHelper.GroupNameToPascalCase(gn); |
| | 21 | 518 | | var escaped = gn.Replace("\"", "\\\""); |
| | 21 | 519 | | sb.AppendLine($" /// <summary>The graph name <c>\"{escaped}\"</c>.</summary>"); |
| | 21 | 520 | | sb.AppendLine($" public const string {propName} = \"{escaped}\";"); |
| | | 521 | | } |
| | 101 | 522 | | sb.AppendLine("}"); |
| | | 523 | | |
| | 101 | 524 | | return sb.ToString(); |
| | | 525 | | } |
| | | 526 | | |
| | | 527 | | public static string GenerateSyringeExtensionsSource( |
| | | 528 | | List<AgentFunctionGroupEntry> groupEntries, |
| | | 529 | | string safeAssemblyName) |
| | | 530 | | { |
| | 101 | 531 | | var sb = new StringBuilder(); |
| | 101 | 532 | | sb.AppendLine("// <auto-generated/>"); |
| | 101 | 533 | | sb.AppendLine("// Needlr AgentFramework AgentFrameworkSyringe Extension Methods"); |
| | 101 | 534 | | sb.AppendLine("#nullable enable"); |
| | 101 | 535 | | sb.AppendLine(); |
| | 101 | 536 | | sb.AppendLine("using System.Diagnostics.CodeAnalysis;"); |
| | 101 | 537 | | sb.AppendLine("using NexusLabs.Needlr.AgentFramework;"); |
| | 101 | 538 | | sb.AppendLine(); |
| | 101 | 539 | | sb.AppendLine($"namespace {safeAssemblyName}.Generated;"); |
| | 101 | 540 | | sb.AppendLine(); |
| | 101 | 541 | | sb.AppendLine("/// <summary>"); |
| | 101 | 542 | | sb.AppendLine("/// Generated strongly-typed extension methods on <see cref=\"AgentFrameworkSyringe\"/>."); |
| | 101 | 543 | | sb.AppendLine("/// Each method registers a named function group without requiring direct type references."); |
| | 101 | 544 | | sb.AppendLine("/// </summary>"); |
| | 101 | 545 | | sb.AppendLine("[global::System.CodeDom.Compiler.GeneratedCodeAttribute(\"NexusLabs.Needlr.AgentFramework.Generat |
| | 101 | 546 | | sb.AppendLine("public static class GeneratedAgentFrameworkSyringeExtensions"); |
| | 101 | 547 | | sb.AppendLine("{"); |
| | | 548 | | |
| | 101 | 549 | | var byGroupName = groupEntries |
| | 14 | 550 | | .GroupBy(e => e.GroupName) |
| | 114 | 551 | | .OrderBy(g => g.Key); |
| | | 552 | | |
| | 228 | 553 | | foreach (var grp in byGroupName) |
| | | 554 | | { |
| | 13 | 555 | | var methodName = $"With{AgentDiscoveryHelper.GroupNameToPascalCase(grp.Key)}"; |
| | 13 | 556 | | var escapedGroupName = grp.Key.Replace("\"", "\\\""); |
| | 27 | 557 | | var types = grp.Select(e => e.TypeName).Distinct().ToList(); |
| | | 558 | | |
| | 13 | 559 | | sb.AppendLine($" /// <summary>Registers the '{escapedGroupName}' function group with the syringe.</summar |
| | 13 | 560 | | sb.AppendLine($" [RequiresUnreferencedCode(\"AgentFramework function setup uses reflection to discover [A |
| | 13 | 561 | | sb.AppendLine($" [RequiresDynamicCode(\"AgentFramework function setup uses reflection APIs that require d |
| | 13 | 562 | | sb.AppendLine($" public static AgentFrameworkSyringe {methodName}(this AgentFrameworkSyringe syringe)"); |
| | 27 | 563 | | sb.AppendLine($" => syringe.AddAgentFunctions(new global::System.Type[] {{ {string.Join(", ", types.S |
| | 13 | 564 | | sb.AppendLine(); |
| | | 565 | | } |
| | | 566 | | |
| | 101 | 567 | | sb.AppendLine("}"); |
| | 101 | 568 | | return sb.ToString(); |
| | | 569 | | } |
| | | 570 | | } |