Let application code and capabilities emit typed `CustomEvent`s and `CapabilityEvent`s into the run event stream and subscribe with `@on_event`
This PR implements the whole run event design — application CustomEvents, capability CapabilityEvents, and the on_event subscription surface — as one stack. Closes #2382, supersedes #3114 and #7794 (whose design discussion and description this one carries forward). It is the core-native answer to the capability-domain-hooks proposal, scoped in this comment and audited against Code Puppy's full callback inventory in pydantic-ai-notes#15.
Harness PRs follow on top: FileSystem emits read/traversal events with RepoContext subscribing (replacing its traversal_tool_names tool-name sniffing), compaction lifecycle events with a cancellable CompactionStartEvent, and deprecation of the ad-hoc on_spend/on_usage/on_fire constructor callbacks. A stacked core PR adds the compaction event family to core itself (emitted by OpenAICompaction/AnthropicCompaction as well as the Harness strategies).
Two event families
Both families are typed dataclass subclasses only — there is no name + untyped-payload shorthand. A quick event is a two-line class; forcing the class keeps every event isinstance-matchable, serializable, and self-documenting:
CustomEvent— application-owned events, emitted from tools, history processors, output validators (await ctx.emit(event)) or code drivingagent.iter()(AgentRun.emit). Forwarded to UI frontends.CapabilityEvent— events capabilities emit, namespaced and stamped with the emitting instance's run id. Not forwarded to frontends by default.
@dataclass(kw_only=True)
class SyncProgressEvent(CustomEvent):
done: int
total: int
await ctx.emit(SyncProgressEvent(done=3, total=9))
A capability family declares a namespace; the wire identity kind is '{namespace}.{snake_case(class name)}', so a bare, collision-prone 'file_read' is unrepresentable:
FILE_SYSTEM_EVENTS = 'file_system'
@dataclass(kw_only=True)
class FileReadEvent(CapabilityEvent, namespace=FILE_SYSTEM_EVENTS):
path: str # the normalized, authorization-checked path
content_hash: str
- Registration is automatic via
__init_subclass__— one class statement is the entire authoring surface. Names/kinds must be process-unique (duplicates rejected at class definition; re-executing the same class definition, as in a notebook, replaces the registration;@dataclass(slots=True)recreation is handled). capability_idis stamped at emit time with the emitting instance's run id — resolved from the per-dispatchRunContextcopy for hooks, and via thecapability_idCapabilityOwnedToolsetstamps on tool definitions for capability-contributed tools (so implicitly-id'd capabilities work too). The union tag stays class-stable while instances remain distinguishable: two MCP capability instances sharekind='mcp.tools_listed'but carrycapability_id='docs_server'/'internal'.tool_call_id/tool_nameare stamped on both families.emitis async-only, so it's available exactly where blocking the loop isn't a concern; sync tools cannot emit.
Live delivery
Events surface to stream consumers (event_stream_handler, run_stream_events(), iter() streaming, UI adapters) as soon as they are emitted — a progress event arrives while the emitting tool is still running, not with its result. Tool execution races task completion against a buffer signal; emission order is preserved (an event emitted in a tool body always precedes that tool's FunctionToolResultEvent).
Subscribing
Capabilities subscribe with a method marker; filtering is by explicit event type (isinstance semantics, statically checked against the parameter annotation — no casts, no name-string matching):
class RepoContext(AbstractCapability[Any]):
@on_event(FileReadEvent, DirectoryListedEvent)
async def _on_traversal(self, ctx: RunContext[Any], event: FileReadEvent | DirectoryListedEvent) -> None:
if note := self._context_file_note(event.path):
ctx.enqueue(note) # lands in history before the next model request
This replaces the tool-name sniffing RepoContext does today (traversal_tool_names + guessing the args dict + re-deriving path validation): it reacts to FileSystem's processed data — the normalized, authorized path — without coupling to tool names.
on_eventreceives all events: framework events (tool calls/results, deferred-tool batches, enqueued-message deliveries, streaming parts), custom events, and capability events. A bare@on_eventsubscribes to everything (the parameter must then be typed as the fullAgentStreamEventunion). Capabilities with no subscriptions cost nothing; a listener automatically enables streaming for an otherwise non-streamingagent.run().- Dispatch order follows capability order; listeners are async and observe-only — they react via side effects (
ctx.enqueue, emitting further events, mutating the event, see below). - App code gets the same surface through the
Hookscapability:@hooks.on.event(FileReadEvent)(the existing transform semantics ofhooks.on.eventare deprecated towardhooks.on.run_event_stream; while deprecated, multiple replacements compose in order).
Dispatch timing. By default, listeners run at the event's stream position: an event enters the run's event buffer at emit time (so stream ordering can never invert), and listeners are invoked as events flow by, in stream order, before the next model request at the latest. Emitters aren't slowed down by their listeners.
Decision events. An event type that expects answers declares inline dispatch on the class, next to its decision fields — then await ctx.emit(...) runs the listener chain before returning, and the emitter reads the outcome off the event (the DOM preventDefault() model):
@dataclass(kw_only=True)
class CompactionStartEvent(CapabilityEvent, namespace=COMPACTION_EVENTS, dispatch='inline'):
strategy: str
estimated_tokens: int
cancelled: bool = False
cancel_reason: str | None = None
def cancel(self, reason: str | None = None) -> None:
self.cancelled = True
self.cancel_reason = reason
# emitter (a compaction strategy):
event = await ctx.emit(CompactionStartEvent(strategy='summarizing', estimated_tokens=41_000))
if event.cancelled:
return # skip compaction this turn
# listener (e.g. Planning, mid-activity):
@on_event(CompactionStartEvent)
async def _hold_compaction(self, ctx: RunContext[Any], event: CompactionStartEvent) -> None:
if self._plan_step_in_flight:
event.cancel('a plan step is mid-flight')
Because the class carries the declaration, an emitter can't forget to wait and read stale fields; the decided state also serializes to the stream, so consumers see the outcome. Inline events are still delivered exactly once on the stream. This subsumes the proposal's before_compaction guard — and generalizes it: any capability can define an intervention point without core growing a new hook, with GuardrailResult-style vocabularies expressible as fields on the event. (Naming convention: events use Start/End; before_/after_ stays hook vocabulary.)
Guardrails between the two families
The custom/capability split is enforced, not conventional:
- A
CapabilityEventwith no resolvable owning capability (a plain@agent.tool, orAgentRun.emit) raisesUserError— app code emitsCustomEvents. - A
CustomEventemitted from inside a capability's hook dispatch raisesUserError— except for app-facing callback capabilities (Hooks,ProcessEventStream), which run user callbacks. That keeps the sanctioned frontend bridge working: capability events do not cross to UI frontends by default (the newUIEventStream.handle_capability_eventdefault emits nothing — internal coordination signals shouldn't leak internal metadata to browsers), and the way to surface one is an application subscriber that re-emits it as aCustomEvent, deliberately choosing the payload.
Serialization and protocol mapping
Registry + schema-time union-rebuild, patterned on the native-tools union (shared pydantic_ai/_event_registry.py): event_kind ('custom'/'capability') routes the closed AgentStreamEvent union to the family; the inner tag (name/kind) selects the concrete class, and the flat wire dict revalidates to the typed subclass. An unregistered tag — a process that hasn't imported the defining package, e.g. a Temporal worker — degrades to UnknownCustomEvent/UnknownCapabilityEvent with the payload preserved in data (re-flattened on re-serialization, so a downstream consumer that has the module imported recovers the typed event) instead of failing validation. Payload fields can't shadow the event envelope (data, capability_id, ...), rejected at class definition.
UI adapters obtain the frontend payload from the overridable CustomEvent.to_payload() (the event's own fields by default):
- AG-UI:
ag_ui.core.CustomEvent(name=..., value=...); anag_ui.core.BaseEventpayload is passed through verbatim (parity with the #2922 tool-return metadata passthrough). - Vercel AI:
DataChunk(type='data-{name}', data=...); data-carrying chunk payloads pass through verbatim (parity with #4230).
Relation to the capability-domain-hooks proposal
HarnessEvent/HarnessEventEmitter→ coreCapabilityEvent+ the run event stream; no per-capability emitter object, noon_event=constructor params (the existingon_spend/on_usage/on_fireparams get deprecation shims pointing at subscriptions).- Tier-2 interventions (
GuardrailResultreuse,before_compaction) → inline-dispatched decision events; guardrails remain the right tool where they exist today. - The proposal's "core ask" (a
CustomEventbridge member inAgentStreamEvent) → this PR'sCustomEventfamily. - Logfire angle: one typed stream to instrument; a stock adapter can mirror capability events to spans without per-capability glue.
Checklist
- Tests (
tests/test_custom_events.py,tests/test_capability_events.py,tests/test_on_event.py, adapter forwarding/suppression tests, Temporal/Prefect field-audit tests) - Docs (
docs/agent.mdCustom Events,docs/capabilities/overview.mdCapability events + Reacting to events,docs/hooks.md, UI adapter docs,docs/durable_execution/temporal.md) - AI generated code (checked by the author in the UI)