| | | 1 | | using System.Diagnostics; |
| | | 2 | | using System.Text.Json; |
| | | 3 | | |
| | | 4 | | using Microsoft.Extensions.AI; |
| | | 5 | | |
| | | 6 | | using NexusLabs.Needlr.AgentFramework.Budget; |
| | | 7 | | using NexusLabs.Needlr.AgentFramework.Context; |
| | | 8 | | using NexusLabs.Needlr.AgentFramework.Diagnostics; |
| | | 9 | | using NexusLabs.Needlr.AgentFramework.Progress; |
| | | 10 | | |
| | | 11 | | namespace NexusLabs.Needlr.AgentFramework.Iterative; |
| | | 12 | | |
| | | 13 | | /// <summary> |
| | | 14 | | /// Default implementation of <see cref="IIterativeAgentLoop"/> that runs an external loop |
| | | 15 | | /// with fresh prompts per iteration, bypassing <c>FunctionInvokingChatClient</c>'s |
| | | 16 | | /// accumulating conversation history. |
| | | 17 | | /// </summary> |
| | | 18 | | /// <remarks> |
| | | 19 | | /// <para> |
| | | 20 | | /// Internally wraps the chat client with <see cref="DiagnosticsChatClientMiddleware"/>, |
| | | 21 | | /// which is the single writer for <see cref="ChatCompletionDiagnostics"/>. The loop |
| | | 22 | | /// itself writes <see cref="ToolCallDiagnostics"/> and OTel metrics for tool calls |
| | | 23 | | /// and run lifecycle. Do not add external chat-completion recording middleware when |
| | | 24 | | /// using this loop — it will produce duplicates. |
| | | 25 | | /// </para> |
| | | 26 | | /// </remarks> |
| | | 27 | | [DoNotAutoRegister] |
| | | 28 | | internal sealed class IterativeAgentLoop : IIterativeAgentLoop |
| | | 29 | | { |
| | | 30 | | private readonly IChatClientAccessor _chatClientAccessor; |
| | | 31 | | private readonly IAgentDiagnosticsWriter? _diagnosticsWriter; |
| | | 32 | | private readonly IAgentExecutionContextAccessor? _executionContextAccessor; |
| | | 33 | | private readonly IProgressReporterAccessor? _progressReporterAccessor; |
| | | 34 | | private readonly ITokenBudgetTracker? _budgetTracker; |
| | | 35 | | private readonly IAgentMetrics? _metrics; |
| | | 36 | | private readonly ChatCompletionActivityMode _activityMode; |
| | | 37 | | |
| | 128 | 38 | | internal IterativeAgentLoop( |
| | 128 | 39 | | IChatClientAccessor chatClientAccessor, |
| | 128 | 40 | | IAgentDiagnosticsWriter? diagnosticsWriter = null, |
| | 128 | 41 | | IAgentExecutionContextAccessor? executionContextAccessor = null, |
| | 128 | 42 | | IProgressReporterAccessor? progressReporterAccessor = null, |
| | 128 | 43 | | ITokenBudgetTracker? budgetTracker = null, |
| | 128 | 44 | | IAgentMetrics? metrics = null, |
| | 128 | 45 | | ChatCompletionActivityMode activityMode = ChatCompletionActivityMode.Always) |
| | | 46 | | { |
| | 128 | 47 | | _chatClientAccessor = chatClientAccessor; |
| | 128 | 48 | | _diagnosticsWriter = diagnosticsWriter; |
| | 128 | 49 | | _executionContextAccessor = executionContextAccessor; |
| | 128 | 50 | | _progressReporterAccessor = progressReporterAccessor; |
| | 128 | 51 | | _budgetTracker = budgetTracker; |
| | 128 | 52 | | _metrics = metrics; |
| | 128 | 53 | | _activityMode = activityMode; |
| | 128 | 54 | | } |
| | | 55 | | |
| | | 56 | | /// <summary> |
| | | 57 | | /// Sentinel wrapper so lifecycle hook exceptions escape the framework catch-all. |
| | | 58 | | /// </summary> |
| | 1 | 59 | | private sealed class LifecycleHookException(Exception inner) : Exception(inner.Message, inner); |
| | | 60 | | |
| | | 61 | | public async Task<IterativeLoopResult> RunAsync( |
| | | 62 | | IterativeLoopOptions options, |
| | | 63 | | IterativeContext context, |
| | | 64 | | CancellationToken cancellationToken = default) |
| | | 65 | | { |
| | 125 | 66 | | ArgumentNullException.ThrowIfNull(options); |
| | 125 | 67 | | ArgumentNullException.ThrowIfNull(context); |
| | | 68 | | |
| | 125 | 69 | | var chatClient = _chatClientAccessor.ChatClient; |
| | | 70 | | |
| | | 71 | | // Apply chat reducer if configured (innermost middleware) |
| | | 72 | | #pragma warning disable MEAI001 // ReducingChatClient is experimental |
| | 125 | 73 | | if (options.ChatReducer is { } reducer) |
| | | 74 | | { |
| | 0 | 75 | | chatClient = new ReducingChatClient(chatClient, reducer); |
| | | 76 | | } |
| | | 77 | | #pragma warning restore MEAI001 |
| | | 78 | | |
| | | 79 | | // Apply per-loop middleware if configured (wraps the reducer if both are set) |
| | 125 | 80 | | if (options.ChatClientFactory is { } loopClientFactory) |
| | | 81 | | { |
| | 4 | 82 | | chatClient = loopClientFactory(chatClient); |
| | | 83 | | } |
| | | 84 | | |
| | | 85 | | // Install diagnostics recording middleware only when the pipeline does |
| | | 86 | | // not already contain one. UsingDiagnostics(), a per-loop factory, or |
| | | 87 | | // manual wiring may have already installed a DiagnosticsRecordingChatClient. |
| | | 88 | | // Installing a second instance would cause every ChatCompletion to be |
| | | 89 | | // recorded twice, inflating token counts by 2×. |
| | | 90 | | // |
| | | 91 | | // Detection uses MEAI's GetService<T>() which walks the DelegatingChatClient |
| | | 92 | | // chain, so it works regardless of where the middleware was installed. |
| | 125 | 93 | | if (chatClient.GetService<DiagnosticsRecordingChatClient>() is null) |
| | | 94 | | { |
| | 112 | 95 | | var chatMiddleware = new DiagnosticsChatClientMiddleware(_metrics, _progressReporterAccessor, _activityMode) |
| | 112 | 96 | | chatClient = new DiagnosticsRecordingChatClient(chatClient, chatMiddleware); |
| | | 97 | | } |
| | | 98 | | |
| | 125 | 99 | | var iterations = new List<IterationRecord>(); |
| | 125 | 100 | | ChatResponse? finalResponse = null; |
| | 125 | 101 | | var succeeded = true; |
| | 125 | 102 | | string? errorMessage = null; |
| | 125 | 103 | | var termination = TerminationReason.Completed; |
| | 125 | 104 | | int totalToolCalls = 0; |
| | | 105 | | |
| | 125 | 106 | | var diagnosticsBuilder = AgentRunDiagnosticsBuilder.StartNew(options.LoopName); |
| | 125 | 107 | | diagnosticsBuilder.SetExecutionMode("IterativeLoop"); |
| | 125 | 108 | | _metrics?.RecordRunStarted(options.LoopName); |
| | | 109 | | |
| | | 110 | | // Bridge: if an execution context accessor is available, set up a scope |
| | | 111 | | // so that DI-resolved tools can access the workspace via |
| | | 112 | | // IAgentExecutionContextAccessor.Current.GetRequiredWorkspace(). |
| | 125 | 113 | | IDisposable? executionContextScope = null; |
| | 125 | 114 | | if (_executionContextAccessor != null) |
| | | 115 | | { |
| | 10 | 116 | | var executionContext = options.ExecutionContext |
| | 10 | 117 | | ?? new AgentExecutionContext( |
| | 10 | 118 | | UserId: "iterative-loop", |
| | 10 | 119 | | OrchestrationId: options.LoopName, |
| | 10 | 120 | | Workspace: context.Workspace); |
| | 10 | 121 | | executionContextScope = _executionContextAccessor.BeginScope(executionContext); |
| | | 122 | | } |
| | | 123 | | |
| | | 124 | | // Track in-progress iteration state so catch handlers can record |
| | | 125 | | // partial IterationRecords when interrupted mid-iteration. |
| | 125 | 126 | | var currentIterationIndex = -1; |
| | 125 | 127 | | List<ToolCallResult>? currentIterationToolCalls = null; |
| | 125 | 128 | | Stopwatch? currentIterationStopwatch = null; |
| | | 129 | | |
| | | 130 | | try |
| | | 131 | | { |
| | 125 | 132 | | context.CancellationToken = cancellationToken; |
| | | 133 | | |
| | 370 | 134 | | for (int i = 0; i < options.MaxIterations; i++) |
| | | 135 | | { |
| | 177 | 136 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 137 | | |
| | 174 | 138 | | context.Iteration = i; |
| | 174 | 139 | | currentIterationIndex = i; |
| | | 140 | | |
| | | 141 | | // Hook: iteration start (wrapped to escape catch-all) |
| | 174 | 142 | | if (options.OnIterationStart != null) |
| | | 143 | | { |
| | 2 | 144 | | await InvokeHookAsync(options.OnIterationStart, i, context).ConfigureAwait(false); |
| | | 145 | | } |
| | | 146 | | |
| | | 147 | | // Build fresh prompt from workspace state |
| | 173 | 148 | | var budgetPressureTriggered = false; |
| | | 149 | | string userPrompt; |
| | | 150 | | try |
| | | 151 | | { |
| | 173 | 152 | | userPrompt = options.PromptFactory(context); |
| | 173 | 153 | | } |
| | 0 | 154 | | catch (Exception ex) |
| | | 155 | | { |
| | 0 | 156 | | succeeded = false; |
| | 0 | 157 | | termination = TerminationReason.Error; |
| | 0 | 158 | | errorMessage = $"Prompt factory failed on iteration {i}: {ex.Message}"; |
| | 0 | 159 | | diagnosticsBuilder.RecordFailure(errorMessage); |
| | 0 | 160 | | break; |
| | | 161 | | } |
| | | 162 | | |
| | | 163 | | // Budget pressure: if token usage is at or above the threshold, |
| | | 164 | | // prepend the finalization instruction and mark this as the last iteration. |
| | 173 | 165 | | if (options.BudgetPressureThreshold is { } threshold |
| | 173 | 166 | | && _budgetTracker is { MaxTokens: > 0 } tracker) |
| | | 167 | | { |
| | 2 | 168 | | var usage = (double)tracker.CurrentTokens / tracker.MaxTokens.Value; |
| | 2 | 169 | | if (usage >= threshold) |
| | | 170 | | { |
| | 0 | 171 | | userPrompt = options.BudgetPressureInstruction + "\n\n" + userPrompt; |
| | 0 | 172 | | budgetPressureTriggered = true; |
| | | 173 | | } |
| | | 174 | | } |
| | | 175 | | |
| | 173 | 176 | | var iterationStopwatch = Stopwatch.StartNew(); |
| | 173 | 177 | | currentIterationStopwatch = iterationStopwatch; |
| | 173 | 178 | | var iterationToolCalls = new List<ToolCallResult>(); |
| | 173 | 179 | | currentIterationToolCalls = iterationToolCalls; |
| | 173 | 180 | | ChatResponse? iterationResponse = null; |
| | 173 | 181 | | long iterationInputTokens = 0; |
| | 173 | 182 | | long iterationOutputTokens = 0; |
| | 173 | 183 | | long iterationTotalTokens = 0; |
| | 173 | 184 | | int llmCallCount = 0; |
| | | 185 | | |
| | | 186 | | // Build messages — always just [system, user], no history |
| | 173 | 187 | | var messages = new List<ChatMessage> |
| | 173 | 188 | | { |
| | 173 | 189 | | new(ChatRole.System, options.Instructions), |
| | 173 | 190 | | new(ChatRole.User, userPrompt), |
| | 173 | 191 | | }; |
| | | 192 | | |
| | 173 | 193 | | var effectiveTools = options.ToolFilter is { } filter |
| | 173 | 194 | | ? filter(i, context, options.Tools) |
| | 173 | 195 | | : options.Tools; |
| | | 196 | | |
| | 173 | 197 | | var chatOptions = new ChatOptions |
| | 173 | 198 | | { |
| | 173 | 199 | | Tools = effectiveTools.Cast<AITool>().ToList(), |
| | 173 | 200 | | }; |
| | | 201 | | |
| | | 202 | | // Execute rounds within this iteration based on ToolResultMode |
| | 173 | 203 | | var maxRounds = options.ToolResultMode switch |
| | 173 | 204 | | { |
| | 49 | 205 | | ToolResultMode.SingleCall => 1, |
| | 108 | 206 | | ToolResultMode.OneRoundTrip => 2, |
| | 16 | 207 | | ToolResultMode.MultiRound => options.MaxToolRoundsPerIteration, |
| | 0 | 208 | | _ => 1, |
| | 173 | 209 | | }; |
| | | 210 | | |
| | 566 | 211 | | for (int round = 0; round < maxRounds; round++) |
| | | 212 | | { |
| | 249 | 213 | | cancellationToken.ThrowIfCancellationRequested(); |
| | | 214 | | |
| | | 215 | | // Check budget pressure between rounds (not just per iteration) |
| | 249 | 216 | | if (round > 0 |
| | 249 | 217 | | && !budgetPressureTriggered |
| | 249 | 218 | | && options.BudgetPressureThreshold is { } roundThreshold |
| | 249 | 219 | | && _budgetTracker is { MaxTokens: > 0 } roundTracker) |
| | | 220 | | { |
| | 2 | 221 | | var roundUsage = (double)roundTracker.CurrentTokens / roundTracker.MaxTokens.Value; |
| | 2 | 222 | | if (roundUsage >= roundThreshold) |
| | | 223 | | { |
| | 1 | 224 | | budgetPressureTriggered = true; |
| | 1 | 225 | | break; |
| | | 226 | | } |
| | | 227 | | } |
| | | 228 | | |
| | | 229 | | ChatResponse response; |
| | | 230 | | |
| | | 231 | | try |
| | | 232 | | { |
| | 248 | 233 | | response = await chatClient.GetResponseAsync( |
| | 248 | 234 | | messages, chatOptions, cancellationToken).ConfigureAwait(false); |
| | 240 | 235 | | } |
| | 5 | 236 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 237 | | { |
| | 1 | 238 | | throw; // genuine cancellation — let outer handler terminate the loop |
| | | 239 | | } |
| | 7 | 240 | | catch (Exception) |
| | | 241 | | { |
| | | 242 | | // Chat completion diagnostics are recorded by the middleware |
| | | 243 | | // wrapping the chat client — the loop does not record them. |
| | 7 | 244 | | diagnosticsBuilder.RecordInputMessageCount(messages.Count); |
| | 7 | 245 | | throw; |
| | | 246 | | } |
| | | 247 | | |
| | 240 | 248 | | llmCallCount++; |
| | | 249 | | |
| | | 250 | | // Track tokens |
| | 720 | 251 | | long callInput = 0, callOutput = 0, callTotal = 0; |
| | 240 | 252 | | if (response.Usage is { } usage) |
| | | 253 | | { |
| | 92 | 254 | | callInput = usage.InputTokenCount ?? 0; |
| | 92 | 255 | | callOutput = usage.OutputTokenCount ?? 0; |
| | 92 | 256 | | callTotal = usage.TotalTokenCount ?? 0; |
| | 92 | 257 | | iterationInputTokens += callInput; |
| | 92 | 258 | | iterationOutputTokens += callOutput; |
| | 92 | 259 | | iterationTotalTokens += callTotal; |
| | | 260 | | } |
| | | 261 | | |
| | 240 | 262 | | var responseMessageCount = response.Messages.Count; |
| | | 263 | | |
| | | 264 | | // Chat completion diagnostics are recorded by the middleware |
| | | 265 | | // wrapping the chat client — the loop does not record them. |
| | 240 | 266 | | diagnosticsBuilder.RecordInputMessageCount(messages.Count); |
| | 240 | 267 | | diagnosticsBuilder.RecordOutputMessageCount(responseMessageCount); |
| | | 268 | | |
| | | 269 | | // Check for tool calls in response |
| | 240 | 270 | | var functionCalls = response.Messages |
| | 240 | 271 | | .SelectMany(m => m.Contents.OfType<FunctionCallContent>()) |
| | 240 | 272 | | .ToList(); |
| | | 273 | | |
| | 240 | 274 | | if (functionCalls.Count == 0) |
| | | 275 | | { |
| | | 276 | | // Model produced text — natural termination for this iteration. |
| | | 277 | | // Capture the full ChatResponse to preserve messages, usage, and |
| | | 278 | | // any other metadata for downstream consumers and evaluation. |
| | 88 | 279 | | iterationResponse = response; |
| | 88 | 280 | | break; |
| | | 281 | | } |
| | | 282 | | |
| | | 283 | | // Execute tool calls — limit to remaining allowance if MaxTotalToolCalls is set |
| | 152 | 284 | | var remainingAllowance = options.MaxTotalToolCalls.HasValue |
| | 152 | 285 | | ? options.MaxTotalToolCalls.Value - totalToolCalls |
| | 152 | 286 | | : (int?)null; |
| | | 287 | | |
| | 152 | 288 | | var callsToExecute = remainingAllowance.HasValue && remainingAllowance.Value < functionCalls.Count |
| | 152 | 289 | | ? functionCalls.Take(remainingAllowance.Value).ToList() |
| | 152 | 290 | | : functionCalls; |
| | | 291 | | |
| | | 292 | | // Build per-call early exit check for AfterEachToolCall mode |
| | 152 | 293 | | Func<List<ToolCallResult>, bool>? perCallEarlyExitCheck = null; |
| | 152 | 294 | | if (options.CheckCompletionAfterToolCalls == ToolCompletionCheckMode.AfterEachToolCall |
| | 152 | 295 | | && options.IsComplete is { } perCallIsComplete) |
| | | 296 | | { |
| | 5 | 297 | | perCallEarlyExitCheck = partialResults => |
| | 5 | 298 | | { |
| | 9 | 299 | | context.LastToolResults = partialResults; |
| | 9 | 300 | | return perCallIsComplete(context); |
| | 5 | 301 | | }; |
| | | 302 | | } |
| | | 303 | | |
| | 152 | 304 | | var (roundResults, earlyExitFromToolCall) = await ExecuteToolCallsAsync( |
| | 152 | 305 | | callsToExecute, options.Tools, diagnosticsBuilder, |
| | 152 | 306 | | i, options.OnToolCall, _progressReporterAccessor, |
| | 152 | 307 | | _metrics, perCallEarlyExitCheck, cancellationToken) |
| | 152 | 308 | | .ConfigureAwait(false); |
| | 152 | 309 | | iterationToolCalls.AddRange(roundResults); |
| | 152 | 310 | | totalToolCalls += roundResults.Count; |
| | | 311 | | |
| | | 312 | | // Early completion check (fires before MaxTotalToolCalls so completion wins) |
| | 152 | 313 | | if (earlyExitFromToolCall) |
| | | 314 | | { |
| | 4 | 315 | | termination = TerminationReason.CompletedEarlyAfterToolCall; |
| | 4 | 316 | | break; |
| | | 317 | | } |
| | | 318 | | |
| | 148 | 319 | | if (options.CheckCompletionAfterToolCalls == ToolCompletionCheckMode.AfterToolRounds |
| | 148 | 320 | | || options.CheckCompletionAfterToolCalls == ToolCompletionCheckMode.AfterEachToolCall) |
| | | 321 | | { |
| | 7 | 322 | | if (options.IsComplete is { } earlyCheck) |
| | | 323 | | { |
| | 7 | 324 | | context.LastToolResults = iterationToolCalls; |
| | 7 | 325 | | if (earlyCheck(context)) |
| | | 326 | | { |
| | 6 | 327 | | termination = TerminationReason.CompletedEarlyAfterToolCall; |
| | 6 | 328 | | break; |
| | | 329 | | } |
| | | 330 | | } |
| | | 331 | | } |
| | | 332 | | |
| | | 333 | | // Check MaxTotalToolCalls guard |
| | 142 | 334 | | if (options.MaxTotalToolCalls is { } maxCalls && totalToolCalls >= maxCalls) |
| | | 335 | | { |
| | 1 | 336 | | termination = TerminationReason.MaxToolCallsReached; |
| | 1 | 337 | | succeeded = false; |
| | 1 | 338 | | errorMessage = $"Cumulative tool call count ({totalToolCalls}) reached MaxTotalToolCalls ({maxCa |
| | 1 | 339 | | diagnosticsBuilder.RecordFailure(errorMessage); |
| | 1 | 340 | | break; |
| | | 341 | | } |
| | | 342 | | |
| | | 343 | | // For SingleCall mode, don't send results back — just store them |
| | 141 | 344 | | if (options.ToolResultMode == ToolResultMode.SingleCall) |
| | | 345 | | { |
| | | 346 | | break; |
| | | 347 | | } |
| | | 348 | | |
| | | 349 | | // For OneRoundTrip/MultiRound, send results back to model |
| | | 350 | | // Add assistant message with tool calls |
| | 110 | 351 | | var assistantMessage = new ChatMessage(ChatRole.Assistant, |
| | 223 | 352 | | functionCalls.Select(fc => (AIContent)fc).ToList()); |
| | 110 | 353 | | messages.Add(assistantMessage); |
| | | 354 | | |
| | | 355 | | // Add tool result messages |
| | 446 | 356 | | foreach (var (fc, result) in functionCalls.Zip(roundResults)) |
| | | 357 | | { |
| | 113 | 358 | | var resultContent = result.Succeeded |
| | 113 | 359 | | ? ToolResultSerializer.Serialize(result.Result) |
| | 113 | 360 | | : $"Error: {result.ErrorMessage}"; |
| | | 361 | | |
| | 113 | 362 | | messages.Add(new ChatMessage(ChatRole.Tool, |
| | 113 | 363 | | [new FunctionResultContent(fc.CallId, resultContent)])); |
| | | 364 | | } |
| | | 365 | | |
| | | 366 | | // For OneRoundTrip, if this was the first round (round 0), |
| | | 367 | | // we'll do ONE more LLM call. If it's round 1, we're done. |
| | | 368 | | // For MultiRound, we continue until maxRounds or text response. |
| | 110 | 369 | | } |
| | | 370 | | |
| | | 371 | | // If a guard triggered termination inside the round loop, break outer loop too |
| | 165 | 372 | | if (termination == TerminationReason.MaxToolCallsReached) |
| | | 373 | | { |
| | | 374 | | // Still record the partial iteration |
| | 1 | 375 | | iterationStopwatch.Stop(); |
| | 1 | 376 | | iterations.Add(new IterationRecord( |
| | 1 | 377 | | Iteration: i, |
| | 1 | 378 | | ToolCalls: iterationToolCalls, |
| | 1 | 379 | | FinalResponse: iterationResponse, |
| | 1 | 380 | | Tokens: new TokenUsage(iterationInputTokens, iterationOutputTokens, iterationTotalTokens, 0, 0), |
| | 1 | 381 | | Duration: iterationStopwatch.Elapsed, |
| | 1 | 382 | | LlmCallCount: llmCallCount, |
| | 1 | 383 | | ToolCallCount: iterationToolCalls.Count)); |
| | 1 | 384 | | context.LastToolResults = iterationToolCalls; |
| | 1 | 385 | | break; |
| | | 386 | | } |
| | | 387 | | |
| | | 388 | | // Early completion after tool call — record iteration, fire hooks, then exit |
| | 164 | 389 | | if (termination == TerminationReason.CompletedEarlyAfterToolCall) |
| | | 390 | | { |
| | 10 | 391 | | iterationStopwatch.Stop(); |
| | 10 | 392 | | iterations.Add(new IterationRecord( |
| | 10 | 393 | | Iteration: i, |
| | 10 | 394 | | ToolCalls: iterationToolCalls, |
| | 10 | 395 | | FinalResponse: iterationResponse, |
| | 10 | 396 | | Tokens: new TokenUsage(iterationInputTokens, iterationOutputTokens, iterationTotalTokens, 0, 0), |
| | 10 | 397 | | Duration: iterationStopwatch.Elapsed, |
| | 10 | 398 | | LlmCallCount: llmCallCount, |
| | 10 | 399 | | ToolCallCount: iterationToolCalls.Count)); |
| | 10 | 400 | | context.LastToolResults = iterationToolCalls; |
| | | 401 | | |
| | 10 | 402 | | if (options.OnIterationEnd != null) |
| | | 403 | | { |
| | 1 | 404 | | await InvokeHookAsync(options.OnIterationEnd, iterations[^1]).ConfigureAwait(false); |
| | | 405 | | } |
| | | 406 | | |
| | 1 | 407 | | break; |
| | | 408 | | } |
| | | 409 | | |
| | 154 | 410 | | iterationStopwatch.Stop(); |
| | | 411 | | |
| | 154 | 412 | | var tokenUsage = new TokenUsage( |
| | 154 | 413 | | InputTokens: iterationInputTokens, |
| | 154 | 414 | | OutputTokens: iterationOutputTokens, |
| | 154 | 415 | | TotalTokens: iterationTotalTokens, |
| | 154 | 416 | | CachedInputTokens: 0, |
| | 154 | 417 | | ReasoningTokens: 0); |
| | | 418 | | |
| | 154 | 419 | | iterations.Add(new IterationRecord( |
| | 154 | 420 | | Iteration: i, |
| | 154 | 421 | | ToolCalls: iterationToolCalls, |
| | 154 | 422 | | FinalResponse: iterationResponse, |
| | 154 | 423 | | Tokens: tokenUsage, |
| | 154 | 424 | | Duration: iterationStopwatch.Elapsed, |
| | 154 | 425 | | LlmCallCount: llmCallCount, |
| | 154 | 426 | | ToolCallCount: iterationToolCalls.Count)); |
| | | 427 | | |
| | | 428 | | // Update context for next iteration |
| | 154 | 429 | | context.LastToolResults = iterationToolCalls; |
| | | 430 | | |
| | | 431 | | // Hook: iteration end (wrapped to escape catch-all) |
| | 154 | 432 | | if (options.OnIterationEnd != null) |
| | | 433 | | { |
| | 4 | 434 | | await InvokeHookAsync(options.OnIterationEnd, iterations[^1]).ConfigureAwait(false); |
| | | 435 | | } |
| | | 436 | | |
| | | 437 | | // Stall detection — compare consecutive iterations |
| | 154 | 438 | | if (options.StallDetection is { } stallOpts && iterations.Count >= 2) |
| | | 439 | | { |
| | 13 | 440 | | var currentTokens = iterations[^1].Tokens.TotalTokens; |
| | 13 | 441 | | var consecutiveSimilar = 0; |
| | | 442 | | |
| | 38 | 443 | | for (int s = iterations.Count - 2; s >= 0; s--) |
| | | 444 | | { |
| | 15 | 445 | | var prevTokens = iterations[s].Tokens.TotalTokens; |
| | 15 | 446 | | if (prevTokens > 0) |
| | | 447 | | { |
| | 15 | 448 | | var delta = Math.Abs(currentTokens - prevTokens) / (double)prevTokens; |
| | 15 | 449 | | if (delta <= stallOpts.TolerancePercent) |
| | | 450 | | { |
| | 6 | 451 | | consecutiveSimilar++; |
| | 6 | 452 | | currentTokens = prevTokens; |
| | | 453 | | } |
| | | 454 | | else |
| | | 455 | | { |
| | | 456 | | break; |
| | | 457 | | } |
| | | 458 | | } |
| | | 459 | | else |
| | | 460 | | { |
| | | 461 | | break; |
| | | 462 | | } |
| | | 463 | | } |
| | | 464 | | |
| | 13 | 465 | | if (consecutiveSimilar >= stallOpts.ConsecutiveThreshold - 1) |
| | | 466 | | { |
| | 2 | 467 | | termination = TerminationReason.StallDetected; |
| | 2 | 468 | | succeeded = false; |
| | 2 | 469 | | errorMessage = $"Stall detected: {consecutiveSimilar + 1} consecutive iterations " + |
| | 2 | 470 | | $"with similar token counts (~{iterations[^1].Tokens.TotalTokens} tokens, " + |
| | 2 | 471 | | $"tolerance {stallOpts.TolerancePercent:P0})."; |
| | 2 | 472 | | diagnosticsBuilder.RecordFailure(errorMessage); |
| | 2 | 473 | | break; |
| | | 474 | | } |
| | | 475 | | } |
| | | 476 | | |
| | | 477 | | // Check IsComplete predicate |
| | 152 | 478 | | if (options.IsComplete?.Invoke(context) == true) |
| | | 479 | | { |
| | 24 | 480 | | termination = TerminationReason.Completed; |
| | 24 | 481 | | break; |
| | | 482 | | } |
| | | 483 | | |
| | | 484 | | // Budget pressure: this was the finalization iteration — stop now |
| | 128 | 485 | | if (budgetPressureTriggered) |
| | | 486 | | { |
| | 1 | 487 | | termination = TerminationReason.BudgetPressure; |
| | 1 | 488 | | break; |
| | | 489 | | } |
| | | 490 | | |
| | | 491 | | // If model produced text (no tool calls), the loop is done |
| | 127 | 492 | | if (iterationResponse != null) |
| | | 493 | | { |
| | 67 | 494 | | finalResponse = iterationResponse; |
| | 67 | 495 | | termination = TerminationReason.NaturalCompletion; |
| | 67 | 496 | | break; |
| | | 497 | | } |
| | 60 | 498 | | } |
| | | 499 | | |
| | | 500 | | // If the loop exhausted MaxIterations without IsComplete returning true |
| | | 501 | | // and without a text response, that's a failure — the agent didn't finish. |
| | 113 | 502 | | if (termination == TerminationReason.Completed |
| | 113 | 503 | | && finalResponse == null |
| | 113 | 504 | | && options.IsComplete?.Invoke(context) != true |
| | 113 | 505 | | && iterations.Count >= options.MaxIterations) |
| | | 506 | | { |
| | 8 | 507 | | succeeded = false; |
| | 8 | 508 | | termination = TerminationReason.MaxIterationsReached; |
| | 8 | 509 | | errorMessage = $"Loop exhausted {options.MaxIterations} iterations without completing. " |
| | 8 | 510 | | + "The IsComplete predicate never returned true and the model never produced a text response."; |
| | 8 | 511 | | diagnosticsBuilder.RecordFailure(errorMessage); |
| | | 512 | | } |
| | 113 | 513 | | } |
| | 8 | 514 | | catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) |
| | | 515 | | { |
| | 4 | 516 | | succeeded = false; |
| | 4 | 517 | | termination = TerminationReason.Cancelled; |
| | 4 | 518 | | errorMessage = $"Loop was cancelled after {iterations.Count} completed iteration(s)."; |
| | 4 | 519 | | diagnosticsBuilder.RecordFailure(errorMessage); |
| | 4 | 520 | | RecordPartialIteration(iterations, currentIterationIndex, currentIterationToolCalls, currentIterationStopwat |
| | 4 | 521 | | } |
| | 4 | 522 | | catch (OperationCanceledException ex) |
| | | 523 | | { |
| | | 524 | | // HTTP timeout (TaskCanceledException with TimeoutException inner) |
| | | 525 | | // or other non-user cancellation — report as Error, not Cancelled. |
| | 4 | 526 | | succeeded = false; |
| | 4 | 527 | | termination = TerminationReason.Error; |
| | 4 | 528 | | errorMessage = ex.InnerException is TimeoutException |
| | 4 | 529 | | ? $"Chat completion timed out on iteration {iterations.Count + 1}: {ex.InnerException.Message}" |
| | 4 | 530 | | : $"Operation cancelled (not by caller) on iteration {iterations.Count + 1}: {ex.Message}"; |
| | 4 | 531 | | diagnosticsBuilder.RecordFailure(errorMessage); |
| | 4 | 532 | | RecordPartialIteration(iterations, currentIterationIndex, currentIterationToolCalls, currentIterationStopwat |
| | 4 | 533 | | } |
| | | 534 | | catch (LifecycleHookException hookEx) |
| | | 535 | | { |
| | | 536 | | // Lifecycle hook exceptions propagate to the caller — they are |
| | | 537 | | // user-controlled code and should not be silently swallowed. |
| | 1 | 538 | | throw hookEx.InnerException!; |
| | | 539 | | } |
| | 3 | 540 | | catch (Exception ex) |
| | | 541 | | { |
| | 3 | 542 | | succeeded = false; |
| | 3 | 543 | | termination = TerminationReason.Error; |
| | 3 | 544 | | errorMessage = ex.Message; |
| | 3 | 545 | | diagnosticsBuilder.RecordFailure(errorMessage); |
| | 3 | 546 | | RecordPartialIteration(iterations, currentIterationIndex, currentIterationToolCalls, currentIterationStopwat |
| | 3 | 547 | | } |
| | | 548 | | |
| | 124 | 549 | | if (finalResponse == null && iterations.Count > 0) |
| | | 550 | | { |
| | | 551 | | // Get final response from last iteration if available |
| | 55 | 552 | | finalResponse = iterations[^1].FinalResponse; |
| | | 553 | | } |
| | | 554 | | |
| | 124 | 555 | | var diagnostics = diagnosticsBuilder.Build(); |
| | 124 | 556 | | diagnosticsBuilder.Dispose(); |
| | 124 | 557 | | _diagnosticsWriter?.Set(diagnostics); |
| | 124 | 558 | | _metrics?.RecordRunCompleted(diagnostics); |
| | 124 | 559 | | executionContextScope?.Dispose(); |
| | | 560 | | |
| | 124 | 561 | | var configuration = new IterativeLoopConfiguration( |
| | 124 | 562 | | ToolResultMode: options.ToolResultMode, |
| | 124 | 563 | | MaxIterations: options.MaxIterations, |
| | 124 | 564 | | MaxToolRoundsPerIteration: options.MaxToolRoundsPerIteration, |
| | 124 | 565 | | MaxTotalToolCalls: options.MaxTotalToolCalls, |
| | 124 | 566 | | BudgetPressureThreshold: options.BudgetPressureThreshold, |
| | 124 | 567 | | LoopName: options.LoopName, |
| | 124 | 568 | | CheckCompletionAfterToolCalls: options.CheckCompletionAfterToolCalls); |
| | | 569 | | |
| | 124 | 570 | | return new IterativeLoopResult( |
| | 124 | 571 | | Iterations: iterations, |
| | 124 | 572 | | FinalResponse: finalResponse, |
| | 124 | 573 | | Diagnostics: diagnostics, |
| | 124 | 574 | | Succeeded: succeeded, |
| | 124 | 575 | | ErrorMessage: errorMessage, |
| | 124 | 576 | | Termination: termination, |
| | 124 | 577 | | Configuration: configuration); |
| | 124 | 578 | | } |
| | | 579 | | |
| | | 580 | | /// <summary> |
| | | 581 | | /// Records a partial <see cref="IterationRecord"/> for an iteration that was |
| | | 582 | | /// interrupted by an exception. Captures whatever tool calls and timing data |
| | | 583 | | /// were accumulated before the interruption. |
| | | 584 | | /// </summary> |
| | | 585 | | private static void RecordPartialIteration( |
| | | 586 | | List<IterationRecord> iterations, |
| | | 587 | | int currentIterationIndex, |
| | | 588 | | List<ToolCallResult>? toolCalls, |
| | | 589 | | Stopwatch? stopwatch) |
| | | 590 | | { |
| | 11 | 591 | | if (currentIterationIndex < 0 || currentIterationIndex < iterations.Count) |
| | | 592 | | { |
| | 3 | 593 | | return; |
| | | 594 | | } |
| | | 595 | | |
| | 8 | 596 | | stopwatch?.Stop(); |
| | 8 | 597 | | iterations.Add(new IterationRecord( |
| | 8 | 598 | | Iteration: currentIterationIndex, |
| | 8 | 599 | | ToolCalls: toolCalls ?? [], |
| | 8 | 600 | | FinalResponse: null, |
| | 8 | 601 | | Tokens: new TokenUsage(0, 0, 0, 0, 0), |
| | 8 | 602 | | Duration: stopwatch?.Elapsed ?? TimeSpan.Zero, |
| | 8 | 603 | | LlmCallCount: 0, |
| | 8 | 604 | | ToolCallCount: toolCalls?.Count ?? 0)); |
| | 8 | 605 | | } |
| | | 606 | | |
| | | 607 | | private static async Task<(List<ToolCallResult> Results, bool EarlyExit)> ExecuteToolCallsAsync( |
| | | 608 | | List<FunctionCallContent> functionCalls, |
| | | 609 | | IReadOnlyList<AITool> tools, |
| | | 610 | | AgentRunDiagnosticsBuilder diagnosticsBuilder, |
| | | 611 | | int iteration, |
| | | 612 | | Func<int, ToolCallResult, Task>? onToolCall, |
| | | 613 | | IProgressReporterAccessor? progressAccessor, |
| | | 614 | | IAgentMetrics? metrics, |
| | | 615 | | Func<List<ToolCallResult>, bool>? earlyExitCheck, |
| | | 616 | | CancellationToken cancellationToken) |
| | | 617 | | { |
| | 152 | 618 | | var toolMap = tools.OfType<AIFunction>() |
| | 316 | 619 | | .ToDictionary(t => t.Name, StringComparer.OrdinalIgnoreCase); |
| | | 620 | | |
| | 152 | 621 | | var results = new List<ToolCallResult>(); |
| | 152 | 622 | | var reporter = progressAccessor?.Current; |
| | | 623 | | |
| | 616 | 624 | | foreach (var fc in functionCalls) |
| | | 625 | | { |
| | 158 | 626 | | var sequence = diagnosticsBuilder.NextToolCallSequence(); |
| | 158 | 627 | | var startedAt = DateTimeOffset.UtcNow; |
| | 158 | 628 | | var stopwatch = Stopwatch.StartNew(); |
| | | 629 | | |
| | 158 | 630 | | using var activity = metrics?.ActivitySource.StartActivity($"agent.tool {fc.Name}", ActivityKind.Internal); |
| | 158 | 631 | | activity?.SetTag("agent.tool.name", fc.Name); |
| | 158 | 632 | | activity?.SetTag("agent.tool.sequence", sequence); |
| | 158 | 633 | | activity?.SetTag("gen_ai.agent.name", diagnosticsBuilder.AgentName); |
| | | 634 | | |
| | 158 | 635 | | reporter?.Report(new ToolCallStartedEvent( |
| | 158 | 636 | | Timestamp: startedAt, |
| | 158 | 637 | | WorkflowId: reporter.WorkflowId, |
| | 158 | 638 | | AgentId: reporter.AgentId, |
| | 158 | 639 | | ParentAgentId: null, |
| | 158 | 640 | | Depth: reporter.Depth, |
| | 158 | 641 | | SequenceNumber: reporter.NextSequence(), |
| | 158 | 642 | | ToolName: fc.Name)); |
| | | 643 | | |
| | 158 | 644 | | if (!toolMap.TryGetValue(fc.Name, out var function)) |
| | | 645 | | { |
| | 2 | 646 | | stopwatch.Stop(); |
| | 2 | 647 | | var errorResult = new ToolCallResult( |
| | 2 | 648 | | FunctionName: fc.Name, |
| | 2 | 649 | | Arguments: ToReadOnly(fc.Arguments), |
| | 2 | 650 | | Result: null, |
| | 2 | 651 | | Duration: stopwatch.Elapsed, |
| | 2 | 652 | | Succeeded: false, |
| | 2 | 653 | | ErrorMessage: $"Unknown tool: '{fc.Name}'"); |
| | | 654 | | |
| | 2 | 655 | | diagnosticsBuilder.AddToolCall(new ToolCallDiagnostics( |
| | 2 | 656 | | Sequence: sequence, |
| | 2 | 657 | | ToolName: fc.Name, |
| | 2 | 658 | | Duration: stopwatch.Elapsed, |
| | 2 | 659 | | Succeeded: false, |
| | 2 | 660 | | ErrorMessage: errorResult.ErrorMessage, |
| | 2 | 661 | | StartedAt: startedAt, |
| | 2 | 662 | | CompletedAt: DateTimeOffset.UtcNow, |
| | 2 | 663 | | CustomMetrics: null) |
| | 2 | 664 | | { |
| | 2 | 665 | | AgentName = diagnosticsBuilder.AgentName, |
| | 2 | 666 | | Arguments = ToReadOnly(fc.Arguments), |
| | 2 | 667 | | ArgumentsCharCount = DiagnosticsCharCounter.JsonLength(fc.Arguments), |
| | 2 | 668 | | }); |
| | 2 | 669 | | metrics?.RecordToolCall(fc.Name, stopwatch.Elapsed, succeeded: false, agentName: diagnosticsBuilder.Agen |
| | 2 | 670 | | activity?.SetStatus(ActivityStatusCode.Error, errorResult.ErrorMessage); |
| | 2 | 671 | | activity?.SetTag("status", "failed"); |
| | | 672 | | |
| | 2 | 673 | | reporter?.Report(new ToolCallFailedEvent( |
| | 2 | 674 | | Timestamp: DateTimeOffset.UtcNow, |
| | 2 | 675 | | WorkflowId: reporter.WorkflowId, |
| | 2 | 676 | | AgentId: reporter.AgentId, |
| | 2 | 677 | | ParentAgentId: null, |
| | 2 | 678 | | Depth: reporter.Depth, |
| | 2 | 679 | | SequenceNumber: reporter.NextSequence(), |
| | 2 | 680 | | ToolName: fc.Name, |
| | 2 | 681 | | ErrorMessage: errorResult.ErrorMessage ?? "Unknown tool", |
| | 2 | 682 | | Duration: stopwatch.Elapsed)); |
| | | 683 | | |
| | 2 | 684 | | results.Add(errorResult); |
| | | 685 | | |
| | 2 | 686 | | if (onToolCall != null) |
| | | 687 | | { |
| | 0 | 688 | | await InvokeHookAsync(onToolCall, iteration, errorResult).ConfigureAwait(false); |
| | | 689 | | } |
| | | 690 | | |
| | 2 | 691 | | if (earlyExitCheck != null && earlyExitCheck(results)) |
| | | 692 | | { |
| | 0 | 693 | | return (results, EarlyExit: true); |
| | | 694 | | } |
| | | 695 | | |
| | 2 | 696 | | continue; |
| | | 697 | | } |
| | | 698 | | |
| | | 699 | | try |
| | | 700 | | { |
| | 156 | 701 | | var result = await function.InvokeAsync( |
| | 156 | 702 | | fc.Arguments is { } args ? new AIFunctionArguments(args) : null, |
| | 156 | 703 | | cancellationToken).ConfigureAwait(false); |
| | | 704 | | |
| | 153 | 705 | | stopwatch.Stop(); |
| | | 706 | | |
| | 153 | 707 | | diagnosticsBuilder.AddToolCall(new ToolCallDiagnostics( |
| | 153 | 708 | | Sequence: sequence, |
| | 153 | 709 | | ToolName: fc.Name, |
| | 153 | 710 | | Duration: stopwatch.Elapsed, |
| | 153 | 711 | | Succeeded: true, |
| | 153 | 712 | | ErrorMessage: null, |
| | 153 | 713 | | StartedAt: startedAt, |
| | 153 | 714 | | CompletedAt: DateTimeOffset.UtcNow, |
| | 153 | 715 | | CustomMetrics: null) |
| | 153 | 716 | | { |
| | 153 | 717 | | AgentName = diagnosticsBuilder.AgentName, |
| | 153 | 718 | | Arguments = ToReadOnly(fc.Arguments), |
| | 153 | 719 | | Result = result, |
| | 153 | 720 | | ArgumentsCharCount = DiagnosticsCharCounter.JsonLength(fc.Arguments), |
| | 153 | 721 | | ResultCharCount = DiagnosticsCharCounter.JsonLength(result), |
| | 153 | 722 | | }); |
| | 153 | 723 | | metrics?.RecordToolCall(fc.Name, stopwatch.Elapsed, succeeded: true, agentName: diagnosticsBuilder.Agent |
| | 153 | 724 | | activity?.SetTag("status", "success"); |
| | | 725 | | |
| | 153 | 726 | | reporter?.Report(new ToolCallCompletedEvent( |
| | 153 | 727 | | Timestamp: DateTimeOffset.UtcNow, |
| | 153 | 728 | | WorkflowId: reporter.WorkflowId, |
| | 153 | 729 | | AgentId: reporter.AgentId, |
| | 153 | 730 | | ParentAgentId: null, |
| | 153 | 731 | | Depth: reporter.Depth, |
| | 153 | 732 | | SequenceNumber: reporter.NextSequence(), |
| | 153 | 733 | | ToolName: fc.Name, |
| | 153 | 734 | | Duration: stopwatch.Elapsed, |
| | 153 | 735 | | CustomMetrics: null)); |
| | | 736 | | |
| | 153 | 737 | | results.Add(new ToolCallResult( |
| | 153 | 738 | | FunctionName: fc.Name, |
| | 153 | 739 | | Arguments: ToReadOnly(fc.Arguments), |
| | 153 | 740 | | Result: result, |
| | 153 | 741 | | Duration: stopwatch.Elapsed, |
| | 153 | 742 | | Succeeded: true, |
| | 153 | 743 | | ErrorMessage: null)); |
| | | 744 | | |
| | 153 | 745 | | if (onToolCall != null) |
| | | 746 | | { |
| | 1 | 747 | | await InvokeHookAsync(onToolCall, iteration, results[^1]).ConfigureAwait(false); |
| | | 748 | | } |
| | 153 | 749 | | } |
| | 3 | 750 | | catch (Exception ex) |
| | | 751 | | { |
| | 3 | 752 | | stopwatch.Stop(); |
| | | 753 | | |
| | 3 | 754 | | diagnosticsBuilder.AddToolCall(new ToolCallDiagnostics( |
| | 3 | 755 | | Sequence: sequence, |
| | 3 | 756 | | ToolName: fc.Name, |
| | 3 | 757 | | Duration: stopwatch.Elapsed, |
| | 3 | 758 | | Succeeded: false, |
| | 3 | 759 | | ErrorMessage: ex.Message, |
| | 3 | 760 | | StartedAt: startedAt, |
| | 3 | 761 | | CompletedAt: DateTimeOffset.UtcNow, |
| | 3 | 762 | | CustomMetrics: null) |
| | 3 | 763 | | { |
| | 3 | 764 | | AgentName = diagnosticsBuilder.AgentName, |
| | 3 | 765 | | Arguments = ToReadOnly(fc.Arguments), |
| | 3 | 766 | | ArgumentsCharCount = DiagnosticsCharCounter.JsonLength(fc.Arguments), |
| | 3 | 767 | | }); |
| | 3 | 768 | | metrics?.RecordToolCall(fc.Name, stopwatch.Elapsed, succeeded: false, agentName: diagnosticsBuilder.Agen |
| | 3 | 769 | | activity?.SetStatus(ActivityStatusCode.Error, ex.Message); |
| | 3 | 770 | | activity?.SetTag("status", "failed"); |
| | | 771 | | |
| | 3 | 772 | | reporter?.Report(new ToolCallFailedEvent( |
| | 3 | 773 | | Timestamp: DateTimeOffset.UtcNow, |
| | 3 | 774 | | WorkflowId: reporter.WorkflowId, |
| | 3 | 775 | | AgentId: reporter.AgentId, |
| | 3 | 776 | | ParentAgentId: null, |
| | 3 | 777 | | Depth: reporter.Depth, |
| | 3 | 778 | | SequenceNumber: reporter.NextSequence(), |
| | 3 | 779 | | ToolName: fc.Name, |
| | 3 | 780 | | ErrorMessage: ex.Message, |
| | 3 | 781 | | Duration: stopwatch.Elapsed)); |
| | | 782 | | |
| | 3 | 783 | | results.Add(new ToolCallResult( |
| | 3 | 784 | | FunctionName: fc.Name, |
| | 3 | 785 | | Arguments: ToReadOnly(fc.Arguments), |
| | 3 | 786 | | Result: null, |
| | 3 | 787 | | Duration: stopwatch.Elapsed, |
| | 3 | 788 | | Succeeded: false, |
| | 3 | 789 | | ErrorMessage: ex.Message)); |
| | | 790 | | |
| | 3 | 791 | | if (onToolCall != null) |
| | | 792 | | { |
| | 0 | 793 | | await InvokeHookAsync(onToolCall, iteration, results[^1]).ConfigureAwait(false); |
| | | 794 | | } |
| | | 795 | | } |
| | | 796 | | |
| | | 797 | | // Per-call early exit check |
| | 156 | 798 | | if (earlyExitCheck != null && earlyExitCheck(results)) |
| | | 799 | | { |
| | 4 | 800 | | return (results, EarlyExit: true); |
| | | 801 | | } |
| | 152 | 802 | | } |
| | | 803 | | |
| | 148 | 804 | | return (results, EarlyExit: false); |
| | 152 | 805 | | } |
| | | 806 | | |
| | | 807 | | private static async Task InvokeHookAsync<T>(Func<T, Task> hook, T arg) |
| | | 808 | | { |
| | | 809 | | try |
| | | 810 | | { |
| | 5 | 811 | | await hook(arg).ConfigureAwait(false); |
| | 5 | 812 | | } |
| | | 813 | | catch (Exception ex) |
| | | 814 | | { |
| | 0 | 815 | | throw new LifecycleHookException(ex); |
| | | 816 | | } |
| | 5 | 817 | | } |
| | | 818 | | |
| | | 819 | | private static async Task InvokeHookAsync<T1, T2>(Func<T1, T2, Task> hook, T1 arg1, T2 arg2) |
| | | 820 | | { |
| | | 821 | | try |
| | | 822 | | { |
| | 3 | 823 | | await hook(arg1, arg2).ConfigureAwait(false); |
| | 2 | 824 | | } |
| | | 825 | | catch (Exception ex) |
| | | 826 | | { |
| | 1 | 827 | | throw new LifecycleHookException(ex); |
| | | 828 | | } |
| | 2 | 829 | | } |
| | | 830 | | |
| | | 831 | | private static IReadOnlyDictionary<string, object?> ToReadOnly( |
| | | 832 | | IDictionary<string, object?>? arguments) => |
| | 316 | 833 | | arguments is IReadOnlyDictionary<string, object?> ro |
| | 316 | 834 | | ? ro |
| | 316 | 835 | | : arguments is not null |
| | 316 | 836 | | ? new Dictionary<string, object?>(arguments) |
| | 316 | 837 | | : new Dictionary<string, object?>(); |
| | | 838 | | |
| | | 839 | | |
| | | 840 | | } |