| | | 1 | | using Microsoft.SemanticKernel; |
| | | 2 | | |
| | | 3 | | using System.Diagnostics.CodeAnalysis; |
| | | 4 | | using System.Reflection; |
| | | 5 | | |
| | | 6 | | namespace NexusLabs.Needlr.SemanticKernel.PluginScanners; |
| | | 7 | | |
| | | 8 | | [RequiresUnreferencedCode("Assembly scanning uses reflection to discover types with [KernelFunction] methods.")] |
| | | 9 | | [RequiresDynamicCode("Assembly scanning uses reflection APIs that may require dynamic code generation.")] |
| | 9 | 10 | | internal sealed class AssemblySemanticKernelPluginScanner( |
| | 9 | 11 | | IReadOnlyList<Assembly> _assemblies) : |
| | | 12 | | ISemanticKernelPluginScanner |
| | | 13 | | { |
| | | 14 | | public IReadOnlyList<Type> ScanForPluginTypes() |
| | | 15 | | { |
| | 9 | 16 | | var list = FromAssemblies(_assemblies) |
| | 9 | 17 | | .Where(HasKernelFunctions) |
| | 9 | 18 | | .Distinct() |
| | 9 | 19 | | .ToArray(); |
| | | 20 | | |
| | 9 | 21 | | return list; |
| | | 22 | | } |
| | | 23 | | |
| | | 24 | | private static IEnumerable<Type> FromAssemblies(IEnumerable<Assembly> assemblies) => |
| | 9 | 25 | | assemblies |
| | 10 | 26 | | .Where(a => !a.IsDynamic) |
| | 9 | 27 | | .SelectMany(SafeGetTypes) |
| | 633 | 28 | | .Where(t => t.IsClass && (!t.IsAbstract || t.IsStatic())); |
| | | 29 | | |
| | | 30 | | private static bool HasKernelFunctions(Type t) => |
| | 603 | 31 | | t.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public) |
| | 3315 | 32 | | .Any(m => m.IsDefined(typeof(KernelFunctionAttribute), inherit: true)); |
| | | 33 | | |
| | | 34 | | private static IEnumerable<Type> SafeGetTypes(Assembly a) |
| | | 35 | | { |
| | 10 | 36 | | try { return a.GetTypes(); } |
| | 0 | 37 | | catch (ReflectionTypeLoadException ex) { return ex.Types.Where(t => t is not null)!; } |
| | 10 | 38 | | } |
| | | 39 | | } |