Skip to main content

Overview

The MemoryProvider interface defines the contract that all memory implementations in AgentLIB must satisfy. This enables agents to work with any memory backend, from simple in-process stores to distributed databases.

Interface Definition

Source: /packages/core/src/types/index.ts:117-127
export interface MemoryProvider {
  readonly type: string
  
  /** Load prior conversation history to inject before the current run */
  read(options: MemoryReadOptions): Promise<ModelMessage[]>
  
  /** Persist the messages produced by a completed run */
  write(messages: ModelMessage[], options: MemoryWriteOptions): Promise<void>
  
  /** Remove all stored memory (optional — not all providers support this) */
  clear?(sessionId?: string): Promise<void>
  
  /** Return raw entries for inspection/debugging */
  entries?(sessionId?: string): Promise<MemoryEntry[]>
}

Required Members

type

readonly type: string
Identifier for the memory provider type (e.g., 'buffer', 'sliding-window', 'redis').

read()

read(options: MemoryReadOptions): Promise<ModelMessage[]>
Load prior conversation history to inject before the current agent run. Parameters:
  • options - Read options (see MemoryReadOptions below)
Returns: Array of messages from the session.

write()

write(messages: ModelMessage[], options: MemoryWriteOptions): Promise<void>
Persist the messages produced by a completed agent run. Parameters:
  • messages - Array of messages to store
  • options - Write options (see MemoryWriteOptions below)

Optional Members

clear()

clear?(sessionId?: string): Promise<void>
Remove all stored memory. Not all providers support this. Parameters:
  • sessionId - If provided, clears only that session. Otherwise clears all.

entries()

entries?(sessionId?: string): Promise<MemoryEntry[]>
Return raw entries for inspection/debugging. Parameters:
  • sessionId - If provided, returns only that session’s entries
Returns: Array of MemoryEntry objects.

Supporting Types

MemoryReadOptions

Source: /packages/core/src/types/index.ts:93-102
interface MemoryReadOptions {
  /** Max number of messages to return (provider may trim older ones) */
  limit?: number | undefined
  
  /** Only return messages from this session */
  sessionId?: string | undefined
  
  /** Semantic query for vector-based providers */
  query?: string | undefined
  
  /** Filter by metadata tags */
  tags?: Record<string, string> | undefined
}
limit
number
Maximum number of messages to return. The provider may trim older ones to fit this limit.
sessionId
string
Only return messages from this session. Most providers default to 'default' if not provided.
query
string
Semantic query string for vector-based memory providers.
tags
Record<string, string>
Filter results by metadata tags.

MemoryWriteOptions

Source: /packages/core/src/types/index.ts:107-111
interface MemoryWriteOptions {
  sessionId?: string | undefined
  tags?: Record<string, string> | undefined
  agentName?: string | undefined
}
sessionId
string
Session identifier for these messages. Defaults to 'default' in most providers.
tags
Record<string, string>
Arbitrary key/value tags for filtering and organization.
agentName
string
Name of the agent that produced these messages.

MemoryEntry

Source: /packages/core/src/types/index.ts:71-76
interface MemoryEntry {
  id: string
  sessionId: string
  messages: ModelMessage[]
  metadata: MemoryMetadata
}
id
string
required
Unique identifier for this entry.
sessionId
string
required
Session this entry belongs to.
messages
ModelMessage[]
required
Array of messages in this entry.
metadata
MemoryMetadata
required
Metadata about this entry (timestamps, agent name, tags, etc.).

MemoryMetadata

Source: /packages/core/src/types/index.ts:78-88
interface MemoryMetadata {
  createdAt: Date
  accessedAt?: Date | undefined
  agentName?: string | undefined
  tags?: Record<string, string> | undefined
  tokenCount?: number | undefined
}
createdAt
Date
required
When this memory entry was created.
accessedAt
Date
When this memory was last accessed/read.
agentName
string
Name of the agent that created this memory.
tags
Record<string, string>
Arbitrary key/value tags for filtering.
tokenCount
number
Estimated token count for this entry.

Implementing a Custom Provider

Basic Implementation

import type { MemoryProvider, MemoryReadOptions, MemoryWriteOptions, ModelMessage } from '@agentlib/core'

export class CustomMemory implements MemoryProvider {
  readonly type = 'custom'
  private store = new Map<string, ModelMessage[]>()

  async read(options: MemoryReadOptions): Promise<ModelMessage[]> {
    const sessionId = options.sessionId ?? 'default'
    return this.store.get(sessionId) ?? []
  }

  async write(messages: ModelMessage[], options: MemoryWriteOptions): Promise<void> {
    const sessionId = options.sessionId ?? 'default'
    this.store.set(sessionId, messages)
  }

  async clear(sessionId?: string): Promise<void> {
    if (sessionId) {
      this.store.delete(sessionId)
    } else {
      this.store.clear()
    }
  }
}

With Full Metadata

import { randomUUID } from 'node:crypto'
import type { MemoryProvider, MemoryEntry, ModelMessage } from '@agentlib/core'

export class AdvancedMemory implements MemoryProvider {
  readonly type = 'advanced'
  private entries = new Map<string, MemoryEntry>()

  async read(options: MemoryReadOptions): Promise<ModelMessage[]> {
    const sessionId = options.sessionId ?? 'default'
    const entry = this.entries.get(sessionId)
    
    if (entry) {
      entry.metadata.accessedAt = new Date()
    }
    
    return entry?.messages ?? []
  }

  async write(messages: ModelMessage[], options: MemoryWriteOptions): Promise<void> {
    const sessionId = options.sessionId ?? 'default'
    const existing = this.entries.get(sessionId)
    
    const entry: MemoryEntry = {
      id: existing?.id ?? randomUUID(),
      sessionId,
      messages,
      metadata: {
        createdAt: existing?.metadata.createdAt ?? new Date(),
        accessedAt: new Date(),
        agentName: options.agentName,
        tags: options.tags,
      },
    }
    
    this.entries.set(sessionId, entry)
  }

  async clear(sessionId?: string): Promise<void> {
    if (sessionId) {
      this.entries.delete(sessionId)
    } else {
      this.entries.clear()
    }
  }

  async entries(sessionId?: string): Promise<MemoryEntry[]> {
    if (sessionId) {
      const entry = this.entries.get(sessionId)
      return entry ? [entry] : []
    }
    return [...this.entries.values()]
  }
}

External Storage Example

import type { MemoryProvider, ModelMessage } from '@agentlib/core'
import { DatabaseClient } from './database'

export class DatabaseMemory implements MemoryProvider {
  readonly type = 'database'
  private db: DatabaseClient

  constructor(connectionString: string) {
    this.db = new DatabaseClient(connectionString)
  }

  async read(options: MemoryReadOptions): Promise<ModelMessage[]> {
    const sessionId = options.sessionId ?? 'default'
    const rows = await this.db.query(
      'SELECT messages FROM memory WHERE session_id = $1',
      [sessionId]
    )
    return rows[0]?.messages ?? []
  }

  async write(messages: ModelMessage[], options: MemoryWriteOptions): Promise<void> {
    const sessionId = options.sessionId ?? 'default'
    await this.db.query(
      'INSERT INTO memory (session_id, messages, updated_at) VALUES ($1, $2, NOW()) ON CONFLICT (session_id) DO UPDATE SET messages = $2, updated_at = NOW()',
      [sessionId, JSON.stringify(messages)]
    )
  }

  async clear(sessionId?: string): Promise<void> {
    if (sessionId) {
      await this.db.query('DELETE FROM memory WHERE session_id = $1', [sessionId])
    } else {
      await this.db.query('DELETE FROM memory')
    }
  }
}

Built-in Implementations

AgentLIB provides several built-in memory providers:

See Also

Build docs developers (and LLMs) love