Agentic Sessions and Protocols ⏱ 11 min read 📁 examples/09_memory_and_todos.mjs

Lesson 12: Persistent Memory and Knowledge Distillation

Build memory-augmented agents with local file and composite memory providers, asynchronous background distillation, eager preload, recency fallback, and fact escaping.

1. Why This Feature Exists

Stateless models forget context between sessions. Merci SDK provides a secure, decoupled memory architecture that distills key user preferences and system state into persistent storage while safeguarding against prompt injection.

2. Key Symbols and Exports

LocalFileMemoryProvider & CompositeMemoryProvider
Storage adapters for persistent user/session episodic facts.
Background Distillation
Extracts long-term facts in the background without blocking the user response loop.
Eager Preload vs Lazy Lookup
Preloads critical facts into session context while lazily retrieving niche domain knowledge.
Untrusted Fact Escaping
Sanitizes retrieved facts to prevent prompt injection attacks via stored memory.
Distill Error Channel
Captures and surfaces background extraction failures without crashing the primary session.

3. Implementation Walkthrough

import {
    ProviderType,
    resolveProvider,
    initializeClient,
    loadCredentials,
    getDefaultModel,
    LocalFileMemoryProvider
} from 'merci-sdk';

const PROVIDER = resolveProvider();
const { client } = await initializeClient({ provider: PROVIDER, options: loadCredentials({ provider: PROVIDER }) });

const memory = new LocalFileMemoryProvider({
    filePath: './user_memory.json',
    preload: true,
    recencyFallback: true
});

const session = client.session(getDefaultModel({ provider: PROVIDER }))
    .withMemory(memory);

// Turn 1: State a preference
await session.run('Remember: I prefer TypeScript with strict typing and no any.');

// Turn 2: Retrieve in a new session
const newSession = client.session(getDefaultModel({ provider: PROVIDER }))
    .withMemory(memory);

const answer = await newSession.run('Generate a User profile model.');
console.log(answer); // Will generate strict TypeScript automatically

4. Wire and Telemetry Mechanics

The MemoryComponent injects stored facts into the prompt wrapped in fenced security tags. After each turn, a background distillation prompt runs asynchronously to extract new facts and updates the local JSON file.

5. Run the Example

Execute the runnable example directly from the repository root:

node examples/09_memory_and_todos.mjs

Read the full example: examples/09_memory_and_todos.mjs →

Expected Output: Demonstrates memory injection, executes multi-turn conversations, runs background distillation, and demonstrates cross-session fact recall.