Bundle: redb-route / redb.Route.Llm (redb.Route.Llm.txt), 94 files
Snapshot: 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
Index: https://redbase.app/src/dev-2026-12-06/redb-route/_index.txt
====
Path: redb-route/redb.Route.Llm/Embeddings/EmbedComponent.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/Embeddings/EmbedComponent.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Llm.Providers;
namespace redb.Route.Llm.Embeddings;
///
/// Embedding transport. Scheme: embed. Producer-only, symmetric with
/// llm://: To("embed://<connectionFactoryName>") turns the
/// exchange body (a text, or a collection of texts) into an embedding vector
/// (float[]) or vectors (float[][]) written to Out.Body.
///
/// The URI host names an (Provider / BaseUrl /
/// ApiKey / ModelId — set ModelId to the embedding model), so different
/// routes can pick different embedding models by name — the same lever as
/// llm://<factory>.
///
///
///
/// From("kafka://texts").To("embed://openai").To("vector://sink");
///
///
///
[EndpointRole(EndpointRole.Producer, Hint = "Use To(\"embed://\").")]
public sealed class EmbedComponent : ComponentBase
{
///
public override string Scheme => "embed";
///
/// Builds the from a resolved connection
/// factory. Defaults to ; override
/// for a custom provider or in tests.
///
public Func ProviderFactory { get; set; } =
OpenAiEmbeddingProvider.Create;
///
public override IEndpoint CreateEndpoint(EndpointUri uri)
{
ArgumentNullException.ThrowIfNull(uri);
var options = new EmbedEndpointOptions();
options.BindFromUri(uri.RawParameters);
options.Validate();
return new EmbedEndpoint(uri, this, options);
}
}
/// Options for an embed:// endpoint.
public sealed class EmbedEndpointOptions : EndpointOptions
{
/// Alternative to the URI host for the connection-factory name.
[RegistryReference(typeof(LlmConnectionFactory))]
public string? ConnectionFactory { get; set; }
///
public override void Validate() { }
}
/// Embedding endpoint. URI path = connection-factory name.
public sealed class EmbedEndpoint : EndpointBase
{
/// Connection-factory name (URI path or ?connectionFactory=).
public string FactoryName { get; }
/// Factory resolved from the route context (null when wired later).
internal LlmConnectionFactory? ResolvedFactory { get; }
/// Creates the endpoint.
public EmbedEndpoint(EndpointUri uri, EmbedComponent component, EmbedEndpointOptions options)
: base(uri, component, options)
{
FactoryName = !string.IsNullOrWhiteSpace(uri.Path) ? uri.Path : (options.ConnectionFactory ?? string.Empty);
if (string.IsNullOrWhiteSpace(FactoryName))
throw new InvalidOperationException(
"embed:// requires a connection factory — use 'embed://' or '?connectionFactory='.");
if (component.Context is not null)
ResolvedFactory = component.Context.GetFromRegistry(FactoryName);
}
///
public override IProducer CreateProducer() => new EmbedProducer(this, Options);
///
public override IConsumer CreateConsumer(IProcessor processor) =>
throw new NotSupportedException("embed:// is producer-only. Use To(\"embed://\").");
}
Path: redb-route/redb.Route.Llm/Embeddings/EmbedProducer.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/Embeddings/EmbedProducer.cs
----
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Llm.Providers;
namespace redb.Route.Llm.Embeddings;
///
/// Embedding producer: embeds the exchange body and writes the vector(s) to
/// Out.Body. A single text → float[]; a collection of texts →
/// float[][] (order preserved).
///
public sealed class EmbedProducer : ConnectableProducer
{
private readonly EmbedEndpoint _endpoint;
private readonly EmbedEndpointOptions _options;
private IEmbeddingProvider? _provider;
/// Creates the producer.
public EmbedProducer(EmbedEndpoint endpoint, EmbedEndpointOptions options)
{
_endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint));
_options = options ?? throw new ArgumentNullException(nameof(options));
}
///
protected override IEndpoint ProducerEndpoint => _endpoint;
///
protected override string ProducerName => $"embed:{_endpoint.FactoryName}";
///
protected override Task ConnectAsync(CancellationToken ct) => Task.CompletedTask;
///
public override async Task Process(IExchange exchange, CancellationToken ct = default)
{
EnsureStarted();
ArgumentNullException.ThrowIfNull(exchange);
var provider = ResolveProvider();
var body = exchange.In.Body;
exchange.Out ??= exchange.In.Clone();
if (body is IEnumerable texts) // a string is IEnumerable, not , so single texts fall through
{
var list = texts.ToList();
var vectors = await provider.EmbedAsync(list, ct).ConfigureAwait(false);
exchange.Out.Body = vectors is float[][] arr ? arr : vectors.ToArray();
exchange.Out.Headers["llm.embedding.count"] = vectors.Count;
exchange.Out.Headers["llm.embedding.dims"] = vectors.Count > 0 ? vectors[0].Length : 0;
}
else
{
var text = body?.ToString() ?? string.Empty;
var vector = await provider.EmbedOneAsync(text, ct).ConfigureAwait(false);
exchange.Out.Body = vector;
exchange.Out.Headers["llm.embedding.dims"] = vector.Length;
}
exchange.Out.Headers["llm.embedding.model"] = provider.ModelId;
exchange.Out.Headers["llm.embedding.provider"] = provider.ProviderId;
}
private IEmbeddingProvider ResolveProvider()
{
if (_provider is not null) return _provider;
var component = (EmbedComponent)_endpoint.Component;
var factory = _endpoint.ResolvedFactory
?? component.Context?.GetFromRegistry(_endpoint.FactoryName)
?? throw new InvalidOperationException(
$"embed://: connection factory '{_endpoint.FactoryName}' is not registered in the route context.");
_provider = component.ProviderFactory(factory);
return _provider;
}
}
Path: redb-route/redb.Route.Llm/Engine/AgentBudgetFactory.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/Engine/AgentBudgetFactory.cs
----
using redb.Route.Llm.Engine.Governance;
namespace redb.Route.Llm.Engine;
///
/// Translates the nullable budget options of an endpoint / builder into an .
///
/// The nulls matter: null means "this dimension is not limited", while
/// spells that as <= 0. Collapsing an unset option to zero would be harmless here (zero is
/// the same as unset for the enforcer) — but doing it in the URI would not, so the options are
/// appended only when set.
///
///
internal static class AgentBudgetFactory
{
/// Builds the per-run budget; all-null maps to .
public static AgentBudget From(int? inputTokens, int? outputTokens, decimal? costUsd)
=> inputTokens is null && outputTokens is null && costUsd is null
? AgentBudget.Unbounded
: new AgentBudget(inputTokens ?? 0, outputTokens ?? 0, costUsd ?? 0m);
}
Path: redb-route/redb.Route.Llm/Engine/AgentEngine.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/Engine/AgentEngine.cs
----
using System.Diagnostics;
using System.Security.Claims;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using Microsoft.Extensions.Logging;
using redb.Route.Abstractions;
using redb.Route.Core;
using redb.Route.Llm.Abstractions.Tools;
using redb.Route.Llm.Engine.Governance;
using redb.Route.Llm.Engine.Observability;
using redb.Route.Llm.Engine.Storage;
using redb.Route.Llm.Expressions;
using redb.Route.Llm.Providers;
using redb.Route.Llm.Telemetry;
using redb.Route.Llm.Tools;
namespace redb.Route.Llm.Engine;
///
/// Default implementation. Drives the tool-loop with
/// governance, idempotency, approval, conversation persistence and audit
/// observability — every dependency is optional and defaults to a Noop
/// implementation so that simple cases (a tool-less, persistence-less call
/// against ) work out of the box.
///
public sealed class AgentEngine : IAgentEngine
{
private static readonly JsonSerializerOptions JsonOptions = new()
{
// UTF-8, not \uXXXX — keep non-ASCII readable and token-cheap on the wire.
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
private readonly ILogger? _logger;
private readonly IProducerTemplate? _producerTemplate;
private readonly IAgentObserver _observer;
private readonly IBudgetEnforcer _budget;
private readonly IApprovalGate _approval;
private readonly IRedactionFilter _redaction;
private readonly IShadowRunner _shadow;
private readonly IConversationStore? _conversation;
private readonly IToolIdempotencyStore? _idempotency;
private readonly IApprovalStore? _approvalStore;
private readonly IToolClaimsSource? _claimsSource;
private readonly IToolCacheStore? _toolCache;
private readonly ICostCalculator _costCalculator;
// The route and connection factory pairs already warned about in-memory stores inside a transaction: the
// warning is said once per step for the life of the engine, not on every exchange.
private readonly System.Collections.Concurrent.ConcurrentDictionary _inMemoryInTransactionWarned = new();
///
/// Backwards-compatible constructor — wires every dependency to its no-op
/// implementation. Use the DI-driven constructor for production wiring.
///
public AgentEngine(ILogger? logger = null)
: this(logger, producerTemplate: null, observer: null, budget: null, approval: null, redaction: null, shadow: null, conversation: null, idempotency: null, approvalStore: null)
{
}
/// Creates an engine with explicit governance / storage dependencies.
/// Optional logger for governance decisions and tool failures.
/// Producer used to dispatch tool calls onto their endpoints.
/// Observability sink; defaults to .
/// Budget enforcer; defaults to (no ceiling).
/// Approval gate; defaults to .
/// Redaction filter; defaults to .
/// Shadow runner; defaults to .
/// Conversation store; absent means the run is not persisted.
/// Idempotency store, consulted for tools with a declared side effect.
/// Audit sink for approval decisions; absent means none are recorded.
///
/// Optional claims source. When absent, a tool that declares
/// is denied — fail closed by design.
///
///
/// Optional cross-run tool cache. Consulted only for ToolCachingPolicy.Persist;
/// Memoize is served by a run-scoped in-process cache. When absent, persisted caching
/// degrades to "not cached" rather than failing.
///
///
/// Prices provider responses for cost budgets; defaults to , which
/// makes a run that requests a cost ceiling fail fast instead of enforcing a zero ceiling.
///
public AgentEngine(
ILogger? logger,
IProducerTemplate? producerTemplate,
IAgentObserver? observer,
IBudgetEnforcer? budget,
IApprovalGate? approval,
IRedactionFilter? redaction,
IShadowRunner? shadow,
IConversationStore? conversation,
IToolIdempotencyStore? idempotency,
IApprovalStore? approvalStore,
IToolClaimsSource? claimsSource = null,
IToolCacheStore? toolCache = null,
ICostCalculator? costCalculator = null)
{
_logger = logger;
_producerTemplate = producerTemplate;
_observer = observer ?? new NoopAgentObserver();
_budget = budget ?? new NoopBudgetEnforcer();
_approval = approval ?? new AutoApproveGate();
_redaction = redaction ?? new NoopRedactionFilter();
_shadow = shadow ?? new NoopShadowRunner();
_conversation = conversation;
_idempotency = idempotency;
_approvalStore = approvalStore;
_claimsSource = claimsSource;
_toolCache = toolCache;
_costCalculator = costCalculator ?? new NullCostCalculator();
}
///
/// Builds an engine from whatever the route context and its DI container can provide — the
/// production composition path. Every seam is optional here (an absent store means "not configured",
/// not "broken"), so a host only has to call AddRedbRouteLlm(), and the engine it resolves
/// carries the governance the package registered.
///
/// Constructing an engine by hand is still possible, but then every seam is the caller's to wire —
/// including the ones added since: use this factory (or DI) unless you intend to replace them all.
///
///
/// Route context whose locator and DI provider are searched for the dependencies.
public static AgentEngine FromContext(IRouteContext context)
{
ArgumentNullException.ThrowIfNull(context);
return new AgentEngine(
logger: Resolve>(context)
?? Resolve(context)?.CreateLogger(),
producerTemplate: Resolve(context),
// Absent collaborators fall back to the same no-ops AddRedbRouteLlm() registers, so a
// bare context (a demo, a hand-rolled host) gets a working engine instead of null references.
observer: Resolve(context) ?? new NoopAgentObserver(),
budget: Resolve(context) ?? new NoopBudgetEnforcer(),
approval: Resolve(context) ?? new AutoApproveGate(),
redaction: Resolve(context) ?? new NoopRedactionFilter(),
shadow: Resolve(context) ?? new NoopShadowRunner(),
conversation: Resolve(context),
idempotency: Resolve(context),
approvalStore: Resolve(context),
claimsSource: Resolve(context),
toolCache: Resolve(context),
costCalculator: Resolve(context));
}
///
/// Finds the engine a host registered — first in the route context's own locator, then in the DI
/// container — or null when the host registered none. Producers, consumers and the inline step
/// must all use this: deliberately looks only at the locator,
/// so asking it alone misses the engine AddRedbRouteLlm() registered in the container.
///
public static IAgentEngine? FindRegistered(IRouteContext context)
{
ArgumentNullException.ThrowIfNull(context);
return context.GetService()
?? context.GetServiceProvider()?.GetService(typeof(IAgentEngine)) as IAgentEngine;
}
///
/// The context's own locator wins (a host may explicitly override a seam there), then the DI
/// provider. deliberately looks only at the locator, so
/// asking one place would miss everything a container registered.
///
///
/// Inside an ambient transaction (a route's .Transacted()) the in-memory conversation and tool
/// idempotency stores this package ships do not take part in it: after a rollback the transcript still holds the
/// rolled-back run's tool calls and results, and a tool call id seen before is answered from memory, so a
/// redelivered message may not call the tool again. The run goes on; one warning per route and connection
/// factory says so. Only the stores the run uses count (the conversation store with a conversation, the
/// idempotency store with tools), and a host's own store implementations are not judged.
///
private void WarnInMemoryStoresInTransaction(AgentRequest request)
{
if (_logger is null || System.Transactions.Transaction.Current is null) return;
var stores = new List(2);
if (_conversation is InMemoryConversationStore && request.ConversationId is not null)
stores.Add(nameof(InMemoryConversationStore));
if (_idempotency is InMemoryToolIdempotencyStore && request.Tools.Count > 0)
stores.Add(nameof(InMemoryToolIdempotencyStore));
if (stores.Count == 0) return;
var route = request.Exchange.RouteId ?? "(no route)";
if (!_inMemoryInTransactionWarned.TryAdd($"{route}\n{request.Factory.Name}", 0)) return;
_logger.LogWarning(
"The llm:{Factory} step of route '{Route}' runs inside an ambient transaction, but {Stores} keep state in memory "
+ "and do not take part in the transaction. If it rolls back, the conversation keeps the rolled-back run's tool "
+ "calls and their results, and a tool call id seen before is answered from memory, so a redelivered message "
+ "may not call the tool again. Register the redb stores with AddRedbLlmStorage(), or move the llm: step out "
+ "of .Transacted(). Said once per route and connection factory.",
request.Factory.Name, route, string.Join(" and ", stores));
}
private static T? Resolve(IRouteContext context) where T : class
=> context.GetService()
?? context.GetServiceProvider()?.GetService(typeof(T)) as T;
///
public async Task RunAsync(AgentRequest request, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(request);
// A cost ceiling that cannot be priced must fail loudly and before the first provider call:
// the alternative is a run that reports "budget enforced" while pricing every call as zero.
if (request.Budget.MaxCostUsd > 0m
&& _costCalculator.Estimate(LlmUsage.Empty, request.Factory) is null)
{
throw new InvalidOperationException(
$"This run requests a cost budget of {request.Budget.MaxCostUsd:F4} USD, but the registered "
+ $"ICostCalculator cannot price model '{request.Factory.ModelId}'. Register a calculator that "
+ "knows the model's rates, or drop the cost ceiling.");
}
WarnInMemoryStoresInTransaction(request);
var provider = request.Factory.Build();
var capabilities = ProjectCapabilities(request.Tools);
var toolSetHash = ComputeToolSetHash(capabilities);
var effectiveTemperature = request.Temperature ?? request.Factory.Temperature;
var effectiveMaxTokens = request.MaxTokens ?? request.Factory.MaxTokens;
var effectiveTopP = request.Factory.TopP;
var runCtx = new AgentRunContext
{
ConversationId = request.ConversationId,
FactoryName = request.Factory.Name,
ProviderId = request.Factory.Provider,
ModelId = request.Factory.ModelId ?? string.Empty,
ExchangeId = request.Exchange.ExchangeId,
RedbName = request.Exchange.Properties.TryGetValue(LlmKeys.RedbName, out var redbName)
&& redbName is string { Length: > 0 } chosen
? chosen
: null
};
await _observer.OnRunStartedAsync(runCtx, ct).ConfigureAwait(false);
var retryCount = ReadRetryCount(request.Exchange);
// One memo per run, dropped when this method returns: "memoised for the lifetime of the agent
// run" is exactly what ToolCachingPolicy.Memoize promises, and nothing may outlive it.
var runCache = new AgentRunToolCache();
// The preamble opens the transcript and stays out of the store: it is part of how the
// assistant is assembled, not something said in this dialog (see AgentRequest.Preamble).
var transcript = new List(request.Preamble);
string? attachUnderId = request.ConversationParentMessageId;
if (_conversation is not null && request.ConversationId is { } convIdToLoad)
{
var path = await _conversation.LoadPathAsync(
convIdToLoad, request.ConversationParentMessageId, request.Exchange, ct).ConfigureAwait(false);
foreach (var node in path)
transcript.Add(node.Message);
if (path.Count > 0)
attachUnderId = path[^1].Id;
// Orphan tool_use recovery: if the loaded transcript ends with an
// assistant message that has unmatched tool_use blocks (e.g. a prior
// run was cancelled / timed out between persisting the assistant
// turn and dispatching tools), synthesize error tool_result blocks
// so the next provider call doesn't 400 on "tool_use without matching
// tool_result". Without this, the conversation poisons itself
// permanently for InMemory and any persistent store alike.
if (transcript.Count > 0 && transcript[^1].Role == "assistant")
{
var orphanResults = new List();
foreach (var block in transcript[^1].Content)
{
if (block is LlmToolUseBlock orphan)
orphanResults.Add(new LlmToolResultBlock(
orphan.ToolUseId,
"{\"error\":\"orphaned_tool_use_recovered\"}",
IsError: true));
}
if (orphanResults.Count > 0)
{
var recovery = new LlmMessage { Role = "user", Content = orphanResults };
transcript.Add(recovery);
attachUnderId = await PersistMessageAsync(
request, attachUnderId, recovery,
iteration: 0, stopReason: null, usage: LlmUsage.Empty,
toolUseId: null,
temperature: null, maxTokens: null, topP: null,
toolSetHash: null, providerSystemFingerprint: null,
providerResponseId: null, latencyMs: null,
retryCount: retryCount,
ct).ConfigureAwait(false);
_logger?.LogWarning(
"Recovered {Count} orphaned tool_use block(s) in conversation {Conv} on load.",
orphanResults.Count, convIdToLoad);
}
}
}
transcript.Add(new LlmMessage { Role = "user", Content = request.UserContent });
PublishConversationContext(request, transcript, iterations: 0, totalUsage: AgentUsage.Zero);
var parentMessageId = await PersistMessageAsync(
request,
parentId: attachUnderId,
message: transcript[^1],
iteration: 0,
stopReason: null,
usage: LlmUsage.Empty,
toolUseId: null,
temperature: null, maxTokens: null, topP: null,
toolSetHash: null, providerSystemFingerprint: null,
providerResponseId: null, latencyMs: null,
retryCount: retryCount,
ct).ConfigureAwait(false);
var iter = 0;
var totalUsage = AgentUsage.Zero;
// Cache counters ride alongside AgentUsage rather than inside it. AgentUsage is the
// BUDGET currency — what the run is allowed to spend — and cache reads/writes are not
// billable input; folding them in would make every budget silently wrong. But dropping
// them was worse: the run's own answer to "is the prompt cache working?" is these two
// numbers, and until now RunAsync summed them per iteration and then threw them away.
var cacheWrite = 0;
var cacheRead = 0;
LlmResponse? last = null;
Exception? terminalException = null;
var cancelled = false;
try
{
while (true)
{
ct.ThrowIfCancellationRequested();
if (iter >= request.MaxIterations)
{
_logger?.LogWarning("Agent reached MaxIterations={Max}; stopping.", request.MaxIterations);
break;
}
var pre = await OutsideTransactionAsync(
() => _budget.PreCheckAsync(request.ConversationId, request.Budget, totalUsage, request.Exchange, ct)).ConfigureAwait(false);
if (!pre.Continue)
{
_logger?.LogInformation("Budget pre-check stopped run: {Reason}", pre.Reason);
break;
}
iter++;
var llmRequest = new LlmRequest
{
ModelId = request.Factory.ModelId,
SystemPrompt = request.SystemPrompt,
// Every iteration of the tool loop resends the same system prompt, so the
// flag rides along — the second turn onward is where the cache pays off.
CacheSystemPrompt = request.CacheSystemPrompt,
Messages = transcript,
Tools = capabilities,
Temperature = effectiveTemperature,
MaxTokens = effectiveMaxTokens,
TopP = effectiveTopP
};
var providerTag = new KeyValuePair("llm.provider", request.Factory.Provider);
var modelTag = new KeyValuePair("llm.model.id", request.Factory.ModelId);
var factoryTag = new KeyValuePair("llm.factory", request.Factory.Name);
var sw = Stopwatch.StartNew();
try
{
last = request.StreamModelCalls
? await CallStreamingAsync(provider, llmRequest, runCtx, iter, request.OnDelta, ct).ConfigureAwait(false)
: await provider.CompleteAsync(llmRequest, ct).ConfigureAwait(false);
LlmMetrics.Calls.Add(1, providerTag, modelTag, factoryTag);
}
catch
{
LlmMetrics.CallsFailed.Add(1, providerTag, modelTag, factoryTag);
throw;
}
finally
{
LlmMetrics.CallDuration.Record(sw.Elapsed.TotalMilliseconds, providerTag, modelTag, factoryTag);
}
if (last.Usage.InputTokens > 0)
LlmMetrics.TokensIn.Add(last.Usage.InputTokens, providerTag, modelTag, factoryTag);
if (last.Usage.OutputTokens > 0)
LlmMetrics.TokensOut.Add(last.Usage.OutputTokens, providerTag, modelTag, factoryTag);
// Cost is what the deployment can price, not a placeholder zero: a cost ceiling must
// not silently collapse into a tokens-only budget.
var iterUsage = new AgentUsage(
last.Usage.InputTokens,
last.Usage.OutputTokens,
_costCalculator.Estimate(last.Usage, request.Factory) ?? 0m);
totalUsage = totalUsage.Add(iterUsage);
cacheWrite += last.Usage.CacheCreationInputTokens;
cacheRead += last.Usage.CacheReadInputTokens;
await _observer.OnIterationCompletedAsync(new AgentIterationContext
{
Run = runCtx,
Iteration = iter,
StopReason = last.StopReason,
IterationUsage = last.Usage,
Duration = sw.Elapsed
}, ct).ConfigureAwait(false);
if (_shadow.Enabled)
_ = SafeRunShadowAsync(provider, llmRequest, last, ct);
transcript.Add(new LlmMessage { Role = "assistant", Content = last.Content });
parentMessageId = await PersistMessageAsync(
request, parentMessageId, transcript[^1],
iteration: iter, stopReason: last.StopReason, usage: last.Usage,
toolUseId: null,
temperature: effectiveTemperature,
maxTokens: effectiveMaxTokens,
topP: effectiveTopP,
toolSetHash: toolSetHash,
providerSystemFingerprint: last.ProviderSystemFingerprint,
providerResponseId: last.ProviderResponseId,
latencyMs: (long)sw.Elapsed.TotalMilliseconds,
retryCount: retryCount,
ct).ConfigureAwait(false);
PublishConversationContext(request, transcript, iter, totalUsage);
var post = await OutsideTransactionAsync(() => _budget.RecordAndCheckAsync(
request.ConversationId, request.Budget, iterUsage, totalUsage, request.Exchange, ct)).ConfigureAwait(false);
if (!post.Continue)
{
_logger?.LogInformation("Budget post-check stopped run: {Reason}", post.Reason);
break;
}
if (last.StopReason != LlmStopReason.ToolUse) break;
var toolResults = new List(last.Content.Count);
foreach (var block in last.Content)
{
if (block is not LlmToolUseBlock use) continue;
var resultBlock = await DispatchToolAsync(request, runCtx, runCache, use, parentMessageId, ct).ConfigureAwait(false);
toolResults.Add(resultBlock);
}
transcript.Add(new LlmMessage { Role = "user", Content = toolResults });
parentMessageId = await PersistMessageAsync(
request, parentMessageId, transcript[^1],
iteration: iter, stopReason: null, usage: LlmUsage.Empty,
toolUseId: null,
temperature: null, maxTokens: null, topP: null,
toolSetHash: null, providerSystemFingerprint: null,
providerResponseId: null, latencyMs: null,
retryCount: retryCount,
ct).ConfigureAwait(false);
}
}
catch (OperationCanceledException)
{
cancelled = true;
throw;
}
catch (Exception ex)
{
terminalException = ex;
throw;
}
finally
{
await _observer.OnRunCompletedAsync(new AgentRunCompletedContext
{
Run = runCtx,
Iterations = iter,
TotalUsage = new LlmUsage(
totalUsage.InputTokens, totalUsage.OutputTokens, cacheWrite, cacheRead),
StopReason = last?.StopReason ?? LlmStopReason.Other,
Exception = terminalException,
Cancelled = cancelled
}, CancellationToken.None).ConfigureAwait(false);
}
// Return the last ASSISTANT content, not transcript[^1]: when the loop stops mid-round (MaxIterations
// or budget) the tail is a tool-results user message with no text, which would surface as an empty
// answer. The last assistant message carries the model's actual output.
// ...and never the preamble's assistant turn: a run that stopped before its first call
// (budget pre-check, MaxIterations=0) has no answer, and the fixed opening line must not
// be handed back as if the model had just said it.
LlmMessage? lastAssistant = null;
for (var i = transcript.Count - 1; i >= request.Preamble.Count; i--)
if (transcript[i].Role == "assistant") { lastAssistant = transcript[i]; break; }
return new AgentResponse
{
Content = (lastAssistant ?? transcript[^1]).Content,
Usage = new LlmUsage(
totalUsage.InputTokens, totalUsage.OutputTokens, cacheWrite, cacheRead),
Iterations = iter,
StopReason = last?.StopReason ?? LlmStopReason.Other
};
}
///
/// One model call made as a stream (). The pieces go to the observer as
/// they arrive; the loop goes on with the whole answer the stream assembled, the same answer a plain call returns,
/// so nothing after the call differs from a run without streaming.
///
private async Task CallStreamingAsync(
ILlmProvider provider, LlmRequest llmRequest, AgentRunContext runCtx, int iteration,
Func? onDelta, CancellationToken ct)
{
LlmResponse? answer = null;
await foreach (var chunk in provider.StreamAsync(llmRequest, ct).WithCancellation(ct).ConfigureAwait(false))
{
foreach (var piece in chunk.Content)
{
var (kind, text) = piece switch
{
LlmTextBlock t => (AgentDeltaKind.Text, t.Text),
LlmThinkingBlock th => (AgentDeltaKind.Thinking, th.Text),
// Completed tool calls ride on the last chunk; they are part of the answer, not a piece of text.
_ => (default(AgentDeltaKind), (string?)null)
};
if (string.IsNullOrEmpty(text)) continue;
var delta = new AgentDeltaContext
{
Run = runCtx,
Iteration = iteration,
Kind = kind,
Text = text
};
await _observer.OnDeltaAsync(delta, ct).ConfigureAwait(false);
if (onDelta is not null) await onDelta(delta, ct).ConfigureAwait(false);
}
if (chunk.Response is not null) answer = chunk.Response;
}
return answer ?? throw new InvalidOperationException(
$"Provider '{provider.ProviderId}' ended its stream without the assembled answer (LlmStreamChunk.Response). "
+ "A provider that overrides StreamAsync must put the whole answer on its last chunk; one that does not "
+ "stream can leave StreamAsync to the interface's default, which does.");
}
private async Task DispatchToolAsync(
AgentRequest request, AgentRunContext runCtx, AgentRunToolCache runCache,
LlmToolUseBlock use, string? messageId, CancellationToken ct)
{
request.Exchange.setProperty(LlmExpressionKeys.Tool, new LlmToolContext
{
Name = use.Name,
ToolUseId = use.ToolUseId,
InputJson = use.InputJson,
ResultJson = null,
Duration = TimeSpan.Zero
});
var sw = Stopwatch.StartNew();
try
{
var result = await DispatchToolCoreAsync(request, runCtx, runCache, use, messageId, ct).ConfigureAwait(false);
sw.Stop();
request.Exchange.setProperty(LlmExpressionKeys.Tool, new LlmToolContext
{
Name = use.Name,
ToolUseId = use.ToolUseId,
InputJson = use.InputJson,
ResultJson = result.OutputJson,
Duration = sw.Elapsed
});
return result;
}
finally
{
// Tool context lives only for the duration of dispatch — clear after the
// caller has had a chance to read ${tool.*} for logging/metrics.
request.Exchange.Properties.Remove(LlmExpressionKeys.Tool);
}
}
private async Task DispatchToolCoreAsync(
AgentRequest request, AgentRunContext runCtx, AgentRunToolCache runCache,
LlmToolUseBlock use, string? messageId, CancellationToken ct)
{
var tool = FindTool(request.Tools, use.Name);
if (tool is null)
{
return new LlmToolResultBlock(use.ToolUseId,
JsonSerializer.Serialize(new { error = "unknown_tool", name = use.Name }, JsonOptions), IsError: true);
}
var redactedInput = _redaction.Redact(use.InputJson, RedactionContext.ToolInput);
// Claims are verified before approval: a caller that cannot prove its identity must not even
// reach the approver's queue. Fail closed — a tool that declares claims this run cannot
// verify is never invoked. The model is told the error code only; the missing-claim list
// stays in the observer/audit channel, so the tool's policy never leaks to the model.
var requiredClaims = tool.Capability.Safety.RequiredClaims;
if (requiredClaims.Count > 0)
{
var held = _claimsSource?.GetClaims(request.Exchange);
var missing = held is null
? [.. requiredClaims]
: requiredClaims.Where(c => !held.Contains(c, StringComparer.Ordinal)).ToArray();
if (missing.Length > 0)
{
await _observer.OnToolInvokedAsync(new AgentToolInvocationContext
{
Run = runCtx,
Tool = tool.Capability,
InputJson = redactedInput,
OutputJson = null,
ToolUseId = use.ToolUseId,
Duration = TimeSpan.Zero,
Skipped = true,
SkipReason = $"{ToolSkipReasons.ClaimsMissing}:{string.Join(",", missing)}"
}, ct).ConfigureAwait(false);
if (held is null)
{
// No principal at all is usually a transport/wiring problem, so it earns a warning.
_logger?.LogWarning(
"Tool '{Tool}' denied: no verifiable principal. Missing: [{Claims}]. Claims source: {Source}.",
use.Name, string.Join(", ", missing),
_claimsSource is null ? "none registered" : _claimsSource.GetType().Name);
}
else
{
// A caller that simply does not hold the claim is a normal decision, not an incident.
_logger?.LogInformation(
"Tool '{Tool}' denied: the principal lacks the required claims. Missing: [{Claims}].",
use.Name, string.Join(", ", missing));
}
return new LlmToolResultBlock(
use.ToolUseId,
JsonSerializer.Serialize(new { error = ToolResultErrors.ClaimsMissing }, JsonOptions),
IsError: true);
}
}
// An external tool (mail, payment, deployment) does something no transaction can take back. Inside an
// ambient transaction - a route's .Transacted() - the run's database work and deferred sends roll back
// together, but the external action would stay done, and a retry after the rollback would do it again.
// So it is not run there: the model gets an error it can answer around, the audit channel records why.
// Checked before approval, so nobody is asked to approve a call that cannot run.
if (tool.Capability.Safety.SideEffect == ToolSideEffect.External
&& System.Transactions.Transaction.Current is not null)
{
await _observer.OnToolInvokedAsync(new AgentToolInvocationContext
{
Run = runCtx,
Tool = tool.Capability,
InputJson = redactedInput,
OutputJson = null,
ToolUseId = use.ToolUseId,
Duration = TimeSpan.Zero,
Skipped = true,
SkipReason = ToolSkipReasons.ExternalInTransaction
}, ct).ConfigureAwait(false);
_logger?.LogWarning(
"Tool '{Tool}' declares SideEffect=External and was called inside an ambient transaction; it was not run, " +
"because its action cannot be rolled back with the transaction. Call it from a route without .Transacted().",
use.Name);
return new LlmToolResultBlock(
use.ToolUseId,
JsonSerializer.Serialize(new { error = ToolResultErrors.ExternalInTransaction }, JsonOptions),
IsError: true);
}
if (tool.Capability.Safety.RequiresApproval)
{
var approvalReq = new ApprovalRequest
{
ConversationId = request.ConversationId,
Tool = tool.Capability,
InputJson = redactedInput,
Exchange = request.Exchange,
ToolUseId = use.ToolUseId
};
var decision = await _approval.AwaitAsync(approvalReq, ct).ConfigureAwait(false);
if (_approvalStore is not null)
await _approvalStore.RecordAsync(approvalReq, decision, request.Exchange, ct).ConfigureAwait(false);
if (!decision.Approved)
{
await _observer.OnToolInvokedAsync(new AgentToolInvocationContext
{
Run = runCtx,
Tool = tool.Capability,
InputJson = redactedInput,
OutputJson = null,
ToolUseId = use.ToolUseId,
Duration = TimeSpan.Zero,
Skipped = true,
SkipReason = $"{ToolSkipReasons.ApprovalDeniedPrefix} {decision.Reason ?? "no reason"}"
}, ct).ConfigureAwait(false);
return new LlmToolResultBlock(use.ToolUseId,
JsonSerializer.Serialize(new { error = ToolResultErrors.ApprovalDenied, reason = decision.Reason }, JsonOptions),
IsError: true);
}
}
// Cache lookup runs before the idempotency reservation: a hit means "this exact input already
// produced this output", which is cheaper than asking "was this tool_use already executed?".
// Approval ran first, so a cached result can never bypass a gate.
//
// The gate is the tool's own declaration, checked here as well as at registration: only a
// read-only tool may be cached, because a cached entry suppresses the side effect it stands for.
// A descriptor that reached the engine without that check (a hand-built AgentRequest) is therefore
// not cached — and says so, instead of silently mutating nothing.
//
// The address is resolved BEFORE the key is built and then REUSED for the dispatch: a descriptor
// may address a per-tenant endpoint, and a BuildEndpointUri that is not pure must not produce one
// address for the key and another for the call.
string? memoKey = null;
string? storeKey = null;
string? resolvedToolUri = null;
var lookedUp = false;
var caching = tool.Capability.Safety.Caching;
var cacheable = caching != ToolCachingPolicy.None
&& tool.Capability.Safety.SideEffect == ToolSideEffect.ReadOnly;
if (caching != ToolCachingPolicy.None && !cacheable)
{
_logger?.LogWarning(
"Tool '{Tool}' declares Caching={Caching} with SideEffect={SideEffect}; its result is not cached. "
+ "Only read-only tools may be cached — registration rejects this combination, so this descriptor "
+ "reached the engine without it.",
use.Name, caching, tool.Capability.Safety.SideEffect);
}
if (cacheable)
{
resolvedToolUri = tool.BuildEndpointUri(use.InputJson, request.Exchange);
var policyFingerprint = ToolCacheKey.PolicyFingerprint(tool.Capability.Safety);
var callerFingerprint = CallerFingerprint(request);
memoKey = caching == ToolCachingPolicy.Memoize
? ToolCacheKey.MemoKey(
tool.Capability.Name, resolvedToolUri, policyFingerprint, callerFingerprint, use.InputJson)
: null;
storeKey = ToolCacheKey.StoreKey(
tool.Capability.Name, resolvedToolUri, use.InputJson, caching, policyFingerprint, callerFingerprint);
string? cachedOutput = null;
if (memoKey is not null)
{
cachedOutput = runCache.Get(memoKey);
lookedUp = true;
}
if (cachedOutput is null && storeKey is not null && _toolCache is not null)
{
// Best effort: a cache that cannot answer must not fail the run. A store outage is an
// operational incident, not a reason to refuse work the tool itself can still do.
try
{
cachedOutput = await _toolCache.GetAsync(storeKey, request.Exchange, ct).ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger?.LogWarning(ex,
"Tool-cache read failed for '{Tool}'; continuing without the cache.", use.Name);
cachedOutput = null;
}
lookedUp = true;
}
if (cachedOutput is not null)
{
LlmMetrics.ToolCacheHits.Add(1, new KeyValuePair("llm.tool.name", use.Name));
await _observer.OnToolInvokedAsync(new AgentToolInvocationContext
{
Run = runCtx,
Tool = tool.Capability,
InputJson = redactedInput,
OutputJson = cachedOutput,
ToolUseId = use.ToolUseId,
Duration = TimeSpan.Zero,
Skipped = true,
SkipReason = ToolSkipReasons.CacheHit
}, ct).ConfigureAwait(false);
return new LlmToolResultBlock(use.ToolUseId, cachedOutput);
}
if (lookedUp)
LlmMetrics.ToolCacheMisses.Add(1, new KeyValuePair("llm.tool.name", use.Name));
}
// Idempotency is opt-in per side-effect class, as the tool's Safety declares: a read-only tool
// has no side effect to de-duplicate, and reserving it costs store round-trips on every call.
// Note what this implies for tools that declare nothing — SideEffect defaults to ReadOnly, so
// "no declaration" means "no replay protection".
var needsIdempotency = tool.Capability.Safety.SideEffect != ToolSideEffect.ReadOnly;
ToolIdempotencyReservation? reservation = null;
if (_idempotency is not null && request.ConversationId is { } convId && needsIdempotency)
{
reservation = await _idempotency.TryReserveAsync(convId, use.ToolUseId, request.Exchange, ct).ConfigureAwait(false);
if (!reservation.IsNew)
{
await _observer.OnToolInvokedAsync(new AgentToolInvocationContext
{
Run = runCtx,
Tool = tool.Capability,
InputJson = redactedInput,
OutputJson = reservation.CachedOutputJson,
ToolUseId = use.ToolUseId,
Duration = TimeSpan.Zero,
Skipped = true,
SkipReason = ToolSkipReasons.IdempotencyHit
}, ct).ConfigureAwait(false);
return new LlmToolResultBlock(use.ToolUseId, reservation.CachedOutputJson ?? "{}");
}
}
var sw = Stopwatch.StartNew();
try
{
var output = await DispatchToolEndpointAsync(request, tool, use, resolvedToolUri, ct).ConfigureAwait(false);
sw.Stop();
LlmMetrics.ToolInvocations.Add(1, new KeyValuePair("llm.tool.name", use.Name));
if (reservation is not null && request.ConversationId is { } completeConvId)
await _idempotency!.CompleteAsync(completeConvId, use.ToolUseId, output, request.Exchange, ct).ConfigureAwait(false);
var redactedOutput = _redaction.Redact(output, RedactionContext.ToolOutput);
// Store only an output the redaction filter left untouched. Storing the redacted body
// would hand the model different data on a hit than on a miss (the returned block below
// carries the raw body); storing the raw body would persist redaction-bypassing content in
// the cache for the whole TTL. The price is honest and documented: a tool whose output is
// redacted is not cached at all.
if (!string.Equals(output, redactedOutput, StringComparison.Ordinal))
{
_logger?.LogDebug(
"Tool '{Name}' output was redacted — result is not cached.", use.Name);
}
else
{
if (memoKey is not null) runCache.Set(memoKey, output);
if (storeKey is not null && _toolCache is not null)
{
// Best effort, same reasoning as the read: a failed write loses a future hit, it does
// not invalidate a tool call that already succeeded. Letting it throw here would turn
// a successful call into an error the model sees — and may retry.
try
{
await _toolCache.SetAsync(storeKey, output, ToolCacheKey.StoreTtl, request.Exchange, ct)
.ConfigureAwait(false);
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
_logger?.LogWarning(ex,
"Tool-cache write failed for '{Tool}'; the result is not cached.", use.Name);
}
}
}
await _observer.OnToolInvokedAsync(new AgentToolInvocationContext
{
Run = runCtx,
Tool = tool.Capability,
InputJson = redactedInput,
OutputJson = redactedOutput,
ToolUseId = use.ToolUseId,
Duration = sw.Elapsed
}, ct).ConfigureAwait(false);
return new LlmToolResultBlock(use.ToolUseId, output);
}
catch (Exception ex)
{
sw.Stop();
LlmMetrics.ToolFailures.Add(1,
new KeyValuePair("llm.tool.name", use.Name),
new KeyValuePair("exception.type", ex.GetType().Name));
_logger?.LogError(ex, "Tool '{Name}' failed", use.Name);
if (reservation is not null && request.ConversationId is { } releaseConvId)
await _idempotency!.ReleaseAsync(releaseConvId, use.ToolUseId, request.Exchange, ct).ConfigureAwait(false);
await _observer.OnToolInvokedAsync(new AgentToolInvocationContext
{
Run = runCtx,
Tool = tool.Capability,
InputJson = redactedInput,
OutputJson = null,
ToolUseId = use.ToolUseId,
Duration = sw.Elapsed,
Exception = ex
}, ct).ConfigureAwait(false);
return new LlmToolResultBlock(use.ToolUseId,
JsonSerializer.Serialize(new { error = ex.GetType().Name, message = ex.Message }, JsonOptions), IsError: true);
}
}
private async Task PersistMessageAsync(
AgentRequest request,
string? parentId,
LlmMessage message,
int iteration,
LlmStopReason? stopReason,
LlmUsage usage,
string? toolUseId,
double? temperature,
int? maxTokens,
double? topP,
string? toolSetHash,
string? providerSystemFingerprint,
string? providerResponseId,
long? latencyMs,
int? retryCount,
CancellationToken ct)
{
if (_conversation is null || request.ConversationId is null) return parentId;
return await _conversation.AppendAsync(
request.ConversationId,
parentId,
message,
new ConversationMessageMeta
{
CreatedAtUtc = DateTime.UtcNow,
Iteration = iteration,
ProviderId = request.Factory.Provider,
ModelId = request.Factory.ModelId,
StopReason = stopReason,
Usage = usage,
ToolUseId = toolUseId,
Temperature = temperature,
MaxTokens = maxTokens,
TopP = topP,
PromptTemplateName = request.PromptTemplateName,
PromptTemplateVersion = request.PromptTemplateVersion,
ToolSetHash = toolSetHash,
ProviderSystemFingerprint = providerSystemFingerprint,
UserId = request.UserId,
AuditTags = request.AuditTags,
FactoryName = string.IsNullOrEmpty(request.Factory.Name) ? null : request.Factory.Name,
BaseUrl = request.Factory.BaseUrl?.ToString(),
ProviderResponseId = providerResponseId,
LatencyMs = latencyMs,
ApiKeyFingerprint = ComputeApiKeyFingerprint(request.Factory.ApiKey),
RetryCount = retryCount
},
request.Exchange,
ct).ConfigureAwait(false);
}
///
/// Reads the retry counter the route framework stamps on the inbound
/// exchange before the engine runs. Sources, in priority order: the
/// per-step RetryProcessor property, the OnExceptionProcessor
/// header, then the DeadLetterProcessor header. Returns null when
/// none are present (first / only delivery).
///
private static int? ReadRetryCount(IExchange exchange)
{
if (exchange.Properties.TryGetValue("RetryAttempt", out var prop) && TryToInt(prop, out var fromProp))
return fromProp;
if (exchange.In?.Headers is { } headers)
{
if (headers.TryGetValue("CamelRedeliveryCounter", out var redeliv) && TryToInt(redeliv, out var fromRedeliv))
return fromRedeliv;
if (headers.TryGetValue("CamelDeadLetterRedeliveryCount", out var dlq) && TryToInt(dlq, out var fromDlq))
return fromDlq;
}
return null;
static bool TryToInt(object? raw, out int value)
{
switch (raw)
{
case int i: value = i; return true;
case long l: value = (int)l; return true;
case string s when int.TryParse(s, out var parsed): value = parsed; return true;
default: value = 0; return false;
}
}
}
///
/// Stable, non-secret fingerprint of the API key — SHA-256 of the UTF-8
/// bytes, first 16 hex chars. Empty / null key → null fingerprint.
///
private static string? ComputeApiKeyFingerprint(string? apiKey)
{
if (string.IsNullOrEmpty(apiKey)) return null;
Span hash = stackalloc byte[32];
SHA256.HashData(Encoding.UTF8.GetBytes(apiKey), hash);
return Convert.ToHexString(hash[..8]).ToLowerInvariant();
}
private async Task SafeRunShadowAsync(ILlmProvider provider, LlmRequest request, LlmResponse response, CancellationToken ct)
{
// The shadow runs beside the primary run, not inside its work: it must not write into the route's
// transaction, and a command of its own on that transaction's connection at the same time as the
// primary run's would be refused.
using var outside = new System.Transactions.TransactionScope(
System.Transactions.TransactionScopeOption.Suppress,
System.Transactions.TransactionScopeAsyncFlowOption.Enabled);
try { await _shadow.RunAsync(provider, request, response, ct).ConfigureAwait(false); }
catch { /* shadow failures must never affect the primary run */ }
}
///
/// Runs a budget call outside the ambient transaction. Tokens are paid when the provider answers, so a
/// rollback of the route must not un-count them: a retry after the rollback would otherwise run against
/// a budget that forgot the spend.
///
private static async ValueTask OutsideTransactionAsync(Func> call)
{
using var outside = new System.Transactions.TransactionScope(
System.Transactions.TransactionScopeOption.Suppress,
System.Transactions.TransactionScopeAsyncFlowOption.Enabled);
var decision = await call().ConfigureAwait(false);
outside.Complete();
return decision;
}
private static void PublishConversationContext(
AgentRequest request, IReadOnlyList transcript, int iterations, AgentUsage totalUsage)
{
LlmMessage? lastAssistant = null;
for (var i = transcript.Count - 1; i >= 0; i--)
{
if (transcript[i].Role == "assistant") { lastAssistant = transcript[i]; break; }
}
request.Exchange.setProperty(LlmExpressionKeys.Conversation, new LlmConversationContext
{
Id = request.ConversationId,
MessageCount = transcript.Count,
Tokens = new LlmUsage(totalUsage.InputTokens, totalUsage.OutputTokens),
Iterations = iterations,
LastMessage = lastAssistant
});
}
private static LlmToolCapability[] ProjectCapabilities(IReadOnlyList tools)
{
if (tools.Count == 0) return [];
var arr = new LlmToolCapability[tools.Count];
for (var i = 0; i < tools.Count; i++) arr[i] = tools[i].Capability;
return arr;
}
private static ILlmToolDescriptor? FindTool(IReadOnlyList tools, string name)
{
foreach (var t in tools)
if (t.Capability.Name == name) return t;
return null;
}
///
/// Everything a tool receives that is NOT the input JSON and still changes its answer: the caller's
/// identity and the header values the route opted into propagating. Both belong in the cache key —
/// a tool route sees a real principal and real headers (see ), so
/// "same input" does not mean "same answer", and without this a persisted entry fetched for one
/// caller could be served to another.
///
/// The ambient conversation / correlation ids and the audit tags are deliberately left out: they are
/// per-run bookkeeping, and folding them in would make a cross-run cache useless. A tool whose output
/// depends on them must not declare Persist.
///
///
private static string CallerFingerprint(AgentRequest request)
{
var sb = new StringBuilder();
var principal = ExchangePrincipal.Get(request.Exchange);
string? subject = null;
if (principal?.Identity is { IsAuthenticated: true } identity)
subject = identity.Name ?? principal.FindFirst(ClaimTypes.NameIdentifier)?.Value;
sb.Append("caller:").Append(subject ?? request.UserId ?? string.Empty).Append('\n');
if (request.PropagateToolHeaders is { Count: > 0 } names)
{
var headers = request.Exchange.In?.Headers;
foreach (var name in names
.Where(n => !string.IsNullOrWhiteSpace(n))
.OrderBy(n => n, StringComparer.OrdinalIgnoreCase))
{
sb.Append("header:").Append(name).Append('=');
if (headers is not null && headers.TryGetValue(name, out var value) && value is not null)
sb.Append(value);
sb.Append('\n');
}
}
return sb.ToString();
}
///
/// Dispatches one tool call onto its redb.Route endpoint.
///
/// The tool runs on a child of the agent exchange, not on a freshly minted
/// one: carries over the parent's
/// Properties (including LlmKeys.RedbName), its RouteId and its
/// DI scope, so scoped services the conversation resolved — principal, tenant
/// accessor, per-exchange IRedbService — are the same instances inside the
/// tool. This is what documents; building a naked
/// exchange severed all of it.
///
///
/// Linked (shared scope) rather than a scope of its own: tool calls are
/// dispatched sequentially inside one iteration (see the foreach in
/// ), so there is no concurrent resolution on the shared
/// scope — a race on a shared scope applies to parallel forks, not to an inline
/// request/reply. A child scope would also defeat
/// the point: the tool would get an empty scope instead of the conversation's.
///
///
/// Headers are filtered by (default-deny), never
/// copied wholesale.
///
///
private async Task DispatchToolEndpointAsync(
AgentRequest request,
ILlmToolDescriptor descriptor,
LlmToolUseBlock use,
string? resolvedUri,
CancellationToken ct)
{
if (_producerTemplate is null)
throw new InvalidOperationException(
"AgentEngine has no IProducerTemplate. Register the engine via AddRedbRouteLlm() so the producer template is injected.");
var parentExchange = request.Exchange;
// The cache block resolves the address when it needs a key; passing it in keeps one resolution
// per dispatch, so a descriptor that is not pure cannot index the cache by one address and call
// another.
var endpointUri = resolvedUri ?? descriptor.BuildEndpointUri(use.InputJson, parentExchange);
if (string.IsNullOrWhiteSpace(endpointUri))
throw new InvalidOperationException(
$"Tool '{descriptor.Capability.Name}' returned an empty endpoint URI.");
var msg = new Message(use.InputJson) { ContentType = "application/json" };
msg.Headers[LlmHeaders.ToolName] = descriptor.Capability.Name;
msg.Headers[LlmHeaders.ToolBridgeEndpoint] = endpointUri;
ToolHeaderPolicy.Apply(request, msg.Headers);
var child = parentExchange.CreateLinkedChild(msg);
try
{
ct.ThrowIfCancellationRequested();
var done = await _producerTemplate.RequestAsync(endpointUri, child, ct).ConfigureAwait(false);
return SerializeReply(done.Out?.Body ?? done.In.Body);
}
finally
{
// Releases only what the tool route itself opened — the named
// `__redb_scope:*` entries it resolved (CreateLinkedChild does not copy the
// parent's). The shared parent scope is marked not-owned on the child, so
// the conversation keeps its scope and connections after the tool returns.
await child.DisposeAsync().ConfigureAwait(false);
}
}
private static readonly JsonSerializerOptions ToolReplyJsonOptions = new(JsonSerializerDefaults.Web)
{
// Non-ASCII tool output stays UTF-8 (not \uXXXX): escaped Cyrillic / CJK
// would ~6× the tokens the model sees and can surface literal \u escapes.
Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};
private static string SerializeReply(object? reply)
{
if (reply is null) return "null";
if (reply is string s) return JsonSerializer.Serialize(s, ToolReplyJsonOptions);
if (reply is IMessage m) return SerializeReply(m.Body);
if (reply is byte[] bytes) return JsonSerializer.Serialize(Convert.ToBase64String(bytes), ToolReplyJsonOptions);
return JsonSerializer.Serialize(reply, reply.GetType(), ToolReplyJsonOptions);
}
///
/// Stable hash of the tool-capability set exposed to the model on a single
/// run. Sorted by name; the source InputSchema string is folded in
/// verbatim — if its key order or whitespace changes between runs, the
/// hash changes too, which is exactly the signal an auditor wants
/// ("the same prompt saw a different tool surface yesterday"). Returns
/// null for the empty set so unused-tool runs don't pollute the column.
///
private static string? ComputeToolSetHash(IReadOnlyList capabilities)
{
if (capabilities.Count == 0) return null;
var sb = new StringBuilder();
foreach (var cap in capabilities.OrderBy(c => c.Name, StringComparer.Ordinal))
{
sb.Append(cap.Name).Append('\n');
sb.Append(cap.Description ?? string.Empty).Append('\n');
sb.Append(cap.InputSchema ?? string.Empty).Append('\n');
// Safety is part of the tool surface the model was given: a policy change between two runs
// is exactly the drift an auditor is looking for ("the same prompt, a weaker gate").
sb.Append("safety:")
.Append(cap.Safety.SideEffect).Append('/')
.Append(cap.Safety.Caching).Append('/')
.Append(cap.Safety.Cost).Append('/')
.Append(cap.Safety.RequiresApproval ? '1' : '0').Append('\n');
// Claims are length-prefixed: joining on a comma would hash ["a,b"] and ["a","b"]
// identically, which is the one collision an audit hash must not have.
foreach (var claim in cap.Safety.RequiredClaims.OrderBy(c => c, StringComparer.Ordinal))
sb.Append("claim:").Append(claim.Length).Append(':').Append(claim).Append('\n');
sb.Append("---\n");
}
var hash = SHA256.HashData(Encoding.UTF8.GetBytes(sb.ToString()));
return Convert.ToHexString(hash).ToLowerInvariant();
}
}
Path: redb-route/redb.Route.Llm/Engine/AgentRequest.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/Engine/AgentRequest.cs
----
using redb.Route.Abstractions;
using redb.Route.Llm.Abstractions.Tools;
using redb.Route.Llm.Engine.Governance;
using redb.Route.Llm.Providers;
namespace redb.Route.Llm.Engine;
///
/// Single agent execution request. Carries the user message, optional system prompt,
/// conversation context and the parent exchange for TX/scope/principal.
///
public sealed class AgentRequest
{
/// Connection factory used to build the provider.
public required LlmConnectionFactory Factory { get; init; }
/// Owning exchange — drives DI scope, headers, principal and observability.
public required IExchange Exchange { get; init; }
/// Initial user message (may include text and tool-result blocks).
public required IReadOnlyList UserContent { get; init; }
/// System prompt for this run.
public string? SystemPrompt { get; init; }
///
/// Ask the provider to cache the system prompt across turns — see
/// . Worth it only when the system prompt
/// is byte-stable; a prompt that varies per request never gets read back.
///
public bool CacheSystemPrompt { get; init; }
///
/// Messages placed before the loaded conversation history on every iteration of the
/// run — a fixed opening exchange the model sees as its own past, a few-shot block, anything
/// that must precede the dialog without being part of it.
///
/// Not persisted and not part of the conversation. The store keeps what was
/// said in this dialog; the preamble is part of how the assistant is assembled, so it is
/// re-attached from the request each time rather than written as rows. That is also what
/// makes it survive a branch rebuild: a fresh branch loads an empty path and the preamble is
/// still there.
///
/// Keep it byte-stable and mark its last message with
/// when the system prompt is cached too — otherwise
/// the cached prefix ends at the system block and the preamble is paid in full on every
/// turn. The first preamble message must be a user turn: providers require the
/// transcript to open with one.
///
public IReadOnlyList Preamble { get; init; } = [];
/// Tools available to the model on this run.
public IReadOnlyList Tools { get; init; } = [];
/// Conversation identifier (when conversation tracking is on).
public string? ConversationId { get; init; }
///
/// Message id of the conversation node this run should attach under.
/// Null = attach under the conversation root (continue at head when resuming;
/// new branch when the conversation already has children).
///
public string? ConversationParentMessageId { get; init; }
/// Per-run budget (defaults to unbounded).
public AgentBudget Budget { get; init; } = AgentBudget.Unbounded;
/// Maximum tool-loop iterations.
public int MaxIterations { get; init; } = 8;
/// Per-call sampling overrides.
public double? Temperature { get; init; }
/// Per-call max-tokens override.
public int? MaxTokens { get; init; }
///
/// Optional name of the prompt template that produced .
/// When set together with , the engine
/// stamps every persisted assistant message with the (name, version) pair so
/// auditors can reconstruct "which exact prompt drove this answer". Stays
/// null when the caller does not use a managed template.
///
public string? PromptTemplateName { get; init; }
/// Version of the prompt template named by .
public string? PromptTemplateVersion { get; init; }
///
/// Stable identifier of the principal that initiated this run (end-user,
/// service account, on-behalf-of subject — host decides). Persisted on
/// every row of the run so audit queries always have a consistent subject.
/// Null when no principal is wired.
///
public string? UserId { get; init; }
///
/// Free-form audit tags captured pre-call (operator-controlled key/value
/// pairs — e.g. ab-bucket=A, tier=premium). The same snapshot
/// is stamped on every row of the run; null / empty when no tags are wired.
///
public IReadOnlyDictionary? AuditTags { get; init; }
///
/// Extra header names the route author opted into propagating from this
/// exchange to every tool call of the run (e.g. x-tenant-id,
/// accept-language). A trailing * makes the entry a prefix match
/// (x-app-*). Propagation is default-deny: without an entry here only
/// , the resolved
/// and the resolved reach a tool —
/// the inbound transport's own headers never do. Null / empty = defaults only.
///
public IReadOnlyList? PropagateToolHeaders { get; init; }
///
/// Make every model call of the run as a stream (stream=calls). The pieces go to
/// as they arrive; the loop goes on with the whole answer
/// the stream assembled, the same answer a plain call returns, so tools, the conversation, the budget and the
/// route's transaction work as without streaming. The connection carries data while the model writes.
///
public bool StreamModelCalls { get; init; }
///
/// Receiver of this run's pieces, beside the observer: the observer is shared by every run of the engine, and this
/// one belongs to the run that set it. stream=body feeds Out.Body through it. Called only when
/// is on, in the order the pieces arrive.
///
public Func? OnDelta { get; init; }
}
/// Final agent response.
public sealed class AgentResponse
{
/// Last assistant content (text + any unanswered tool calls).
public required IReadOnlyList Content { get; init; }
/// Aggregate token usage across all iterations.
public LlmUsage Usage { get; init; } = LlmUsage.Empty;
/// Number of tool-loop iterations consumed.
public int Iterations { get; init; }
/// Final stop reason of the last provider call.
public LlmStopReason StopReason { get; init; } = LlmStopReason.EndTurn;
/// Convenience accessor — first text block in , or empty.
public string Text
{
get
{
foreach (var b in Content)
if (b is LlmTextBlock t) return t.Text;
return string.Empty;
}
}
}
Path: redb-route/redb.Route.Llm/Engine/Eval/LlmEvalCase.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/Engine/Eval/LlmEvalCase.cs
----
using redb.Route.Llm.Abstractions.Tools;
using redb.Route.Llm.Engine.Governance;
using redb.Route.Llm.Providers;
namespace redb.Route.Llm.Engine.Eval;
///
/// Declarative description of a single eval case. Combines the inputs the harness
/// feeds to with the assertions it scores
/// against the produced . Cases are pure data so the
/// same set can be replayed offline (via ReplayProvider) and against a
/// live provider.
///
public sealed class LlmEvalCase
{
/// Stable scenario name — also persisted on .
public required string Scenario { get; init; }
/// System prompt for the run. Null = no system prompt.
public string? SystemPrompt { get; init; }
/// User content blocks for the initial turn. Use for the common text-only case.
public IReadOnlyList UserContent { get; init; } = [];
/// Tools available to the model on this case (empty = no tools).
public IReadOnlyList Tools { get; init; } = [];
/// Maximum tool-loop iterations forwarded to .
public int MaxIterations { get; init; } = 4;
/// Per-run budget forwarded to .
public AgentBudget Budget { get; init; } = AgentBudget.Unbounded;
/// Sampling temperature override.
public double? Temperature { get; init; }
/// Max-tokens override.
public int? MaxTokens { get; init; }
/// Substrings the final assistant text must contain (case-sensitive).
public IReadOnlyList ExpectedTextContains { get; init; } = [];
/// Substrings the final assistant text must NOT contain (case-sensitive).
public IReadOnlyList ExpectedTextNotContains { get; init; } = [];
/// Tool names that must be invoked at least once across the run (in any order).
public IReadOnlyList ExpectedToolCalls { get; init; } = [];
/// When set, the run's final stop reason must equal this value.
public LlmStopReason? ExpectedStopReason { get; init; }
/// When set, the run's iteration count must be ≤ this value.
public int? MaxObservedIterations { get; init; }
/// When set, the run's total cost must be ≤ this value (USD).
public decimal? MaxObservedCostUsd { get; init; }
///
/// Optional custom scorer — receives the final and
/// returns a . Composes with the built-in
/// assertions: a case fails when any built-in assertion fails OR the custom
/// scorer returns = false.
///
public Func? CustomScorer { get; init; }
/// Convenience: builds a single-text-block .
public static IReadOnlyList UserText(string text) => [new LlmTextBlock(text)];
}
///
/// Outcome of a custom scorer. Pass=false marks the case as failed regardless of
/// other assertions; and flow into
/// the persisted .
///
public readonly record struct LlmEvalCaseScore(
bool Pass,
double? Score = null,
IReadOnlyDictionary? Dimensions = null,
string? Notes = null)
{
/// Convenience: passing score with no extras.
public static readonly LlmEvalCaseScore Passed = new(true);
}
Path: redb-route/redb.Route.Llm/Engine/Eval/LlmEvalRunner.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/Engine/Eval/LlmEvalRunner.cs
----
using System.Diagnostics;
using redb.Route.Core;
using redb.Route.Llm.Engine.Governance;
using redb.Route.Llm.Engine.Storage;
using redb.Route.Llm.Providers;
namespace redb.Route.Llm.Engine.Eval;
///
/// Drives a batch of through an ,
/// scores each run against the case's assertions, and (when configured) persists
/// the outcome via . Designed for both offline
/// regression suites (paired with ReplayProvider) and live smoke runs.
///
public sealed class LlmEvalRunner
{
private readonly IAgentEngine _engine;
private readonly LlmConnectionFactory _factory;
private readonly IEvalRunStore? _store;
/// Creates a runner bound to a concrete engine + provider factory.
/// Engine implementation under test.
/// Provider factory threaded through every .
/// Optional store for run records — null disables persistence.
public LlmEvalRunner(IAgentEngine engine, LlmConnectionFactory factory, IEvalRunStore? store = null)
{
_engine = engine ?? throw new ArgumentNullException(nameof(engine));
_factory = factory ?? throw new ArgumentNullException(nameof(factory));
_store = store;
}
/// Runs a single case to completion and returns the scored result.
public async Task RunAsync(LlmEvalCase @case, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(@case);
var sw = Stopwatch.StartNew();
AgentResponse? response = null;
Exception? failure = null;
try
{
response = await _engine.RunAsync(BuildRequest(@case), ct).ConfigureAwait(false);
}
catch (Exception ex)
{
failure = ex;
}
sw.Stop();
var result = Score(@case, response, failure, sw.Elapsed);
if (_store is not null)
await _store.SaveAsync(ToRecord(@case, result), ct: ct).ConfigureAwait(false);
return result;
}
///
/// Runs every case in sequentially. Failures in one
/// case never prevent the others from running — each
/// captures its own pass/fail and exception (if any).
///
public async Task> RunAllAsync(
IEnumerable cases, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(cases);
var results = new List();
foreach (var c in cases)
{
ct.ThrowIfCancellationRequested();
results.Add(await RunAsync(c, ct).ConfigureAwait(false));
}
return results;
}
private AgentRequest BuildRequest(LlmEvalCase @case)
{
var content = @case.UserContent.Count > 0 ? @case.UserContent : LlmEvalCase.UserText(@case.Scenario);
var bodyText = content.OfType().FirstOrDefault()?.Text ?? @case.Scenario;
return new AgentRequest
{
Factory = _factory,
Exchange = new Exchange(new Message(bodyText)),
UserContent = content,
SystemPrompt = @case.SystemPrompt,
Tools = @case.Tools,
MaxIterations = @case.MaxIterations,
Budget = @case.Budget,
Temperature = @case.Temperature,
MaxTokens = @case.MaxTokens
};
}
private static LlmEvalResult Score(
LlmEvalCase @case, AgentResponse? response, Exception? failure, TimeSpan duration)
{
var failures = new List();
if (failure is not null)
{
failures.Add($"engine threw: {failure.GetType().Name}: {failure.Message}");
return new LlmEvalResult
{
Case = @case,
Response = null,
Pass = false,
Failures = failures,
Duration = duration,
Exception = failure
};
}
var resp = response!;
var text = resp.Text;
foreach (var needle in @case.ExpectedTextContains)
if (!text.Contains(needle, StringComparison.Ordinal))
failures.Add($"expected text to contain '{needle}'");
foreach (var needle in @case.ExpectedTextNotContains)
if (text.Contains(needle, StringComparison.Ordinal))
failures.Add($"expected text to NOT contain '{needle}'");
if (@case.ExpectedStopReason is { } expectedStop && resp.StopReason != expectedStop)
failures.Add($"expected stop reason {expectedStop}, got {resp.StopReason}");
if (@case.MaxObservedIterations is { } maxIter && resp.Iterations > maxIter)
failures.Add($"iterations {resp.Iterations} exceeded max {maxIter}");
// Tool-call expectations are checked against the assistant turns recorded
// in the final transcript — only the last assistant message is on
// AgentResponse.Content, so we approximate by detecting tool-use blocks
// there. The integration tests use FakeProvider/ReplayProvider which
// surface tool calls explicitly enough for this check.
if (@case.ExpectedToolCalls.Count > 0)
{
var seen = new HashSet(StringComparer.Ordinal);
foreach (var b in resp.Content)
if (b is LlmToolUseBlock use) seen.Add(use.Name);
foreach (var name in @case.ExpectedToolCalls)
if (!seen.Contains(name))
failures.Add($"expected tool '{name}' to be invoked");
}
var customScore = @case.CustomScorer?.Invoke(resp);
if (customScore is { Pass: false } cs)
failures.Add(cs.Notes is { Length: > 0 } ? $"custom scorer failed: {cs.Notes}" : "custom scorer failed");
return new LlmEvalResult
{
Case = @case,
Response = resp,
Pass = failures.Count == 0,
Failures = failures,
Duration = duration,
Score = customScore?.Score,
Dimensions = customScore?.Dimensions,
Notes = customScore?.Notes
};
}
private EvalRunRecord ToRecord(LlmEvalCase @case, LlmEvalResult result)
{
var resp = result.Response;
var iterUsage = resp is null
? AgentUsage.Zero
: new AgentUsage(resp.Usage.InputTokens, resp.Usage.OutputTokens, 0m);
var iterations = resp is null
? Array.Empty()
: new[]
{
new EvalIterationRecord
{
Iteration = resp.Iterations,
InputTokens = resp.Usage.InputTokens,
OutputTokens = resp.Usage.OutputTokens,
DurationMs = (int)result.Duration.TotalMilliseconds,
Score = result.Score,
Notes = result.Notes
}
};
return new EvalRunRecord
{
RunId = Guid.NewGuid().ToString("N"),
Scenario = @case.Scenario,
AgentFingerprint = BuildFingerprint(@case),
Score = result.Score ?? (result.Pass ? 1.0 : 0.0),
TotalUsage = iterUsage,
Iterations = iterations,
Dimensions = result.Dimensions
};
}
private string BuildFingerprint(LlmEvalCase @case) =>
$"{_factory.Provider}/{_factory.ModelId ?? "default"}#{@case.Scenario}";
}
/// Outcome of a single evaluated case.
public sealed class LlmEvalResult
{
/// The case that produced this result.
public required LlmEvalCase Case { get; init; }
/// Agent response — null when the engine threw.
public AgentResponse? Response { get; init; }
/// True when every assertion passed.
public required bool Pass { get; init; }
/// Human-readable failure messages — empty when is true.
public IReadOnlyList Failures { get; init; } = [];
/// Wall-clock duration of the run.
public TimeSpan Duration { get; init; }
/// Custom scorer's score, if any.
public double? Score { get; init; }
/// Custom scorer's dimensions, if any.
public IReadOnlyDictionary? Dimensions { get; init; }
/// Custom scorer's free-form notes, if any.
public string? Notes { get; init; }
/// Engine exception, when the run threw.
public Exception? Exception { get; init; }
}
Path: redb-route/redb.Route.Llm/Engine/Governance/IApprovalGate.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/Engine/Governance/IApprovalGate.cs
----
using redb.Route.Abstractions;
using redb.Route.Llm.Abstractions.Tools;
namespace redb.Route.Llm.Engine.Governance;
///
/// Gate that blocks a tool call until an approver responds. The agent loop calls
/// before dispatching a tool whose
/// is set — that flag is the only trigger in this
/// release; a tool's side-effect class does not reach the gate on its own.
///
public interface IApprovalGate
{
///
/// Awaits an approval decision for the given tool call.
///
/// Pending approval request.
/// Cancellation token.
/// The approver's decision.
Task AwaitAsync(ApprovalRequest request, CancellationToken ct = default);
}
/// Pending tool-call approval request handed to the gate.
public sealed class ApprovalRequest
{
/// Conversation identifier (when persistence is on).
public string? ConversationId { get; init; }
/// Tool that will be executed.
public required LlmToolCapability Tool { get; init; }
/// Tool input JSON exactly as it would be passed to the bridged endpoint.
public required string InputJson { get; init; }
/// Parent exchange owning the call (carries principal, headers, scope).
public required IExchange Exchange { get; init; }
/// Tool-use id from the model response — propagated to the approver and audit.
public required string ToolUseId { get; init; }
}
/// Outcome of an approval decision.
public sealed class ApprovalDecision
{
/// True = proceed with the tool call; false = abort.
public required bool Approved { get; init; }
/// Identifier of the approval (for audit / receipt). May be null.
public string? ApprovalId { get; init; }
/// Optional reason supplied by the approver (especially on rejection).
public string? Reason { get; init; }
/// Convenience factory for an auto-approval decision.
public static ApprovalDecision Approve(string? approvalId = null) =>
new() { Approved = true, ApprovalId = approvalId };
/// Convenience factory for a denial decision.
public static ApprovalDecision Deny(string reason) =>
new() { Approved = false, Reason = reason };
}
///
/// Default gate that auto-approves every request — used in development and in
/// fully-trusted scenarios. **Do not use in production** for tools with
/// or .
///
public sealed class AutoApproveGate : IApprovalGate
{
///
public Task AwaitAsync(ApprovalRequest request, CancellationToken ct = default)
=> Task.FromResult(ApprovalDecision.Approve("auto"));
}
///
/// Gate that denies every approval request. Opt-in: it is not registered by default
/// (the shipped default is ), and nothing picks it up automatically
/// when mutating tools are present. Swap it in explicitly when a host wants approvals to fail closed:
/// services.Replace(ServiceDescriptor.Singleton<IApprovalGate, DenyAllGate>());
///
public sealed class DenyAllGate : IApprovalGate
{
///
public Task AwaitAsync(ApprovalRequest request, CancellationToken ct = default)
=> Task.FromResult(ApprovalDecision.Deny("no approval gate configured"));
}
Path: redb-route/redb.Route.Llm/Engine/Governance/IBudgetEnforcer.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/Engine/Governance/IBudgetEnforcer.cs
----
using redb.Route.Abstractions;
namespace redb.Route.Llm.Engine.Governance;
///
/// Enforces token and cost budgets on agent runs. Called before and after each
/// provider call so the engine can stop early or refuse an iteration when the
/// budget is exhausted.
///
public interface IBudgetEnforcer
{
///
/// Checks whether the agent run is allowed to continue at the start of an
/// iteration. Implementations may inspect
/// against a configured budget and return .
///
/// Conversation identifier (null when no persistence).
/// Per-run budget (zero or negative components mean unlimited).
/// Aggregated usage across iterations completed so far.
/// Cancellation token.
ValueTask PreCheckAsync(
string? conversationId,
AgentBudget budget,
AgentUsage usageSoFar,
CancellationToken ct = default);
///
/// Records usage produced by the iteration and returns a decision whether the agent may
/// continue. The engine passes per-iteration and running totals; accumulating them on an
/// is up to the implementation — see
/// , the one shipped enforcer that does.
///
ValueTask RecordAndCheckAsync(
string? conversationId,
AgentBudget budget,
AgentUsage iterationUsage,
AgentUsage totalUsage,
CancellationToken ct = default);
///
/// with the run's exchange, which
/// the engine calls: an enforcer that stores usage reads it from the instance the endpoint chose
/// (?redb=). The default ignores the exchange, so an enforcer that stores nothing implements only the
/// member without it.
///
ValueTask PreCheckAsync(
string? conversationId,
AgentBudget budget,
AgentUsage usageSoFar,
IExchange? exchange,
CancellationToken ct = default)
=> PreCheckAsync(conversationId, budget, usageSoFar, ct);
///
/// with the
/// run's exchange, which the engine calls: an enforcer that stores usage writes it to the instance the endpoint
/// chose (?redb=). The default ignores the exchange.
///
ValueTask RecordAndCheckAsync(
string? conversationId,
AgentBudget budget,
AgentUsage iterationUsage,
AgentUsage totalUsage,
IExchange? exchange,
CancellationToken ct = default)
=> RecordAndCheckAsync(conversationId, budget, iterationUsage, totalUsage, ct);
}
/// Per-run budget. Components ≤ 0 disable that dimension of enforcement.
public readonly record struct AgentBudget(int MaxInputTokens, int MaxOutputTokens, decimal MaxCostUsd)
{
/// Unbounded budget — used when caller didn't supply one.
public static readonly AgentBudget Unbounded = new(0, 0, 0m);
/// True when every dimension is disabled (Unbounded).
public bool IsUnbounded => MaxInputTokens <= 0 && MaxOutputTokens <= 0 && MaxCostUsd <= 0m;
}
/// Running usage measured against an .
public readonly record struct AgentUsage(int InputTokens, int OutputTokens, decimal CostUsd)
{
/// Zero usage — used as the running total starting point.
public static readonly AgentUsage Zero = new(0, 0, 0m);
/// Adds two usages component-wise.
public AgentUsage Add(AgentUsage other) =>
new(InputTokens + other.InputTokens, OutputTokens + other.OutputTokens, CostUsd + other.CostUsd);
}
/// Outcome of a budget enforcement decision.
public readonly record struct BudgetDecision(bool Continue, string? Reason)
{
/// Allows the iteration to proceed.
public static readonly BudgetDecision Allow = new(true, null);
/// Stops the agent run with a human-readable reason.
public static BudgetDecision Stop(string reason) => new(false, reason);
}
/// Default no-op budget enforcer — always allows execution.
public sealed class NoopBudgetEnforcer : IBudgetEnforcer
{
///
public ValueTask PreCheckAsync(
string? conversationId, AgentBudget budget, AgentUsage usageSoFar, CancellationToken ct = default)
=> ValueTask.FromResult(BudgetDecision.Allow);
///
public ValueTask RecordAndCheckAsync(
string? conversationId, AgentBudget budget, AgentUsage iterationUsage, AgentUsage totalUsage, CancellationToken ct = default)
=> ValueTask.FromResult(BudgetDecision.Allow);
}
///
/// In-process budget enforcer — checks components against the running
/// total. Does NOT persist between runs and takes no store: cross-run budgets need a custom
/// over an .
///
public sealed class InMemoryBudgetEnforcer : IBudgetEnforcer
{
///
public ValueTask PreCheckAsync(
string? conversationId, AgentBudget budget, AgentUsage usageSoFar, CancellationToken ct = default)
{
if (budget.IsUnbounded) return ValueTask.FromResult(BudgetDecision.Allow);
return ValueTask.FromResult(Check(budget, usageSoFar));
}
///
public ValueTask RecordAndCheckAsync(
string? conversationId, AgentBudget budget, AgentUsage iterationUsage, AgentUsage totalUsage, CancellationToken ct = default)
{
if (budget.IsUnbounded) return ValueTask.FromResult(BudgetDecision.Allow);
return ValueTask.FromResult(Check(budget, totalUsage));
}
private static BudgetDecision Check(AgentBudget budget, AgentUsage usage)
{
if (budget.MaxInputTokens > 0 && usage.InputTokens >= budget.MaxInputTokens)
return BudgetDecision.Stop($"input-token budget exceeded ({usage.InputTokens}/{budget.MaxInputTokens})");
if (budget.MaxOutputTokens > 0 && usage.OutputTokens >= budget.MaxOutputTokens)
return BudgetDecision.Stop($"output-token budget exceeded ({usage.OutputTokens}/{budget.MaxOutputTokens})");
if (budget.MaxCostUsd > 0m && usage.CostUsd >= budget.MaxCostUsd)
return BudgetDecision.Stop($"cost budget exceeded ({usage.CostUsd:F4}/{budget.MaxCostUsd:F4} USD)");
return BudgetDecision.Allow;
}
}
Path: redb-route/redb.Route.Llm/Engine/Governance/ICostCalculator.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/Engine/Governance/ICostCalculator.cs
----
using redb.Route.Llm.Providers;
namespace redb.Route.Llm.Engine.Governance;
///
/// Prices one provider response so a cost budget can be enforced. The engine asks this once per
/// iteration and once before the first call (to prove the model can be priced at all).
///
/// Return null only when this deployment cannot price the call at all — a model whose rates it
/// does not know. A calculator that knows the rates returns 0m for zero usage; returning
/// null there would make the engine refuse a cost-budgeted run it could actually enforce.
///
///
public interface ICostCalculator
{
/// Estimated cost in USD for one response, or null when the model cannot be priced.
/// Token usage reported by the provider for the call.
/// The connection factory the call was made through (model id, provider id).
decimal? Estimate(LlmUsage usage, LlmConnectionFactory factory);
}
///
/// Default calculator: prices nothing. Registered by AddRedbRouteLlm() so the engine always has
/// a calculator to ask; a run that requests a cost budget while this one is registered fails fast
/// instead of silently enforcing a zero ceiling.
///
public sealed class NullCostCalculator : ICostCalculator
{
///
public decimal? Estimate(LlmUsage usage, LlmConnectionFactory factory) => null;
}
Path: redb-route/redb.Route.Llm/Engine/Governance/IRedactionFilter.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/Engine/Governance/IRedactionFilter.cs
----
namespace redb.Route.Llm.Engine.Governance;
///
/// Removes secrets / PII from strings before they are logged, persisted to
/// , or sent to observers. Applied to
/// both inbound user content and outbound model content, plus tool input/output.
///
public interface IRedactionFilter
{
///
/// Returns the redacted form of . Implementations
/// must be deterministic so re-saves don't re-redact already-masked tokens.
///
string Redact(string text, RedactionContext context);
}
/// Context flags that influence how a piece of text is redacted.
[Flags]
public enum RedactionContext
{
/// Unspecified.
None = 0,
/// Text is part of the user-supplied prompt.
UserInput = 1,
/// Text is model-generated content.
ModelOutput = 2,
/// Text is tool input JSON.
ToolInput = 4,
/// Text is tool output JSON.
ToolOutput = 8,
/// Text is going to be logged (vs stored).
Log = 16
}
/// Default redaction filter — returns the input untouched.
public sealed class NoopRedactionFilter : IRedactionFilter
{
///
public string Redact(string text, RedactionContext context) => text;
}
Path: redb-route/redb.Route.Llm/Engine/Governance/IShadowRunner.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/Engine/Governance/IShadowRunner.cs
----
using redb.Route.Llm.Providers;
namespace redb.Route.Llm.Engine.Governance;
///
/// Optional shadow runner — when enabled, every primary provider call is also
/// executed against an alternate factory, results compared and the divergence
/// recorded via the for offline review.
/// The user-visible response always comes from the primary call; the shadow run
/// never affects routing.
///
public interface IShadowRunner
{
/// True when a shadow run should be executed alongside the primary.
bool Enabled { get; }
///
/// Executes the shadow call. Implementations should be fire-and-forget from
/// the caller's perspective — exceptions must not propagate.
///
/// Provider used for the visible response.
/// Request that was sent to the primary provider.
/// Primary provider response — for divergence comparison.
/// Cancellation token.
Task RunAsync(
ILlmProvider primary,
LlmRequest request,
LlmResponse primaryResponse,
CancellationToken ct = default);
}
/// Default no-op shadow runner — disabled, never executes anything.
public sealed class NoopShadowRunner : IShadowRunner
{
///
public bool Enabled => false;
///
public Task RunAsync(ILlmProvider primary, LlmRequest request, LlmResponse primaryResponse, CancellationToken ct = default)
=> Task.CompletedTask;
}
Path: redb-route/redb.Route.Llm/Engine/Governance/StoreBudgetEnforcer.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/Engine/Governance/StoreBudgetEnforcer.cs
----
using redb.Route.Abstractions;
using redb.Route.Llm.Engine.Storage;
namespace redb.Route.Llm.Engine.Governance;
///
/// Budget enforcement that survives the run: usage is accumulated per conversation in an
/// , and the per-run ceiling from is checked
/// against that running total. A conversation that already spent its budget therefore stops the next
/// run as well — that is the point of storing it, and it is a behaviour change worth knowing about:
/// a run that passes today can stop once the conversation's total crosses the ceiling.
///
/// Registered by AddRedbLlmStorage() in place of the shipped per-run defaults. The engine calls the
/// members that carry the run's exchange, and the store gets it: the rows go to the redb instance the endpoint
/// chose (?redb=), else the store's own default. The members without an exchange use the store's default.
///
///
/// Without a conversation id there is nowhere to accumulate, so the check degrades to the per-run one.
///
///
public sealed class StoreBudgetEnforcer : IBudgetEnforcer
{
private readonly ICostBudgetStore _store;
private readonly InMemoryBudgetEnforcer _perRun = new();
/// Creates the enforcer over .
public StoreBudgetEnforcer(ICostBudgetStore store)
{
ArgumentNullException.ThrowIfNull(store);
_store = store;
}
///
public ValueTask PreCheckAsync(
string? conversationId, AgentBudget budget, AgentUsage usageSoFar, CancellationToken ct = default)
=> PreCheckAsync(conversationId, budget, usageSoFar, exchange: null, ct);
///
public ValueTask RecordAndCheckAsync(
string? conversationId, AgentBudget budget, AgentUsage iterationUsage, AgentUsage totalUsage,
CancellationToken ct = default)
=> RecordAndCheckAsync(conversationId, budget, iterationUsage, totalUsage, exchange: null, ct);
///
public async ValueTask PreCheckAsync(
string? conversationId, AgentBudget budget, AgentUsage usageSoFar, IExchange? exchange,
CancellationToken ct = default)
{
if (budget.IsUnbounded) return BudgetDecision.Allow;
if (conversationId is null)
return await _perRun.PreCheckAsync(null, budget, usageSoFar, ct).ConfigureAwait(false);
var accumulated = await _store.GetUsageAsync(conversationId, exchange, ct).ConfigureAwait(false);
return await _perRun.PreCheckAsync(conversationId, budget, accumulated, ct).ConfigureAwait(false);
}
///
public async ValueTask RecordAndCheckAsync(
string? conversationId, AgentBudget budget, AgentUsage iterationUsage, AgentUsage totalUsage,
IExchange? exchange, CancellationToken ct = default)
{
if (budget.IsUnbounded) return BudgetDecision.Allow;
if (conversationId is null)
return await _perRun.RecordAndCheckAsync(null, budget, iterationUsage, totalUsage, ct).ConfigureAwait(false);
var total = await _store.AddAsync(conversationId, iterationUsage, exchange, ct).ConfigureAwait(false);
return await _perRun.RecordAndCheckAsync(conversationId, budget, iterationUsage, total, ct).ConfigureAwait(false);
}
}
Path: redb-route/redb.Route.Llm/Engine/IAgentEngine.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/Engine/IAgentEngine.cs
----
namespace redb.Route.Llm.Engine;
///
/// Drives the tool-loop: provider call → tool dispatch → provider call → ... until
/// end_turn, max iterations, budget cap or cancellation. Owns governance
/// (budget, shadow, idempotency, approval) — provider implementations stay pure.
///
public interface IAgentEngine
{
/// Runs the agent to completion.
Task RunAsync(AgentRequest request, CancellationToken ct = default);
}
Path: redb-route/redb.Route.Llm/Engine/Observability/IAgentObserver.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/Engine/Observability/IAgentObserver.cs
----
using redb.Route.Llm.Abstractions.Tools;
using redb.Route.Llm.Providers;
namespace redb.Route.Llm.Engine.Observability;
///
/// Receives lifecycle notifications about an agent run. Implementations are
/// expected to be non-blocking — heavy work (DB writes, network IO) should be
/// queued. Multiple observers may be registered via DI; the engine fans out
/// calls in registration order.
///
public interface IAgentObserver
{
/// Called once when an agent run begins.
Task OnRunStartedAsync(AgentRunContext context, CancellationToken ct = default);
/// Called after each provider call returns, before tool dispatch.
Task OnIterationCompletedAsync(AgentIterationContext context, CancellationToken ct = default);
/// Called for each tool invocation, after it returns or throws.
Task OnToolInvokedAsync(AgentToolInvocationContext context, CancellationToken ct = default);
/// Called once when an agent run ends (whether normally or via cancellation/error).
Task OnRunCompletedAsync(AgentRunCompletedContext context, CancellationToken ct = default);
///
/// Called for each piece of a streamed model call (stream=calls) as it arrives: visible text or the
/// model's thinking. A piece is partial; the whole answer follows in
/// and in the stored conversation. Not called when the model call is not streamed. Pieces come at the rate the
/// model writes, so an observer must not do slow work here. Default: nothing.
///
Task OnDeltaAsync(AgentDeltaContext context, CancellationToken ct = default) => Task.CompletedTask;
}
/// What a streamed piece is.
public enum AgentDeltaKind
{
/// Visible text of the answer.
Text,
/// The model's thinking: never part of the visible answer.
Thinking
}
/// One piece of a streamed model call.
public sealed class AgentDeltaContext
{
/// Identifiers shared with the rest of the run.
public required AgentRunContext Run { get; init; }
/// Iteration index, starting from 1: the model call this piece belongs to.
public required int Iteration { get; init; }
/// What the piece is.
public required AgentDeltaKind Kind { get; init; }
/// The piece, as the provider sent it.
public required string Text { get; init; }
}
/// Common identifiers passed to every observer call within one agent run.
public sealed class AgentRunContext
{
/// Conversation identifier (when persistence is on).
public string? ConversationId { get; init; }
/// Connection factory name, model id, provider id.
public required string FactoryName { get; init; }
/// Provider identifier ("openai", "anthropic", ...).
public required string ProviderId { get; init; }
/// Model identifier as resolved from the factory.
public required string ModelId { get; init; }
/// Exchange id of the parent exchange that initiated the run.
public required string ExchangeId { get; init; }
///
/// The redb instance the endpoint chose for its storage (?redb=, ), or null for
/// the registration's default. An observer that writes (the audit) writes there, as the stores do.
///
public string? RedbName { get; init; }
}
/// Per-iteration snapshot — usage, stop reason, content shape.
public sealed class AgentIterationContext
{
/// Identifiers shared with the rest of the run.
public required AgentRunContext Run { get; init; }
/// Iteration index, starting from 1.
public required int Iteration { get; init; }
/// Stop reason of this iteration's provider response.
public required LlmStopReason StopReason { get; init; }
/// Usage produced by this iteration alone (not cumulative).
public required LlmUsage IterationUsage { get; init; }
/// Wall-clock duration of the provider call.
public required TimeSpan Duration { get; init; }
}
/// Tool invocation outcome.
public sealed class AgentToolInvocationContext
{
/// Identifiers shared with the rest of the run.
public required AgentRunContext Run { get; init; }
/// Tool that was invoked (or attempted).
public required LlmToolCapability Tool { get; init; }
/// Tool input JSON.
public required string InputJson { get; init; }
/// Tool output JSON (null when the call raised an exception).
public string? OutputJson { get; init; }
/// Tool-use id from the model response.
public required string ToolUseId { get; init; }
/// Wall-clock duration of the tool execution.
public required TimeSpan Duration { get; init; }
/// Exception thrown by the tool, if any.
public Exception? Exception { get; init; }
///
/// True when the call was skipped instead of executed: an idempotency hit, an approval denial, an
/// unverifiable claim requirement, or a tool-cache hit. carries which.
///
public bool Skipped { get; init; }
///
/// Reason for skipping (when is true). Engine-emitted values are the
/// constants of ; the approval path adds the gate's own reason text.
///
public string? SkipReason { get; init; }
}
/// Final state of an agent run.
public sealed class AgentRunCompletedContext
{
/// Identifiers shared with the rest of the run.
public required AgentRunContext Run { get; init; }
/// Number of iterations the loop completed.
public required int Iterations { get; init; }
/// Aggregate usage across all iterations.
public required LlmUsage TotalUsage { get; init; }
/// Final stop reason from the last iteration.
public required LlmStopReason StopReason { get; init; }
/// Exception that terminated the run, if any.
public Exception? Exception { get; init; }
/// True when the run was cancelled (via CancellationToken or budget stop).
public bool Cancelled { get; init; }
}
/// Default observer — discards all events.
public sealed class NoopAgentObserver : IAgentObserver
{
///
public Task OnRunStartedAsync(AgentRunContext context, CancellationToken ct = default) => Task.CompletedTask;
///
public Task OnIterationCompletedAsync(AgentIterationContext context, CancellationToken ct = default) => Task.CompletedTask;
///
public Task OnToolInvokedAsync(AgentToolInvocationContext context, CancellationToken ct = default) => Task.CompletedTask;
///
public Task OnRunCompletedAsync(AgentRunCompletedContext context, CancellationToken ct = default) => Task.CompletedTask;
}
///
/// Composite observer — fans out events to every registered .
/// Exceptions in one observer never break the fan-out.
///
public sealed class CompositeAgentObserver : IAgentObserver
{
private readonly IReadOnlyList _observers;
/// Creates a composite over the provided observers (order preserved).
public CompositeAgentObserver(IEnumerable observers)
{
_observers = observers?.ToArray() ?? throw new ArgumentNullException(nameof(observers));
}
///
public Task OnRunStartedAsync(AgentRunContext context, CancellationToken ct = default) =>
Fan(o => o.OnRunStartedAsync(context, ct));
///
public Task OnIterationCompletedAsync(AgentIterationContext context, CancellationToken ct = default) =>
Fan(o => o.OnIterationCompletedAsync(context, ct));
///
public Task OnToolInvokedAsync(AgentToolInvocationContext context, CancellationToken ct = default) =>
Fan(o => o.OnToolInvokedAsync(context, ct));
///
public Task OnRunCompletedAsync(AgentRunCompletedContext context, CancellationToken ct = default) =>
Fan(o => o.OnRunCompletedAsync(context, ct));
///
public Task OnDeltaAsync(AgentDeltaContext context, CancellationToken ct = default) =>
Fan(o => o.OnDeltaAsync(context, ct));
private async Task Fan(Func dispatch)
{
foreach (var observer in _observers)
{
try { await dispatch(observer).ConfigureAwait(false); }
catch { /* observers must not break the fan-out */ }
}
}
}
Path: redb-route/redb.Route.Llm/Engine/PromptRef.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/Engine/PromptRef.cs
----
using redb.Route.Abstractions;
using redb.Route.Llm.Engine.Storage;
namespace redb.Route.Llm.Engine;
///
/// Resolver for prompt references used by ?initialBodyRef= and
/// ?systemPromptRef= URI parameters.
///
/// Convention (matches the framework-wide #name registry-ref pattern
/// already used by Kafka/S3/Firebase connection-factory refs in redb.Route):
///
///
/// null / empty → null
/// #name → lookup name in (latest version),
/// then fall back to as a plain string.
/// anything else → returned verbatim as a literal prompt
///
/// A #name ref that does not resolve in either registry returns null —
/// callers decide whether to substitute an empty string or surface an error.
///
internal static class PromptRef
{
public static async ValueTask ResolveAsync(
string? raw,
IPromptTemplateRegistry? templates,
IRouteContext? context,
IExchange? exchange,
CancellationToken ct)
{
if (string.IsNullOrEmpty(raw)) return null;
if (raw[0] != '#') return raw;
var name = raw[1..];
if (name.Length == 0) return null;
if (templates is not null)
{
var tmpl = await templates.GetAsync(name, version: null, exchange, ct).ConfigureAwait(false);
if (tmpl is not null) return tmpl.Body;
}
return context?.GetFromRegistry(name);
}
}
Path: redb-route/redb.Route.Llm/Engine/Storage/IApprovalStore.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/Engine/Storage/IApprovalStore.cs
----
using System.Collections.Concurrent;
using redb.Route.Abstractions;
using redb.Route.Llm.Engine.Governance;
namespace redb.Route.Llm.Engine.Storage;
///
/// Persists approval decisions for audit and replay. Every call answered by
/// should land here so reviewers can correlate the
/// gate's verdict with the resulting tool call.
///
/// The optional exchange parameter on every method carries the route
/// pipeline's current exchange; REDB-backed implementations resolve a
/// per-exchange through
/// IRouteContext.GetRedbService(name, exchange) using the named-redb
/// hint stored in . In-memory implementations
/// ignore it.
/// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an
/// ambient (a , a
/// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared
/// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange,
/// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations
/// take part in no transaction.
///
///
public interface IApprovalStore
{
/// Records a decision against the pending request.
Task RecordAsync(ApprovalRequest request, ApprovalDecision decision, IExchange? exchange = null, CancellationToken ct = default);
/// Looks up the previously-recorded decision for .
Task FindAsync(string approvalId, IExchange? exchange = null, CancellationToken ct = default);
}
/// An approval decision joined with the request that triggered it.
public sealed class ApprovalRecord
{
/// Approval identifier (also stored on the audit row).
public required string ApprovalId { get; init; }
/// Conversation the approval belonged to.
public string? ConversationId { get; init; }
/// Tool name that was gated.
public required string ToolName { get; init; }
/// Tool input JSON as it was about to be dispatched.
public required string InputJson { get; init; }
/// True when the gate allowed the call.
public required bool Approved { get; init; }
/// Reason text supplied by the approver (especially on denial).
public string? Reason { get; init; }
/// Wall-clock timestamp the decision was recorded.
public DateTime CreatedAtUtc { get; init; } = DateTime.UtcNow;
}
/// In-memory approval store — sufficient for tests and demos.
public sealed class InMemoryApprovalStore : IApprovalStore
{
private readonly ConcurrentDictionary _records = new(StringComparer.Ordinal);
///
public Task RecordAsync(ApprovalRequest request, ApprovalDecision decision, IExchange? exchange = null, CancellationToken ct = default)
{
var id = decision.ApprovalId ?? Guid.NewGuid().ToString("N");
_records[id] = new ApprovalRecord
{
ApprovalId = id,
ConversationId = request.ConversationId,
ToolName = request.Tool.Name,
InputJson = request.InputJson,
Approved = decision.Approved,
Reason = decision.Reason
};
return Task.CompletedTask;
}
///
public Task FindAsync(string approvalId, IExchange? exchange = null, CancellationToken ct = default) =>
Task.FromResult(_records.TryGetValue(approvalId, out var rec) ? rec : null);
}
Path: redb-route/redb.Route.Llm/Engine/Storage/IBatchStore.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/Engine/Storage/IBatchStore.cs
----
using System.Collections.Concurrent;
using redb.Route.Abstractions;
namespace redb.Route.Llm.Engine.Storage;
///
/// Tracks async-batch jobs submitted to LLM providers (Anthropic Message
/// Batches, OpenAI Batch API, vLLM batch endpoints). The framework does not
/// prescribe a submit protocol — providers stay free to implement
/// SubmitAsync however they like — but every submitted batch should be
/// registered here so that incoming webhooks can be correlated, deduplicated
/// and routed back to the originating conversation.
///
/// Idempotency of the callback itself is the caller's responsibility (use
/// with the batch id as key); this store
/// only persists the submit-time metadata.
///
///
/// The optional exchange parameter on every method carries the route
/// pipeline's current exchange; REDB-backed implementations resolve a
/// per-exchange through
/// IRouteContext.GetRedbService(name, exchange) using the named-redb
/// hint stored in . In-memory implementations
/// ignore it.
/// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an
/// ambient (a , a
/// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared
/// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange,
/// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations
/// take part in no transaction.
///
///
public interface IBatchStore
{
/// Records a batch submission. Replaces an existing row with the same id.
Task RegisterAsync(BatchJobRecord record, IExchange? exchange = null, CancellationToken ct = default);
///
/// Records many batch submissions at once. Bulk-friendly stores commit the
/// whole set in a single transaction; the default falls back to a loop.
///
async Task RegisterManyAsync(IEnumerable records, IExchange? exchange = null, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(records);
foreach (var record in records)
{
ct.ThrowIfCancellationRequested();
await RegisterAsync(record, exchange, ct).ConfigureAwait(false);
}
}
/// Loads a previously-registered batch by id; null if unknown.
Task GetAsync(string batchId, IExchange? exchange = null, CancellationToken ct = default);
///
/// Updates lifecycle status and optional fields. Unknown ids are ignored
/// silently — callers should treat a missing row as "not ours" and not as
/// an error condition.
///
Task UpdateStatusAsync(
string batchId,
string status,
DateTimeOffset? completedAtUtc = null,
string? errorMessage = null,
IExchange? exchange = null,
CancellationToken ct = default);
/// Marks a batch as completed; convenience wrapper around .
Task MarkCompletedAsync(string batchId, IExchange? exchange = null, CancellationToken ct = default) =>
UpdateStatusAsync(batchId, "completed", DateTimeOffset.UtcNow, null, exchange, ct);
/// Marks a batch as failed; convenience wrapper around .
Task MarkFailedAsync(string batchId, string errorMessage, IExchange? exchange = null, CancellationToken ct = default) =>
UpdateStatusAsync(batchId, "failed", DateTimeOffset.UtcNow, errorMessage, exchange, ct);
}
/// A persisted batch-submission record.
public sealed class BatchJobRecord
{
/// Provider-issued batch identifier — the business key.
public required string BatchId { get; init; }
/// "anthropic", "openai", or any custom provider id.
public required string ProviderId { get; init; }
/// Model id at submit-time.
public string ModelId { get; init; } = string.Empty;
/// Optional conversation correlation; empty when the batch is conversation-less.
public string ConversationId { get; init; } = string.Empty;
/// Lifecycle: "submitted" / "running" / "completed" / "failed" / "cancelled".
public string Status { get; init; } = "submitted";
/// When the host submitted the batch.
public DateTime SubmittedAtUtc { get; init; } = DateTime.UtcNow;
/// When the callback fired (or the host marked completion); null while pending.
public DateTime? CompletedAtUtc { get; init; }
/// Optional URL where the host can fetch results; null when results arrive inline.
public string? ResultUrl { get; init; }
/// Free-form metadata captured at submit time (caller-controlled JSON).
public string? MetadataJson { get; init; }
/// Last error message recorded against the batch; null while healthy.
public string? ErrorMessage { get; init; }
///
/// Opt-in: when true and the batch resolves to "completed",
/// appends the assistant
/// turn extracted from the callback body to
/// under . Has no effect when the conversation
/// id is empty or the conversation store is not registered. Default false.
///
public bool AppendToConversation { get; init; }
}
/// In-memory — entries live only for the process lifetime.
public sealed class InMemoryBatchStore : IBatchStore
{
private readonly ConcurrentDictionary _rows = new(StringComparer.Ordinal);
///
public Task RegisterAsync(BatchJobRecord record, IExchange? exchange = null, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(record);
ArgumentException.ThrowIfNullOrWhiteSpace(record.BatchId);
_rows[record.BatchId] = record;
return Task.CompletedTask;
}
///
public Task GetAsync(string batchId, IExchange? exchange = null, CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
return Task.FromResult(_rows.TryGetValue(batchId, out var hit) ? hit : null);
}
///
public Task UpdateStatusAsync(
string batchId,
string status,
DateTimeOffset? completedAtUtc = null,
string? errorMessage = null,
IExchange? exchange = null,
CancellationToken ct = default)
{
ArgumentException.ThrowIfNullOrWhiteSpace(batchId);
ArgumentException.ThrowIfNullOrWhiteSpace(status);
if (!_rows.TryGetValue(batchId, out var existing)) return Task.CompletedTask;
var updated = new BatchJobRecord
{
BatchId = existing.BatchId,
ProviderId = existing.ProviderId,
ModelId = existing.ModelId,
ConversationId = existing.ConversationId,
Status = status,
SubmittedAtUtc = existing.SubmittedAtUtc,
CompletedAtUtc = completedAtUtc?.UtcDateTime ?? existing.CompletedAtUtc,
ResultUrl = existing.ResultUrl,
MetadataJson = existing.MetadataJson,
ErrorMessage = errorMessage ?? existing.ErrorMessage,
AppendToConversation = existing.AppendToConversation
};
_rows[batchId] = updated;
return Task.CompletedTask;
}
}
Path: redb-route/redb.Route.Llm/Engine/Storage/IConversationStore.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/Engine/Storage/IConversationStore.cs
----
using System.Collections.Concurrent;
using redb.Route.Abstractions;
using redb.Route.Llm.Providers;
namespace redb.Route.Llm.Engine.Storage;
///
/// Persists conversation transcripts so that an agent run can be resumed,
/// branched, or replayed offline. The contract is intentionally tree-shaped:
/// every message has an optional parent identifier, which lets callers branch
/// from any node — required to model regenerate / parallel tool-calls / what-if
/// flows. The flat "append-only history" pattern falls out naturally when the
/// caller always passes the previously-appended message id as parentId.
///
/// The optional exchange parameter on every method carries the current
/// route exchange when the call originates from inside a route pipeline.
/// REDB-backed implementations resolve a per-exchange IRedbService
/// (and its named siblings via ) through
/// IRouteContext.GetRedbService(name, exchange), which already manages
/// per-exchange scopes and disposal. In-memory implementations ignore it.
/// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an
/// ambient (a , a
/// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared
/// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange,
/// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations
/// take part in no transaction.
///
///
public interface IConversationStore
{
///
/// Appends as a child of
/// (or as the root when is null) and returns the
/// new message identifier.
///
Task AppendAsync(
string conversationId,
string? parentId,
LlmMessage message,
ConversationMessageMeta meta,
IExchange? exchange = null,
CancellationToken ct = default);
///
/// Loads the linear path from the conversation root to .
/// Passing null returns the path to the most-recently-appended leaf.
///
Task> LoadPathAsync(
string conversationId,
string? leafId = null,
IExchange? exchange = null,
CancellationToken ct = default);
///
/// Loads the full tree for the conversation (every branch). Used for
/// observability dashboards and eval replays — NOT for hot-path requests.
///
Task> LoadTreeAsync(
string conversationId,
IExchange? exchange = null,
CancellationToken ct = default);
}
/// Queryable metadata that lives on the message node — hoisted from
/// the message body so that index-friendly filters (date range, role,
/// iteration) can run without scanning the full payload.
public sealed class ConversationMessageMeta
{
/// Wall-clock timestamp the message was appended.
public DateTime CreatedAtUtc { get; init; } = DateTime.UtcNow;
/// Agent iteration index (1-based) that produced the message; 0 for the user prompt.
public int Iteration { get; init; }
/// Provider id ("openai", "anthropic", ...) — null for non-provider messages.
public string? ProviderId { get; init; }
/// Model id as resolved at the time of the call.
public string? ModelId { get; init; }
/// Stop reason for assistant messages.
public LlmStopReason? StopReason { get; init; }
/// Token usage attributed to this turn.
public LlmUsage Usage { get; init; } = LlmUsage.Empty;
/// Tool-use id when the message is a tool result.
public string? ToolUseId { get; init; }
///
/// Effective sampling temperature passed to the provider for the call
/// that produced this assistant message; null on user / tool-result rows.
///
public double? Temperature { get; init; }
/// Effective max-output-tokens cap; null on non-assistant rows.
public int? MaxTokens { get; init; }
/// Effective top-p value; null on non-assistant rows.
public double? TopP { get; init; }
/// Prompt-template name resolved at call time (FK into PromptTemplateProps).
public string? PromptTemplateName { get; init; }
/// Prompt-template version paired with .
public string? PromptTemplateVersion { get; init; }
///
/// Stable hash of the tool-capabilities set exposed to the model on this
/// call. Allows auditors to detect tool-surface drift across runs.
///
public string? ToolSetHash { get; init; }
///
/// Opaque provider-side fingerprint identifying the backend configuration
/// that served the call (OpenAI's system_fingerprint). Null when the
/// provider does not surface one.
///
public string? ProviderSystemFingerprint { get; init; }
///
/// Stable identifier of the principal that initiated the agent turn that
/// produced this row. The same value is stamped on every row of the turn
/// (system / user / tool / assistant) so audit queries always have a
/// consistent subject. Captured pre-call; null when no principal is wired.
///
public string? UserId { get; init; }
///
/// Free-form audit tags captured pre-call from the fluent
/// .Audit(k,v) builder and / or llm.audit.<name> headers.
/// The same snapshot is stamped on every row of the turn. Null / empty
/// when no tags are wired.
///
public IReadOnlyDictionary? AuditTags { get; init; }
///
/// Connection-factory alias used for this call (LlmConnectionFactory.Name) —
/// the operator-chosen profile name. Audits the *intent* on top of
/// / .
///
public string? FactoryName { get; init; }
///
/// Effective base URL set on the connection factory. Null when the
/// factory used the provider's built-in default endpoint.
///
public string? BaseUrl { get; init; }
///
/// Provider-issued response identifier (top-level id on
/// OpenAI / Anthropic / xAI / Together). Null on non-assistant rows.
///
public string? ProviderResponseId { get; init; }
///
/// Wall-clock time (milliseconds) the provider spent producing the
/// assistant turn this row belongs to. Null on non-assistant rows.
///
public long? LatencyMs { get; init; }
///
/// Stable, non-secret fingerprint of the API key used for the call —
/// SHA-256 of the key, first 16 hex chars. Null when the factory exposes
/// no ApiKey.
///
public string? ApiKeyFingerprint { get; init; }
///
/// How many times the route framework retried the inbound exchange before
/// the call succeeded. Read from
/// exchange.Properties["RetryAttempt"] (set by
/// RetryProcessor) with fallbacks to
/// exchange.In.Headers["CamelRedeliveryCounter"]
/// (OnExceptionProcessor) and
/// exchange.In.Headers["CamelDeadLetterRedeliveryCount"]
/// (DeadLetterProcessor). Null on first / only delivery.
///
public int? RetryCount { get; init; }
}
/// A persisted conversation message with its tree placement and metadata.
public sealed class ConversationMessage
{
/// Store-assigned message id.
public required string Id { get; init; }
/// Parent message id; null for the root.
public string? ParentId { get; init; }
/// Conversation this message belongs to.
public required string ConversationId { get; init; }
/// Persisted message payload.
public required LlmMessage Message { get; init; }
/// Metadata captured at append time.
public required ConversationMessageMeta Meta { get; init; }
}
///
/// In-memory conversation store — suitable for unit tests and demos.
/// Replace with the redb-backed implementation in redb.Route.Llm.Storage.Redb.
///
public sealed class InMemoryConversationStore : IConversationStore
{
private readonly ConcurrentDictionary> _byConversation = new();
///
public Task AppendAsync(string conversationId, string? parentId, LlmMessage message, ConversationMessageMeta meta, IExchange? exchange = null, CancellationToken ct = default)
{
var id = Guid.NewGuid().ToString("N");
var node = new ConversationMessage
{
Id = id,
ParentId = parentId,
ConversationId = conversationId,
Message = message,
Meta = meta
};
var bucket = _byConversation.GetOrAdd(conversationId, _ => new List());
lock (bucket) bucket.Add(node);
return Task.FromResult(id);
}
///
public Task> LoadPathAsync(string conversationId, string? leafId = null, IExchange? exchange = null, CancellationToken ct = default)
{
if (!_byConversation.TryGetValue(conversationId, out var bucket))
return Task.FromResult>([]);
ConversationMessage[] snapshot;
lock (bucket) snapshot = bucket.ToArray();
var leaf = leafId is null
? snapshot.LastOrDefault()
: snapshot.FirstOrDefault(m => m.Id == leafId);
if (leaf is null) return Task.FromResult>([]);
var byId = snapshot.ToDictionary(m => m.Id);
var path = new List();
var cursor = leaf;
while (cursor is not null)
{
path.Add(cursor);
cursor = cursor.ParentId is { } pid && byId.TryGetValue(pid, out var parent) ? parent : null;
}
path.Reverse();
return Task.FromResult>(path);
}
///
public Task> LoadTreeAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default)
{
if (!_byConversation.TryGetValue(conversationId, out var bucket))
return Task.FromResult>([]);
lock (bucket) return Task.FromResult>(bucket.ToArray());
}
}
Path: redb-route/redb.Route.Llm/Engine/Storage/ICostBudgetStore.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/Engine/Storage/ICostBudgetStore.cs
----
using System.Collections.Concurrent;
using redb.Route.Abstractions;
using redb.Route.Llm.Engine.Governance;
namespace redb.Route.Llm.Engine.Storage;
///
/// Persists running cost / token usage per conversation so that an
/// implementation can enforce budgets across multiple agent runs
/// (not just within one).
///
/// is that consumer: AddRedbLlmStorage() registers it in
/// place of the shipped per-run defaults, and it reads this store before each run and adds to it after
/// each iteration. Implementations must be safe for concurrent updates.
///
///
/// The optional exchange parameter on every method carries the route
/// pipeline's current exchange; REDB-backed implementations resolve a
/// per-exchange through
/// IRouteContext.GetRedbService(name, exchange) using the named-redb
/// hint stored in . In-memory implementations
/// ignore it.
/// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an
/// ambient (a , a
/// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared
/// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange,
/// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations
/// take part in no transaction.
///
///
public interface ICostBudgetStore
{
/// Returns the running total for the conversation, or when unknown.
ValueTask GetUsageAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default);
/// Atomically adds the iteration usage to the running total and returns the updated total.
ValueTask AddAsync(string conversationId, AgentUsage delta, IExchange? exchange = null, CancellationToken ct = default);
/// Resets the running total — used after a billing period rollover or by tests.
ValueTask ResetAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default);
}
/// In-memory cost/token store. Replace with the redb-backed implementation in production.
public sealed class InMemoryCostBudgetStore : ICostBudgetStore
{
private readonly ConcurrentDictionary _totals = new(StringComparer.Ordinal);
///
public ValueTask GetUsageAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default) =>
ValueTask.FromResult(_totals.TryGetValue(conversationId, out var u) ? u : AgentUsage.Zero);
///
public ValueTask AddAsync(string conversationId, AgentUsage delta, IExchange? exchange = null, CancellationToken ct = default)
{
var updated = _totals.AddOrUpdate(conversationId, delta, (_, current) => current.Add(delta));
return ValueTask.FromResult(updated);
}
///
public ValueTask ResetAsync(string conversationId, IExchange? exchange = null, CancellationToken ct = default)
{
_totals.TryRemove(conversationId, out _);
return ValueTask.CompletedTask;
}
}
Path: redb-route/redb.Route.Llm/Engine/Storage/IEvalRunStore.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/Engine/Storage/IEvalRunStore.cs
----
using System.Collections.Concurrent;
using redb.Route.Abstractions;
using redb.Route.Llm.Engine.Governance;
namespace redb.Route.Llm.Engine.Storage;
///
/// Persists the outcome of a recorded evaluation run. Used by the eval harness
/// to track regression scores between agent / prompt / model versions.
///
/// The optional exchange parameter on every method carries the route
/// pipeline's current exchange; REDB-backed implementations resolve a
/// per-exchange through
/// IRouteContext.GetRedbService(name, exchange). In-memory
/// implementations ignore it.
/// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an
/// ambient (a , a
/// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared
/// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange,
/// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations
/// take part in no transaction.
///
///
public interface IEvalRunStore
{
/// Persists a completed evaluation run.
Task SaveAsync(EvalRunRecord record, IExchange? exchange = null, CancellationToken ct = default);
///
/// Persists many evaluation runs at once. Bulk-friendly stores commit the
/// whole set in a single transaction; the default falls back to a loop.
///
async Task SaveManyAsync(IEnumerable records, IExchange? exchange = null, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(records);
foreach (var record in records)
{
ct.ThrowIfCancellationRequested();
await SaveAsync(record, exchange, ct).ConfigureAwait(false);
}
}
/// Loads a single run by its identifier.
Task GetAsync(string runId, IExchange? exchange = null, CancellationToken ct = default);
///
/// Lists runs filtered by scenario name. Returns newest first.
///
Task> ListAsync(string? scenario = null, int take = 50, IExchange? exchange = null, CancellationToken ct = default);
}
/// An evaluation run snapshot.
public sealed class EvalRunRecord
{
/// Identifier assigned by the eval harness.
public required string RunId { get; init; }
/// Scenario name (e.g. "summarize-pr", "sql-rag").
public required string Scenario { get; init; }
/// Agent / prompt / model fingerprint that produced the run.
public required string AgentFingerprint { get; init; }
/// Aggregate score in [0.0, 1.0]; null when not scored.
public double? Score { get; init; }
/// Total usage observed across the run.
public AgentUsage TotalUsage { get; init; } = AgentUsage.Zero;
/// Per-iteration metrics — empty when the harness did not record per-iteration data.
public IReadOnlyList Iterations { get; init; } = [];
/// Custom scoring dimensions (e.g. "accuracy" = 0.92).
public IReadOnlyDictionary? Dimensions { get; init; }
/// Fixture identifiers / version hashes consumed by the run.
public IReadOnlyDictionary? Fixtures { get; init; }
/// Wall-clock timestamp the record was created.
public DateTime CreatedAtUtc { get; init; } = DateTime.UtcNow;
}
/// Per-iteration metric inside an .
public sealed class EvalIterationRecord
{
/// 1-based iteration index within the run.
public int Iteration { get; init; }
/// Input tokens consumed by this iteration.
public int InputTokens { get; init; }
/// Output tokens produced by this iteration.
public int OutputTokens { get; init; }
/// Wall-clock duration of the iteration in milliseconds.
public int DurationMs { get; init; }
/// Per-iteration score in [0.0, 1.0]; null when not scored.
public double? Score { get; init; }
/// Optional free-form note (judge rationale, failure tag, etc.).
public string? Notes { get; init; }
}
/// In-memory eval run store — used by unit tests; production swaps in the redb implementation.
public sealed class InMemoryEvalRunStore : IEvalRunStore
{
private readonly ConcurrentDictionary _records = new(StringComparer.Ordinal);
///
public Task SaveAsync(EvalRunRecord record, IExchange? exchange = null, CancellationToken ct = default)
{
_records[record.RunId] = record;
return Task.CompletedTask;
}
///
public Task GetAsync(string runId, IExchange? exchange = null, CancellationToken ct = default) =>
Task.FromResult(_records.TryGetValue(runId, out var rec) ? rec : null);
///
public Task> ListAsync(string? scenario = null, int take = 50, IExchange? exchange = null, CancellationToken ct = default)
{
IEnumerable q = _records.Values;
if (scenario is not null)
q = q.Where(r => string.Equals(r.Scenario, scenario, StringComparison.Ordinal));
var result = q.OrderByDescending(r => r.CreatedAtUtc).Take(take).ToArray();
return Task.FromResult>(result);
}
}
Path: redb-route/redb.Route.Llm/Engine/Storage/IKnowledgeStore.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/Engine/Storage/IKnowledgeStore.cs
----
using System.Collections.Concurrent;
using redb.Route.Abstractions;
namespace redb.Route.Llm.Engine.Storage;
///
/// Persists embedding-backed knowledge chunks for retrieval-augmented agent
/// runs. The MVP contract is intentionally narrow — upsert + cosine-similarity
/// query over an opaque vector. Providers that index the chunks separately
/// (e.g. pgvector, Qdrant) wrap this interface.
///
/// The optional exchange parameter on every method carries the route
/// pipeline's current exchange; REDB-backed implementations resolve a
/// per-exchange through
/// IRouteContext.GetRedbService(name, exchange). In-memory
/// implementations ignore it.
/// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an
/// ambient (a , a
/// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared
/// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange,
/// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations
/// take part in no transaction.
///
///
public interface IKnowledgeStore
{
/// Persists or replaces a chunk by its .
Task UpsertAsync(KnowledgeChunk chunk, IExchange? exchange = null, CancellationToken ct = default);
///
/// Persists or replaces many chunks at once. Bulk-friendly stores commit
/// the whole set in a single transaction — orders of magnitude faster than
/// looping . The default implementation falls back
/// to a sequential loop for stores that have no bulk path.
///
async Task UpsertManyAsync(IEnumerable chunks, IExchange? exchange = null, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(chunks);
foreach (var chunk in chunks)
{
ct.ThrowIfCancellationRequested();
await UpsertAsync(chunk, exchange, ct).ConfigureAwait(false);
}
}
/// Drops a chunk by id; no-op when not found.
Task DeleteAsync(string chunkId, IExchange? exchange = null, CancellationToken ct = default);
/// Returns the most-similar chunks for the query embedding.
Task> SearchAsync(
ReadOnlyMemory queryEmbedding,
int topK,
string? collection = null,
IExchange? exchange = null,
CancellationToken ct = default);
///
/// Keyword fallback — returns up to chunks whose text
/// contains (case-insensitive substring), ranked by
/// occurrence count. For corpora with no embeddings, or callers with no query
/// vector (e.g. a small structured rule-set where exact terms beat semantic
/// similarity). Backends push the substring filter down (SQL LIKE) and
/// rank only the matched set — no full-table scan.
///
/// The default implementation throws ;
/// stores that can express a substring filter override it. Adding this as a
/// default member keeps the interface source-compatible for existing
/// implementers.
///
///
Task> SearchTextAsync(
string query,
int topK,
string? collection = null,
IExchange? exchange = null,
CancellationToken ct = default)
=> throw new NotSupportedException(
$"{GetType().Name} does not support keyword search; supply a query embedding and call SearchAsync.");
}
/// A single embedded knowledge chunk.
public sealed class KnowledgeChunk
{
/// Stable identifier — caller-supplied so updates can replace a chunk in place.
public required string Id { get; init; }
/// Optional collection / namespace partition (e.g. tenant id, document set).
public string? Collection { get; init; }
/// Original chunk text shown to the model when the chunk is retrieved.
public required string Text { get; init; }
/// Embedding vector; dimensionality is implementation-defined.
public required ReadOnlyMemory Embedding { get; init; }
/// Optional structured metadata (JSON) — e.g. source URL, page number.
public string? MetadataJson { get; init; }
/// Wall-clock timestamp the chunk was last upserted.
public DateTime UpdatedAtUtc { get; init; } = DateTime.UtcNow;
}
/// A chunk returned by , with score.
public sealed record KnowledgeSearchResult(KnowledgeChunk Chunk, double Score);
///
/// In-memory knowledge store — does an O(N) cosine-similarity scan on every
/// query. Suitable for unit tests and small fixtures only; swap in the
/// production store for anything larger than a few thousand chunks.
///
public sealed class InMemoryKnowledgeStore : IKnowledgeStore
{
private readonly ConcurrentDictionary _chunks = new(StringComparer.Ordinal);
///
public Task UpsertAsync(KnowledgeChunk chunk, IExchange? exchange = null, CancellationToken ct = default)
{
_chunks[chunk.Id] = chunk;
return Task.CompletedTask;
}
///
public Task DeleteAsync(string chunkId, IExchange? exchange = null, CancellationToken ct = default)
{
_chunks.TryRemove(chunkId, out _);
return Task.CompletedTask;
}
///
public Task> SearchAsync(
ReadOnlyMemory queryEmbedding, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default)
{
var query = queryEmbedding.Span;
var ranked = new List();
foreach (var chunk in _chunks.Values)
{
if (collection is not null && !string.Equals(chunk.Collection, collection, StringComparison.Ordinal))
continue;
var score = CosineSimilarity(query, chunk.Embedding.Span);
ranked.Add(new KnowledgeSearchResult(chunk, score));
}
var top = ranked.OrderByDescending(r => r.Score).Take(Math.Max(1, topK)).ToArray();
return Task.FromResult>(top);
}
///
public Task> SearchTextAsync(
string query, int topK, string? collection = null, IExchange? exchange = null, CancellationToken ct = default)
{
if (string.IsNullOrWhiteSpace(query))
return Task.FromResult>([]);
var ranked = new List();
foreach (var chunk in _chunks.Values)
{
if (collection is not null && !string.Equals(chunk.Collection, collection, StringComparison.Ordinal))
continue;
var score = KnowledgeTextMatch.CountOccurrences(chunk.Text, query);
if (score == 0) continue;
ranked.Add(new KnowledgeSearchResult(chunk, score));
}
var top = ranked.OrderByDescending(r => r.Score).Take(Math.Max(1, topK)).ToArray();
return Task.FromResult>(top);
}
private static double CosineSimilarity(ReadOnlySpan a, ReadOnlySpan b)
{
var len = Math.Min(a.Length, b.Length);
if (len == 0) return 0d;
double dot = 0, na = 0, nb = 0;
for (var i = 0; i < len; i++)
{
dot += a[i] * b[i];
na += a[i] * a[i];
nb += b[i] * b[i];
}
var denom = Math.Sqrt(na) * Math.Sqrt(nb);
return denom <= 0 ? 0d : dot / denom;
}
}
/// Shared keyword-match scoring for implementations.
internal static class KnowledgeTextMatch
{
/// Case-insensitive count of non-overlapping occurrences in .
public static int CountOccurrences(string? haystack, string? needle)
{
if (string.IsNullOrEmpty(haystack) || string.IsNullOrEmpty(needle)) return 0;
var count = 0;
var i = 0;
while ((i = haystack.IndexOf(needle, i, StringComparison.OrdinalIgnoreCase)) >= 0)
{
count++;
i += needle.Length;
}
return count;
}
}
Path: redb-route/redb.Route.Llm/Engine/Storage/IPromptTemplateRegistry.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/Engine/Storage/IPromptTemplateRegistry.cs
----
using System.Collections.Concurrent;
using redb.Route.Abstractions;
namespace redb.Route.Llm.Engine.Storage;
///
/// Resolves a named prompt template into the actual system / user text the
/// engine should send to the provider. Versioning is required so that a
/// recorded eval run can be replayed against the exact template that produced it.
///
/// The optional exchange parameter on every method carries the route
/// pipeline's current exchange; REDB-backed implementations resolve a
/// per-exchange through
/// IRouteContext.GetRedbService(name, exchange). In-memory
/// implementations ignore it.
/// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an
/// ambient (a , a
/// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared
/// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange,
/// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations
/// take part in no transaction.
///
///
public interface IPromptTemplateRegistry
{
///
/// Returns the requested template. When is null,
/// the latest version is returned.
///
Task GetAsync(string name, string? version = null, IExchange? exchange = null, CancellationToken ct = default);
/// Registers or updates a template version.
Task SetAsync(PromptTemplate template, IExchange? exchange = null, CancellationToken ct = default);
/// Enumerates every version of every template — used for tooling.
Task> ListAsync(IExchange? exchange = null, CancellationToken ct = default);
}
/// A versioned prompt template.
public sealed class PromptTemplate
{
/// Stable template name (free of versioning).
public required string Name { get; init; }
/// Version string (semver, hash, or monotonically-increasing tag).
public required string Version { get; init; }
/// Template body — placeholder substitution is the caller's responsibility.
public required string Body { get; init; }
/// Optional human description.
public string? Description { get; init; }
/// Wall-clock timestamp the version was registered.
public DateTime CreatedAtUtc { get; init; } = DateTime.UtcNow;
}
/// In-memory registry — registered templates live only for the process lifetime.
public sealed class InMemoryPromptTemplateRegistry : IPromptTemplateRegistry
{
private readonly ConcurrentDictionary _templates = new(StringComparer.Ordinal);
///
public Task GetAsync(string name, string? version = null, IExchange? exchange = null, CancellationToken ct = default)
{
if (version is not null)
{
return Task.FromResult(_templates.TryGetValue(Key(name, version), out var exact) ? exact : null);
}
var latest = _templates.Values
.Where(t => string.Equals(t.Name, name, StringComparison.Ordinal))
.OrderByDescending(t => t.CreatedAtUtc)
.FirstOrDefault();
return Task.FromResult(latest);
}
///
public Task SetAsync(PromptTemplate template, IExchange? exchange = null, CancellationToken ct = default)
{
_templates[Key(template.Name, template.Version)] = template;
return Task.CompletedTask;
}
///
public Task> ListAsync(IExchange? exchange = null, CancellationToken ct = default) =>
Task.FromResult>(_templates.Values.ToArray());
private static string Key(string name, string version) => $"{name}@{version}";
}
Path: redb-route/redb.Route.Llm/Engine/Storage/IToolCacheStore.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/Engine/Storage/IToolCacheStore.cs
----
using System.Collections.Concurrent;
using redb.Route.Abstractions;
namespace redb.Route.Llm.Engine.Storage;
///
/// Caches deterministic / read-only tool outputs by a content-hash key so repeated calls can skip
/// the underlying work: inside one run for ToolCachingPolicy.Memoize (served in process,
/// never through this store) and across runs for ToolCachingPolicy.Persist.
///
/// The agent loop consults this store for Persist tools, after approval and before the
/// idempotency store: a hit means "this exact input already produced this output", which is cheaper
/// than asking "was this tool_use already executed?", and it is reported to observers as a skipped
/// invocation with SkipReason = "cache_hit". Only read-only tools may declare a caching
/// policy — a cached entry suppresses the side effect it stands for, so the route build rejects
/// Caching != None on a mutating tool.
///
///
/// An output the redaction filter changed is never stored: persisting the raw body would keep
/// redaction-bypassing content in the store, and persisting the redacted body would hand the model
/// different data on a hit than on a miss.
///
///
/// The optional exchange parameter on every method carries the route
/// pipeline's current exchange; REDB-backed implementations resolve a
/// per-exchange through
/// IRouteContext.GetRedbService(name, exchange). In-memory
/// implementations ignore it.
/// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an
/// ambient (a , a
/// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared
/// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange,
/// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations
/// take part in no transaction.
///
///
/// A store does not report metrics. Hit/miss counters belong to the agent loop, which is the
/// only layer that sees both this store and the run-scoped memo; a store that counted as well would
/// count every persisted read twice.
///
///
public interface IToolCacheStore
{
/// Returns the cached output for , or null on a miss.
ValueTask GetAsync(string cacheKey, IExchange? exchange = null, CancellationToken ct = default);
/// Stores the cached output and (optionally) sets a relative time-to-live.
ValueTask SetAsync(string cacheKey, string outputJson, TimeSpan? ttl = null, IExchange? exchange = null, CancellationToken ct = default);
/// Drops every entry — used by tests.
ValueTask ClearAsync(IExchange? exchange = null, CancellationToken ct = default);
}
/// In-memory tool cache. TTL is honoured lazily — entries are dropped on read.
public sealed class InMemoryToolCacheStore : IToolCacheStore
{
private readonly ConcurrentDictionary _entries = new(StringComparer.Ordinal);
///
public ValueTask GetAsync(string cacheKey, IExchange? exchange = null, CancellationToken ct = default)
{
if (!_entries.TryGetValue(cacheKey, out var entry)) return ValueTask.FromResult(null);
if (entry.ExpiresAtUtc is { } exp && exp <= DateTime.UtcNow)
{
_entries.TryRemove(cacheKey, out _);
return ValueTask.FromResult(null);
}
return ValueTask.FromResult(entry.OutputJson);
}
///
public ValueTask SetAsync(string cacheKey, string outputJson, TimeSpan? ttl = null, IExchange? exchange = null, CancellationToken ct = default)
{
var expires = ttl is { } t && t > TimeSpan.Zero ? DateTime.UtcNow.Add(t) : (DateTime?)null;
_entries[cacheKey] = new Entry(outputJson, expires);
return ValueTask.CompletedTask;
}
///
public ValueTask ClearAsync(IExchange? exchange = null, CancellationToken ct = default)
{
_entries.Clear();
return ValueTask.CompletedTask;
}
private readonly record struct Entry(string OutputJson, DateTime? ExpiresAtUtc);
}
Path: redb-route/redb.Route.Llm/Engine/Storage/IToolIdempotencyStore.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/Engine/Storage/IToolIdempotencyStore.cs
----
using redb.Route.Abstractions;
namespace redb.Route.Llm.Engine.Storage;
///
/// Tracks tool invocations so that retried or duplicated tool calls produce a
/// single side effect. The contract is intentionally a thin wrapper over
/// — the redb-backed implementation reuses
/// the existing IdempotentEntryProps table to avoid duplicating schema.
///
/// The optional exchange parameter on every method carries the route
/// pipeline's current exchange; REDB-backed implementations resolve a
/// per-exchange through
/// IRouteContext.GetRedbService(name, exchange). In-memory
/// implementations ignore it.
/// Without an exchange a redb-backed implementation opens a redb scope of its own for the call. That scope joins an
/// ambient (a , a
/// route's .Transacted()) as every redb connection does, but not a transaction begun on the context's shared
/// IRedbService (ExecuteAtomicAsync, BeginTransaction), which it does not see: pass the exchange,
/// or use a TransactionScope, when the call must commit or roll back with that work. In-memory implementations
/// take part in no transaction.
///
///
public interface IToolIdempotencyStore
{
///
/// Attempts to reserve for the given conversation.
/// Returns the cached result on a duplicate, or
/// when the caller should execute the tool and finalize via .
///
Task TryReserveAsync(
string conversationId,
string toolUseId,
IExchange? exchange = null,
CancellationToken ct = default);
/// Persists the tool output JSON for the previously-reserved key.
Task CompleteAsync(
string conversationId,
string toolUseId,
string outputJson,
IExchange? exchange = null,
CancellationToken ct = default);
/// Releases the reservation on failure so a retry can re-run the tool.
Task ReleaseAsync(
string conversationId,
string toolUseId,
IExchange? exchange = null,
CancellationToken ct = default);
}
/// Outcome of .
public sealed class ToolIdempotencyReservation
{
/// True when this caller owns the reservation and must execute the tool.
public required bool IsNew { get; init; }
/// Cached output JSON when is false and the prior call completed.
public string? CachedOutputJson { get; init; }
/// Sentinel reservation indicating the caller must execute the tool.
public static readonly ToolIdempotencyReservation NewReservation = new() { IsNew = true };
/// Builds a hit reservation that returns the previously-recorded output.
public static ToolIdempotencyReservation Hit(string outputJson) => new()
{
IsNew = false,
CachedOutputJson = outputJson
};
}
///
/// In-memory idempotency store backed by a thin
/// composition — the registered repository handles the dedup key, an internal
/// dictionary remembers the cached output.
///
/// With a ttl, a completed call is forgotten that long after it completed: its key leaves the repository and
/// its output leaves the store, lazily, on a later reservation (no timer). A reservation still in flight (reserved,
/// neither completed nor released) is never aged out, so a second run of the same call cannot start while the first is
/// still running, however long it takes. Without a ttl nothing expires.
///
///
public sealed class InMemoryToolIdempotencyStore : IToolIdempotencyStore
{
private sealed record Completed(string OutputJson, DateTimeOffset At);
private readonly IIdempotentRepository _repository;
private readonly TimeSpan? _ttl;
private readonly TimeProvider _time;
private readonly System.Collections.Concurrent.ConcurrentDictionary _outputs = new(StringComparer.Ordinal);
/// Creates a store over the given idempotency repository.
/// Keeps the reservation keys.
/// How long a completed call is remembered after it completed; null keeps it for the life of the store.
/// The clock the ttl is measured with; by default.
public InMemoryToolIdempotencyStore(IIdempotentRepository repository, TimeSpan? ttl = null, TimeProvider? time = null)
{
_repository = repository ?? throw new ArgumentNullException(nameof(repository));
if (ttl is { } t && t <= TimeSpan.Zero)
throw new ArgumentOutOfRangeException(nameof(ttl), ttl, "The ttl must be positive.");
_ttl = ttl;
_time = time ?? TimeProvider.System;
}
///
public async Task TryReserveAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default)
{
if (_ttl is { } ttl)
await EvictCompletedBeforeAsync(_time.GetUtcNow() - ttl, ct).ConfigureAwait(false);
var key = BuildKey(conversationId, toolUseId);
var added = await _repository.Add(key, ct).ConfigureAwait(false);
if (added) return ToolIdempotencyReservation.NewReservation;
return _outputs.TryGetValue(key, out var cached)
? ToolIdempotencyReservation.Hit(cached.OutputJson)
: ToolIdempotencyReservation.Hit("{}");
}
///
public async Task CompleteAsync(string conversationId, string toolUseId, string outputJson, IExchange? exchange = null, CancellationToken ct = default)
{
var key = BuildKey(conversationId, toolUseId);
_outputs[key] = new Completed(outputJson, _time.GetUtcNow());
await _repository.Confirm(key, ct).ConfigureAwait(false);
}
///
public async Task ReleaseAsync(string conversationId, string toolUseId, IExchange? exchange = null, CancellationToken ct = default)
{
var key = BuildKey(conversationId, toolUseId);
_outputs.TryRemove(key, out _);
await _repository.Remove(key, ct).ConfigureAwait(false);
}
///
/// Forgets every call completed before : the key first, so a concurrent reservation either
/// still finds key and output or starts afresh, never a key without its output; then exactly the output that was
/// read, so an output a new run of the same call wrote in between stays.
///
private async Task EvictCompletedBeforeAsync(DateTimeOffset cutoff, CancellationToken ct)
{
foreach (var entry in _outputs)
{
if (entry.Value.At >= cutoff) continue;
await _repository.Remove(entry.Key, ct).ConfigureAwait(false);
_outputs.TryRemove(entry);
}
}
private static string BuildKey(string conversationId, string toolUseId) =>
$"llm-tool:{conversationId}:{toolUseId}";
}
Path: redb-route/redb.Route.Llm/Engine/ToolHeaderPolicy.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/Engine/ToolHeaderPolicy.cs
----
namespace redb.Route.Llm.Engine;
///
/// Decides which headers of the agent's exchange are visible to a tool route.
///
/// The policy is default-deny: a tool never sees the raw inbound header set
/// (an HTTP consumer's Authorization / Cookie must not leak into every
/// tool call just because the tool is mounted on the same host). Only
/// , the run's resolved principal / audit tags, and the
/// names the route author opted into via
/// AgentRequest.PropagateToolHeaders are copied.
///
///
/// Principal and audit tags are propagated as resolved values, not as raw headers.
/// LlmProducer resolves the principal from the ?user= option first
/// (including its ${header.X} expression form) and only falls back to the
/// llm.user.id header; copying the header alone would silently drop the
/// option-driven case. Same for ?audit= tags. The raw headers are used as a
/// fallback so an engine driven without LlmProducer still propagates them.
///
///
/// Trust model:llm.user.id and llm.audit.* are read off the
/// inbound exchange by the producer, so a transport that forwards client headers
/// verbatim (a plain HTTP consumer) lets the caller set them. That is already true
/// for what the engine persists in MessageProps.UserId; propagating the same
/// value to tools does not widen it. The route — not this policy — is responsible
/// for stripping or overwriting client-supplied llm.* headers before the
/// llm:// hop when tools make access decisions on them.
///
///
public static class ToolHeaderPolicy
{
///
/// Headers copied from the agent exchange to every tool call without opt-in:
/// the conversation id and the two correlation-id spellings the framework
/// already treats as ambient.
///
public static readonly IReadOnlyList DefaultHeaders =
[
LlmHeaders.ConversationId,
"X-Correlation-Id",
"CorrelationId"
];
///
/// Fills with the headers a tool route is allowed to see
/// for this run. Existing entries in (the engine's own
/// llm.tool.* stamps) are never overwritten by propagation.
///
/// The agent run — source of the parent exchange, resolved principal, audit tags and opt-in list.
/// Header dictionary of the tool message being built.
public static void Apply(AgentRequest request, IDictionary target)
{
ArgumentNullException.ThrowIfNull(request);
ArgumentNullException.ThrowIfNull(target);
var source = request.Exchange.In?.Headers;
foreach (var name in DefaultHeaders)
Copy(source, target, name);
// Principal: resolved value wins over the raw header (see class remarks).
if (!string.IsNullOrEmpty(request.UserId))
target[LlmHeaders.UserId] = request.UserId;
else
Copy(source, target, LlmHeaders.UserId);
// Audit tags: same rule — resolved snapshot first, raw llm.audit.* as fallback.
if (request.AuditTags is { Count: > 0 })
{
foreach (var tag in request.AuditTags)
target[LlmHeaders.AuditTagPrefix + tag.Key] = tag.Value;
}
else
{
CopyByPrefix(source, target, LlmHeaders.AuditTagPrefix);
}
if (request.PropagateToolHeaders is not { Count: > 0 } optIn) return;
foreach (var pattern in optIn)
{
if (string.IsNullOrWhiteSpace(pattern)) continue;
if (pattern.Length > 1 && pattern[^1] == '*')
CopyByPrefix(source, target, pattern[..^1]);
else
Copy(source, target, pattern);
}
}
private static void Copy(IDictionary? from, IDictionary to, string key)
{
if (from is null) return;
if (from.TryGetValue(key, out var v) && v is not null)
to[key] = v;
}
private static void CopyByPrefix(IDictionary? from, IDictionary to, string prefix)
{
if (from is null || prefix.Length == 0) return;
foreach (var kv in from)
{
if (kv.Value is null) continue;
if (!kv.Key.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) continue;
to[kv.Key] = kv.Value;
}
}
///
/// Parses the CSV form used by the endpoint URI
/// (?propagateToolHeaders=x-tenant-id,x-app-*) into a name list.
/// Returns null for null/empty input so callers can leave the field unset.
///
/// Comma-separated header names; a trailing * marks a prefix match.
public static IReadOnlyList? ParseCsv(string? csv)
{
if (string.IsNullOrWhiteSpace(csv)) return null;
var names = new List();
foreach (var raw in csv.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
{
var name = System.Web.HttpUtility.UrlDecode(raw).Trim();
if (name.Length > 0) names.Add(name);
}
return names.Count == 0 ? null : names;
}
}
Path: redb-route/redb.Route.Llm/Expressions/LlmExpressionContexts.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/Expressions/LlmExpressionContexts.cs
----
using redb.Route.Llm.Providers;
namespace redb.Route.Llm.Expressions;
///
/// Snapshot of the current conversation visible to the
/// ${conversation.*} expression family. Set by
/// on the parent exchange under
/// the well-known key .
///
public sealed class LlmConversationContext
{
/// Conversation identifier (matches AgentRequest.ConversationId).
public string? Id { get; init; }
/// Number of messages in the transcript so far (includes the seeding user message).
public int MessageCount { get; init; }
/// Aggregate token usage across the current run.
public LlmUsage Tokens { get; init; } = LlmUsage.Empty;
/// Number of completed tool-loop iterations.
public int Iterations { get; init; }
/// Latest assistant message in the transcript (null before the first model response).
public LlmMessage? LastMessage { get; init; }
}
///
/// Snapshot of the tool currently being dispatched, visible to the
/// ${tool.*} expression family. Set by
/// on the parent exchange under
/// the well-known key .
///
public sealed class LlmToolContext
{
/// Tool name as declared in the tool_use block.
public string Name { get; init; } = string.Empty;
/// Provider-issued tool use id (correlates the call to its result block).
public string ToolUseId { get; init; } = string.Empty;
/// Raw JSON input passed to the tool.
public string InputJson { get; init; } = "{}";
/// Raw JSON output produced by the tool. Null while the tool is in flight.
public string? ResultJson { get; init; }
/// Wall-clock execution duration. while in flight.
public System.TimeSpan Duration { get; init; }
}
/// Well-known exchange property keys used by the LLM expression integration.
public static class LlmExpressionKeys
{
/// Exchange property holding the current .
public const string Conversation = "llm.conversation";
/// Exchange property holding the current .
public const string Tool = "llm.tool";
}
Path: redb-route/redb.Route.Llm/Expressions/LlmExpressionResolverSetup.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/Expressions/LlmExpressionResolverSetup.cs
----
using System;
using System.Reflection;
using redb.Route.Abstractions;
using redb.Route.Expressions;
namespace redb.Route.Llm.Expressions;
///
/// Registers ${conversation.*} and ${tool.*} resolvers with
/// . The resolvers read the well-known
/// exchange properties published by
/// (, )
/// and walk the requested path via reflection — so adding fields to
/// /
/// automatically makes them available in templates.
///
public static class LlmExpressionResolverSetup
{
private static int _initialized;
///
/// Idempotently registers the LLM prefix resolvers. Safe to call from
/// every host's composition root — subsequent calls are no-ops.
///
public static void EnsureRegistered()
{
if (System.Threading.Interlocked.CompareExchange(ref _initialized, 1, 0) != 0)
return;
ExpressionResolver.RegisterPrefixResolver("conversation.", (exchange, path) =>
ResolvePath(exchange.getProperty