Skip to content

Middleware Lifecycle ​

Middleware participates in an agent run through lifecycle hooks, wrappers, state updates, and events. Use middleware when behavior must sit around the agent loop instead of inside one tool.

Common uses include permission gates, retry policy, error formatting, tool-call timeout, logging, compaction, content handling, and UI-facing request/response events.

Pipeline Shape ​

Shared middleware is registered on AgentRuntimeBuilder and reaches every agent the runtime runs. Use WithMiddleware, ReplaceMiddleware<T>, InsertMiddlewareBefore<T>, MoveMiddlewareToStart<T>, and RemoveMiddleware<T> to shape that shared list. A middleware that takes settings is declared on the agent's definition with AgentConfig.WithMiddleware<T>(config); a middleware the definition declares supersedes the shared instance of the same type for that agent.

ReplaceMiddleware<T> keeps the first existing position and removes duplicate matches. InsertMiddlewareBefore<T> uses the first anchor and appends when the anchor has not been registered yet. Complete all ordering operations before BuildAsync(). Each agent's pipeline order is fixed when that agent is built, the first time it runs.

Execution Order ​

Hooks follow a stack-shaped model:

SurfaceOrder
Before* hooksregistration order
After* hooksreverse registration order
OnErrorAsyncreverse registration order
model/function wrappersfirst registered is outermost

If middleware is registered as A, then B, then C, wrapper execution is:

text
A(B(C(core)))

This is important for error handling. A retry middleware registered before a timeout middleware wraps the timeout behavior. A formatter registered later is closer to the core operation.

Main Hook Families ​

Message-turn hooks run around a user message turn. Iteration hooks run around an agent loop iteration. Function hooks run around tool/function execution. Thread hooks run around thread fork commit. Runtime hooks run around agent start/stop.

Wrapper hooks are different from Before* and After* hooks. They receive a handler and can decide whether to call it, call it more than once, transform inputs, transform outputs, or catch errors. Function wrappers always participate. Streaming model wrappers opt in by returning a non-null stream.

Runtime start/stop hooks of shared middleware run once per AgentRuntime: start during BuildAsync(), stop when the runtime is disposed. Middleware an agent's definition declares runs its start hooks when that agent is built and its stop hooks when that agent is disposed. Every RunAsync(...) call uses the input, message-turn, iteration, function, thread, and error hooks. See The Runtime And Its Agents for when agents are built.

ToolHarness Middleware ​

IToolHarnessMiddleware inherits all IAgentMiddleware hooks and adds hooks for the harness-local pipeline:

HookWhen it runs
OnHarnessActivatedAsyncAfter all middleware instances for the harness are constructed
OnHarnessExpandedAsyncOnce after a collapsed harness visibility transition commits
OnHarnessDeactivatingAsyncBefore harness middleware disposal, in reverse order

Harness middleware has two activation policies. Collapse.Middlewares is expansion-gated. [ToolHarnessMiddleware] is eager and activates for each accepted input even while the harness remains collapsed. Collapsing continues to control visibility only.

See ToolHarness Middleware for declaration and lifecycle examples.

Hook Reference ​

IAgentMiddleware has hooks at each layer of the runtime. Override only the hooks your middleware needs.

LayerHookWhen it runsCommon uses
RuntimeBeforeStartAsyncOnce, during BuildAsync() for shared middleware or when the agent is built for definition middleware, before the input loop startsAllocate runtime resources, validate startup, configure audio/realtime resources
RuntimeAfterStartedAsyncOnce, right after BeforeStartAsync, after the input loop has startedAvailability diagnostics, background work that depends on the running loop
RuntimeBeforeStopAsyncOnce, when the runtime (for definition middleware, the agent) is disposed, before the runtime input loop stopsGraceful drain decisions, buffer flushing, shutdown diagnostics
RuntimeAfterStoppedAsyncOnce, when the runtime (for definition middleware, the agent) is disposed, after the runtime input loop has stopped and registered resources were disposedFinal telemetry, cleanup confirmation
InputBeforeInputAsyncBefore an accepted input event reaches its handlerInput normalization, rejection, auditing, input-level policy
InputAfterInputAsyncAfter input handling completes, fails, or is cancelledInput metrics, diagnostics, cleanup
Message turnBeforeMessageTurnAsyncBefore processing one user message turnRAG injection, memory retrieval, context augmentation, run-config inspection
Message turnAfterMessageTurnAsyncAfter a message turn completesMemory extraction, analytics, turn-level logging
IterationBeforeIterationAsyncBefore each model iterationPrompt/message modification, chat option tuning, per-iteration policy
Model wrapperWrapModelTurnStreamingAsyncAround the streaming model turn when the middleware opts inRetry, caching, request modification, streaming transformation, progressive metrics
Tool iterationBeforeToolExecutionAsyncAfter the model returns tool calls but before tools executeWhole-iteration tool validation, permission checks, tool filtering
Function batchBeforeParallelBatchAsyncBefore a parallel batch of functions executesBatch-level permissions, rate limiting, batch approval
FunctionBeforeFunctionAsyncBefore each individual function executesArgument validation, per-function permission checks, logging, overrides
Function wrapperWrapFunctionCallAsyncAround the actual function bodyRetry, caching, timeout, result transformation
FunctionAfterFunctionAsyncAfter a function completes or throwsResult formatting, function telemetry, exception observation
IterationAfterIterationAsyncAfter tool results are collected for an iterationResult aggregation, error recovery, state updates
Thread lifecycleBeforeThreadForkCommitAsyncAfter a target thread has been materialized for a fork, before it is persistedCompact copied history, stamp thread metadata, rewrite thread-local middleware state
ErrorOnErrorAsyncOnce for each terminal non-cancellation failureCentralized logging, metrics, policy, graceful termination

For the exact properties and mutable control fields on every hook context, see Middleware Hook Fields.

BeforeThreadForkCommitAsync is the fork hook. It sees both the source thread and the not-yet-persisted target thread, plus the fork point and ThreadForkOptions. Use it when the target thread should start differently from a raw copy, such as compacting copied history, adding thread-local metadata, or adjusting copied middleware state before the new thread becomes durable.

Fork events are a different surface. After a fork is committed, thread event projection records the committed state with durable events such as THREAD_CREATED with fork metadata, later THREAD_UPDATED header/tree changes, and THREAD_MIDDLEWARE_STATE_COMMITTED. Those events describe what was committed; they are not pre-commit mutation hooks.

Streaming Wrapper Probe ​

WrapModelTurnStreamingAsync(...) uses nullable return semantics. Returning null means the middleware does not intercept the streaming model turn.

During pipeline construction, the framework probes each middleware once to see whether it returns a stream. If it opts in, the middleware is called again when the stream actually executes. Avoid side effects before returning the IAsyncEnumerable.

Prefer this shape:

csharp
public IAsyncEnumerable<AgentModelUpdate>? WrapModelTurnStreamingAsync(
    AgentModelTurnRequest request,
    Func<AgentModelTurnRequest, IAsyncEnumerable<AgentModelUpdate>> next,
    CancellationToken cancellationToken)
{
    return RunAsync(request, next, cancellationToken);
}

private async IAsyncEnumerable<AgentModelUpdate> RunAsync(
    AgentModelTurnRequest request,
    Func<AgentModelTurnRequest, IAsyncEnumerable<AgentModelUpdate>> next,
    [System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken)
{
    // Side effects here run during enumeration, not during the probe.
    Console.WriteLine("Model stream started.");

    await foreach (var update in next(request).WithCancellation(cancellationToken))
    {
        yield return update;
    }
}

Do not increment counters, emit events, mutate request-related state, or start background work before returning the stream. That work can happen during the probe even if no tokens have been enumerated yet.

State Updates ​

Middleware state is immutable. Use UpdateState(...) for core state or multi-state atomic updates. Use UpdateMiddlewareState<TState>(...) for simple updates to one middleware state record.

csharp
namespace GettingStarted;

public sealed class TurnCountingMiddleware : IAgentMiddleware
{
    public Task BeforeIterationAsync(
        BeforeIterationContext context,
        CancellationToken cancellationToken)
    {
        context.UpdateMiddlewareState<TurnCounterState>(state => state with
        {
            Count = state.Count + 1
        });

        return Task.CompletedTask;
    }
}

[MiddlewareState(Persistent = true, Scope = StateScope.Thread)]
public sealed record TurnCounterState
{
    public int Count { get; init; }
}

Do not read state, await unrelated work, and then write a derived value. Put the read inside the update lambda so the update is based on the current state at the time of mutation.

Use UpdateState(...) when you need to update loop state directly:

csharp
context.UpdateState(state => state with
{
    IsTerminated = true,
    TerminationReason = "Stopped by middleware policy"
});

Scoped Middleware ​

Function-level middleware can be scoped with AsGlobal, ForToolHarness, ForSkill, or ForFunction. Scope filtering applies to all three function surfaces:

  • BeforeFunctionAsync
  • WrapFunctionCallAsync
  • AfterFunctionAsync

Model and turn hooks remain global because they do not target one function call. Function scopes are evaluated against the current request, including any function substitution performed by an outer wrapper.

Skill scopes use the active typed capability relationship between the skill activation and its revealed functions. They do not depend on legacy IsSkillContainer metadata.

Error Scope ​

OnErrorAsync is the terminal failure observer for the middleware runtime. It runs exactly once for model, function, iteration, message-turn, input, runtime, and thread-fork failures.

Caller cancellation remains on the cancellation lifecycle and does not invoke OnErrorAsync. An exception may cross several framework boundaries, but the router marks it after the first observation so handlers do not run twice.

Built-In Middleware Order ​

When the runtime builds an agent, it adds the built-in middleware its definition implies or the runtime's features need. Source-checked built-ins include content upload/reference/image middleware, retry, function timeout, error formatting, container/collapsing, client tools, and logging.

Because wrappers are first-registered-is-outermost, the recommended error-handling stack is:

text
RetryMiddleware(FunctionTimeoutMiddleware(ErrorFormattingMiddleware(core)))

See Error Handling for details.

Built for production .NET agent applications.