Let capabilities emit typed `CapabilityEvent`s and subscribe to run events with `@on_event`
Stacked on #6258. Together with it and one more PR on top, this implements the design for capability events: typed events that capabilities emit and that other capabilities, application code, and instrumentation can subscribe to — the core-native answer to the capability-domain-hooks proposal, scoped in this comment. This description doubles as an introduction to the whole design; the pieces land as a stack:
- #6258 —
CustomEvent: events emitted by application code (name + payload, or typed subclasses), forwarded to UI frontends. - This PR — the capability side, whole:
CapabilityEvent(events emitted by capabilities, namespaced and stamped with the emitting instance's id, not forwarded to frontends by default) plus the subscription surface — anon_eventcapability hook, an@on_eventmethod marker,hooks.on.eventapp parity, and dispatch semantics including inline-dispatched "decision" events. - Harness PRs —
FileSystememits read/traversal events,RepoContextsubscribes (replacing itstraversal_tool_namestool-name sniffing), compaction lifecycle events with a cancellableBeforeCompactionEvent, and deprecation of the ad-hocon_spend/on_usage/on_fireconstructor callbacks in favor of this mechanism.
Defining and emitting events
A capability family declares a namespace constant and defines its events as dataclass subclasses whose fields are the payload:
# pydantic_ai_harness/filesystem/_events.py
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
# inside the capability's hook or contributed tool
await ctx.emit_event(FileReadEvent(path=normalized, content_hash=digest))
- The wire identity
kindis'{namespace}.{snake_case(class name)}'('file_system.file_read'; name overridable vianame='...'), so a bare, collision-prone'file_read'is unrepresentable, and duplicates are rejected at class definition. Registration is automatic via__init_subclass__— one class statement is the entire authoring surface. capability_idis stamped at emit time with the emitting instance's run id: resolved from the per-dispatchRunContextcopy for hooks, and through the contributing toolset's id for capability-contributed tools. 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 like custom events.- Events surface on the run's event stream (
event_stream_handler,run_stream_events(),iter()streaming) alongside the framework's own events.
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.- 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).
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 — an event emitted at the end of a tool body always precedes that tool's FunctionToolResultEvent), 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_event(...) runs the listener chain before returning, and the emitter reads the outcome off the event (the DOM preventDefault() model):
@dataclass(kw_only=True)
class BeforeCompactionEvent(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_event(BeforeCompactionEvent(strategy='summarizing', estimated_tokens=41_000))
if event.cancelled:
return # skip compaction this turn
# listener (e.g. Planning, mid-activity):
@on_event(BeforeCompactionEvent)
async def _hold_compaction(self, ctx: RunContext[Any], event: BeforeCompactionEvent) -> 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. 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.
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_event) 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
Same registry + schema-time union-rebuild mechanism as CustomEvent (shared _event_registry.py, patterned on the native-tools union): event_kind='capability' routes the closed AgentStreamEvent union to the family, kind selects the concrete class, and the flat wire dict revalidates to the typed subclass. An unregistered kind — a process that hasn't imported the defining package, e.g. a Temporal worker — degrades to 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.
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) → #6258, extended with typed subclasses. - Logfire angle: one typed stream to instrument; a stock adapter can mirror capability events to spans without per-capability glue.
Checklist
- Tests (
tests/test_capability_events.py,tests/test_on_event.py, adapter suppression tests, Temporal field-exclusion), docs (docs/capabilities/overview.md"Capability events" + "Reacting to events",docs/hooks.md,docs/agent.mdcross-link) - AI generated code (checked by the author in the UI)