Overview of Agent Middleware hooks
mainAgent middleware allows you to inject custom logic (logging, tracing, input rewriting, etc.) at key lifecycle points without modifying agent or model code. There are two types of hooks:
- Onion hooks (
onAgent,onReasoning,onActing,onModelCall): These wrap the next handler. You can execute logic before or afternext.apply(input)and observe the intermediate event stream. - Transformer hooks (
onSystemPrompt): These form a pipeline where the output of one middleware is the input to the next. There is no "inner layer."
Hook Positions
| Position | Type | Description |
|---|---|---|
onAgent | Onion | Wraps the full reply flow (all ReAct rounds, tool execution, and final output) |
onReasoning | Onion | Wraps one reasoning step (input assembly → model call → streaming decode) |
onActing | Onion | Wraps the execution of a single tool call (only for tools executed inside the agent runtime) |
onModelCall | Onion | Wraps a raw ChatModel API call |
onSystemPrompt | Transformer | Triggers when the system prompt is assembled; middlewares run in sequence |
Execution Order
- Onion hooks: The first middleware in the list is the outermost. For
[mw1, mw2], the order is:mw1 pre → mw2 pre → inner → mw2 post → mw1 post. - Transformer hooks: Processed left-to-right. For
[mw1, mw2], the order is:originalPrompt → mw1.onSystemPrompt() → mw2.onSystemPrompt() → final.