@elizaos/plugin-memory 1.0.5 → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/README.md +339 -207
  2. package/dist/browser/index.browser.js +348 -151
  3. package/dist/browser/index.browser.js.map +23 -13
  4. package/dist/cjs/index.node.cjs +2200 -1047
  5. package/dist/cjs/index.node.js.map +23 -13
  6. package/dist/evaluators/consolidation.d.ts +19 -0
  7. package/dist/evaluators/summarization.d.ts +5 -24
  8. package/dist/index.d.ts +152 -30
  9. package/dist/node/index.node.js +2242 -1084
  10. package/dist/node/index.node.js.map +23 -13
  11. package/dist/prompts/consolidation.d.ts +35 -0
  12. package/dist/prompts/summarization.d.ts +25 -0
  13. package/dist/providers/action-results.d.ts +2 -0
  14. package/dist/providers/long-term-memory.d.ts +18 -11
  15. package/dist/providers/recent-conversation-summary.d.ts +2 -0
  16. package/dist/repositories/conversation-summary.d.ts +33 -0
  17. package/dist/repositories/index.d.ts +17 -0
  18. package/dist/repositories/long-term-memory.d.ts +53 -0
  19. package/dist/schemas/conversation-summaries.d.ts +494 -0
  20. package/dist/schemas/index.d.ts +16 -6
  21. package/dist/schemas/long-term-memories.d.ts +308 -70
  22. package/dist/services/memory-service.d.ts +95 -51
  23. package/dist/types/index.d.ts +299 -55
  24. package/dist/utils/db-mapping.d.ts +20 -0
  25. package/dist/utils/decay-scoring.d.ts +41 -0
  26. package/dist/utils/embedding.d.ts +21 -0
  27. package/dist/utils/formatting.d.ts +17 -0
  28. package/dist/utils/index.d.ts +17 -0
  29. package/dist/utils/search-merging.d.ts +18 -0
  30. package/dist/utils/token-counter.d.ts +53 -0
  31. package/package.json +83 -1
  32. package/dist/actions/remember.d.ts +0 -11
  33. package/dist/evaluators/long-term-extraction.d.ts +0 -8
  34. package/dist/providers/short-term-memory.d.ts +0 -19
  35. package/dist/schemas/memory-access-logs.d.ts +0 -154
  36. package/dist/schemas/session-summaries.d.ts +0 -283
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Memory Consolidation Prompts
3
+ *
4
+ * Research: Section 2.2.2 "Proposed Extraction Prompt Structure"
5
+ *
6
+ * This module contains all prompts used for memory consolidation.
7
+ * Prompts are structured to use Chain-of-Thought (CoT) reasoning to
8
+ * distinguish transient events from persistent facts.
9
+ *
10
+ * Key Principles:
11
+ * - Clear mission statement
12
+ * - Explicit definitions (transient vs persistent)
13
+ * - Strict extraction rules
14
+ * - Structured XML output (more reliable than JSON for LLMs)
15
+ * - CoT examples for few-shot learning
16
+ */
17
+ /**
18
+ * System prompt for the consolidation engine
19
+ *
20
+ * This replaces runtime.character.system temporarily during consolidation
21
+ */
22
+ export declare const CONSOLIDATION_SYSTEM_PROMPT = "You are the \"Cortex\" \u2014 an advanced Memory Extraction Engine.\nYour function is to parse conversation logs and extract persistent facts into a structured database format.\n\n# CORE DIRECTIVE: \"Subject-First\" Extraction\nYou must rephrase memories to focus on the *topic*, not the user. This optimizes vector retrieval.\n- BAD: \"User likes to trade Bitcoin.\" (Too generic)\n- GOOD: \"Bitcoin (BTC) is a preferred trading asset.\" (Topic-focused)\n\n# COMPRESSION RULES (CRITICAL)\n1. **Aggressive Filtering**: Most user chatter is noise. If it won't be relevant in 30 days, DO NOT extract it.\n2. **Merge & Dedupe**: Do not create three separate memories for one topic. Combine them.\n - *Input:* \"I like Red. I also like Blue. And Green.\"\n - *Output:* \"Red, Blue, and Green are the preferred colors.\"\n3. **Conflict Resolution**: If a new fact contradicts an old one, mark 'isContradiction' as true.\n\n# OUTPUT FORMAT\nPhase 1: [ANALYSIS]\n- List extracted points.\n- MARK items as [TRANSIENT] (Ignore) or [MERGE] (Combine).\n- Refine the final wording.\n\nPhase 2: [MEMORIES]\nFormat: `MEM|TYPE|CATEGORY|CONFIDENCE|IS_CONTRADICTION|CONTENT`\n\nTypes: EPISODIC, SEMANTIC, PROCEDURAL\nCategories: bio, health, finance, preferences, relationships, skills, work\n";
23
+ export declare function buildExtractionPrompt(conversationLog: string): string;
24
+ /**
25
+ * Contradiction detection prompt
26
+ *
27
+ * Research: Section 4.3.1 "Detection Logic"
28
+ *
29
+ * Used to determine if a new memory contradicts existing memories
30
+ */
31
+ export declare function buildContradictionPrompt(newMemoryContent: string, existingMemories: Array<{
32
+ content: string;
33
+ confidence: number;
34
+ createdAt: string;
35
+ }>): string;
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Hierarchical Summarization Prompts
3
+ *
4
+ * Research: Section 5.1.2 "Hierarchical Episodic Summarization"
5
+ *
6
+ * These prompts implement recursive, multi-level summarization:
7
+ * - Level 1: Summarize raw messages into narrative paragraphs
8
+ * - Level 2+: Summarize lower-level summaries into higher-level abstractions
9
+ *
10
+ * Goal: Achieve 10x token compression while preserving conversational narrative
11
+ */
12
+ /**
13
+ * System prompt for Level 1 summarization (messages → summary)
14
+ */
15
+ export declare const SUMMARIZATION_SYSTEM_PROMPT = "You are \"Chronos\", a master summarizer.\nYour function is to condense conversation logs into concise, subject-first narrative summaries.\n\n# CORE DIRECTIVE: \"Subject-First\" Summarization\nYou must rephrase the narrative to focus on the *topic*, not the user. This optimizes vector retrieval.\n- BAD: \"User asked about Python.\" (Too generic)\n- GOOD: \"Python programming inquiries were addressed.\" (Topic-focused)\n\n# COMPRESSION RULES\n1. **Be Concise**: Target 2-4 sentences. Maximum 100 words.\n2. **Be Factual**: No interpretation, no speculation. Only what actually happened.\n3. **Be Narrative**: Write as a story, not a bullet list.\n4. **Preserve Key Facts**: If the user revealed important information (preferences, identity, needs), include it.\n5. **Exclude Trivia**: Skip greetings, acknowledgments, and filler conversation.\n\n# OUTPUT FORMAT\nPhase 1: [ANALYSIS]\n- Identify key topics.\n- Draft the summary.\n- Refine wording to be subject-first.\n\nPhase 2: [RESULT]\nFormat: `SUMM|TAGS|CONTENT`\n- TAGS: Comma-separated list of key topics (lowercase)\n- CONTENT: The narrative summary text (must be a single line, no newlines)\n";
16
+ export declare function buildLevel1SummaryPrompt(formattedMessages: string, previousSummary?: string): string;
17
+ /**
18
+ * System prompt for Level 2+ summarization (summaries → meta-summary)
19
+ */
20
+ export declare const HIGHER_LEVEL_SUMMARIZATION_SYSTEM_PROMPT = "You are \"Chronos\", a Meta-Summarization Agent.\nYour task is to compress multiple conversation summaries into a single, higher-level summary.\n\n# MISSION\nTransform a list of conversation summaries into one concise meta-summary that captures:\n1. **Overarching themes** across the summaries\n2. **Key events or milestones** (e.g., \"User onboarded\", \"Project completed\")\n3. **Evolving context** (e.g., \"User's preferences shifted from X to Y\")\n\n# RULES\n- **Subject-First**: Focus on the topic, not the user.\n- **Abstract Higher**: Don't repeat specifics from each summary. Find the pattern.\n- **Chronological Flow**: Maintain temporal order if it matters.\n- **Preserve Critical Facts**: If summaries mention important identity or preferences, keep them.\n\n# OUTPUT FORMAT\nPhase 1: [ANALYSIS]\n- Identify themes and milestones.\n- Combine related points.\n- Refine to subject-first.\n\nPhase 2: [RESULT]\nFormat: `SUMM|TAGS|CONTENT`\n- TAGS: Comma-separated list of key topics (lowercase)\n- CONTENT: The meta-summary text (must be a single line, no newlines)\n";
21
+ export declare function buildHigherLevelSummaryPrompt(formattedSummaries: string): string;
22
+ /**
23
+ * Estimate token count from text (used as fallback)
24
+ */
25
+ export declare function estimateTokensInSummary(text: string): number;
@@ -0,0 +1,2 @@
1
+ import { type Provider } from '@elizaos/core';
2
+ export declare const actionResultsProvider: Provider;
@@ -1,17 +1,24 @@
1
1
  import { type Provider } from '@elizaos/core';
2
2
  /**
3
- * Long-term Memory Provider
3
+ * Long-Term Memory Provider (Facts Only)
4
4
  *
5
- * Provides persistent facts about the user that have been learned across
6
- * all conversations. This includes:
7
- * - User identity and roles
8
- * - Domain expertise
9
- * - Preferences
10
- * - Goals and projects
11
- * - Custom definitions
12
- * - Behavioral patterns
5
+ * Research: Section 3 "RAG Strategy" - Semantic & Procedural Knowledge
13
6
  *
14
- * This provider enriches the context with relevant long-term information
15
- * to make the agent's responses more personalized and contextually aware.
7
+ * This provider focuses ONLY on persistent knowledge about the user:
8
+ * - **Semantic Facts**: Timeless information (preferences, identity, skills)
9
+ * - **Procedural Patterns**: How the user does things, tool preferences
10
+ *
11
+ * DOES NOT INCLUDE:
12
+ * - Recent messages (handled by RECENT_CONTEXT)
13
+ * - Conversation summaries (handled by RECENT_CONTEXT)
14
+ * - Current message (handled by RECENT_CONTEXT)
15
+ *
16
+ * Design Philosophy:
17
+ * - Pure knowledge retrieval (no conversational context)
18
+ * - Used in FINAL response phase (after planning)
19
+ * - Provides "who is this user" context
20
+ *
21
+ * Template Variables Provided:
22
+ * - `longTermMemories`: Formatted semantic/procedural facts
16
23
  */
17
24
  export declare const longTermMemoryProvider: Provider;
@@ -0,0 +1,2 @@
1
+ import { type Provider } from '@elizaos/core';
2
+ export declare const recentContextProvider: Provider;
@@ -0,0 +1,33 @@
1
+ import type { IAgentRuntime, UUID } from '@elizaos/core';
2
+ import { type ConversationSummary, type EmbeddingDimensionColumn } from '../types/index';
3
+ /**
4
+ * Conversation Summary Repository
5
+ *
6
+ * Research: Section 5.1.2 "Hierarchical Conversation Summarization"
7
+ * Handles database operations for conversation summaries
8
+ */
9
+ export declare class ConversationSummaryRepository {
10
+ private runtime;
11
+ private embeddingDimension?;
12
+ constructor(runtime: IAgentRuntime, embeddingDimension?: EmbeddingDimensionColumn);
13
+ /**
14
+ * Get database instance with health check
15
+ */
16
+ private getDb;
17
+ /**
18
+ * Insert a new summary
19
+ */
20
+ insert(summary: Omit<ConversationSummary, 'id' | 'createdAt' | 'lastAccessedAt' | 'accessCount'>, embedding?: number[]): Promise<ConversationSummary>;
21
+ /**
22
+ * Find summaries by level
23
+ */
24
+ findByLevel(roomId: UUID, level: number): Promise<ConversationSummary[]>;
25
+ /**
26
+ * Vector search for summaries
27
+ */
28
+ vectorSearch(entityId: UUID, roomId: UUID, queryEmbedding: number[], limit?: number): Promise<ConversationSummary[]>;
29
+ /**
30
+ * Update access metadata for summaries
31
+ */
32
+ updateAccessMetadata(summaryIds: UUID[]): Promise<void>;
33
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Repository Layer for Memory Plugin
3
+ *
4
+ * This module provides data access repositories that encapsulate
5
+ * all database operations for the memory system.
6
+ *
7
+ * Repositories handle:
8
+ * - Database connection management
9
+ * - CRUD operations
10
+ * - Query building
11
+ * - Transaction management
12
+ * - Health checks for long-running operations
13
+ *
14
+ * Research: Clean Architecture - Separation of data access from business logic
15
+ */
16
+ export * from './long-term-memory';
17
+ export * from './conversation-summary';
@@ -0,0 +1,53 @@
1
+ import type { IAgentRuntime, UUID } from '@elizaos/core';
2
+ import { type LongTermMemory, type LongTermMemoryRetrievalResult, type LongTermMemorySearchParams, type EmbeddingDimensionColumn, MemoryType } from '../types/index';
3
+ /**
4
+ * Long-Term Memory Repository
5
+ *
6
+ * Handles all database operations for long-term memories
7
+ * Provides clean data access layer separated from business logic
8
+ */
9
+ export declare class LongTermMemoryRepository {
10
+ private runtime;
11
+ private embeddingDimension?;
12
+ constructor(runtime: IAgentRuntime, embeddingDimension?: EmbeddingDimensionColumn);
13
+ /**
14
+ * Get database instance with health check
15
+ */
16
+ private getDb;
17
+ /**
18
+ * Insert a new memory into database
19
+ */
20
+ insert(memory: Omit<LongTermMemory, 'id' | 'createdAt' | 'lastAccessedAt' | 'accessCount' | 'isActive' | 'embedding'>, embedding?: number[]): Promise<LongTermMemory>;
21
+ /**
22
+ * Find memory by ID
23
+ */
24
+ findById(id: UUID): Promise<LongTermMemory | null>;
25
+ /**
26
+ * Update existing memory
27
+ */
28
+ update(id: UUID, updates: Partial<LongTermMemory>, newEmbedding?: number[]): Promise<void>;
29
+ /**
30
+ * Delete memory (hard delete)
31
+ */
32
+ delete(id: UUID): Promise<void>;
33
+ /**
34
+ * Find memories by entity with optional filters
35
+ */
36
+ findByEntity(entityId: UUID, type?: MemoryType, limit?: number, includeInactive?: boolean): Promise<LongTermMemory[]>;
37
+ /**
38
+ * Vector search for memories
39
+ */
40
+ vectorSearch(params: LongTermMemorySearchParams, queryEmbedding: number[], similarityThreshold?: number): Promise<LongTermMemoryRetrievalResult[]>;
41
+ /**
42
+ * Fetch all active memories for BM25 indexing
43
+ */
44
+ fetchAllActive(): Promise<Array<{
45
+ id: UUID;
46
+ content: string;
47
+ embeddingContext: string;
48
+ }>>;
49
+ /**
50
+ * Update access metadata (lastAccessedAt and accessCount)
51
+ */
52
+ updateAccessMetadata(memoryIds: UUID[]): Promise<void>;
53
+ }