Skip to content

Middleware Hook Fields ​

This reference lists the fields available to each IAgentMiddleware hook in HPD-Agent 0.9.7. The exact context types are public; middleware should depend on the fields documented here rather than internal agent state.

Shared Hook Context ​

Turn, iteration, function, thread-fork, and error hooks derive from HookContext. They share:

FieldPurpose
AgentNameCurrent agent name
ConversationIdSession/conversation identity
TraceIdTrace identity shared by the turn
ThreadExecutionIdAccepted execution identity, when available
MessageTurnIdDurable message-turn identity
AgentConfigThe agent definition the agent was built from
ComponentConfigConfiguration captured for this run; components read it through IConfig<T>.For(context)
ClientSetResolved client-family instances
SubAgentRunConfigsShared and exact direct-child run configurations, when applicable
Session, SessionIdSession metadata and identity
Thread, ThreadIdCurrent thread and identity
ServicesAgent/input child-scope service provider
ContentStoreConfigured content store
RuntimeCapabilitiesRuntime-scoped capability registry
EventFlowsInterruptible event-flow registry

Shared methods:

  • Analyze<T>(...) reads loop state under the state lock.
  • UpdateState(...) atomically updates core or multiple middleware states.
  • UpdateMiddlewareState<T>(...) and GetMiddlewareState<T>() handle one state record.
  • PublishAsync(...) publishes one-way events.
  • RequestAsync<TRequest,TResponse>(...) publishes and waits for a response.
  • RunAsync(...) submits runtime control input.

Runtime Hooks ​

BeforeStartContext, AfterStartedContext, BeforeStopContext, and AfterStoppedContext derive from RuntimeHookContext.

Shared runtime fields: AgentName, AgentConfig, RunConfig, ClientSet, Services, EventCoordinator, ThreadEvents, EventFlows, StructEvents, ContentStore, RuntimeCapabilities, RuntimeId, CreatedAt, RuntimeCancellationToken, and HasActiveRuntimeInputs.

Shared runtime methods: PublishAsync, RunAsync, RegisterClientToolOperation, TryResolveClientToolOperation, RegisterDisposable, and RegisterAsyncDisposable.

HookAdditional fieldsWritable control
BeforeStartAsyncShared runtime fieldsCancelStart, CancelReason
AfterStartedAsyncStartedAtNone
BeforeStopAsyncReasonDrainPendingInputs, DrainTimeout
AfterStoppedAsyncReason, StartedAt, StoppedAt, Duration, ErrorNone

Input Hooks ​

Input hooks use a narrower surface than HookContext.

HookFieldsControl
BeforeInputAsyncInput, Cancelled, CancelReason, AgentName, Config, ServicesReplaceInput(...), CancelInput(...)
AfterInputAsyncInput, Result, Error, Cancelled, Duration, Cancellation, AgentName, Config, ServicesObservation only

Session and thread identities carried by the input are available through context.Input.SessionId, context.Input.ThreadId, and process-local Session/Thread properties where the input type provides them.

Message-Turn Hooks ​

HookFieldsMutation
BeforeMessageTurnAsyncSourceInput, TriggerSource, UserInputMessages, RuntimeContextMessages, ThreadHistory, RunConfig, shared context fieldsUser input messages and thread history are mutable. The number of input messages cannot change. Runtime-context messages can be replaced individually with ReplaceRuntimeContextMessage(...).
AfterMessageTurnAsyncSourceInput, TriggerSource, UserInputMessages, RuntimeContextMessages, FinalResponse, TurnHistory, RunConfig, TurnUsage, IterationUsage, shared context fieldsTurnHistory is mutable before accounting closes and history is persisted.

AgentTurnTriggerSource is one of UserInput, BackgroundNotification, SteeringContinuation, RuntimeContext, or Resume.

Iteration Hooks ​

HookFieldsControl
BeforeIterationAsyncIteration, Messages, Options, RunConfig, IsFirstIteration, PreviousIterationsUsage, PreviousIterationUsage, shared context fieldsMessages and Options are mutable. Set SkipLLMCall and supply OverrideResponse to bypass the model call.
AfterIterationAsyncIteration, ToolResults, RunConfig, AllToolsSucceeded, AnyToolFailed, shared context fieldsObservation and middleware-state updates.

AllToolsSucceeded checks that every result has no exception. AnyToolFailed reports whether at least one result carries an exception.

Tool and Function Hooks ​

HookFieldsControl
BeforeToolExecutionAsyncResponse, ToolCalls, RunConfig, shared context fieldsSet SkipToolExecution and OverrideResponse to bypass every tool requested in the current model response.
BeforeParallelBatchAsyncParallelFunctions, BatchId, RunConfig, shared context fieldsBatch inspection only. Per-function control remains in BeforeFunctionAsync.
BeforeFunctionAsyncFunction, FunctionCallId, Invocation, ToolCallIndex, Arguments, InvocationMode, PermissionGrant, PermissionRequired, ToolHarnessName, SkillName, ClientToolOperations, RunConfig, shared context fieldsSet BlockExecution and OverrideResult for one function call.
AfterFunctionAsyncFunction, FunctionCallId, Invocation, ToolCallIndex, InvocationMode, OriginalResult, Result, Exception, ResultMetadata, CommittedToolBodyOperation, ToolHarnessName, SkillName, RunConfig, shared context fieldsResult and Exception are mutable. Helpers include IsSuccess, IsFailure, IsSkillFunction, and IsToolHarnessFunction.

BeforeFunctionContext.Function may be null for an unknown or unavailable function. ClientToolOperations is present only when the runtime owns client-tool operations. SkillName is an informational attribution field and may be null for a referenced function; use ForSkill(...) for reliable skill scoping.

Parallel batch entries ​

Each ParallelFunctionInfo contains:

  • Function and FunctionName
  • CallId
  • Arguments
  • Invocation
  • ResolvedInvocation

ToolInvocationInfo contains BatchId, CallId, FunctionName, and ToolCallIndex.

Model Wrapper ​

WrapModelTurnStreamingAsync receives AgentModelTurnRequest:

FieldPurpose
TransportChat or Realtime
ChatModel, RealtimeModelSelected transport client
Messages, OptionsProvider-bound request
State, IterationCurrent loop snapshot and iteration
EventFlows, EventCoordinator, EventPublisherObservation and event coordination
Session, ContentStore, ClientSet, RunConfigResolved invocation context
StructEventsProcess-local realtime struct events

Return null to pass through. Otherwise return an async stream around handler(request). Side effects belong inside the iterator, not in wrapper setup.

AgentModelUpdate variants include chat updates, text and reasoning deltas, audio deltas, input transcripts, tool-call updates, response lifecycle updates, and usage updates.

Function Wrapper ​

WrapFunctionCallAsync receives an immutable FunctionRequest:

FieldPurpose
Function, FunctionName, CallIdInvocation identity
ArgumentsImmutable argument dictionary
State, RunConfig, SubAgentRunConfigsAgent and run context
Invocation, InvocationModeBatch and action/invocation-mode facts
PermissionGrant, PermissionRequiredPermission admission facts
ResultMetadataMutable per-call metadata side channel
ToolHarnessName, SkillNameCapability attribution
CancellationTokenOptional timeout/retry cancellation override
EventCoordinator, EventPublisher, StructEventsObservation surfaces

Use request.Override(function: ..., arguments: ...) to create a modified request without mutating the original.

Thread Fork ​

BeforeThreadForkCommitContext provides:

  • SourceThread
  • TargetThread, before persistence
  • ForkedAtMessageIndex
  • ForkedAtMessageId
  • ForkOptions
  • HistoricalEvents, writable by framework-approved middleware history mutations
  • Shared context fields

Framework-owned target identity, topology, registry, grants, and operation facts cannot be replaced.

Error Hook ​

ErrorContext provides:

FieldPurpose
ErrorOriginal terminal exception
SourceTyped ErrorSource
IterationCurrent iteration when the failure occurred
RunConfigAssociated run configuration, when available
ErrorDetails, ErrorCategoryProvider-aware classification
IsModelError, IsToolError, IsIterationError, IsMessageTurnErrorTurn-path helpers
IsInputError, IsRuntimeError, IsThreadForkErrorLifecycle-path helpers
IsModelNotFoundError, IsRetryableErrorClassification helpers
Shared context fields and state/event methodsObservation and policy

OnErrorAsync is observation-first. The original failure still propagates after all handlers complete.

ToolHarness Lifecycle ​

HookFields
OnHarnessActivatedAsyncHarnessIdentity, InputExecutionId, ComponentConfig, Services, RunConfig, SessionId, ThreadId
OnHarnessExpandedAsyncHarnessIdentity, InputExecutionId, Reason, ExpansionCallId, RevealedFunctions
OnHarnessDeactivatingAsyncHarnessIdentity, InputExecutionId, Reason

ToolHarnessActivationContext also provides:

  • GetService<T>() and GetRequiredService<T>()
  • GetRequiredServicesOwned<TMiddleware>()
  • GetRequiredAgentResource<T>()
  • GetCanonicalWorkspaceIdentity()

Built for production .NET agent applications.