Path: redb-route/redb.Route.Llm/Storage/Redb/RedbAuditObserver.cs Snapshot: redb-route, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-route Page: https://redbase.app/src/dev-2026-12-06/redb-route/redb.Route.Llm/Storage/Redb/RedbAuditObserver.cs ---- using Microsoft.Extensions.Logging; using redb.Core; using redb.Core.Models.Entities; using redb.Route.Abstractions; using redb.Route.Llm.Engine.Observability; using redb.Route.Llm.Storage.Redb.Schemas; using redb.Route.RedbCore.Extensions; namespace redb.Route.Llm.Storage.Redb; /// /// REDB-backed that persists one /// row per tool invocation. Non-blocking by /// contract: a failed write never breaks a run, and it is logged as a warning with /// the tool, the tool_use id and the exchange id, so the missing row can be found. /// /// The observer is invoked from inside the agent loop, not from a route /// pipeline, and therefore has no IExchange in scope. Many runs call it at /// once, so every call opens a redb scope of its own with /// IRouteContext.CreateRedbScope(name) and releases it: a shared instance would /// put every run on one connection. The scope uses the constructor-supplied default /// name, or the host's default service when null. A custom observer can be /// substituted to pipe audit rows elsewhere. /// /// /// The row belongs to the route's transaction when there is one: under /// .Transacted() it is written and rolled back together with the tool writes it /// describes. /// /// public sealed class RedbAuditObserver : IAgentObserver { private readonly IRouteContext _context; private readonly string? _defaultRedbName; private ILogger? _logger; /// Creates the observer. Scheme is synced by the host's redb.InitializeAsync(). public RedbAuditObserver(IRouteContext context, string? defaultRedbName = null) { _context = context ?? throw new ArgumentNullException(nameof(context)); _defaultRedbName = defaultRedbName; } /// public Task OnRunStartedAsync(AgentRunContext context, CancellationToken ct = default) => Task.CompletedTask; /// public Task OnIterationCompletedAsync(AgentIterationContext context, CancellationToken ct = default) => Task.CompletedTask; /// public async Task OnToolInvokedAsync(AgentToolInvocationContext context, CancellationToken ct = default) { try { var outcome = context.Exception is not null ? "error" : context.Skipped ? (context.SkipReason?.Contains("denied", StringComparison.OrdinalIgnoreCase) == true ? "denied" : "skipped") : "success"; var row = new RedbObject { // The tool name leads the row name so an operator can slice by tool on a base field // (_objects.name) and read the scheme without joining anything. Filtering by the ToolName // property is also server-side (props-typed Where), just costlier. name = $"audit:{context.Tool.Name}:{context.Run.ExchangeId}:{context.ToolUseId}", Props = new ToolAuditProps { ConversationId = context.Run.ConversationId ?? string.Empty, ToolName = context.Tool.Name, ToolUseId = context.ToolUseId, InvokedAtUtc = DateTimeOffset.UtcNow.Subtract(context.Duration), DurationMs = (int)context.Duration.TotalMilliseconds, Outcome = outcome, SkipReason = context.SkipReason, InputJson = context.InputJson, OutputJson = context.OutputJson, ErrorMessage = context.Exception?.Message } }; // The instance the endpoint chose (?redb=) decides, as it does for every store; else the registration's. await using var scope = _context.CreateRedbScope(context.Run.RedbName ?? _defaultRedbName); await scope.Service.SaveAsync(row).ConfigureAwait(false); } catch (Exception ex) { // A lost audit row never breaks the run, but it must not vanish either: the operator has to be able to // find the gap. That includes a refusal to open the scope, which is a configuration error. Logger()?.LogWarning(ex, "Audit row for tool '{Tool}' (tool_use {ToolUseId}, exchange {ExchangeId}) was not written; the run goes on.", context.Tool.Name, context.ToolUseId, context.Run.ExchangeId); } } /// public Task OnRunCompletedAsync(AgentRunCompletedContext context, CancellationToken ct = default) => Task.CompletedTask; private ILogger? Logger() => _logger ??= (_context.GetService() ?? _context.GetServiceProvider()?.GetService(typeof(ILoggerFactory)) as ILoggerFactory) ?.CreateLogger(); }