> For the complete documentation index, see [llms.txt](https://ai.ortusbooks.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://ai.ortusbooks.com/main-components/middleware.md).

# Middleware

Middleware overview and navigation hub for all built-in middleware classes

{% hint style="info" %}
Since BoxLang AI v3.0+. This section is the middleware documentation hub: architecture, lifecycle hooks, return semantics, and one dedicated page per middleware class.
{% endhint %}

Middleware wraps agent and model execution in layers. Each layer can observe, mutate, retry, reject, defer, or suspend work around LLM and tool calls without changing business logic.

## Execution Flow

```
Agent.run(input)
  -> beforeAgentRun (in order)
  -> beforeLLMCall
  -> wrapLLMCall(handler)
  -> afterLLMCall
  -> beforeToolCall (for each tool call)
  -> wrapToolCall(handler)
  -> afterToolCall
  -> afterToolBatch (once per turn)
  -> afterAgentRun (reverse order)
```

Inbound hooks (`before*`) run in registration order. Outbound hooks (`after*`) run in reverse order. Wrap hooks (`wrapLLMCall`, `wrapToolCall`) are around-advice and call `handler()` to continue.

## Attach Middleware

```javascript
agent = aiAgent(
    name      : "assistant",
    middleware: [
        new LoggingMiddleware(),
        new RetryMiddleware( maxRetries: 3 ),
        new GuardrailMiddleware( blockedTools: [ "deleteRecord" ] )
    ]
)
```

```javascript
agent = aiAgent( name: "assistant" )
    .withMiddleware( new LoggingMiddleware() )
    .withMiddleware( new RetryMiddleware() )
```

## Hook Reference

| Hook             | Fires When                              | Context Keys                                                  |
| ---------------- | --------------------------------------- | ------------------------------------------------------------- |
| `beforeAgentRun` | Before an agent run starts              | `agent`, `input`, `messages`, `params`, `options`             |
| `afterAgentRun`  | After an agent run completes            | `agent`, `input`, `messages`, `params`, `options`, `response` |
| `beforeLLMCall`  | Before each LLM call                    | `model`, `chatRequest`, `messages`                            |
| `afterLLMCall`   | After each LLM call                     | `model`, `chatRequest`, `messages`, `response`                |
| `beforeToolCall` | Before each tool invocation             | `tool`, `toolName`, `toolArgs`, `toolCallId`                  |
| `afterToolCall`  | After each tool invocation              | `tool`, `toolName`, `toolArgs`, `toolCallId`, `result`        |
| `afterToolBatch` | Once after all tool decisions in a turn | `chatRequest`, `assistantMessage`, `batch`                    |
| `onError`        | On uncaught middleware exceptions       | `error`, `phase`, `context`                                   |
| `onAttach`       | When attached to an agent/model         | attached instance                                             |

## AiMiddlewareResult

Each hook returns `AiMiddlewareResult`.

| Method             | Meaning                                    |
| ------------------ | ------------------------------------------ |
| `continue()`       | Proceed normally                           |
| `cancel(reason)`   | Stop execution                             |
| `approve()`        | Approve a tool call                        |
| `reject(reason)`   | Reject a tool call                         |
| `edit(args)`       | Replace tool args                          |
| `suspend(pending)` | Suspend run for resume                     |
| `defer(pending)`   | Mark pending and continue batch evaluation |

Predicates include `isContinue()`, `isCancelled()`, `isApproved()`, `isRejected()`, `isEdit()`, `isSuspended()`, `isDeferred()`, and `isTerminal()`.

## Middleware Catalog

### Core Middleware

* [LoggingMiddleware](/main-components/middleware/logging.md)
* [RetryMiddleware](/main-components/middleware/retry.md)
* [GuardrailMiddleware](/main-components/middleware/guardrail.md)
* [MaxToolCallsMiddleware](/main-components/middleware/max-tool-calls.md)
* [HumanInTheLoopMiddleware](/main-components/middleware/human-in-the-loop.md)
* [FlightRecorderMiddleware](/main-components/middleware/flight-recorder.md)
* [RunControlMiddleware (internal)](/main-components/middleware/run-control.md)

### Security Middleware

* [InputSanitizerMiddleware](/main-components/middleware/input-sanitizer.md)
* [OutputGuardMiddleware](/main-components/middleware/output-guard.md)
* [LLMGuardMiddleware](/main-components/middleware/llm-guard.md)

## Related

* [Agent Middleware](/main-components/agents/middleware.md)
* [Human-in-the-Loop](/main-components/human-in-the-loop.md)
* [Gateways](/main-components/gateways.md)
* [Security Guide](/advanced/security.md)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://ai.ortusbooks.com/main-components/middleware.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
