Make `wrap_*` hooks enclose complete stage lifecycles
Every stage of a run (the run itself, each node, model request, tool call, and output) now has one hook lifecycle, with wrap_* outermost:
wrap_* enter → before_* → operation (on_*_error if it fails) → after_* → wrap_* exit
Before this PR, wrap_* sat between before_* and after_*, so a wrapper couldn't see or control what the before_*/after_* hooks did, and gen_ai.input.messages missed changes a wrapper made (#7441).
[!WARNING]
Compatibility impact: Capabilities that depend on the old relative order of wrap_* and before_*/after_*/on_*_error hooks can behave differently, even though every hook signature is unchanged and existing code still imports and type-checks. The changes users can hit are listed below.
Why this can ship in a minor release: the relative order of the hook families was never a documented guarantee beyond "wraps nest as middleware", the old order made wrap_* unable to enclose a stage, and every public signature is unchanged. OpenTelemetry span changes are explicitly permitted by the version policy.
Migration: put policy that must always run (authorization, mandatory redaction) in an outer wrap_* hook rather than in before_*, since a wrapper that returns without calling its handler now skips the inner hooks. Raise an exception other than ModelRetry from before_model_request to abort a run. Add messages to persistent history through ctx.messages, not by appending to request_context.messages.
What changes:
- Hook order.
wrap_*enclosesbefore_*, the operation withon_*_errorrecovery, andafter_*:- A wrapper that returns without calling its handler skips
before_*andafter_*, including request-time delivery of enqueued messages. on_*_errorrecovers before the wrapper sees the failure.- Exceptions from
before_*/after_*reach the wrapper. - Calling a non-model handler again repeats the inner hooks.
- A wrapper that returns without calling its handler skips
wrap_model_requestmay call its handler only once. A second call raisesUserError.- Request messages are request-only. Assigning or mutating
request_context.messageschanges only the current request;ctx.messagesis persistent history. Appending torequest_context.messagesinbefore_model_requeststill reaches history but emits aPydanticAIDeprecationWarning. ModelRetryfrombefore_model_requestretries the request with a retry prompt, drawing on the output retry budget. It used to propagate out of the run.run_stream()counts requests likerun().usage.requestscounts a step once, when core commits the response the agent acts on. That response can come from the provider, a recovery, a wrapper's cached response orSkipModelRequest, or the partial of an interrupted stream. A model call that fails without recovery doesn't count; any usage it reported does. This was alreadyrun()'s behaviour;run_stream()used to count a call when its lazy stream was opened, before anything was sent. While a step streams,AgentStream.usagealready includes it, butAgentRun.usagecounts it only once the response is committed.request_limitis checked at the start of each step, beforewrap_model_request, so steps a wrapper answers from a cache are bounded too.- Context variables.
- Values set in
after_runno longer reach the caller afteragent.run()returns (never documented). on_run_errornow sees values set during the run.- In
run_stream(), values set bybefore_model_requestreach later tool, output and run hooks, but values set later in the model request may not.
- Values set in
- Durable execution.
before_model_requestsees the durable model, so model calls made from it dispatch durably. - Cancellation.
on_run_errorand thenwrap_runboth observe aCancelledError.- A result
on_run_errorreturns for it is discarded, as before. - The run still ends cancelled.
- Spans (OpenTelemetry; permitted by the version policy):
- Span attributes are set after the handler call (#7441).
- Spans include time spent in
before_*/after_*hooks. - An
after_tool_executetransformation is what the tool span records as the result. - A request recovered by
on_model_request_erroris recorded as a success, and anafter_*failure marks the span as an error. - Request spans capture the request as prepared.
- Usage metrics use the provider's billed response even if a hook substitutes another.
- A skipped provider call has no provider model attributes or metrics.
- Harness.
SpendLimitsnow counts every response the provider billed, including one that a capability nested inside it rejects, soSpendCompositionWarningis no longer emitted. It is deprecated, and importing it warns.- Compaction capabilities update persistent history and the current request together, so list
Memoryafter compaction (documented; whether core should support request-only injected blocks natively is being decided separately).
New public surface: none. Core keeps a private record of the responses the provider billed during a model request (ModelRequestContext._usage_responses). The Instrumentation capability and the Harness's SpendLimits read it; whether to make it public waits for the per-attempt model-request work in #9348.
Related and follow-ups:
- #7212 (
on_run_errorbypassed whenbefore_runraises) is by design under this contract:on_*_errorcovers only the stage's core operation. on_model_request_errorfor streams that fail to open, raised in review here, lands in #9348, which primes stream opening for agents that define the hook.- The partial response of an interrupted stream counts in usage and history but isn't in the billed-response record
SpendLimitsreads, as onmain: #9601.
Verification: lifecycle, message-persistence, streaming, cancellation, Logfire, durable and Harness suites in CI. New counting tests in tests/test_capability_hooks.py:
test_failed_model_request_is_not_counted_as_a_requesttest_skipped_model_request_is_counted_as_a_requesttest_request_limit_bounds_responses_a_wrapper_returns_without_the_model
Each runs in both run modes. Cancellation is covered by tests/test_run_cancellation.py::test_run_capabilities_cannot_recover_cancellation, and the deprecated alias by tests/harness/spend/test_spend.py::test_spend_composition_warning_is_a_deprecated_alias.
- Closes #7441
Checklist
- No breaking changes in accordance with the version policy.
- Any permitted compatibility impact has a label, warning, migration, release note, and exact API-check waiver.
- PR title is fit for the release changelog.
🤖 Generated with Claude Code