@elizaos/plugin-memory 1.1.2 → 2.0.0-alpha

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 (43) hide show
  1. package/dist/evaluators/index.d.ts +3 -0
  2. package/dist/evaluators/index.d.ts.map +1 -0
  3. package/dist/evaluators/long-term-extraction.d.ts +1 -6
  4. package/dist/evaluators/long-term-extraction.d.ts.map +1 -0
  5. package/dist/evaluators/summarization.d.ts +1 -28
  6. package/dist/evaluators/summarization.d.ts.map +1 -0
  7. package/dist/generated/prompts/typescript/prompts.d.ts +16 -0
  8. package/dist/generated/prompts/typescript/prompts.d.ts.map +1 -0
  9. package/dist/index.d.ts +7 -38
  10. package/dist/index.d.ts.map +1 -0
  11. package/dist/{node/index.node.js → index.js} +931 -980
  12. package/dist/index.js.map +20 -0
  13. package/dist/providers/context-summary.d.ts +2 -11
  14. package/dist/providers/context-summary.d.ts.map +1 -0
  15. package/dist/providers/index.d.ts +3 -0
  16. package/dist/providers/index.d.ts.map +1 -0
  17. package/dist/providers/long-term-memory.d.ts +2 -16
  18. package/dist/providers/long-term-memory.d.ts.map +1 -0
  19. package/dist/schemas/index.d.ts +4 -9
  20. package/dist/schemas/index.d.ts.map +1 -0
  21. package/dist/schemas/long-term-memories.d.ts +1 -4
  22. package/dist/schemas/long-term-memories.d.ts.map +1 -0
  23. package/dist/schemas/memory-access-logs.d.ts +20 -58
  24. package/dist/schemas/memory-access-logs.d.ts.map +1 -0
  25. package/dist/schemas/session-summaries.d.ts +1 -4
  26. package/dist/schemas/session-summaries.d.ts.map +1 -0
  27. package/dist/services/memory-service.d.ts +7 -75
  28. package/dist/services/memory-service.d.ts.map +1 -0
  29. package/dist/types/index.d.ts +5 -26
  30. package/dist/types/index.d.ts.map +1 -0
  31. package/package.json +45 -48
  32. package/README.md +0 -335
  33. package/dist/actions/remember.d.ts +0 -11
  34. package/dist/browser/index.browser.js +0 -205
  35. package/dist/browser/index.browser.js.map +0 -19
  36. package/dist/browser/index.d.ts +0 -2
  37. package/dist/cjs/index.d.ts +0 -2
  38. package/dist/cjs/index.node.cjs +0 -1168
  39. package/dist/cjs/index.node.js.map +0 -19
  40. package/dist/index.browser.d.ts +0 -2
  41. package/dist/index.node.d.ts +0 -2
  42. package/dist/node/index.d.ts +0 -2
  43. package/dist/node/index.node.js.map +0 -19
@@ -1,205 +0,0 @@
1
- var _A=Object.defineProperty;var $A=(B,Q)=>{for(var J in Q)_A(B,J,{get:Q[J],enumerable:!0,configurable:!0,set:(K)=>Q[J]=()=>K})};import{Service as OA,logger as H}from"@elizaos/core";import{eq as X,and as R,desc as f,sql as AA,cosineDistance as RA,gte as kA}from"drizzle-orm";var d={};$A(d,{sessionSummaries:()=>j,memoryAccessLogs:()=>e,longTermMemories:()=>$});import{sql as s}from"drizzle-orm";import{pgTable as UA,text as p,integer as VA,jsonb as GA,real as m,index as C,varchar as w,timestamp as y}from"drizzle-orm/pg-core";var $=UA("long_term_memories",{id:w("id",{length:36}).primaryKey(),agentId:w("agent_id",{length:36}).notNull(),entityId:w("entity_id",{length:36}).notNull(),category:p("category").notNull(),content:p("content").notNull(),metadata:GA("metadata"),embedding:m("embedding").array(),confidence:m("confidence").default(1),source:p("source"),createdAt:y("created_at").default(s`now()`).notNull(),updatedAt:y("updated_at").default(s`now()`).notNull(),lastAccessedAt:y("last_accessed_at"),accessCount:VA("access_count").default(0)},(B)=>({agentEntityIdx:C("long_term_memories_agent_entity_idx").on(B.agentId,B.entityId),categoryIdx:C("long_term_memories_category_idx").on(B.category),confidenceIdx:C("long_term_memories_confidence_idx").on(B.confidence),createdAtIdx:C("long_term_memories_created_at_idx").on(B.createdAt)}));import{sql as o}from"drizzle-orm";import{pgTable as XA,text as jA,integer as t,jsonb as r,real as HA,index as c,varchar as T,timestamp as v}from"drizzle-orm/pg-core";var j=XA("session_summaries",{id:T("id",{length:36}).primaryKey(),agentId:T("agent_id",{length:36}).notNull(),roomId:T("room_id",{length:36}).notNull(),entityId:T("entity_id",{length:36}),summary:jA("summary").notNull(),messageCount:t("message_count").notNull(),lastMessageOffset:t("last_message_offset").notNull().default(0),startTime:v("start_time").notNull(),endTime:v("end_time").notNull(),topics:r("topics"),metadata:r("metadata"),embedding:HA("embedding").array(),createdAt:v("created_at").default(o`now()`).notNull(),updatedAt:v("updated_at").default(o`now()`).notNull()},(B)=>({agentRoomIdx:c("session_summaries_agent_room_idx").on(B.agentId,B.roomId),entityIdx:c("session_summaries_entity_idx").on(B.entityId),startTimeIdx:c("session_summaries_start_time_idx").on(B.startTime)}));import{sql as WA}from"drizzle-orm";import{pgTable as FA,text as NA,integer as EA,real as LA,index as l,varchar as h,timestamp as PA}from"drizzle-orm/pg-core";var e=FA("memory_access_logs",{id:h("id",{length:36}).primaryKey(),agentId:h("agent_id",{length:36}).notNull(),memoryId:h("memory_id",{length:36}).notNull(),memoryType:NA("memory_type").notNull(),accessedAt:PA("accessed_at").default(WA`now()`).notNull(),roomId:h("room_id",{length:36}),relevanceScore:LA("relevance_score"),wasUseful:EA("was_useful")},(B)=>({memoryIdx:l("memory_access_logs_memory_idx").on(B.memoryId),agentIdx:l("memory_access_logs_agent_idx").on(B.agentId),accessedAtIdx:l("memory_access_logs_accessed_at_idx").on(B.accessedAt)}));class D extends OA{static serviceType="memory";sessionMessageCounts;memoryConfig;lastExtractionCheckpoints;capabilityDescription="Advanced memory management with short-term summarization and long-term persistent facts";constructor(B){super(B);this.sessionMessageCounts=new Map,this.lastExtractionCheckpoints=new Map,this.memoryConfig={shortTermSummarizationThreshold:16,shortTermRetainRecent:6,shortTermSummarizationInterval:10,longTermExtractionEnabled:!0,longTermVectorSearchEnabled:!1,longTermConfidenceThreshold:0.85,longTermExtractionThreshold:30,longTermExtractionInterval:10,summaryModelType:"TEXT_LARGE",summaryMaxTokens:2500,summaryMaxNewMessages:20}}static async start(B){let Q=new D(B);return await Q.initialize(B),Q}async stop(){H.info("MemoryService stopped")}async initialize(B){this.runtime=B;let Q=B.getSetting("MEMORY_SUMMARIZATION_THRESHOLD");if(Q)this.memoryConfig.shortTermSummarizationThreshold=parseInt(Q,10);let J=B.getSetting("MEMORY_RETAIN_RECENT");if(J)this.memoryConfig.shortTermRetainRecent=parseInt(J,10);let K=B.getSetting("MEMORY_SUMMARIZATION_INTERVAL");if(K)this.memoryConfig.shortTermSummarizationInterval=parseInt(K,10);let A=B.getSetting("MEMORY_MAX_NEW_MESSAGES");if(A)this.memoryConfig.summaryMaxNewMessages=parseInt(A,10);let Y=B.getSetting("MEMORY_LONG_TERM_ENABLED");if(Y==="false")this.memoryConfig.longTermExtractionEnabled=!1;else if(Y==="true")this.memoryConfig.longTermExtractionEnabled=!0;let Z=B.getSetting("MEMORY_CONFIDENCE_THRESHOLD");if(Z)this.memoryConfig.longTermConfidenceThreshold=parseFloat(Z);let U=B.getSetting("MEMORY_EXTRACTION_THRESHOLD");if(U)this.memoryConfig.longTermExtractionThreshold=parseInt(U,10);let V=B.getSetting("MEMORY_EXTRACTION_INTERVAL");if(V)this.memoryConfig.longTermExtractionInterval=parseInt(V,10);H.debug({summarizationThreshold:this.memoryConfig.shortTermSummarizationThreshold,summarizationInterval:this.memoryConfig.shortTermSummarizationInterval,maxNewMessages:this.memoryConfig.summaryMaxNewMessages,retainRecent:this.memoryConfig.shortTermRetainRecent,longTermEnabled:this.memoryConfig.longTermExtractionEnabled,extractionThreshold:this.memoryConfig.longTermExtractionThreshold,extractionInterval:this.memoryConfig.longTermExtractionInterval,confidenceThreshold:this.memoryConfig.longTermConfidenceThreshold},"MemoryService initialized")}getDb(){let B=this.runtime.db;if(!B)throw Error("Database not available");return B}getConfig(){return{...this.memoryConfig}}updateConfig(B){this.memoryConfig={...this.memoryConfig,...B}}incrementMessageCount(B){let J=(this.sessionMessageCounts.get(B)||0)+1;return this.sessionMessageCounts.set(B,J),J}resetMessageCount(B){this.sessionMessageCounts.set(B,0)}async shouldSummarize(B){return await this.runtime.countMemories(B,!1,"messages")>=this.memoryConfig.shortTermSummarizationThreshold}getExtractionKey(B,Q){return`memory:extraction:${B}:${Q}`}async getLastExtractionCheckpoint(B,Q){let J=this.getExtractionKey(B,Q),K=this.lastExtractionCheckpoints.get(J);if(K!==void 0)return K;try{let Y=await this.runtime.getCache(J)??0;return this.lastExtractionCheckpoints.set(J,Y),Y}catch(A){return H.warn({error:A},"Failed to get extraction checkpoint from cache"),0}}async setLastExtractionCheckpoint(B,Q,J){let K=this.getExtractionKey(B,Q);this.lastExtractionCheckpoints.set(K,J);try{await this.runtime.setCache(K,J),H.debug(`Set extraction checkpoint for ${B} in room ${Q} at message count ${J}`)}catch(A){H.error({error:A},"Failed to persist extraction checkpoint to cache")}}async shouldRunExtraction(B,Q,J){let K=this.memoryConfig.longTermExtractionThreshold,A=this.memoryConfig.longTermExtractionInterval;if(J<K)return!1;let Y=await this.getLastExtractionCheckpoint(B,Q),Z=Math.floor(J/A)*A,U=J>=K&&Z>Y;return H.debug({entityId:B,roomId:Q,currentMessageCount:J,threshold:K,interval:A,lastCheckpoint:Y,currentCheckpoint:Z,shouldRun:U},"Extraction check"),U}async storeLongTermMemory(B){let Q=this.getDb(),J=crypto.randomUUID(),K=new Date,A={id:J,createdAt:K,updatedAt:K,accessCount:0,...B};try{await Q.insert($).values({id:A.id,agentId:A.agentId,entityId:A.entityId,category:A.category,content:A.content,metadata:A.metadata||{},embedding:A.embedding,confidence:A.confidence,source:A.source,accessCount:A.accessCount,createdAt:K,updatedAt:K,lastAccessedAt:A.lastAccessedAt})}catch(Y){throw H.error({error:Y},"Failed to store long-term memory"),Y}return H.info(`Stored long-term memory: ${A.category} for entity ${A.entityId}`),A}async getLongTermMemories(B,Q,J=10){let K=this.getDb(),A=[X($.agentId,this.runtime.agentId),X($.entityId,B)];if(Q)A.push(X($.category,Q));return(await K.select().from($).where(R(...A)).orderBy(f($.confidence),f($.updatedAt)).limit(J)).map((Z)=>({id:Z.id,agentId:Z.agentId,entityId:Z.entityId,category:Z.category,content:Z.content,metadata:Z.metadata,embedding:Z.embedding,confidence:Z.confidence,source:Z.source,createdAt:Z.createdAt,updatedAt:Z.updatedAt,lastAccessedAt:Z.lastAccessedAt,accessCount:Z.accessCount}))}async updateLongTermMemory(B,Q,J){let K=this.getDb(),A={updatedAt:new Date};if(J.content!==void 0)A.content=J.content;if(J.metadata!==void 0)A.metadata=J.metadata;if(J.confidence!==void 0)A.confidence=J.confidence;if(J.embedding!==void 0)A.embedding=J.embedding;if(J.lastAccessedAt!==void 0)A.lastAccessedAt=J.lastAccessedAt;if(J.accessCount!==void 0)A.accessCount=J.accessCount;await K.update($).set(A).where(R(X($.id,B),X($.agentId,this.runtime.agentId),X($.entityId,Q))),H.info(`Updated long-term memory: ${B} for entity ${Q}`)}async deleteLongTermMemory(B,Q){await this.getDb().delete($).where(R(X($.id,B),X($.agentId,this.runtime.agentId),X($.entityId,Q))),H.info(`Deleted long-term memory: ${B} for entity ${Q}`)}async getCurrentSessionSummary(B){let J=await this.getDb().select().from(j).where(R(X(j.agentId,this.runtime.agentId),X(j.roomId,B))).orderBy(f(j.updatedAt)).limit(1);if(J.length===0)return null;let K=J[0];return{id:K.id,agentId:K.agentId,roomId:K.roomId,entityId:K.entityId,summary:K.summary,messageCount:K.messageCount,lastMessageOffset:K.lastMessageOffset,startTime:K.startTime,endTime:K.endTime,topics:K.topics||[],metadata:K.metadata,embedding:K.embedding,createdAt:K.createdAt,updatedAt:K.updatedAt}}async storeSessionSummary(B){let Q=this.getDb(),J=crypto.randomUUID(),K=new Date,A={id:J,createdAt:K,updatedAt:K,...B};return await Q.insert(j).values({id:A.id,agentId:A.agentId,roomId:A.roomId,entityId:A.entityId||null,summary:A.summary,messageCount:A.messageCount,lastMessageOffset:A.lastMessageOffset,startTime:A.startTime,endTime:A.endTime,topics:A.topics||[],metadata:A.metadata||{},embedding:A.embedding,createdAt:K,updatedAt:K}),H.info(`Stored session summary for room ${A.roomId}`),A}async updateSessionSummary(B,Q,J){let K=this.getDb(),A={updatedAt:new Date};if(J.summary!==void 0)A.summary=J.summary;if(J.messageCount!==void 0)A.messageCount=J.messageCount;if(J.lastMessageOffset!==void 0)A.lastMessageOffset=J.lastMessageOffset;if(J.endTime!==void 0)A.endTime=J.endTime;if(J.topics!==void 0)A.topics=J.topics;if(J.metadata!==void 0)A.metadata=J.metadata;if(J.embedding!==void 0)A.embedding=J.embedding;await K.update(j).set(A).where(R(X(j.id,B),X(j.agentId,this.runtime.agentId),X(j.roomId,Q))),H.info(`Updated session summary: ${B} for room ${Q}`)}async getSessionSummaries(B,Q=5){return(await this.getDb().select().from(j).where(R(X(j.agentId,this.runtime.agentId),X(j.roomId,B))).orderBy(f(j.updatedAt)).limit(Q)).map((A)=>({id:A.id,agentId:A.agentId,roomId:A.roomId,entityId:A.entityId,summary:A.summary,messageCount:A.messageCount,lastMessageOffset:A.lastMessageOffset,startTime:A.startTime,endTime:A.endTime,topics:A.topics||[],metadata:A.metadata,embedding:A.embedding,createdAt:A.createdAt,updatedAt:A.updatedAt}))}async searchLongTermMemories(B,Q,J=5,K=0.7){if(!this.memoryConfig.longTermVectorSearchEnabled)return H.warn("Vector search is not enabled, falling back to recent memories"),this.getLongTermMemories(B,void 0,J);let A=this.getDb();try{let Y=Q.map((_)=>Number.isFinite(_)?Number(_.toFixed(6)):0),Z=AA`1 - (${RA($.embedding,Y)})`,U=[X($.agentId,this.runtime.agentId),X($.entityId,B),AA`${$.embedding} IS NOT NULL`];if(K>0)U.push(kA(Z,K));return(await A.select({memory:$,similarity:Z}).from($).where(R(...U)).orderBy(f(Z)).limit(J)).map((_)=>({id:_.memory.id,agentId:_.memory.agentId,entityId:_.memory.entityId,category:_.memory.category,content:_.memory.content,metadata:_.memory.metadata,embedding:_.memory.embedding,confidence:_.memory.confidence,source:_.memory.source,createdAt:_.memory.createdAt,updatedAt:_.memory.updatedAt,lastAccessedAt:_.memory.lastAccessedAt,accessCount:_.memory.accessCount,similarity:_.similarity}))}catch(Y){return H.warn({error:Y},"Vector search failed, falling back to recent memories"),this.getLongTermMemories(B,void 0,J)}}async getFormattedLongTermMemories(B){let Q=await this.getLongTermMemories(B,void 0,20);if(Q.length===0)return"";let J=new Map;for(let A of Q){if(!J.has(A.category))J.set(A.category,[]);J.get(A.category)?.push(A)}let K=[];for(let[A,Y]of J.entries()){let Z=A.split("_").map((V)=>V.charAt(0).toUpperCase()+V.slice(1)).join(" "),U=Y.map((V)=>`- ${V.content}`).join(`
2
- `);K.push(`**${Z}**:
3
- ${U}`)}return K.join(`
4
-
5
- `)}}import{logger as L,ModelType as zA,composePromptFromState as BA}from"@elizaos/core";async function qA(B,Q){return(await B.getMemories({tableName:"messages",roomId:Q,count:100,unique:!1})).filter((A)=>!(A.content?.type==="action_result"&&A.metadata?.type==="action_result")&&(A.metadata?.type==="agent_response_message"||A.metadata?.type==="user_message")).length}var fA=`# Task: Summarize Conversation
6
-
7
- You are analyzing a conversation to create a concise summary that captures the key points, topics, and important details.
8
-
9
- # Recent Messages
10
- {{recentMessages}}
11
-
12
- # Instructions
13
- Generate a summary that:
14
- 1. Captures the main topics discussed
15
- 2. Highlights key information shared
16
- 3. Notes any decisions made or questions asked
17
- 4. Maintains context for future reference
18
- 5. Is concise but comprehensive
19
-
20
- **IMPORTANT**: Keep the summary under 2500 tokens. Be comprehensive but concise.
21
-
22
- Also extract:
23
- - **Topics**: List of main topics discussed (comma-separated)
24
- - **Key Points**: Important facts or decisions (bullet points)
25
-
26
- Respond in this XML format:
27
- <summary>
28
- <text>Your comprehensive summary here</text>
29
- <topics>topic1, topic2, topic3</topics>
30
- <keyPoints>
31
- <point>First key point</point>
32
- <point>Second key point</point>
33
- </keyPoints>
34
- </summary>`,DA=`# Task: Update and Condense Conversation Summary
35
-
36
- You are updating an existing conversation summary with new messages, while keeping the total summary concise.
37
-
38
- # Existing Summary
39
- {{existingSummary}}
40
-
41
- # Existing Topics
42
- {{existingTopics}}
43
-
44
- # New Messages Since Last Summary
45
- {{newMessages}}
46
-
47
- # Instructions
48
- Update the summary by:
49
- 1. Merging the existing summary with insights from the new messages
50
- 2. Removing redundant or less important details to stay under the token limit
51
- 3. Keeping the most important context and decisions
52
- 4. Adding new topics if they emerge
53
- 5. **CRITICAL**: Keep the ENTIRE updated summary under 2500 tokens
54
-
55
- The goal is a rolling summary that captures the essence of the conversation without growing indefinitely.
56
-
57
- Respond in this XML format:
58
- <summary>
59
- <text>Your updated and condensed summary here</text>
60
- <topics>topic1, topic2, topic3</topics>
61
- <keyPoints>
62
- <point>First key point</point>
63
- <point>Second key point</point>
64
- </keyPoints>
65
- </summary>`;function bA(B){let Q=B.match(/<text>([\s\S]*?)<\/text>/),J=B.match(/<topics>([\s\S]*?)<\/topics>/),K=B.matchAll(/<point>([\s\S]*?)<\/point>/g),A=Q?Q[1].trim():"Summary not available",Y=J?J[1].split(",").map((U)=>U.trim()).filter(Boolean):[],Z=Array.from(K).map((U)=>U[1].trim());return{summary:A,topics:Y,keyPoints:Z}}var JA={name:"MEMORY_SUMMARIZATION",description:"Automatically summarizes conversations to optimize context usage",similes:["CONVERSATION_SUMMARY","CONTEXT_COMPRESSION","MEMORY_OPTIMIZATION"],alwaysRun:!0,validate:async(B,Q)=>{if(!Q.content?.text)return!1;let J=B.getService("memory");if(!J)return!1;let K=J.getConfig(),A=await qA(B,Q.roomId),Y=await J.getCurrentSessionSummary(Q.roomId);if(!Y)return A>=K.shortTermSummarizationThreshold;else return A-Y.lastMessageOffset>=K.shortTermSummarizationInterval},handler:async(B,Q)=>{let J=B.getService("memory");if(!J){L.error("MemoryService not found");return}let K=J.getConfig(),{roomId:A}=Q;try{L.info(`Starting summarization for room ${A}`);let Y=await J.getCurrentSessionSummary(A),Z=Y?.lastMessageOffset||0,V=(await B.getMemories({tableName:"messages",roomId:A,count:1000,unique:!1})).filter((E)=>!(E.content?.type==="action_result"&&E.metadata?.type==="action_result")&&(E.metadata?.type==="agent_response_message"||E.metadata?.type==="user_message")),_=V.length,W=_-Z;if(W===0){L.debug("No new dialogue messages to summarize");return}let F=K.summaryMaxNewMessages||50,x=Math.min(W,F);if(W>F)L.warn(`Capping new dialogue messages at ${F} (${W} available). Oldest messages will be skipped.`);let k=V.sort((E,q)=>(E.createdAt||0)-(q.createdAt||0)),N=k.slice(Z,Z+x);if(N.length===0){L.debug("No new dialogue messages retrieved after filtering");return}let G=N.map((E)=>{return`${E.entityId===B.agentId?B.character.name:"User"}: ${E.content.text||"[non-text message]"}`}).join(`
66
- `),z=await B.composeState(Q),S,b;if(Y)b=DA,S=BA({state:{...z,existingSummary:Y.summary,existingTopics:Y.topics?.join(", ")||"None",newMessages:G},template:b});else{let E=k.map((q)=>{return`${q.entityId===B.agentId?B.character.name:"User"}: ${q.content.text||"[non-text message]"}`}).join(`
67
- `);b=fA,S=BA({state:{...z,recentMessages:E},template:b})}let YA=await B.useModel(zA.TEXT_LARGE,{prompt:S,maxTokens:K.summaryMaxTokens||2500}),O=bA(YA);L.info(`${Y?"Updated":"Generated"} summary: ${O.summary.substring(0,100)}...`);let i=Z+N.length,I=N[0],M=N[N.length-1],ZA=Y?Y.startTime:I?.createdAt&&I.createdAt>0?new Date(I.createdAt):new Date,a=M?.createdAt&&M.createdAt>0?new Date(M.createdAt):new Date;if(Y)await J.updateSessionSummary(Y.id,A,{summary:O.summary,messageCount:Y.messageCount+N.length,lastMessageOffset:i,endTime:a,topics:O.topics,metadata:{keyPoints:O.keyPoints}}),L.info(`Updated summary for room ${A}: ${N.length} new dialogue messages processed (offset: ${Z} → ${i})`);else await J.storeSessionSummary({agentId:B.agentId,roomId:A,entityId:Q.entityId!==B.agentId?Q.entityId:void 0,summary:O.summary,messageCount:_,lastMessageOffset:_,startTime:ZA,endTime:a,topics:O.topics,metadata:{keyPoints:O.keyPoints}}),L.info(`Created new summary for room ${A}: ${_} dialogue messages summarized (offset: 0 → ${_})`)}catch(Y){L.error({error:Y},"Error during summarization:")}},examples:[]};import{logger as P,ModelType as CA,composePromptFromState as TA}from"@elizaos/core";var g;((K)=>{K.EPISODIC="episodic";K.SEMANTIC="semantic";K.PROCEDURAL="procedural"})(g||={});var vA=`# Task: Extract Long-Term Memory (Strict Criteria)
68
-
69
- You are analyzing a conversation to extract ONLY the most critical, persistent information about the user using cognitive science memory categories.
70
-
71
- # Recent Messages
72
- {{recentMessages}}
73
-
74
- # Current Long-Term Memories
75
- {{existingMemories}}
76
-
77
- # Memory Categories (Based on Cognitive Science)
78
-
79
- ## 1. EPISODIC Memory
80
- Personal experiences and specific events with temporal/spatial context.
81
- **Examples:**
82
- - "User completed migration project from MongoDB to PostgreSQL in Q2 2024"
83
- - "User encountered authentication bug in production on March 15th"
84
- - "User had a negative experience with Docker networking in previous job"
85
-
86
- **Requirements:**
87
- - Must include WHO did WHAT, WHEN/WHERE
88
- - Must be a specific, concrete event (not a pattern)
89
- - Must have significant impact or relevance to future work
90
-
91
- ## 2. SEMANTIC Memory
92
- General facts, concepts, knowledge, and established truths about the user.
93
- **Examples:**
94
- - "User is a senior backend engineer with 8 years experience"
95
- - "User specializes in distributed systems and microservices architecture"
96
- - "User's primary programming language is TypeScript"
97
- - "User works at Acme Corp as technical lead"
98
-
99
- **Requirements:**
100
- - Must be factual, timeless information
101
- - Must be explicitly stated or demonstrated conclusively
102
- - No speculation or inference from single instances
103
- - Core identity, expertise, or knowledge only
104
-
105
- ## 3. PROCEDURAL Memory
106
- Skills, workflows, methodologies, and how-to knowledge.
107
- **Examples:**
108
- - "User follows strict TDD workflow: write tests first, then implementation"
109
- - "User prefers git rebase over merge to maintain linear history"
110
- - "User's debugging process: check logs → reproduce locally → binary search"
111
- - "User always writes JSDoc comments before implementing functions"
112
-
113
- **Requirements:**
114
- - Must describe HOW user does something
115
- - Must be a repeated, consistent pattern (seen 3+ times or explicitly stated as standard practice)
116
- - Must be a workflow, methodology, or skill application
117
- - Not one-off preferences
118
-
119
- # ULTRA-STRICT EXTRACTION CRITERIA
120
-
121
- ## ✅ DO EXTRACT (Only These):
122
-
123
- **EPISODIC:**
124
- - Significant completed projects or milestones
125
- - Important bugs, incidents, or problems encountered
126
- - Major decisions made with lasting impact
127
- - Formative experiences that shape future work
128
-
129
- **SEMANTIC:**
130
- - Professional identity (role, title, company)
131
- - Core expertise and specializations (stated explicitly or demonstrated conclusively)
132
- - Primary languages, frameworks, or tools (not exploratory use)
133
- - Established facts about their work context
134
-
135
- **PROCEDURAL:**
136
- - Consistent workflows demonstrated 3+ times or explicitly stated
137
- - Standard practices user always follows
138
- - Methodology preferences with clear rationale
139
- - Debugging, testing, or development processes
140
-
141
- ## ❌ NEVER EXTRACT:
142
-
143
- - **One-time requests or tasks** (e.g., "can you generate an image", "help me debug this")
144
- - **Casual conversations** without lasting significance
145
- - **Exploratory questions** (e.g., "how does X work?")
146
- - **Temporary context** (current bug, today's task)
147
- - **Preferences from single occurrence** (e.g., user asked for code once)
148
- - **Social pleasantries** (thank you, greetings)
149
- - **Testing or experimentation** (trying out a feature)
150
- - **Common patterns everyone has** (likes clear explanations)
151
- - **Situational information** (working on feature X today)
152
- - **Opinions without persistence** (single complaint, isolated praise)
153
- - **General knowledge** (not specific to user)
154
-
155
- # Quality Gates (ALL Must Pass)
156
-
157
- 1. **Significance Test**: Will this matter in 3+ months?
158
- 2. **Specificity Test**: Is this concrete and actionable?
159
- 3. **Evidence Test**: Is there strong evidence (3+ instances OR explicit self-identification)?
160
- 4. **Uniqueness Test**: Is this specific to THIS user (not generic)?
161
- 5. **Confidence Test**: Confidence must be >= 0.85 (be VERY conservative)
162
- 6. **Non-Redundancy Test**: Does this add NEW information not in existing memories?
163
-
164
- # Confidence Scoring (Be Conservative)
165
-
166
- - **0.95-1.0**: User explicitly stated as core identity/practice AND demonstrated multiple times
167
- - **0.85-0.94**: User explicitly stated OR consistently demonstrated 5+ times
168
- - **0.75-0.84**: Strong pattern (3-4 instances) with supporting context
169
- - **Below 0.75**: DO NOT EXTRACT (insufficient evidence)
170
-
171
- # Critical Instructions
172
-
173
- 1. **Default to NOT extracting** - When in doubt, skip it
174
- 2. **Require overwhelming evidence** - One or two mentions is NOT enough
175
- 3. **Focus on what's PERSISTENT** - Not what's temporary or situational
176
- 4. **Verify against existing memories** - Don't duplicate or contradict
177
- 5. **Maximum 2-3 extractions per run** - Quality over quantity
178
-
179
- **If there are no qualifying facts (which is common), respond with <memories></memories>**
180
-
181
- # Response Format
182
-
183
- <memories>
184
- <memory>
185
- <category>semantic</category>
186
- <content>User is a senior TypeScript developer with 8 years of backend experience</content>
187
- <confidence>0.95</confidence>
188
- </memory>
189
- <memory>
190
- <category>procedural</category>
191
- <content>User follows TDD workflow: writes tests before implementation, runs tests after each change</content>
192
- <confidence>0.88</confidence>
193
- </memory>
194
- <memory>
195
- <category>episodic</category>
196
- <content>User led database migration from MongoDB to PostgreSQL for payment system in Q2 2024</content>
197
- <confidence>0.92</confidence>
198
- </memory>
199
- </memories>`;function hA(B){let Q=B.matchAll(/<memory>[\s\S]*?<category>(.*?)<\/category>[\s\S]*?<content>(.*?)<\/content>[\s\S]*?<confidence>(.*?)<\/confidence>[\s\S]*?<\/memory>/g),J=[];for(let K of Q){let A=K[1].trim(),Y=K[2].trim(),Z=parseFloat(K[3].trim());if(!Object.values(g).includes(A)){P.warn(`Invalid memory category: ${A}`);continue}if(Y&&!isNaN(Z))J.push({category:A,content:Y,confidence:Z})}return J}var KA={name:"LONG_TERM_MEMORY_EXTRACTION",description:"Extracts long-term facts about users from conversations",similes:["MEMORY_EXTRACTION","FACT_LEARNING","USER_PROFILING"],alwaysRun:!0,validate:async(B,Q)=>{if(Q.entityId===B.agentId)return!1;if(!Q.content?.text)return!1;let J=B.getService("memory");if(!J)return!1;if(!J.getConfig().longTermExtractionEnabled)return P.debug("Long-term memory extraction is disabled"),!1;let A=await B.countMemories(Q.roomId,!1,"messages");return await J.shouldRunExtraction(Q.entityId,Q.roomId,A)},handler:async(B,Q)=>{let J=B.getService("memory");if(!J){P.error("MemoryService not found");return}let K=J.getConfig(),{entityId:A,roomId:Y}=Q;try{P.info(`Extracting long-term memories for entity ${A}`);let U=(await B.getMemories({tableName:"messages",roomId:Y,count:20,unique:!1})).sort((G,z)=>(G.createdAt||0)-(z.createdAt||0)).map((G)=>{return`${G.entityId===B.agentId?B.character.name:"User"}: ${G.content.text||"[non-text message]"}`}).join(`
200
- `),V=await J.getLongTermMemories(A,void 0,30),_=V.length>0?V.map((G)=>`[${G.category}] ${G.content} (confidence: ${G.confidence})`).join(`
201
- `):"None yet",W=await B.composeState(Q),F=TA({state:{...W,recentMessages:U,existingMemories:_},template:vA}),x=await B.useModel(CA.TEXT_LARGE,{prompt:F}),k=hA(x);P.info(`Extracted ${k.length} long-term memories`);for(let G of k)if(G.confidence>=Math.max(K.longTermConfidenceThreshold,0.85))await J.storeLongTermMemory({agentId:B.agentId,entityId:A,category:G.category,content:G.content,confidence:G.confidence,source:"conversation",metadata:{roomId:Y,extractedAt:new Date().toISOString()}}),P.info(`Stored long-term memory: [${G.category}] ${G.content.substring(0,50)}...`);else P.debug(`Skipped low-confidence memory: ${G.content} (confidence: ${G.confidence}, threshold: ${Math.max(K.longTermConfidenceThreshold,0.85)})`);let N=await B.countMemories(Y,!1,"messages");await J.setLastExtractionCheckpoint(A,Y,N),P.debug(`Updated extraction checkpoint to ${N} for entity ${A} in room ${Y}`)}catch(Z){P.error({error:Z},"Error during long-term memory extraction:")}},examples:[]};import{logger as xA,addHeader as SA}from"@elizaos/core";var u={name:"LONG_TERM_MEMORY",description:"Persistent facts and preferences about the user",position:50,get:async(B,Q,J)=>{try{let K=B.getService("memory");if(!K)return{data:{memories:[]},values:{longTermMemories:""},text:""};let{entityId:A}=Q;if(A===B.agentId)return{data:{memories:[]},values:{longTermMemories:""},text:""};let Y=await K.getLongTermMemories(A,void 0,25);if(Y.length===0)return{data:{memories:[]},values:{longTermMemories:""},text:""};let Z=await K.getFormattedLongTermMemories(A),U=SA("# What I Know About You",Z),V=new Map;for(let W of Y){let F=V.get(W.category)||0;V.set(W.category,F+1)}let _=Array.from(V.entries()).map(([W,F])=>`${W}: ${F}`).join(", ");return{data:{memories:Y,categoryCounts:Object.fromEntries(V)},values:{longTermMemories:U,memoryCategories:_},text:U}}catch(K){return xA.error({error:K},"Error in longTermMemoryProvider:"),{data:{memories:[]},values:{longTermMemories:""},text:""}}}};import{addHeader as QA,logger as IA}from"@elizaos/core";var n={name:"SUMMARIZED_CONTEXT",description:"Provides summarized context from previous conversations",position:96,get:async(B,Q,J)=>{try{let K=B.getService("memory"),{roomId:A}=Q;if(!K)return{data:{summary:null},values:{sessionSummaries:"",sessionSummariesWithTopics:""},text:""};let Y=await K.getCurrentSessionSummary(A);if(!Y)return{data:{summary:null},values:{sessionSummaries:"",sessionSummariesWithTopics:""},text:""};let Z=`${Y.messageCount} messages`,U=new Date(Y.startTime).toLocaleDateString(),V=`**Previous Conversation** (${Z}, ${U})
202
- `;V+=Y.summary;let _=V;if(Y.topics&&Y.topics.length>0)_+=`
203
- *Topics: ${Y.topics.join(", ")}*`;let W=QA("# Conversation Summary",V),F=QA("# Conversation Summary",_);return{data:{summary:Y},values:{sessionSummaries:W,sessionSummariesWithTopics:F},text:F}}catch(K){return IA.error({error:K},"Error in contextSummaryProvider:"),{data:{summary:null},values:{sessionSummaries:"",sessionSummariesWithTopics:""},text:""}}}};var MA={name:"memory",description:"Advanced memory management with conversation summarization and long-term persistent memory",services:[D],evaluators:[JA,KA],providers:[u,n],schema:d},pA=MA;export{j as sessionSummaries,MA as memoryPlugin,e as memoryAccessLogs,u as longTermMemoryProvider,$ as longTermMemories,pA as default,n as contextSummaryProvider,D as MemoryService,g as LongTermMemoryCategory};
204
-
205
- //# debugId=63795FFE83D49E7A64756E2164756E21
@@ -1,19 +0,0 @@
1
- {
2
- "version": 3,
3
- "sources": ["../../src/services/memory-service.ts", "../../src/schemas/long-term-memories.ts", "../../src/schemas/session-summaries.ts", "../../src/schemas/memory-access-logs.ts", "../../src/evaluators/summarization.ts", "../../src/evaluators/long-term-extraction.ts", "../../src/types/index.ts", "../../src/providers/long-term-memory.ts", "../../src/providers/context-summary.ts", "../../src/index.ts"],
4
- "sourcesContent": [
5
- "import {\n type IAgentRuntime,\n Service,\n type UUID,\n logger,\n type ServiceTypeName,\n} from '@elizaos/core';\nimport { eq, and, desc, sql, cosineDistance, gte } from 'drizzle-orm';\nimport {\n type LongTermMemory,\n type SessionSummary,\n type MemoryConfig,\n LongTermMemoryCategory,\n} from '../types/index';\nimport { longTermMemories, sessionSummaries } from '../schemas/index';\n\n/**\n * Memory Service\n * Manages both short-term (session summaries) and long-term (persistent facts) memory\n */\nexport class MemoryService extends Service {\n static serviceType: ServiceTypeName = 'memory' as ServiceTypeName;\n\n private sessionMessageCounts: Map<UUID, number>;\n private memoryConfig: MemoryConfig;\n private lastExtractionCheckpoints: Map<string, number>; // Track last extraction per entity-room pair\n\n capabilityDescription =\n 'Advanced memory management with short-term summarization and long-term persistent facts';\n\n constructor(runtime?: IAgentRuntime) {\n super(runtime);\n this.sessionMessageCounts = new Map();\n this.lastExtractionCheckpoints = new Map();\n this.memoryConfig = {\n shortTermSummarizationThreshold: 16, // Start summarization at 16 messages\n shortTermRetainRecent: 6, // Show last 6 messages when summarization is active\n shortTermSummarizationInterval: 10, // Update summary every 10 new messages\n longTermExtractionEnabled: true,\n longTermVectorSearchEnabled: false,\n longTermConfidenceThreshold: 0.85, // Stricter threshold - only high-confidence extractions\n longTermExtractionThreshold: 30, // Increased from 20 - need more context before extraction\n longTermExtractionInterval: 10, // Increased from 5 - extract less frequently\n summaryModelType: 'TEXT_LARGE',\n summaryMaxTokens: 2500,\n summaryMaxNewMessages: 20, // Cap new messages in update to prevent context bloat\n };\n }\n\n static async start(runtime: IAgentRuntime): Promise<Service> {\n const service = new MemoryService(runtime);\n await service.initialize(runtime);\n return service;\n }\n\n async stop(): Promise<void> {\n // No cleanup needed for this service\n logger.info('MemoryService stopped');\n }\n\n async initialize(runtime: IAgentRuntime): Promise<void> {\n this.runtime = runtime;\n\n // Load configuration from runtime settings\n const threshold = runtime.getSetting('MEMORY_SUMMARIZATION_THRESHOLD');\n if (threshold) {\n this.memoryConfig.shortTermSummarizationThreshold = parseInt(threshold, 10);\n }\n\n const retainRecent = runtime.getSetting('MEMORY_RETAIN_RECENT');\n if (retainRecent) {\n this.memoryConfig.shortTermRetainRecent = parseInt(retainRecent, 10);\n }\n\n const summarizationInterval = runtime.getSetting('MEMORY_SUMMARIZATION_INTERVAL');\n if (summarizationInterval) {\n this.memoryConfig.shortTermSummarizationInterval = parseInt(summarizationInterval, 10);\n }\n\n const maxNewMessages = runtime.getSetting('MEMORY_MAX_NEW_MESSAGES');\n if (maxNewMessages) {\n this.memoryConfig.summaryMaxNewMessages = parseInt(maxNewMessages, 10);\n }\n\n const longTermEnabled = runtime.getSetting('MEMORY_LONG_TERM_ENABLED');\n // Only override default if explicitly set to 'false'\n if (longTermEnabled === 'false') {\n this.memoryConfig.longTermExtractionEnabled = false;\n } else if (longTermEnabled === 'true') {\n this.memoryConfig.longTermExtractionEnabled = true;\n }\n // Otherwise keep the default value (true)\n\n const confidenceThreshold = runtime.getSetting('MEMORY_CONFIDENCE_THRESHOLD');\n if (confidenceThreshold) {\n this.memoryConfig.longTermConfidenceThreshold = parseFloat(confidenceThreshold);\n }\n\n const extractionThreshold = runtime.getSetting('MEMORY_EXTRACTION_THRESHOLD');\n if (extractionThreshold) {\n this.memoryConfig.longTermExtractionThreshold = parseInt(extractionThreshold, 10);\n }\n\n const extractionInterval = runtime.getSetting('MEMORY_EXTRACTION_INTERVAL');\n if (extractionInterval) {\n this.memoryConfig.longTermExtractionInterval = parseInt(extractionInterval, 10);\n }\n\n logger.debug(\n {\n summarizationThreshold: this.memoryConfig.shortTermSummarizationThreshold,\n summarizationInterval: this.memoryConfig.shortTermSummarizationInterval,\n maxNewMessages: this.memoryConfig.summaryMaxNewMessages,\n retainRecent: this.memoryConfig.shortTermRetainRecent,\n longTermEnabled: this.memoryConfig.longTermExtractionEnabled,\n extractionThreshold: this.memoryConfig.longTermExtractionThreshold,\n extractionInterval: this.memoryConfig.longTermExtractionInterval,\n confidenceThreshold: this.memoryConfig.longTermConfidenceThreshold,\n },\n 'MemoryService initialized'\n );\n }\n\n /**\n * Get the Drizzle database instance\n */\n private getDb(): any {\n const db = (this.runtime as any).db;\n if (!db) {\n throw new Error('Database not available');\n }\n return db;\n }\n\n /**\n * Get configuration\n */\n getConfig(): MemoryConfig {\n return { ...this.memoryConfig };\n }\n\n /**\n * Update configuration\n */\n updateConfig(updates: Partial<MemoryConfig>): void {\n this.memoryConfig = { ...this.memoryConfig, ...updates };\n }\n\n /**\n * Track message count for a room\n */\n incrementMessageCount(roomId: UUID): number {\n const current = this.sessionMessageCounts.get(roomId) || 0;\n const newCount = current + 1;\n this.sessionMessageCounts.set(roomId, newCount);\n return newCount;\n }\n\n /**\n * Reset message count for a room\n */\n resetMessageCount(roomId: UUID): void {\n this.sessionMessageCounts.set(roomId, 0);\n }\n\n /**\n * Check if summarization is needed for a room\n */\n async shouldSummarize(roomId: UUID): Promise<boolean> {\n const count = await this.runtime.countMemories(roomId, false, 'messages');\n return count >= this.memoryConfig.shortTermSummarizationThreshold;\n }\n\n /**\n * Generate cache key for tracking extraction checkpoints per entity-room pair\n */\n private getExtractionKey(entityId: UUID, roomId: UUID): string {\n return `memory:extraction:${entityId}:${roomId}`;\n }\n\n /**\n * Get the last extraction checkpoint for an entity in a room\n * Uses the cache table via adapter\n */\n async getLastExtractionCheckpoint(entityId: UUID, roomId: UUID): Promise<number> {\n const key = this.getExtractionKey(entityId, roomId);\n\n // Check in-memory cache first\n const cached = this.lastExtractionCheckpoints.get(key);\n if (cached !== undefined) {\n return cached;\n }\n\n // Check database cache table via adapter\n try {\n const checkpoint = await this.runtime.getCache<number>(key);\n const messageCount = checkpoint ?? 0;\n\n // Cache it in memory for faster access\n this.lastExtractionCheckpoints.set(key, messageCount);\n\n return messageCount;\n } catch (error) {\n logger.warn({ error }, 'Failed to get extraction checkpoint from cache');\n return 0;\n }\n }\n\n /**\n * Set the last extraction checkpoint for an entity in a room\n * Uses the cache table via adapter\n */\n async setLastExtractionCheckpoint(\n entityId: UUID,\n roomId: UUID,\n messageCount: number\n ): Promise<void> {\n const key = this.getExtractionKey(entityId, roomId);\n\n // Update in-memory cache\n this.lastExtractionCheckpoints.set(key, messageCount);\n\n // Persist to database cache table via adapter\n try {\n await this.runtime.setCache(key, messageCount);\n logger.debug(\n `Set extraction checkpoint for ${entityId} in room ${roomId} at message count ${messageCount}`\n );\n } catch (error) {\n logger.error({ error }, 'Failed to persist extraction checkpoint to cache');\n }\n }\n\n /**\n * Check if long-term extraction should run based on message count and interval\n */\n async shouldRunExtraction(\n entityId: UUID,\n roomId: UUID,\n currentMessageCount: number\n ): Promise<boolean> {\n const threshold = this.memoryConfig.longTermExtractionThreshold;\n const interval = this.memoryConfig.longTermExtractionInterval;\n \n // Don't run extraction until we reach the minimum threshold\n if (currentMessageCount < threshold) {\n return false;\n }\n\n const lastCheckpoint = await this.getLastExtractionCheckpoint(entityId, roomId);\n\n // Calculate the current checkpoint (e.g., if interval=5: 20, 25, 30, 35...)\n const currentCheckpoint = Math.floor(currentMessageCount / interval) * interval;\n\n // Run if we're at or past a checkpoint and haven't processed this checkpoint yet\n const shouldRun = currentMessageCount >= threshold && currentCheckpoint > lastCheckpoint;\n\n logger.debug(\n {\n entityId,\n roomId,\n currentMessageCount,\n threshold,\n interval,\n lastCheckpoint,\n currentCheckpoint,\n shouldRun,\n },\n 'Extraction check'\n );\n\n return shouldRun;\n }\n\n /**\n * Store a long-term memory\n */\n async storeLongTermMemory(\n memory: Omit<LongTermMemory, 'id' | 'createdAt' | 'updatedAt'>\n ): Promise<LongTermMemory> {\n const db = this.getDb();\n\n const id = crypto.randomUUID() as UUID;\n const now = new Date();\n\n const newMemory: LongTermMemory = {\n id,\n createdAt: now,\n updatedAt: now,\n accessCount: 0,\n ...memory,\n };\n\n try {\n await db.insert(longTermMemories).values({\n id: newMemory.id,\n agentId: newMemory.agentId,\n entityId: newMemory.entityId,\n category: newMemory.category,\n content: newMemory.content,\n metadata: newMemory.metadata || {},\n embedding: newMemory.embedding,\n confidence: newMemory.confidence,\n source: newMemory.source,\n accessCount: newMemory.accessCount,\n createdAt: now,\n updatedAt: now,\n lastAccessedAt: newMemory.lastAccessedAt,\n });\n } catch (error) {\n logger.error({ error }, 'Failed to store long-term memory');\n throw error;\n }\n\n logger.info(`Stored long-term memory: ${newMemory.category} for entity ${newMemory.entityId}`);\n return newMemory;\n }\n\n /**\n * Retrieve long-term memories for an entity\n */\n async getLongTermMemories(\n entityId: UUID,\n category?: LongTermMemoryCategory,\n limit: number = 10\n ): Promise<LongTermMemory[]> {\n const db = this.getDb();\n\n const conditions = [\n eq(longTermMemories.agentId, this.runtime.agentId),\n eq(longTermMemories.entityId, entityId),\n ];\n\n if (category) {\n conditions.push(eq(longTermMemories.category, category));\n }\n\n const results = await db\n .select()\n .from(longTermMemories)\n .where(and(...conditions))\n .orderBy(desc(longTermMemories.confidence), desc(longTermMemories.updatedAt))\n .limit(limit);\n\n return results.map((row) => ({\n id: row.id as UUID,\n agentId: row.agentId as UUID,\n entityId: row.entityId as UUID,\n category: row.category as LongTermMemoryCategory,\n content: row.content,\n metadata: row.metadata as Record<string, unknown>,\n embedding: row.embedding as number[],\n confidence: row.confidence as number,\n source: row.source as string,\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n lastAccessedAt: row.lastAccessedAt,\n accessCount: row.accessCount as number,\n }));\n }\n\n /**\n * Update a long-term memory\n * Enforces multi-tenancy by verifying agentId and entityId\n */\n async updateLongTermMemory(\n id: UUID,\n entityId: UUID,\n updates: Partial<Omit<LongTermMemory, 'id' | 'agentId' | 'entityId' | 'createdAt'>>\n ): Promise<void> {\n const db = this.getDb();\n\n const updateData: any = {\n updatedAt: new Date(),\n };\n\n if (updates.content !== undefined) {\n updateData.content = updates.content;\n }\n\n if (updates.metadata !== undefined) {\n updateData.metadata = updates.metadata;\n }\n\n if (updates.confidence !== undefined) {\n updateData.confidence = updates.confidence;\n }\n\n if (updates.embedding !== undefined) {\n updateData.embedding = updates.embedding;\n }\n\n if (updates.lastAccessedAt !== undefined) {\n updateData.lastAccessedAt = updates.lastAccessedAt;\n }\n\n if (updates.accessCount !== undefined) {\n updateData.accessCount = updates.accessCount;\n }\n\n // Enforce multi-tenancy: only update if agentId and entityId match\n await db\n .update(longTermMemories)\n .set(updateData)\n .where(\n and(\n eq(longTermMemories.id, id),\n eq(longTermMemories.agentId, this.runtime.agentId),\n eq(longTermMemories.entityId, entityId)\n )\n );\n\n logger.info(`Updated long-term memory: ${id} for entity ${entityId}`);\n }\n\n /**\n * Delete a long-term memory\n * Enforces multi-tenancy by verifying agentId and entityId\n */\n async deleteLongTermMemory(id: UUID, entityId: UUID): Promise<void> {\n const db = this.getDb();\n\n // Enforce multi-tenancy: only delete if agentId and entityId match\n await db\n .delete(longTermMemories)\n .where(\n and(\n eq(longTermMemories.id, id),\n eq(longTermMemories.agentId, this.runtime.agentId),\n eq(longTermMemories.entityId, entityId)\n )\n );\n\n logger.info(`Deleted long-term memory: ${id} for entity ${entityId}`);\n }\n\n /**\n * Get the current session summary for a room (latest one)\n */\n async getCurrentSessionSummary(roomId: UUID): Promise<SessionSummary | null> {\n const db = this.getDb();\n\n const results = await db\n .select()\n .from(sessionSummaries)\n .where(\n and(eq(sessionSummaries.agentId, this.runtime.agentId), eq(sessionSummaries.roomId, roomId))\n )\n .orderBy(desc(sessionSummaries.updatedAt))\n .limit(1);\n\n if (results.length === 0) {\n return null;\n }\n\n const row = results[0];\n return {\n id: row.id as UUID,\n agentId: row.agentId as UUID,\n roomId: row.roomId as UUID,\n entityId: row.entityId as UUID | undefined,\n summary: row.summary,\n messageCount: row.messageCount,\n lastMessageOffset: row.lastMessageOffset,\n startTime: row.startTime,\n endTime: row.endTime,\n topics: (row.topics as string[]) || [],\n metadata: row.metadata as Record<string, unknown>,\n embedding: row.embedding as number[],\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n };\n }\n\n /**\n * Store a session summary (initial creation)\n */\n async storeSessionSummary(\n summary: Omit<SessionSummary, 'id' | 'createdAt' | 'updatedAt'>\n ): Promise<SessionSummary> {\n const db = this.getDb();\n\n const id = crypto.randomUUID() as UUID;\n const now = new Date();\n\n const newSummary: SessionSummary = {\n id,\n createdAt: now,\n updatedAt: now,\n ...summary,\n };\n\n await db.insert(sessionSummaries).values({\n id: newSummary.id,\n agentId: newSummary.agentId,\n roomId: newSummary.roomId,\n entityId: newSummary.entityId || null,\n summary: newSummary.summary,\n messageCount: newSummary.messageCount,\n lastMessageOffset: newSummary.lastMessageOffset,\n startTime: newSummary.startTime,\n endTime: newSummary.endTime,\n topics: newSummary.topics || [],\n metadata: newSummary.metadata || {},\n embedding: newSummary.embedding,\n createdAt: now,\n updatedAt: now,\n });\n\n logger.info(`Stored session summary for room ${newSummary.roomId}`);\n return newSummary;\n }\n\n /**\n * Update an existing session summary\n * Enforces multi-tenancy by verifying agentId\n */\n async updateSessionSummary(\n id: UUID,\n roomId: UUID,\n updates: Partial<Omit<SessionSummary, 'id' | 'agentId' | 'roomId' | 'createdAt' | 'updatedAt'>>\n ): Promise<void> {\n const db = this.getDb();\n\n const updateData: any = {\n updatedAt: new Date(),\n };\n\n if (updates.summary !== undefined) {\n updateData.summary = updates.summary;\n }\n\n if (updates.messageCount !== undefined) {\n updateData.messageCount = updates.messageCount;\n }\n\n if (updates.lastMessageOffset !== undefined) {\n updateData.lastMessageOffset = updates.lastMessageOffset;\n }\n\n if (updates.endTime !== undefined) {\n updateData.endTime = updates.endTime;\n }\n\n if (updates.topics !== undefined) {\n updateData.topics = updates.topics;\n }\n\n if (updates.metadata !== undefined) {\n updateData.metadata = updates.metadata;\n }\n\n if (updates.embedding !== undefined) {\n updateData.embedding = updates.embedding;\n }\n\n // Enforce multi-tenancy: only update if agentId and roomId match\n await db\n .update(sessionSummaries)\n .set(updateData)\n .where(\n and(\n eq(sessionSummaries.id, id),\n eq(sessionSummaries.agentId, this.runtime.agentId),\n eq(sessionSummaries.roomId, roomId)\n )\n );\n\n logger.info(`Updated session summary: ${id} for room ${roomId}`);\n }\n\n /**\n * Get session summaries for a room\n */\n async getSessionSummaries(roomId: UUID, limit: number = 5): Promise<SessionSummary[]> {\n const db = this.getDb();\n\n const results = await db\n .select()\n .from(sessionSummaries)\n .where(\n and(eq(sessionSummaries.agentId, this.runtime.agentId), eq(sessionSummaries.roomId, roomId))\n )\n .orderBy(desc(sessionSummaries.updatedAt))\n .limit(limit);\n\n return results.map((row) => ({\n id: row.id as UUID,\n agentId: row.agentId as UUID,\n roomId: row.roomId as UUID,\n entityId: row.entityId as UUID | undefined,\n summary: row.summary,\n messageCount: row.messageCount,\n lastMessageOffset: row.lastMessageOffset,\n startTime: row.startTime,\n endTime: row.endTime,\n topics: (row.topics as string[]) || [],\n metadata: row.metadata as Record<string, unknown>,\n embedding: row.embedding as number[],\n createdAt: row.createdAt,\n updatedAt: row.updatedAt,\n }));\n }\n\n /**\n * Search long-term memories by semantic similarity (if embeddings are available)\n */\n async searchLongTermMemories(\n entityId: UUID,\n queryEmbedding: number[],\n limit: number = 5,\n matchThreshold: number = 0.7\n ): Promise<LongTermMemory[]> {\n if (!this.memoryConfig.longTermVectorSearchEnabled) {\n logger.warn('Vector search is not enabled, falling back to recent memories');\n return this.getLongTermMemories(entityId, undefined, limit);\n }\n\n const db = this.getDb();\n\n try {\n // Clean the vector to ensure all numbers are finite and properly formatted\n const cleanVector = queryEmbedding.map((n) =>\n Number.isFinite(n) ? Number(n.toFixed(6)) : 0\n );\n\n // Calculate similarity using Drizzle's cosineDistance\n const similarity = sql<number>`1 - (${cosineDistance(\n longTermMemories.embedding,\n cleanVector\n )})`;\n\n const conditions = [\n eq(longTermMemories.agentId, this.runtime.agentId),\n eq(longTermMemories.entityId, entityId),\n sql`${longTermMemories.embedding} IS NOT NULL`,\n ];\n\n // Add similarity threshold if specified\n if (matchThreshold > 0) {\n conditions.push(gte(similarity, matchThreshold));\n }\n\n const results = await db\n .select({\n memory: longTermMemories,\n similarity,\n })\n .from(longTermMemories)\n .where(and(...conditions))\n .orderBy(desc(similarity))\n .limit(limit);\n\n return results.map((row) => ({\n id: row.memory.id as UUID,\n agentId: row.memory.agentId as UUID,\n entityId: row.memory.entityId as UUID,\n category: row.memory.category as LongTermMemoryCategory,\n content: row.memory.content,\n metadata: row.memory.metadata as Record<string, unknown>,\n embedding: row.memory.embedding as number[],\n confidence: row.memory.confidence as number,\n source: row.memory.source as string,\n createdAt: row.memory.createdAt,\n updatedAt: row.memory.updatedAt,\n lastAccessedAt: row.memory.lastAccessedAt,\n accessCount: row.memory.accessCount as number,\n similarity: row.similarity,\n }));\n } catch (error) {\n logger.warn({ error }, 'Vector search failed, falling back to recent memories');\n return this.getLongTermMemories(entityId, undefined, limit);\n }\n }\n\n /**\n * Get all long-term memories formatted for context\n */\n async getFormattedLongTermMemories(entityId: UUID): Promise<string> {\n const memories = await this.getLongTermMemories(entityId, undefined, 20);\n\n if (memories.length === 0) {\n return '';\n }\n\n // Group by category\n const grouped = new Map<LongTermMemoryCategory, LongTermMemory[]>();\n\n for (const memory of memories) {\n if (!grouped.has(memory.category)) {\n grouped.set(memory.category, []);\n }\n grouped.get(memory.category)?.push(memory);\n }\n\n // Format each category\n const sections: string[] = [];\n\n for (const [category, categoryMemories] of grouped.entries()) {\n const categoryName = category\n .split('_')\n .map((word) => word.charAt(0).toUpperCase() + word.slice(1))\n .join(' ');\n\n const items = categoryMemories.map((m) => `- ${m.content}`).join('\\n');\n sections.push(`**${categoryName}**:\\n${items}`);\n }\n\n return sections.join('\\n\\n');\n }\n}\n",
6
- "import { sql } from 'drizzle-orm';\nimport {\n pgTable,\n text,\n integer,\n jsonb,\n real,\n index,\n varchar,\n timestamp,\n} from 'drizzle-orm/pg-core';\n\n/**\n * Long-term memory storage table\n * Stores persistent facts about users across all conversations\n */\nexport const longTermMemories = pgTable(\n 'long_term_memories',\n {\n id: varchar('id', { length: 36 }).primaryKey(),\n agentId: varchar('agent_id', { length: 36 }).notNull(),\n entityId: varchar('entity_id', { length: 36 }).notNull(),\n category: text('category').notNull(),\n content: text('content').notNull(),\n metadata: jsonb('metadata'),\n embedding: real('embedding').array(),\n confidence: real('confidence').default(1.0),\n source: text('source'),\n createdAt: timestamp('created_at')\n .default(sql`now()`)\n .notNull(),\n updatedAt: timestamp('updated_at')\n .default(sql`now()`)\n .notNull(),\n lastAccessedAt: timestamp('last_accessed_at'),\n accessCount: integer('access_count').default(0),\n },\n (table) => ({\n agentEntityIdx: index('long_term_memories_agent_entity_idx').on(table.agentId, table.entityId),\n categoryIdx: index('long_term_memories_category_idx').on(table.category),\n confidenceIdx: index('long_term_memories_confidence_idx').on(table.confidence),\n createdAtIdx: index('long_term_memories_created_at_idx').on(table.createdAt),\n })\n);\n",
7
- "import { sql } from 'drizzle-orm';\nimport {\n pgTable,\n text,\n integer,\n jsonb,\n real,\n index,\n varchar,\n timestamp,\n} from 'drizzle-orm/pg-core';\n\n/**\n * Session summaries table\n * Stores condensed summaries of conversation sessions\n */\nexport const sessionSummaries = pgTable(\n 'session_summaries',\n {\n id: varchar('id', { length: 36 }).primaryKey(),\n agentId: varchar('agent_id', { length: 36 }).notNull(),\n roomId: varchar('room_id', { length: 36 }).notNull(),\n entityId: varchar('entity_id', { length: 36 }),\n summary: text('summary').notNull(),\n messageCount: integer('message_count').notNull(),\n lastMessageOffset: integer('last_message_offset').notNull().default(0),\n startTime: timestamp('start_time').notNull(),\n endTime: timestamp('end_time').notNull(),\n topics: jsonb('topics'),\n metadata: jsonb('metadata'),\n embedding: real('embedding').array(),\n createdAt: timestamp('created_at')\n .default(sql`now()`)\n .notNull(),\n updatedAt: timestamp('updated_at')\n .default(sql`now()`)\n .notNull(),\n },\n (table) => ({\n agentRoomIdx: index('session_summaries_agent_room_idx').on(table.agentId, table.roomId),\n entityIdx: index('session_summaries_entity_idx').on(table.entityId),\n startTimeIdx: index('session_summaries_start_time_idx').on(table.startTime),\n })\n);\n",
8
- "import { sql } from 'drizzle-orm';\nimport { pgTable, text, integer, real, index, varchar, timestamp } from 'drizzle-orm/pg-core';\n\n/**\n * Memory access logs (optional - for tracking and improving memory retrieval)\n */\nexport const memoryAccessLogs = pgTable(\n 'memory_access_logs',\n {\n id: varchar('id', { length: 36 }).primaryKey(),\n agentId: varchar('agent_id', { length: 36 }).notNull(),\n memoryId: varchar('memory_id', { length: 36 }).notNull(),\n memoryType: text('memory_type').notNull(), // 'long_term' or 'session_summary'\n accessedAt: timestamp('accessed_at')\n .default(sql`now()`)\n .notNull(),\n roomId: varchar('room_id', { length: 36 }),\n relevanceScore: real('relevance_score'),\n wasUseful: integer('was_useful'), // 1 = useful, 0 = not useful, null = unknown\n },\n (table) => ({\n memoryIdx: index('memory_access_logs_memory_idx').on(table.memoryId),\n agentIdx: index('memory_access_logs_agent_idx').on(table.agentId),\n accessedAtIdx: index('memory_access_logs_accessed_at_idx').on(table.accessedAt),\n })\n);\n",
9
- "import {\n type IAgentRuntime,\n type Memory,\n type Evaluator,\n logger,\n ModelType,\n composePromptFromState,\n type UUID,\n} from \"@elizaos/core\";\nimport { MemoryService } from \"../services/memory-service\";\nimport type { SummaryResult } from \"../types/index\";\n\n/**\n * Helper function to get dialogue messages count (excluding action results)\n * This matches the filtering logic in short-term-memory provider\n */\nasync function getDialogueMessageCount(\n runtime: IAgentRuntime,\n roomId: UUID\n): Promise<number> {\n // We need to fetch messages to filter them properly\n // Fetch a reasonable batch to check\n const messages = await runtime.getMemories({\n tableName: \"messages\",\n roomId,\n count: 100, // Check last 100 messages\n unique: false,\n });\n\n const dialogueMessages = messages.filter(\n (msg) =>\n !(\n msg.content?.type === \"action_result\" &&\n msg.metadata?.type === \"action_result\"\n ) &&\n (msg.metadata?.type === \"agent_response_message\" ||\n msg.metadata?.type === \"user_message\")\n );\n\n return dialogueMessages.length;\n}\n\n/**\n * Template for generating initial conversation summary\n */\nconst initialSummarizationTemplate = `# Task: Summarize Conversation\n\nYou are analyzing a conversation to create a concise summary that captures the key points, topics, and important details.\n\n# Recent Messages\n{{recentMessages}}\n\n# Instructions\nGenerate a summary that:\n1. Captures the main topics discussed\n2. Highlights key information shared\n3. Notes any decisions made or questions asked\n4. Maintains context for future reference\n5. Is concise but comprehensive\n\n**IMPORTANT**: Keep the summary under 2500 tokens. Be comprehensive but concise.\n\nAlso extract:\n- **Topics**: List of main topics discussed (comma-separated)\n- **Key Points**: Important facts or decisions (bullet points)\n\nRespond in this XML format:\n<summary>\n <text>Your comprehensive summary here</text>\n <topics>topic1, topic2, topic3</topics>\n <keyPoints>\n <point>First key point</point>\n <point>Second key point</point>\n </keyPoints>\n</summary>`;\n\n/**\n * Template for updating/condensing an existing summary\n */\nconst updateSummarizationTemplate = `# Task: Update and Condense Conversation Summary\n\nYou are updating an existing conversation summary with new messages, while keeping the total summary concise.\n\n# Existing Summary\n{{existingSummary}}\n\n# Existing Topics\n{{existingTopics}}\n\n# New Messages Since Last Summary\n{{newMessages}}\n\n# Instructions\nUpdate the summary by:\n1. Merging the existing summary with insights from the new messages\n2. Removing redundant or less important details to stay under the token limit\n3. Keeping the most important context and decisions\n4. Adding new topics if they emerge\n5. **CRITICAL**: Keep the ENTIRE updated summary under 2500 tokens\n\nThe goal is a rolling summary that captures the essence of the conversation without growing indefinitely.\n\nRespond in this XML format:\n<summary>\n <text>Your updated and condensed summary here</text>\n <topics>topic1, topic2, topic3</topics>\n <keyPoints>\n <point>First key point</point>\n <point>Second key point</point>\n </keyPoints>\n</summary>`;\n\n/**\n * Parse XML summary response\n */\nfunction parseSummaryXML(xml: string): SummaryResult {\n const summaryMatch = xml.match(/<text>([\\s\\S]*?)<\\/text>/);\n const topicsMatch = xml.match(/<topics>([\\s\\S]*?)<\\/topics>/);\n const keyPointsMatches = xml.matchAll(/<point>([\\s\\S]*?)<\\/point>/g);\n\n const summary = summaryMatch\n ? summaryMatch[1].trim()\n : \"Summary not available\";\n const topics = topicsMatch\n ? topicsMatch[1]\n .split(\",\")\n .map((t) => t.trim())\n .filter(Boolean)\n : [];\n const keyPoints = Array.from(keyPointsMatches).map((match) =>\n match[1].trim()\n );\n\n return { summary, topics, keyPoints };\n}\n\n/**\n * Short-term Memory Summarization Evaluator\n *\n * Automatically generates and updates conversation summaries when conversations\n * exceed the configured threshold (default: 16 messages).\n *\n * BEHAVIOR:\n * - Monitors message count per room\n * - Creates initial summary when count >= threshold (e.g., 16 messages)\n * - Updates summary at regular intervals (e.g., every 10 new messages)\n * - Condenses existing summary with new messages to stay under token limit\n * - Tracks offset to avoid re-processing messages\n * - Caps new messages per update to prevent context bloat (default: 20)\n *\n * OPTIMIZATION:\n * - Only triggers LLM when crossing threshold or interval boundaries\n * - Processes only NEW messages since last update\n * - Maintains rolling summary (fixed size, not ever-growing)\n * - LLM is instructed to merge and condense, keeping under 2500 tokens\n *\n * INTEGRATION:\n * Works with shortTermMemoryProvider which:\n * - Shows full conversation when < threshold (no summarization needed)\n * - Shows summaries + recent messages when >= threshold (optimized context)\n *\n * This creates an adaptive system that starts with full context and seamlessly\n * transitions to efficient summarization as conversations grow.\n */\nexport const summarizationEvaluator: Evaluator = {\n name: \"MEMORY_SUMMARIZATION\",\n description:\n \"Automatically summarizes conversations to optimize context usage\",\n similes: [\n \"CONVERSATION_SUMMARY\",\n \"CONTEXT_COMPRESSION\",\n \"MEMORY_OPTIMIZATION\",\n ],\n alwaysRun: true,\n\n validate: async (\n runtime: IAgentRuntime,\n message: Memory\n ): Promise<boolean> => {\n // Only run after actual messages (not during generation or on empty messages)\n if (!message.content?.text) {\n return false;\n }\n\n const memoryService = runtime.getService(\"memory\") as MemoryService | null;\n if (!memoryService) {\n return false;\n }\n\n const config = memoryService.getConfig();\n\n // Get dialogue message count (excluding action results)\n const currentDialogueCount = await getDialogueMessageCount(\n runtime,\n message.roomId\n );\n\n // Get existing summary to check if we need initial or update\n const existingSummary = await memoryService.getCurrentSessionSummary(\n message.roomId\n );\n\n if (!existingSummary) {\n // No summary yet - create initial summary when dialogue threshold is reached\n const shouldSummarize =\n currentDialogueCount >= config.shortTermSummarizationThreshold;\n return shouldSummarize;\n } else {\n // Summary exists - check if we have enough new dialogue messages since last update\n const newDialogueCount =\n currentDialogueCount - existingSummary.lastMessageOffset;\n const shouldUpdate =\n newDialogueCount >= config.shortTermSummarizationInterval;\n return shouldUpdate;\n }\n },\n\n handler: async (runtime: IAgentRuntime, message: Memory): Promise<void> => {\n const memoryService = runtime.getService(\"memory\") as MemoryService;\n if (!memoryService) {\n logger.error(\"MemoryService not found\");\n return;\n }\n\n const config = memoryService.getConfig();\n const { roomId } = message;\n\n try {\n logger.info(`Starting summarization for room ${roomId}`);\n\n // Get the current summary (if any)\n const existingSummary = await memoryService.getCurrentSessionSummary(\n roomId\n );\n const lastOffset = existingSummary?.lastMessageOffset || 0;\n\n // Get all messages and filter to dialogue only\n const allMessages = await runtime.getMemories({\n tableName: \"messages\",\n roomId,\n count: 1000, // Get a large batch to ensure we have all relevant messages\n unique: false,\n });\n\n // Filter to dialogue messages only (matching provider logic)\n const allDialogueMessages = allMessages.filter(\n (msg) =>\n !(\n msg.content?.type === \"action_result\" &&\n msg.metadata?.type === \"action_result\"\n ) &&\n (msg.metadata?.type === \"agent_response_message\" ||\n msg.metadata?.type === \"user_message\")\n );\n\n // Get total dialogue message count\n const totalDialogueCount = allDialogueMessages.length;\n\n // Calculate how many new dialogue messages we have since last summary\n const newDialogueCount = totalDialogueCount - lastOffset;\n\n if (newDialogueCount === 0) {\n logger.debug(\"No new dialogue messages to summarize\");\n return;\n }\n\n // Cap the number of new messages to prevent context bloat\n const maxNewMessages = config.summaryMaxNewMessages || 50;\n const messagesToProcess = Math.min(newDialogueCount, maxNewMessages);\n\n // Log if we're hitting the cap\n if (newDialogueCount > maxNewMessages) {\n logger.warn(\n `Capping new dialogue messages at ${maxNewMessages} (${newDialogueCount} available). Oldest messages will be skipped.`\n );\n }\n\n // Sort all dialogue messages by timestamp\n const sortedDialogueMessages = allDialogueMessages.sort(\n (a, b) => (a.createdAt || 0) - (b.createdAt || 0)\n );\n\n // Get new dialogue messages since last offset\n const newDialogueMessages = sortedDialogueMessages.slice(\n lastOffset,\n lastOffset + messagesToProcess\n );\n\n if (newDialogueMessages.length === 0) {\n logger.debug(\"No new dialogue messages retrieved after filtering\");\n return;\n }\n\n // Format messages for summarization\n const formattedMessages = newDialogueMessages\n .map((msg) => {\n const sender =\n msg.entityId === runtime.agentId ? runtime.character.name : \"User\";\n return `${sender}: ${msg.content.text || \"[non-text message]\"}`;\n })\n .join(\"\\n\");\n\n // Generate or update summary using LLM\n const state = await runtime.composeState(message);\n let prompt: string;\n let template: string;\n\n if (existingSummary) {\n // Update existing summary\n template = updateSummarizationTemplate;\n prompt = composePromptFromState({\n state: {\n ...state,\n existingSummary: existingSummary.summary,\n existingTopics: existingSummary.topics?.join(\", \") || \"None\",\n newMessages: formattedMessages,\n },\n template,\n });\n } else {\n // Create initial summary - use ALL dialogue messages for comprehensive initial summary\n const initialMessages = sortedDialogueMessages\n .map((msg) => {\n const sender =\n msg.entityId === runtime.agentId\n ? runtime.character.name\n : \"User\";\n return `${sender}: ${msg.content.text || \"[non-text message]\"}`;\n })\n .join(\"\\n\");\n\n template = initialSummarizationTemplate;\n prompt = composePromptFromState({\n state: {\n ...state,\n recentMessages: initialMessages,\n },\n template,\n });\n }\n\n const response = await runtime.useModel(ModelType.TEXT_LARGE, {\n prompt,\n maxTokens: config.summaryMaxTokens || 2500,\n });\n\n const summaryResult = parseSummaryXML(response);\n\n logger.info(\n `${\n existingSummary ? \"Updated\" : \"Generated\"\n } summary: ${summaryResult.summary.substring(0, 100)}...`\n );\n\n // Calculate new offset based on dialogue messages processed\n const newOffset = lastOffset + newDialogueMessages.length;\n\n // Get timing info\n const firstMessage = newDialogueMessages[0];\n const lastMessage = newDialogueMessages[newDialogueMessages.length - 1];\n\n const startTime = existingSummary\n ? existingSummary.startTime\n : firstMessage?.createdAt && firstMessage.createdAt > 0\n ? new Date(firstMessage.createdAt)\n : new Date();\n const endTime =\n lastMessage?.createdAt && lastMessage.createdAt > 0\n ? new Date(lastMessage.createdAt)\n : new Date();\n\n if (existingSummary) {\n // Update existing summary\n await memoryService.updateSessionSummary(existingSummary.id, roomId, {\n summary: summaryResult.summary,\n messageCount:\n existingSummary.messageCount + newDialogueMessages.length,\n lastMessageOffset: newOffset,\n endTime,\n topics: summaryResult.topics,\n metadata: {\n keyPoints: summaryResult.keyPoints,\n },\n });\n\n logger.info(\n `Updated summary for room ${roomId}: ${newDialogueMessages.length} new dialogue messages processed (offset: ${lastOffset} → ${newOffset})`\n );\n } else {\n // Create new summary - offset is total dialogue count\n await memoryService.storeSessionSummary({\n agentId: runtime.agentId,\n roomId,\n entityId:\n message.entityId !== runtime.agentId ? message.entityId : undefined,\n summary: summaryResult.summary,\n messageCount: totalDialogueCount,\n lastMessageOffset: totalDialogueCount,\n startTime,\n endTime,\n topics: summaryResult.topics,\n metadata: {\n keyPoints: summaryResult.keyPoints,\n },\n });\n\n logger.info(\n `Created new summary for room ${roomId}: ${totalDialogueCount} dialogue messages summarized (offset: 0 → ${totalDialogueCount})`\n );\n }\n\n // Note: We do NOT delete messages - they stay in the database\n // The offset tracks what dialogue messages have been summarized\n } catch (error) {\n logger.error({ error }, \"Error during summarization:\");\n }\n },\n\n examples: [],\n};\n",
10
- "import {\n type IAgentRuntime,\n type Memory,\n type Evaluator,\n logger,\n ModelType,\n composePromptFromState,\n} from \"@elizaos/core\";\nimport { MemoryService } from \"../services/memory-service\";\nimport { LongTermMemoryCategory, type MemoryExtraction } from \"../types/index\";\n\n/**\n * Template for extracting long-term memories using cognitive science memory types\n */\nconst extractionTemplate = `# Task: Extract Long-Term Memory (Strict Criteria)\n\nYou are analyzing a conversation to extract ONLY the most critical, persistent information about the user using cognitive science memory categories.\n\n# Recent Messages\n{{recentMessages}}\n\n# Current Long-Term Memories\n{{existingMemories}}\n\n# Memory Categories (Based on Cognitive Science)\n\n## 1. EPISODIC Memory\nPersonal experiences and specific events with temporal/spatial context.\n**Examples:**\n- \"User completed migration project from MongoDB to PostgreSQL in Q2 2024\"\n- \"User encountered authentication bug in production on March 15th\"\n- \"User had a negative experience with Docker networking in previous job\"\n\n**Requirements:**\n- Must include WHO did WHAT, WHEN/WHERE\n- Must be a specific, concrete event (not a pattern)\n- Must have significant impact or relevance to future work\n\n## 2. SEMANTIC Memory\nGeneral facts, concepts, knowledge, and established truths about the user.\n**Examples:**\n- \"User is a senior backend engineer with 8 years experience\"\n- \"User specializes in distributed systems and microservices architecture\"\n- \"User's primary programming language is TypeScript\"\n- \"User works at Acme Corp as technical lead\"\n\n**Requirements:**\n- Must be factual, timeless information\n- Must be explicitly stated or demonstrated conclusively\n- No speculation or inference from single instances\n- Core identity, expertise, or knowledge only\n\n## 3. PROCEDURAL Memory\nSkills, workflows, methodologies, and how-to knowledge.\n**Examples:**\n- \"User follows strict TDD workflow: write tests first, then implementation\"\n- \"User prefers git rebase over merge to maintain linear history\"\n- \"User's debugging process: check logs → reproduce locally → binary search\"\n- \"User always writes JSDoc comments before implementing functions\"\n\n**Requirements:**\n- Must describe HOW user does something\n- Must be a repeated, consistent pattern (seen 3+ times or explicitly stated as standard practice)\n- Must be a workflow, methodology, or skill application\n- Not one-off preferences\n\n# ULTRA-STRICT EXTRACTION CRITERIA\n\n## ✅ DO EXTRACT (Only These):\n\n**EPISODIC:**\n- Significant completed projects or milestones\n- Important bugs, incidents, or problems encountered\n- Major decisions made with lasting impact\n- Formative experiences that shape future work\n\n**SEMANTIC:**\n- Professional identity (role, title, company)\n- Core expertise and specializations (stated explicitly or demonstrated conclusively)\n- Primary languages, frameworks, or tools (not exploratory use)\n- Established facts about their work context\n\n**PROCEDURAL:**\n- Consistent workflows demonstrated 3+ times or explicitly stated\n- Standard practices user always follows\n- Methodology preferences with clear rationale\n- Debugging, testing, or development processes\n\n## ❌ NEVER EXTRACT:\n\n- **One-time requests or tasks** (e.g., \"can you generate an image\", \"help me debug this\")\n- **Casual conversations** without lasting significance\n- **Exploratory questions** (e.g., \"how does X work?\")\n- **Temporary context** (current bug, today's task)\n- **Preferences from single occurrence** (e.g., user asked for code once)\n- **Social pleasantries** (thank you, greetings)\n- **Testing or experimentation** (trying out a feature)\n- **Common patterns everyone has** (likes clear explanations)\n- **Situational information** (working on feature X today)\n- **Opinions without persistence** (single complaint, isolated praise)\n- **General knowledge** (not specific to user)\n\n# Quality Gates (ALL Must Pass)\n\n1. **Significance Test**: Will this matter in 3+ months?\n2. **Specificity Test**: Is this concrete and actionable?\n3. **Evidence Test**: Is there strong evidence (3+ instances OR explicit self-identification)?\n4. **Uniqueness Test**: Is this specific to THIS user (not generic)?\n5. **Confidence Test**: Confidence must be >= 0.85 (be VERY conservative)\n6. **Non-Redundancy Test**: Does this add NEW information not in existing memories?\n\n# Confidence Scoring (Be Conservative)\n\n- **0.95-1.0**: User explicitly stated as core identity/practice AND demonstrated multiple times\n- **0.85-0.94**: User explicitly stated OR consistently demonstrated 5+ times\n- **0.75-0.84**: Strong pattern (3-4 instances) with supporting context\n- **Below 0.75**: DO NOT EXTRACT (insufficient evidence)\n\n# Critical Instructions\n\n1. **Default to NOT extracting** - When in doubt, skip it\n2. **Require overwhelming evidence** - One or two mentions is NOT enough\n3. **Focus on what's PERSISTENT** - Not what's temporary or situational\n4. **Verify against existing memories** - Don't duplicate or contradict\n5. **Maximum 2-3 extractions per run** - Quality over quantity\n\n**If there are no qualifying facts (which is common), respond with <memories></memories>**\n\n# Response Format\n\n<memories>\n <memory>\n <category>semantic</category>\n <content>User is a senior TypeScript developer with 8 years of backend experience</content>\n <confidence>0.95</confidence>\n </memory>\n <memory>\n <category>procedural</category>\n <content>User follows TDD workflow: writes tests before implementation, runs tests after each change</content>\n <confidence>0.88</confidence>\n </memory>\n <memory>\n <category>episodic</category>\n <content>User led database migration from MongoDB to PostgreSQL for payment system in Q2 2024</content>\n <confidence>0.92</confidence>\n </memory>\n</memories>`;\n\n/**\n * Parse XML memory extraction response\n */\nfunction parseMemoryExtractionXML(xml: string): MemoryExtraction[] {\n const memoryMatches = xml.matchAll(\n /<memory>[\\s\\S]*?<category>(.*?)<\\/category>[\\s\\S]*?<content>(.*?)<\\/content>[\\s\\S]*?<confidence>(.*?)<\\/confidence>[\\s\\S]*?<\\/memory>/g\n );\n\n const extractions: MemoryExtraction[] = [];\n\n for (const match of memoryMatches) {\n const category = match[1].trim() as LongTermMemoryCategory;\n const content = match[2].trim();\n const confidence = parseFloat(match[3].trim());\n\n // Validate category\n if (!Object.values(LongTermMemoryCategory).includes(category)) {\n logger.warn(`Invalid memory category: ${category}`);\n continue;\n }\n\n if (content && !isNaN(confidence)) {\n extractions.push({ category, content, confidence });\n }\n }\n\n return extractions;\n}\n\n/**\n * Long-term Memory Extraction Evaluator\n *\n * Analyzes conversations to extract persistent facts about users that should be remembered\n * across all future conversations.\n */\nexport const longTermExtractionEvaluator: Evaluator = {\n name: \"LONG_TERM_MEMORY_EXTRACTION\",\n description: \"Extracts long-term facts about users from conversations\",\n similes: [\"MEMORY_EXTRACTION\", \"FACT_LEARNING\", \"USER_PROFILING\"],\n alwaysRun: true,\n\n validate: async (\n runtime: IAgentRuntime,\n message: Memory\n ): Promise<boolean> => {\n // Only run on user messages (not agent's own)\n if (message.entityId === runtime.agentId) {\n return false;\n }\n\n if (!message.content?.text) {\n return false;\n }\n\n const memoryService = runtime.getService(\"memory\") as MemoryService | null;\n if (!memoryService) {\n return false;\n }\n\n const config = memoryService.getConfig();\n if (!config.longTermExtractionEnabled) {\n logger.debug(\"Long-term memory extraction is disabled\");\n return false;\n }\n\n // Count total messages from this entity in this room\n const currentMessageCount = await runtime.countMemories(\n message.roomId,\n false,\n \"messages\"\n );\n\n const shouldRun = await memoryService.shouldRunExtraction(\n message.entityId,\n message.roomId,\n currentMessageCount\n );\n return shouldRun;\n },\n\n handler: async (runtime: IAgentRuntime, message: Memory): Promise<void> => {\n const memoryService = runtime.getService(\"memory\") as MemoryService;\n if (!memoryService) {\n logger.error(\"MemoryService not found\");\n return;\n }\n\n const config = memoryService.getConfig();\n const { entityId, roomId } = message;\n\n try {\n logger.info(`Extracting long-term memories for entity ${entityId}`);\n\n // Get recent conversation context\n const recentMessages = await runtime.getMemories({\n tableName: \"messages\",\n roomId,\n count: 20,\n unique: false,\n });\n\n const formattedMessages = recentMessages\n .sort((a, b) => (a.createdAt || 0) - (b.createdAt || 0))\n .map((msg) => {\n const sender =\n msg.entityId === runtime.agentId ? runtime.character.name : \"User\";\n return `${sender}: ${msg.content.text || \"[non-text message]\"}`;\n })\n .join(\"\\n\");\n\n // Get existing long-term memories\n const existingMemories = await memoryService.getLongTermMemories(\n entityId,\n undefined,\n 30\n );\n const formattedExisting =\n existingMemories.length > 0\n ? existingMemories\n .map(\n (m) =>\n `[${m.category}] ${m.content} (confidence: ${m.confidence})`\n )\n .join(\"\\n\")\n : \"None yet\";\n\n // Generate extraction using LLM\n const state = await runtime.composeState(message);\n const prompt = composePromptFromState({\n state: {\n ...state,\n recentMessages: formattedMessages,\n existingMemories: formattedExisting,\n },\n template: extractionTemplate,\n });\n\n const response = await runtime.useModel(ModelType.TEXT_LARGE, {\n prompt,\n });\n\n const extractions = parseMemoryExtractionXML(response);\n\n logger.info(`Extracted ${extractions.length} long-term memories`);\n\n // Store each extracted memory\n for (const extraction of extractions) {\n // Apply stricter confidence threshold (0.85 minimum)\n if (\n extraction.confidence >=\n Math.max(config.longTermConfidenceThreshold, 0.85)\n ) {\n await memoryService.storeLongTermMemory({\n agentId: runtime.agentId,\n entityId,\n category: extraction.category,\n content: extraction.content,\n confidence: extraction.confidence,\n source: \"conversation\",\n metadata: {\n roomId,\n extractedAt: new Date().toISOString(),\n },\n });\n\n logger.info(\n `Stored long-term memory: [${\n extraction.category\n }] ${extraction.content.substring(0, 50)}...`\n );\n } else {\n logger.debug(\n `Skipped low-confidence memory: ${\n extraction.content\n } (confidence: ${extraction.confidence}, threshold: ${Math.max(\n config.longTermConfidenceThreshold,\n 0.85\n )})`\n );\n }\n }\n\n // Update the extraction checkpoint after successful extraction\n const currentMessageCount = await runtime.countMemories(\n roomId,\n false,\n \"messages\"\n );\n await memoryService.setLastExtractionCheckpoint(\n entityId,\n roomId,\n currentMessageCount\n );\n logger.debug(\n `Updated extraction checkpoint to ${currentMessageCount} for entity ${entityId} in room ${roomId}`\n );\n } catch (error) {\n logger.error({ error }, \"Error during long-term memory extraction:\");\n }\n },\n\n examples: [],\n};\n",
11
- "import type { UUID } from '@elizaos/core';\n\n/**\n * Categories of long-term memory based on cognitive science\n * \n * Following the widely accepted classification of human long-term memory:\n * - EPISODIC: Personal experiences and events (what happened, when, where)\n * - SEMANTIC: Facts, concepts, and knowledge (what things mean)\n * - PROCEDURAL: Skills and how-to knowledge (how to do things)\n */\nexport enum LongTermMemoryCategory {\n EPISODIC = 'episodic', // Specific events, experiences, and interactions (e.g., \"User worked on bug #123 last Tuesday\")\n SEMANTIC = 'semantic', // General facts, concepts, and knowledge (e.g., \"User is a Python developer\", \"User prefers async/await\")\n PROCEDURAL = 'procedural', // Skills, workflows, and how-to knowledge (e.g., \"User follows TDD workflow\", \"User uses git rebase instead of merge\")\n}\n\n/**\n * Long-term memory entry\n */\nexport interface LongTermMemory {\n id: UUID;\n agentId: UUID;\n entityId: UUID; // The user/entity this memory is about\n category: LongTermMemoryCategory;\n content: string; // The actual memory content\n metadata?: Record<string, unknown>; // Additional structured data\n embedding?: number[]; // Vector embedding for semantic search\n confidence?: number; // Confidence score (0-1)\n source?: string; // Where this memory came from (conversation, manual, etc.)\n createdAt: Date;\n updatedAt: Date;\n lastAccessedAt?: Date;\n accessCount?: number;\n similarity?: number; // Optional similarity score from vector search\n}\n\n/**\n * Short-term memory session summary\n */\nexport interface SessionSummary {\n id: UUID;\n agentId: UUID;\n roomId: UUID;\n entityId?: UUID; // Optional: specific user in the session\n summary: string; // The summarized conversation\n messageCount: number; // Number of messages summarized\n lastMessageOffset: number; // Index of last summarized message (for pagination)\n startTime: Date; // Timestamp of first message\n endTime: Date; // Timestamp of last message\n topics?: string[]; // Main topics discussed\n metadata?: Record<string, unknown>;\n embedding?: number[]; // Vector embedding of the summary\n createdAt: Date;\n updatedAt: Date; // Track when summary was last updated\n}\n\n/**\n * Configuration for memory plugin\n */\nexport interface MemoryConfig {\n // Short-term memory settings\n shortTermSummarizationThreshold: number; // Messages count before summarization\n shortTermRetainRecent: number; // Number of recent messages to keep after summarization\n shortTermSummarizationInterval: number; // Update summary every N messages after threshold (e.g., 10)\n\n // Long-term memory settings\n longTermExtractionEnabled: boolean;\n longTermVectorSearchEnabled: boolean;\n longTermConfidenceThreshold: number; // Minimum confidence to store\n longTermExtractionThreshold: number; // Minimum messages before starting extraction (default 20)\n longTermExtractionInterval: number; // Run extraction every N messages after threshold (e.g., 5, 10, 15...)\n\n // Summarization settings\n summaryModelType?: string;\n summaryMaxTokens?: number;\n summaryMaxNewMessages?: number; // Max new messages to include in update (prevents context bloat)\n}\n\n/**\n * Memory extraction result from evaluator\n */\nexport interface MemoryExtraction {\n category: LongTermMemoryCategory;\n content: string;\n confidence: number;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Summary generation result\n */\nexport interface SummaryResult {\n summary: string;\n topics: string[];\n keyPoints: string[];\n}\n",
12
- "import {\n type IAgentRuntime,\n type Memory,\n type Provider,\n type State,\n logger,\n addHeader,\n} from '@elizaos/core';\nimport { MemoryService } from '../services/memory-service';\n\n/**\n * Long-term Memory Provider\n *\n * Provides persistent facts about the user that have been learned across\n * all conversations. This includes:\n * - User identity and roles\n * - Domain expertise\n * - Preferences\n * - Goals and projects\n * - Custom definitions\n * - Behavioral patterns\n *\n * This provider enriches the context with relevant long-term information\n * to make the agent's responses more personalized and contextually aware.\n */\nexport const longTermMemoryProvider: Provider = {\n name: 'LONG_TERM_MEMORY',\n description: 'Persistent facts and preferences about the user',\n position: 50, // Run early to establish user context\n\n get: async (runtime: IAgentRuntime, message: Memory, _state: State) => {\n try {\n const memoryService = runtime.getService('memory') as MemoryService | null;\n if (!memoryService) {\n return {\n data: { memories: [] },\n values: { longTermMemories: '' },\n text: '',\n };\n }\n\n const { entityId } = message;\n\n // Skip for agent's own messages\n if (entityId === runtime.agentId) {\n return {\n data: { memories: [] },\n values: { longTermMemories: '' },\n text: '',\n };\n }\n\n // Get long-term memories for this entity\n const memories = await memoryService.getLongTermMemories(entityId, undefined, 25);\n\n if (memories.length === 0) {\n return {\n data: { memories: [] },\n values: { longTermMemories: '' },\n text: '',\n };\n }\n\n // Format memories using the service's built-in formatter\n const formattedMemories = await memoryService.getFormattedLongTermMemories(entityId);\n\n const text = addHeader('# What I Know About You', formattedMemories);\n\n // Create a summary of memory categories for quick reference\n const categoryCounts = new Map<string, number>();\n for (const memory of memories) {\n const count = categoryCounts.get(memory.category) || 0;\n categoryCounts.set(memory.category, count + 1);\n }\n\n const categoryList = Array.from(categoryCounts.entries())\n .map(([cat, count]) => `${cat}: ${count}`)\n .join(', ');\n\n return {\n data: {\n memories,\n categoryCounts: Object.fromEntries(categoryCounts),\n },\n values: {\n longTermMemories: text,\n memoryCategories: categoryList,\n },\n text,\n };\n } catch (error) {\n logger.error({ error }, 'Error in longTermMemoryProvider:');\n return {\n data: { memories: [] },\n values: { longTermMemories: '' },\n text: '',\n };\n }\n },\n};\n",
13
- "import {\n type IAgentRuntime,\n type Memory,\n type Provider,\n type State,\n addHeader,\n logger,\n} from '@elizaos/core';\nimport { MemoryService } from '../services/memory-service';\n\n/**\n * Context Summary Provider\n *\n * Provides summarized context from previous conversations.\n * Returns session summaries with and without topics for flexible usage.\n *\n * Values returned:\n * - sessionSummaries: Summary text only (without topics)\n * - sessionSummariesWithTopics: Summary text with topics included\n */\nexport const contextSummaryProvider: Provider = {\n name: 'SUMMARIZED_CONTEXT',\n description: 'Provides summarized context from previous conversations',\n position: 96,\n\n get: async (runtime: IAgentRuntime, message: Memory, _state: State) => {\n try {\n const memoryService = runtime.getService('memory') as MemoryService | null;\n const { roomId } = message;\n\n // If no memory service, return empty\n if (!memoryService) {\n return {\n data: {\n summary: null,\n },\n values: {\n sessionSummaries: '',\n sessionSummariesWithTopics: '',\n },\n text: '',\n };\n }\n\n // Get current session summary\n const currentSummary = await memoryService.getCurrentSessionSummary(roomId);\n\n if (!currentSummary) {\n return {\n data: {\n summary: null,\n },\n values: {\n sessionSummaries: '',\n sessionSummariesWithTopics: '',\n },\n text: '',\n };\n }\n\n // Format summary without topics\n const messageRange = `${currentSummary.messageCount} messages`;\n const timeRange = new Date(currentSummary.startTime).toLocaleDateString();\n\n let summaryOnly = `**Previous Conversation** (${messageRange}, ${timeRange})\\n`;\n summaryOnly += currentSummary.summary;\n\n // Format summary with topics\n let summaryWithTopics = summaryOnly;\n if (currentSummary.topics && currentSummary.topics.length > 0) {\n summaryWithTopics += `\\n*Topics: ${currentSummary.topics.join(', ')}*`;\n }\n\n const sessionSummaries = addHeader('# Conversation Summary', summaryOnly);\n const sessionSummariesWithTopics = addHeader('# Conversation Summary', summaryWithTopics);\n\n return {\n data: {\n summary: currentSummary,\n },\n values: {\n sessionSummaries,\n sessionSummariesWithTopics,\n },\n text: sessionSummariesWithTopics,\n };\n } catch (error) {\n logger.error({ error }, 'Error in contextSummaryProvider:');\n return {\n data: {\n summary: null,\n },\n values: {\n sessionSummaries: '',\n sessionSummariesWithTopics: '',\n },\n text: '',\n };\n }\n },\n};\n",
14
- "import type { Plugin } from '@elizaos/core';\nimport { MemoryService } from './services/memory-service';\nimport { summarizationEvaluator } from './evaluators/summarization';\nimport { longTermExtractionEvaluator } from './evaluators/long-term-extraction';\n// import { shortTermMemoryProvider } from './providers/short-term-memory';\nimport { longTermMemoryProvider } from './providers/long-term-memory';\nimport { contextSummaryProvider } from './providers/context-summary';\n// import { rememberAction } from './actions/remember';\nimport * as schema from './schemas/index';\n\nexport * from './types/index';\nexport * from './schemas/index';\nexport { MemoryService } from './services/memory-service';\nexport { contextSummaryProvider } from './providers/context-summary';\nexport { longTermMemoryProvider } from './providers/long-term-memory';\n\n/**\n * Memory Plugin\n *\n * Advanced memory management plugin that provides:\n *\n * **Short-term Memory (Conversation Summarization)**:\n * - Automatically summarizes long conversations to reduce context size\n * - Retains recent messages while archiving older ones as summaries\n * - Configurable thresholds for when to summarize\n *\n * **Long-term Memory (Persistent Facts)**:\n * - Extracts and stores persistent facts about users\n * - Categorizes information (identity, expertise, preferences, etc.)\n * - Provides context-aware user profiles across all conversations\n *\n * **Components**:\n * - `MemoryService`: Manages all memory operations\n * - Evaluators: Process conversations to create summaries and extract facts\n * - Providers: Inject memory context into conversations\n * - Actions: Allow manual memory storage via user commands\n *\n * **Configuration** (via environment variables):\n * - `MEMORY_SUMMARIZATION_THRESHOLD`: Messages before summarization (default: 50)\n * - `MEMORY_RETAIN_RECENT`: Recent messages to keep (default: 10)\n * - `MEMORY_LONG_TERM_ENABLED`: Enable long-term extraction (default: true)\n * - `MEMORY_CONFIDENCE_THRESHOLD`: Minimum confidence to store (default: 0.7)\n *\n * **Database Tables**:\n * - `long_term_memories`: Persistent user facts\n * - `session_summaries`: Conversation summaries\n * - `memory_access_logs`: Optional usage tracking\n */\nexport const memoryPlugin: Plugin = {\n name: 'memory',\n description:\n 'Advanced memory management with conversation summarization and long-term persistent memory',\n\n services: [MemoryService],\n\n evaluators: [summarizationEvaluator, longTermExtractionEvaluator],\n\n providers: [\n longTermMemoryProvider,\n contextSummaryProvider,\n ],\n\n // actions: [rememberAction],\n\n // Export schema for dynamic migrations\n schema,\n};\n\nexport default memoryPlugin;\n"
15
- ],
16
- "mappings": "iIAAA,kBAEE,aAEA,sBAGF,aAAS,SAAI,UAAK,SAAM,qBAAK,UAAgB,2GCP7C,cAAS,oBACT,kBACE,WACA,aACA,YACA,WACA,WACA,aACA,eACA,4BAOK,IAAM,EAAmB,GAC9B,qBACA,CACE,GAAI,EAAQ,KAAM,CAAE,OAAQ,EAAG,CAAC,EAAE,WAAW,EAC7C,QAAS,EAAQ,WAAY,CAAE,OAAQ,EAAG,CAAC,EAAE,QAAQ,EACrD,SAAU,EAAQ,YAAa,CAAE,OAAQ,EAAG,CAAC,EAAE,QAAQ,EACvD,SAAU,EAAK,UAAU,EAAE,QAAQ,EACnC,QAAS,EAAK,SAAS,EAAE,QAAQ,EACjC,SAAU,GAAM,UAAU,EAC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KAAM,CACJ,QAAS,IACX,EACA,OAAQ,CACN,iBAAkB,GAClB,2BAA4B,EAC9B,EACA,KAAM,EACR,EAIF,IAAM,EAAe,GAAG,EAAe,wBACjC,EAAY,IAAI,KAAK,EAAe,SAAS,EAAE,mBAAmB,EAEpE,EAAc,8BAA8B,MAAiB;AAAA,EACjE,GAAe,EAAe,QAG9B,IAAI,EAAoB,EACxB,GAAI,EAAe,QAAU,EAAe,OAAO,OAAS,EAC1D,GAAqB;AAAA,WAAc,EAAe,OAAO,KAAK,IAAI,KAGpE,IAAM,EAAmB,GAAU,yBAA0B,CAAW,EAClE,EAA6B,GAAU,yBAA0B,CAAiB,EAExF,MAAO,CACL,KAAM,CACJ,QAAS,CACX,EACA,OAAQ,CACN,mBACA,4BACF,EACA,KAAM,CACR,EACA,MAAO,EAAO,CAEd,OADA,GAAO,MAAM,CAAE,OAAM,EAAG,kCAAkC,EACnD,CACL,KAAM,CACJ,QAAS,IACX,EACA,OAAQ,CACN,iBAAkB,GAClB,2BAA4B,EAC9B,EACA,KAAM,EACR,GAGN,ECpDO,IAAM,GAAuB,CAClC,KAAM,SACN,YACE,6FAEF,SAAU,CAAC,CAAa,EAExB,WAAY,CAAC,GAAwB,EAA2B,EAEhE,UAAW,CACT,EACA,CACF,EAKA,QACF,EAEe",
17
- "debugId": "63795FFE83D49E7A64756E2164756E21",
18
- "names": []
19
- }
@@ -1,2 +0,0 @@
1
- export * from '../index';
2
- export { default } from '../index';
@@ -1,2 +0,0 @@
1
- export * from '../index';
2
- export { default } from '../index';