How to use middleware to sanitize input, validate output, and trigger retries before guardrails and hooks run.