What are Events?
Events provide observability into agent execution. Every significant action—starting a run, calling a tool, emitting a reasoning step—fires a typed event that you can listen to. Unlike middleware (which can modify execution), events are read-only observers. Use them for:- Logging and debugging
- Telemetry and metrics
- UI updates (streaming, progress indicators)
- Analytics and monitoring
Event Emitter
Agents use a fully-typed event emitter:Core Events
AgentLIB defines a typed event map:Subscribing to Events
Basic Subscription
One-time Listeners
Unsubscribing
Event Reference
run:start
Fired whenagent.run() is called, before any processing begins.
packages/core/src/agent/agent.ts:88
run:end
Fired when execution completes successfully.packages/core/src/agent/agent.ts:95
step:reasoning
Fired every time a reasoning engine pushes a step.packages/core/src/reasoning/context.ts:47
model:request
Fired before sending a request to the LLM.model:response
Fired when the LLM responds.tool:before
Fired before a tool is executed.packages/core/src/reasoning/context.ts:67
tool:after
Fired after a tool completes or fails.packages/core/src/reasoning/context.ts:94-115
memory:read
Fired when memory is loaded.packages/core/src/agent/agent.ts:124
memory:write
Fired when memory is persisted.packages/core/src/agent/agent.ts:139
error
Fired when an error occurs during execution.packages/core/src/agent/agent.ts:98
cancel
Fired when execution is canceled.Custom Events
You can emit custom events from tools or middleware:Common Event Patterns
Progress Tracking
Streaming UI Updates
Cost Calculation
Logging
Analytics
Events vs. Middleware
| Feature | Events | Middleware |
|---|---|---|
| Purpose | Observe execution | Modify/control execution |
| Can modify context | No | Yes |
| Can cancel execution | No | Yes (via throw/cancel) |
| Scoped execution | No (global) | Yes (scope-specific) |
| Async handlers | Yes | Yes |
| Best for | Logging, analytics, UI updates | Auth, validation, rate limiting |
When to Use Events
- Read-only observation
- Telemetry and metrics
- UI updates (progress, streaming)
- Debugging and logging
- Multiple independent listeners
When to Use Middleware
- Modify execution context
- Validate or transform data
- Authentication/authorization
- Rate limiting
- Caching
- Control flow (cancel, retry)
Event Handler Best Practices
-
Keep handlers fast
-
Handle errors
-
Avoid side effects in hot paths
-
Clean up listeners
-
Use typed events
Debugging with Events
Next Steps
- Agents - Learn about agent execution lifecycle
- Middleware - Compare middleware vs. events
- Reasoning - Understand reasoning step events
- Tools - Monitor tool execution with events