memories-lite 0.9.5 → 0.99.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,37 +1,76 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getMemoriesAsSystem = exports.getMemoriesAsPrefix = exports.MEMORY_STRING_SYSTEM_OLD = exports.MEMORY_STRING_PREFIX = exports.MEMORY_STRING_SYSTEM = exports.MemoryUpdateSchema = exports.FactRetrievalSchema_extended = exports.FactRetrievalSchema_simple = void 0;
3
+ exports.getMemoriesAsSystem = exports.getMemoriesAsPrefix = exports.MEMORY_STRING_PREFIX = exports.MEMORY_STRING_SYSTEM = exports.MemoryUpdateSchema = exports.FactRetrievalSchema_extended = exports.FactRetrievalSchema_simple = exports.DEFAULT_DISCUSSION_PROMPT = exports.DiscussionSynthesisSchema = void 0;
4
+ exports.getDiscussionSynthesisMessages = getDiscussionSynthesisMessages;
4
5
  exports.getFactRetrievalMessages = getFactRetrievalMessages;
5
6
  exports.getUpdateMemoryMessages = getUpdateMemoryMessages;
6
7
  exports.parseMessages = parseMessages;
7
8
  exports.removeCodeBlocks = removeCodeBlocks;
8
9
  const zod_1 = require("zod");
9
- // Define Zod schema for fact retrieval output
10
+ // ══════════════════════════════════════════════════════════════════════════════
11
+ // DISCUSSION SYNTHESIS - Nouveau système de mémoire
12
+ // ══════════════════════════════════════════════════════════════════════════════
13
+ /**
14
+ * Schema pour la synthèse de discussion
15
+ * Produit un titre court et une synthèse opérationnelle
16
+ */
17
+ exports.DiscussionSynthesisSchema = zod_1.z.object({
18
+ title: zod_1.z.string().describe("Titre court et descriptif (6-10 mots)"),
19
+ summary: zod_1.z.string().describe("Synthèse opérationnelle des points clés (50-100 mots)")
20
+ });
21
+ /**
22
+ * Prompt par défaut pour la synthèse de discussion
23
+ * Peut être remplacé via capturePrompt dans AddMemoryOptions
24
+ */
25
+ exports.DEFAULT_DISCUSSION_PROMPT = `Tu es un expert en synthèse opérationnelle.
26
+
27
+ À partir de cette discussion, génère :
28
+ 1. TITRE: Un titre court et descriptif (6-10 mots) qui capture l'essence de la demande
29
+ 2. SUMMARY: Les points clés du chemin de résolution (50-100 mots)
30
+
31
+ Cette synthèse servira à retrouver et réappliquer ce pattern de résolution similaire.
32
+ Utilise la même langue que la discussion.
33
+
34
+ Discussion à synthétiser:
35
+ `;
36
+ /**
37
+ * Génère les messages pour la synthèse de discussion
38
+ * @param discussion - Contenu de la discussion formatée
39
+ * @param capturePrompt - Prompt custom optionnel (remplace DEFAULT_DISCUSSION_PROMPT)
40
+ * @returns [systemPrompt, userPrompt]
41
+ */
42
+ function getDiscussionSynthesisMessages(discussion, capturePrompt) {
43
+ const systemPrompt = capturePrompt || exports.DEFAULT_DISCUSSION_PROMPT;
44
+ return [systemPrompt, discussion];
45
+ }
46
+ // ══════════════════════════════════════════════════════════════════════════════
47
+ // @deprecated - Ancien système de capture (todo, factual)
48
+ // Ces exports sont conservés pour compatibilité mais ne doivent plus être utilisés
49
+ // ══════════════════════════════════════════════════════════════════════════════
50
+ /**
51
+ * @deprecated Use DiscussionSynthesisSchema instead
52
+ */
10
53
  exports.FactRetrievalSchema_simple = zod_1.z.object({
11
54
  facts: zod_1.z
12
55
  .array(zod_1.z.string())
13
56
  .describe("An array of distinct facts extracted from the conversation."),
14
57
  });
15
- //1. **Factual memory** – stable facts & preferences
16
- //2. **Episodic memory** time‑stamped events / interactions
17
- //3. **Procedural memory** step‑by‑step know‑how
18
- //4. **Todo memory** – explicit user tasks to remember
19
- //
58
+ /**
59
+ * @deprecated Use DiscussionSynthesisSchema instead
60
+ * Types todo et factual supprimés - seul assistant_preference reste pour compatibilité
61
+ */
20
62
  exports.FactRetrievalSchema_extended = zod_1.z.object({
21
63
  facts: zod_1.z
22
64
  .array(zod_1.z.object({
23
65
  fact: zod_1.z.string().describe("The fact extracted from the conversation."),
24
66
  existing: zod_1.z.boolean().describe("Whether the fact is already present"),
25
- type: zod_1.z.enum(["assistant_preference", "factual", "episodic", "procedural", "todo"])
26
- .describe(`The type of the fact.
27
- Use 'assistant_preference' for Assistant behavior preferences (style/language/constraints/commands).
28
- Use 'episodic' always for time-based events.
29
- Use 'procedural' for how-to/business questions (e.g., « je veux résilier un bail, comment faire ? »).
30
- Use 'todo' ONLY if the user explicitly asks to save/keep as a todo (e.g., « garde/enregistre en todo », « ajoute un todo »). Do not infer todos.
31
- `),
67
+ type: zod_1.z.enum(["assistant_preference"])
68
+ .describe(`The type of the fact. Only 'assistant_preference' is supported.`),
32
69
  }))
33
70
  });
34
- // Define Zod schema for memory update output
71
+ /**
72
+ * @deprecated Memory updates are disabled - use capture() for new memories
73
+ */
35
74
  exports.MemoryUpdateSchema = zod_1.z.object({
36
75
  memory: zod_1.z
37
76
  .array(zod_1.z.strictObject({
@@ -48,18 +87,11 @@ exports.MemoryUpdateSchema = zod_1.z.object({
48
87
  .string()
49
88
  .describe("The reason why you selected this event."),
50
89
  type: zod_1.z
51
- .enum(["factual", "episodic", "todo", "procedural", "assistant_preference"])
52
- .describe("Type of the memory. Use 'assistant_preference' for Assistant behavior preferences, 'procedural' for all business processes."),
90
+ .enum(["assistant_preference"])
91
+ .describe("Type of the memory. Only 'assistant_preference' is supported."),
53
92
  }))
54
93
  .describe("An array representing the state of memory items after processing new facts."),
55
94
  });
56
- /**
57
- * Practical Application:
58
- *
59
- * If the task is "factual" (e.g., "Where do I live?") → retrieve factual memory.
60
- * If the task is temporal or event-based ("What was I doing yesterday?") → retrieve episodic memory.
61
- * If the task is a user task/reminder (e.g., "Add a reminder to call the bank tomorrow") → retrieve todo memory.
62
- */
63
95
  exports.MEMORY_STRING_SYSTEM = `# DIRECTIVES FOR MEMORIES
64
96
  - Information stored in memory is always enclosed within the <memories> tag.
65
97
  - Prioritize the latest user message over memories (the user's current question is authoritative).
@@ -69,44 +101,37 @@ exports.MEMORY_STRING_SYSTEM = `# DIRECTIVES FOR MEMORIES
69
101
  - By default, do not reference this section or the memories in your response.
70
102
  - Use memories only to guide reasoning; do not respond to the memories themselves.`;
71
103
  exports.MEMORY_STRING_PREFIX = "Use these contextual memories to guide your response. Prioritize the user's question. Ignore irrelevant memories.";
72
- exports.MEMORY_STRING_SYSTEM_OLD = `# USER AND MEMORIES PREFERENCES:
73
- - Utilize the provided memories to guide your responses.
74
- - Disregard any memories that are not relevant.
75
- - By default, do not reference this section or the memories in your response.
76
- `;
77
- // Deprecated: getFactRetrievalMessages_O removed in favor of getFactRetrievalMessages
104
+ /**
105
+ * @deprecated Use getDiscussionSynthesisMessages instead
106
+ * Cette fonction est conservée pour compatibilité avec l'ancien système
107
+ */
78
108
  function getFactRetrievalMessages(parsedMessages, customRules = "", defaultLanguage = "French") {
79
109
  const injectCustomRules = (customRules) => customRules ? `\n# PRE-EXISTING FACTS\n${customRules}` : "";
80
- const systemPrompt = `You are a Personal Information Organizer, specialized in accurately storing facts, user memories, and preferences. You are also an expert in job tasks extraction.
110
+ const systemPrompt = `You are a Personal Information Organizer, specialized in extracting and structuring user facts and preferences for AI personalization. You also handle explicit task extraction (todos only).
81
111
 
82
112
  Filter content before extracting triplets:
83
- - Relevance: keep only statements directly about the user (preferences, identity, actions, experiences) or explicit tasks; drop weather/small talk.
113
+ - Relevance: keep only statements directly about the user (preferences with the AI, identity relevant to personalization, actions/experiences that affect responses) or explicit todos; drop weather/small talk.
84
114
  - Disinterest: if the user rejects the topic (e.g., "cette information ne m'intéresse pas", "not interested"), return {"facts":[]}.
85
- - Business/procedures: if the user asks about processes, regulations, or third-party policies (company workflows, public steps, legal actions), classify as "procedural". This applies even if personal pronouns are used.
86
- - Action requests to the assistant (find/search/locate/call/email/book/reserve) are NOT preferences. Unless the user explicitly asks to save as a todo, do not create a memory for such requests (return {"facts":[]}).
87
-
88
- You must strictly extract {Subject, Predicate, Object} triplets by following these rules (max 12 triplets):
115
+ - Ignore business/process/regulation/company-policy content entirely (no extraction, no memory).
116
+ - Action requests to the assistant (find/search/locate/call/email/book/reserve) are NOT preferences. Unless the user explicitly asks to save as a todo, return {"facts":[]}.
117
+
118
+ You must strictly extract {Subject, Predicate, Object} triplets (max 12):
89
119
  1. Identify named entities, preferences, and meaningful user-related concepts:
90
- - Extract triplets that describe facts *about the user* based on their statements, covering areas like preferences, beliefs, actions, experiences, learning, identity, work, or relationships (e.g., "I love working").
91
- - Apply explicit, precise, and unambiguous predicates (e.g., "owns", "is located at", "is a", "has function", "causes", etc.).
92
- - Determine the triplet type ("assistant_preference", "procedural", "episodic", "factual", "todo"):
93
- - "assistant_preference": ONLY when the user specifies response style/language/format or interaction constraints.
94
- - "procedural": for how-to/business questions (e.g., « je veux résilier un bail, comment faire ? »).
95
- - "todo": ONLY if the user explicitly requests to save/keep as todo (e.g., « garde/enregistre en todo », « ajoute un todo »). Never infer todo from intent alone.
96
- - If multiple types apply (excluding assistant_preference and todo rules above), priority: procedural > episodic > factual.
97
- - "episodic" If a fact depends on a temporal, situational, or immediate personal context, then that fact AND ALL OF ITS sub-facts MUST be classified as episodic.
98
- - "procedural" for business processes (e.g., "Looking for customer John Doe address", "How to create a new contract").
99
- - "factual" for stable user data (except procedural that prevails).
100
-
101
- - Eliminate introductions, sub-facts, detailed repetitive elements, stylistic fillers, or vague statements. General facts always takes precedence over multiple sub-facts (signal vs noise).
102
- - The query intention can include specific preferences about how the Assistant should respond (e.g., "answer concisely", "explain in detail").
103
- - Compress each OUTPUT (fact and reason) 10 words.
104
- - Do not include type labels or annotations inside the fact text (e.g., avoid "(todo)", "(procedural)"). Use the separate 'type' field only.
105
- - DO NOT infer personal facts from third-party informations.
106
- - Treat "**ASSISTANT**:" as responses to enrich context of your reasoning process about the USER query.
107
- 2. Use pronoun "I" instead of "The user" in the subject of the triplet.
108
- 3. Do not output any facts already present in section # PRE-EXISTING FACTS.
109
- - If you find facts already present in section # PRE-EXISTING FACTS, use field "existing" to store them.
120
+ - Extract triplets *about the user* that help AI personalization (preferences, stable facts, explicit todos).
121
+ - Use explicit, precise, unambiguous predicates (e.g., "prefers", "speaks", "is a", "uses").
122
+ - Triplet type {"assistant_preference","factual","todo"} only:
123
+ - "assistant_preference": response style/language/format or interaction constraints.
124
+ - "factual": stable user data relevant to personalization (e.g., language, timezone, tools used).
125
+ - "todo": ONLY if the user explicitly asks to save/keep as todo. Never infer from intent alone.
126
+ - Remove introductions, sub-facts, repetitions, fillers, vague statements; prefer the general fact over details.
127
+ - Each triplet (S,P,O) 10 words total.
128
+ - Do not include type labels inside fact text; use the 'type' field only.
129
+ - Do not infer personal facts from third-party information.
130
+ - Treat "**ASSISTANT**:" as context only; never as a fact source.
131
+
132
+ 2. Use pronoun "I" as the Subject (not "The user").
133
+ 3. Do not output facts already in # PRE-EXISTING FACTS.
134
+ - If found, put them in "existing" (list of matched facts or IDs).
110
135
 
111
136
  ${injectCustomRules(customRules)}
112
137
 
@@ -120,52 +145,75 @@ Remember the following:
120
145
  const userPrompt = `Extract exact facts from the following conversation in the same language as the user. If the user expresses disinterest or asks to ignore the topic, return {"facts":[]}. Limit output to ≤ 12 triplets and strictly follow the JSON schema.\n${parsedMessages}`;
121
146
  return [systemPrompt, userPrompt];
122
147
  }
148
+ /**
149
+ * @deprecated Memory updates are disabled by config
150
+ */
123
151
  function getUpdateMemoryMessages(retrievedOldMemory, newRetrievedFacts, defaultLanguage = "French", userInstruction) {
124
152
  const serializeFacts = (facts) => {
125
153
  if (facts.length === 0)
126
154
  return "";
127
155
  if (facts[0].fact) {
128
- return facts.map((elem) => `* ${elem.fact} (${elem.type})`).join("\n");
156
+ return facts.map((elem) => `- "${elem.fact}" (type:${elem.type})`).join("\n");
129
157
  }
130
158
  else {
131
159
  return facts.join("\n");
132
160
  }
133
161
  };
134
162
  const serializeMemory = (memory) => {
135
- return memory.map((elem) => `* ${elem.id} - ${elem.text}`).join("\n");
163
+ return memory.map((elem) => `- "${elem.text}" (id:${elem.id})`).join("\n");
136
164
  };
137
165
  return `ROLE:
138
- You are a smart memory manager dedicated on users. You are expert in semantic comparison, RDF inference and boolean logic.
166
+ You are the Memory Manager module of an AI assistant. You are specialized in semantic reasoning, fact consistency, and memory lifecycle operations.
167
+ Your job is to maintain a coherent, contradiction-free knowledge base (long-term memory) of user facts.
139
168
 
140
169
  MISSION:
141
- For each new user fact from "# New Retrieved Facts", you MUSTmerge it into "# Current Memory" by assigning exactly ONE of: ADD, DELETE, UPDATE, or NONE:
142
-
143
- 1. Semantic compare each new facts to memory, for each fact:
144
- - If the new fact **contradicts**, **negates**, **reverses**, **retracts**, or **cancels** the meaning of a memory entry THEN DELETE.
145
- ⛔ You MUST NOT treat this as an UPDATE. Contradictions invalidate the original fact.
146
- - Else If the new fact **specializes** the previous fact (adds precision, extends the detail without changing the core meaning) THEN UPDATE.
147
- - Else If it is **equivalent** → NONE.
148
- - Else If it is **completely new** → ADD.
149
- - Else (default) NONE.
150
- 2. Event mapping from user intent (imperatives prevail):
151
- - DELETE if user asks to remove.
152
- - UPDATE if user asks to change: "mets à jour", "modifie", "corrige", "update", "change", "replace".
153
- - ADD if user asks to add: "ajoute", "add" (including explicit todo adds).
154
- 3. If no match is found:
155
- - Generate a new ID for ADD
156
- 5. Assign the action (IF you can't find a match, restart the process)
170
+ Given:
171
+ 1. A set of **Current Memory** facts (each with unique ID and textual content).
172
+ 2. A set of **New Retrieved Facts** from the user or external sources.
173
+ 3. (Optional) A **User Instruction** indicating explicit intent (add, modify, delete).
174
+
175
+ You must process each new fact individually and decide **exactly one** action: **ADD**, **DELETE**, **UPDATE**, or **NONE**, following these rules, in this order:
176
+
177
+ 1. **User intent override**
178
+ If the User Instruction clearly requests adding, updating, or removal (e.g. “ajoute X”, “mets à jour Y”, “supprime Z”), you **must** respect that and assign the corresponding action for the matching fact, superseding semantic rules.
179
+
180
+ 2. **Semantic consistency check**
181
+ For each new fact:
182
+ - If it **contradicts**, **negates**, or **cancels** an existing memory item, you **DELETE** the memory item.
183
+ - Else, if the new fact is a **specialization** (i.e. same core meaning + additional detail) of an existing one, **UPDATE** that memory (keeping the same ID).
184
+ - Else, if it is **semantically equivalent** (i.e. redundant or paraphrased), assign **NONE** (no change).
185
+ - Else, if it is entirely **new** (no overlap or relation), **ADD** it (generate a new ID).
186
+ - Otherwise (if ambiguous or borderline), assign **NONE** (do not delete).
187
+
188
+ 3. **ID reuse and consistency**
189
+ - For **UPDATE**, reuse the existing memory item’s ID.
190
+ - For **DELETE**, simply remove the item from the final memory output.
191
+ - For **ADD**, generate a new unique ID (e.g. UUID).
192
+ - If memory is initially empty, treat all new facts as **ADD**.
193
+
194
+ 4. **Output formatting**
195
+ Return the updated memory state in strict JSON format. Each memory entry must include:
196
+ - \`id\` (string)
197
+ - \`text\` (string, the pure factual content)
198
+ - Optionally for updates: \`old_text\` (the prior version)
199
+ - *(No extra annotation or type markup in \`text\`)*
200
+
201
+ If there are no facts at all, return \`{"memory": []}\`.
202
+
203
+ *You must not output any other text besides the valid JSON result.*
157
204
 
158
205
  # Output Instructions
159
- - Default user language is ${defaultLanguage}.
206
+ - Default user language is "${defaultLanguage}".
160
207
  - Each memory item must follow this strict format:
161
- - UPDATE also include the previous text: \`old_memory\`.
162
- - ⚠️ Reuse correct IDs for UPDATE and DELETE.
163
- - Generate random IDs for ADDs.
208
+ - UPDATE must also include the previous text: \`old_text\`.
209
+ - Reuse correct IDs for UPDATE.
210
+ - For DELETE, exclude the removed item from the final memory list.
211
+ - Generate random IDs for ADDs (format: UUID).
164
212
  - If memory is empty, treat all facts as ADD.
165
213
  - Without facts, return an empty memory: \`{"memory": []}\`
166
214
  - Memory must strictly reflect valid facts.
167
- - Contradictions, cancellations, negations, or ambiguities must be handled by DELETE.
168
- - The field 'text' must be the pure memory content only: do not add any type markers or parentheses like "(todo)".
215
+ - Contradictions, cancellations, or negations must be handled by DELETE. Ambiguities must be handled by NONE.
216
+ - The field 'text' must be the pure memory content only: do not add any type markers or parentheses.
169
217
 
170
218
  # Current Memory (extract and reuse their IDs for UPDATE or DELETE events):
171
219
  ${serializeMemory(retrievedOldMemory)}
@@ -173,8 +221,7 @@ ${serializeMemory(retrievedOldMemory)}
173
221
  # New Retrieved Facts:
174
222
  ${serializeFacts(newRetrievedFacts)}
175
223
 
176
- # User Instruction:
177
- ${userInstruction || ""}
224
+ # User Instruction: "${userInstruction || ''}"
178
225
 
179
226
  Return the updated memory in JSON format only. Do not output anything else.`;
180
227
  }
@@ -198,8 +245,10 @@ const getMemoriesAsPrefix = (memories) => {
198
245
  };
199
246
  exports.getMemoriesAsPrefix = getMemoriesAsPrefix;
200
247
  const getMemoriesAsSystem = (memories, facts) => {
248
+ if (!memories || memories.length === 0)
249
+ return "";
201
250
  const memoryString = memories.map((mem) => `- ${mem.memory}`).concat(facts || []).join("\n");
202
- return `${exports.MEMORY_STRING_SYSTEM}\n<memories>${memoryString}\n</memories>`;
251
+ return `${exports.MEMORY_STRING_SYSTEM}\n<memories>\n${memoryString}\n</memories>`;
203
252
  };
204
253
  exports.getMemoriesAsSystem = getMemoriesAsSystem;
205
254
  function parseMessages(messages) {