Let capabilities emit typed `CapabilityEvent`s and subscribe to run events with `@on_event`

Merged
DO
3mo ago
+1332-80

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:

  1. #6258 — CustomEvent: events emitted by application code (name + payload, or typed subclasses), forwarded to UI frontends.
  2. 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 — an on_event capability hook, an @on_event method marker, hooks.on.event app parity, and dispatch semantics including inline-dispatched "decision" events.
  3. Harness PRs — FileSystem emits read/traversal events, RepoContext subscribes (replacing its traversal_tool_names tool-name sniffing), compaction lifecycle events with a cancellable BeforeCompactionEvent, and deprecation of the ad-hoc on_spend/on_usage/on_fire constructor 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 kind is '{namespace}.{snake_case(class name)}' ('file_system.file_read'; name overridable via name='...'), 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_id is stamped at emit time with the emitting instance's run id: resolved from the per-dispatch RunContext copy 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 share kind='mcp.tools_listed' but carry capability_id='docs_server' / 'internal'. tool_call_id/tool_name are 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_event receives all events: framework events (tool calls/results, deferred-tool batches, enqueued-message deliveries, streaming parts), custom events, and capability events. A bare @on_event subscribes to everything (the parameter must then be typed as the full AgentStreamEvent union). 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 Hooks capability: @hooks.on.event(FileReadEvent) (the existing transform semantics of hooks.on.event are deprecated toward hooks.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 CapabilityEvent with no resolvable owning capability (a plain @agent.tool, or AgentRun.emit_event) raises UserError — app code emits CustomEvents.
  • A CustomEvent emitted from inside a capability's hook dispatch raises UserError — 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 new UIEventStream.handle_capability_event default 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 a CustomEvent, 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 → core CapabilityEvent + the run event stream; no per-capability emitter object, no on_event= constructor params (the existing on_spend/on_usage/on_fire params get deprecation shims pointing at subscriptions).
  • Tier-2 interventions (GuardrailResult reuse, before_compaction) → inline-dispatched decision events; guardrails remain the right tool where they exist today.
  • The proposal's "core ask" (a CustomEvent bridge member in AgentStreamEvent) → #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.md cross-link)
  • AI generated code (checked by the author in the UI)