Skip to main content
Memory lifecycle hooks let your memory backend react when the agent compresses context, switches sessions, writes to memory, or delegates to a subagent.
The user chats normally; lifecycle hooks fire on compression, session changes, and delegation so memory stays in sync.

Quick Start

1

Simplest

Override just one hook to get started:
2

All Four Hooks

Implement all lifecycle hooks for full control:

How It Works


The Four Hooks

on_pre_compress

Called before context compression discards messages.
When does this fire? When context utilization exceeds compact_threshold and the agent needs to discard older messages. Example:

on_session_switch

Called when the active session ID changes.
When does this fire? Currently defined but not yet called - reserved for future session rotation features. Example:

on_memory_write

Called after successful memory storage operations.
When does this fire? After Agent.store_memory() successfully writes to built-in memory. Example:

on_delegation

Called after a subagent completes a delegated task.
When does this fire? After subagent execution completes in handoff operations. Example:

Sync vs Async Selection

The agent automatically detects the execution context. If you’re in an async context and provide both sync and async versions, the async version runs as a fire-and-forget task for better performance.

The New Action Parameter

Agent.store_memory() now accepts an action parameter:
The memory provider must support the requested action or a ValueError is raised.

Configuration Options

All four hooks are optional with no-op defaults. The protocol uses runtime_checkable so your memory class only needs to implement the hooks you need.

Common Patterns

Mirror writes to external vector store:
Persist subagent results in knowledge graph:
Summarize discarded turns before compression:

Best Practices

Hooks run on the agent thread and can block execution. Keep operations lightweight or delegate to background workers for heavy processing like vector embeddings or API calls.
Hook failures are caught and logged at warning level. They should never break the agent loop. Always wrap your hook logic in try-catch and log errors appropriately.
If your memory provider does network I/O (database calls, API requests), implement the aon_* async variants. The agent will automatically schedule them as fire-and-forget tasks in async contexts.
All hooks are optional. Only implement the lifecycle events that matter for your use case. Empty implementations have zero performance impact.

Memory

Core memory concepts and storage types

Advanced Memory

Custom backends and advanced patterns

Context Compression

How context compression triggers hooks

Handoffs

Agent delegation and subagent patterns