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