Overview
SlidingWindowMemory is a token-aware in-process memory provider. Instead of counting raw messages, it tracks conversation turns (user+assistant pairs) and enforces a token budget when retrieving history.
Best for: production systems that need precise context window management.
Constructor
Configuration
Maximum token budget for the retrieved history window.
Maximum number of conversation turns (user+assistant pairs) to keep.
Older turns are evicted to make room for newer ones.
Methods
read()
Retrieve conversation history with token budget applied.options.sessionId- Session identifier (defaults to'default')options.limit- Maximum number of messages to returnoptions.query- Semantic query (not used by SlidingWindowMemory)options.tags- Filter by metadata tags (not used by SlidingWindowMemory)
maxTokens.
Behavior:
- Flattens turns into messages
- Applies token budget using
trimToTokenBudget() - Updates access timestamp
write()
Persist messages, organized into conversation turns.messages- Array of messages to storeoptions.sessionId- Session identifier (defaults to'default')options.agentName- Name of the agent storing the messagesoptions.tags- Metadata tags for filtering
- Filters out system messages
- Groups messages into logical turns
- Merges with existing turns and keeps the most recent
maxTurns - Stores token count in metadata
clear()
Remove stored memory.sessionId- If provided, clears only that session. Otherwise clears all sessions.
entries()
Retrieve raw memory entries for inspection/debugging.sessionId- If provided, returns only that session’s entry
MemoryEntry objects with metadata including token counts.
stats()
Get statistics for a specific session.sessionId- Session to inspect
null if session not found.
Usage Examples
Basic Usage
Monitoring Token Usage
Production Configuration
Inspecting Entries
Turn Grouping
SlidingWindowMemory groups messages into logical conversation turns. A turn consists of:- User message
- Assistant message(s)
- Any tool call/response sequences
Type Reference
Source:/packages/memory/src/sliding-window.ts:11-24