@melandlabs/memory-store 1.1.6 → 1.1.7

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.
@@ -7,6 +7,345 @@ import '@melandlabs/ai/memory';
7
7
  import '@melandlabs/rag';
8
8
  import '@melandlabs/contracts';
9
9
 
10
+ // src/search/iterative-recall.ts
11
+ var SYSTEM_PROMPT = `You are a research assistant collecting evidence from a user's conversation history. You are NOT answering the question; only gather the most useful memory.
12
+
13
+ Actions:
14
+ search \u2014 search by concise keywords. Previously returned chunks are automatically excluded.
15
+ Action Input: {"keywords":["keyword1","keyword2"],"date_from":"YYYY-MM-DD","date_to":"YYYY-MM-DD"}
16
+ The date fields are optional; omit them unless an absolute date range is useful.
17
+
18
+ note \u2014 save relevant results from the LAST search by their 1-based result number.
19
+ Action Input: {"indices":[1,3]}
20
+
21
+ finish \u2014 finish collecting evidence.
22
+ Action Input: {}
23
+
24
+ Workflow: search -> note -> search again -> note -> finish.
25
+ Review every result. Call note before another search because the prior result list is replaced. Use diverse keywords on later searches. Never answer the question.
26
+
27
+ Output exactly:
28
+ Thought: one short sentence
29
+ Action: one action name
30
+ Action Input: valid JSON object`;
31
+ function deriveKeywordsFromQuery(query) {
32
+ return query.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter((token) => token.length >= 2);
33
+ }
34
+ function formatDateHint(dateFrom, dateTo) {
35
+ if (!dateFrom && !dateTo) {
36
+ return void 0;
37
+ }
38
+ const fromText = dateFrom ?? "the beginning";
39
+ const toText = dateTo ?? "now";
40
+ return `Restrict searches to the date range ${fromText} to ${toText}. You may still emit narrower date_from/date_to bounds when useful.`;
41
+ }
42
+ function buildInitialPrompt(query, dateHint) {
43
+ const hintText = dateHint ? `
44
+ ${dateHint}` : "";
45
+ return `${SYSTEM_PROMPT}
46
+
47
+ Question to research: ${query}${hintText}
48
+ Search the conversation history and collect all relevant evidence. Start with a broad keyword search.`;
49
+ }
50
+ function buildObservationPrompt(hits) {
51
+ if (hits.length === 0) {
52
+ return "Observation: No matching memory found.\nRespond with the next action only.";
53
+ }
54
+ const blocks = hits.map((hit, index) => {
55
+ const lines = [`Result ${index + 1} | score=${hit.similarity.toFixed(4)}`];
56
+ for (const line of hit.content.split("\n")) {
57
+ if (line.trim()) lines.push(line);
58
+ }
59
+ return lines.join("\n");
60
+ });
61
+ return `Observation:
62
+ ${blocks.join("\n\n")}
63
+
64
+ Respond with the next action only.`;
65
+ }
66
+ function stripCodeFences(text) {
67
+ return text.replace(/```(?:json)?\s*([\s\S]*?)\s*```/g, "$1");
68
+ }
69
+ function extractJsonObject(text) {
70
+ const start = text.indexOf("{");
71
+ if (start === -1) {
72
+ return void 0;
73
+ }
74
+ let depth = 0;
75
+ let inString = false;
76
+ let escaped = false;
77
+ for (let i = start; i < text.length; i += 1) {
78
+ const ch = text[i];
79
+ if (escaped) {
80
+ escaped = false;
81
+ continue;
82
+ }
83
+ if (inString) {
84
+ if (ch === "\\") {
85
+ escaped = true;
86
+ } else if (ch === '"') {
87
+ inString = false;
88
+ }
89
+ continue;
90
+ }
91
+ if (ch === '"') {
92
+ inString = true;
93
+ } else if (ch === "{") {
94
+ depth += 1;
95
+ } else if (ch === "}") {
96
+ depth -= 1;
97
+ if (depth === 0) {
98
+ return text.slice(start, i + 1);
99
+ }
100
+ }
101
+ }
102
+ return void 0;
103
+ }
104
+ function parseAction(text) {
105
+ const cleaned = stripCodeFences(text);
106
+ const actionMatch = cleaned.match(/Action:\s*([\w_]+)/);
107
+ if (!actionMatch) return null;
108
+ const action = actionMatch[1].trim().toLowerCase();
109
+ if (action === "finish") {
110
+ return { type: "finish" };
111
+ }
112
+ const inputMatch = cleaned.match(/Action Input:\s*/s);
113
+ if (!inputMatch || inputMatch.index === void 0) return null;
114
+ const jsonText = extractJsonObject(cleaned.slice(inputMatch.index + inputMatch[0].length));
115
+ if (!jsonText) return null;
116
+ let parsedJson = null;
117
+ for (const candidate of [jsonText, jsonText.replace(/'/g, '"')]) {
118
+ try {
119
+ parsedJson = JSON.parse(candidate);
120
+ break;
121
+ } catch {
122
+ }
123
+ }
124
+ if (!parsedJson) return null;
125
+ if (action === "search") {
126
+ const keywords = parsedJson.keywords;
127
+ if (!Array.isArray(keywords) || !keywords.every((k) => typeof k === "string")) {
128
+ return null;
129
+ }
130
+ return {
131
+ type: "search",
132
+ keywords,
133
+ dateFrom: typeof parsedJson.date_from === "string" ? parsedJson.date_from : void 0,
134
+ dateTo: typeof parsedJson.date_to === "string" ? parsedJson.date_to : void 0
135
+ };
136
+ }
137
+ if (action === "note") {
138
+ const indices = parsedJson.indices;
139
+ if (!Array.isArray(indices) || !indices.every((i) => typeof i === "number")) {
140
+ return null;
141
+ }
142
+ return { type: "note", indices };
143
+ }
144
+ return null;
145
+ }
146
+ function createIterativeRecallPlanner(deps) {
147
+ const { complete, options = {} } = deps;
148
+ const defaults = {
149
+ maxIterations: 4,
150
+ searchTopK: 5,
151
+ disabled: false,
152
+ fallbackToBaseline: true
153
+ };
154
+ let lastDegraded = false;
155
+ let iterationsWithValidAction = 0;
156
+ return {
157
+ lastDegraded: () => lastDegraded,
158
+ async plan(input) {
159
+ const opts = {
160
+ ...defaults,
161
+ ...options,
162
+ ...input.options
163
+ };
164
+ lastDegraded = false;
165
+ iterationsWithValidAction = 0;
166
+ if (opts.disabled || !input.query.trim()) {
167
+ return { evidence: [], stats: { iterations: 0, searches: 0, notes: 0 } };
168
+ }
169
+ const messages = [
170
+ { role: "system", content: SYSTEM_PROMPT },
171
+ {
172
+ role: "user",
173
+ content: buildInitialPrompt(input.query, formatDateHint(input.dateFrom, input.dateTo))
174
+ }
175
+ ];
176
+ const evidence = /* @__PURE__ */ new Map();
177
+ const excludedIds = /* @__PURE__ */ new Set();
178
+ let lastHits = [];
179
+ let searches = 0;
180
+ let notes = 0;
181
+ let iterations = 0;
182
+ let completeThrew = false;
183
+ for (let i = 0; i < opts.maxIterations; i += 1) {
184
+ iterations = i + 1;
185
+ let reply;
186
+ try {
187
+ reply = await complete(messages.map((m) => `${m.role}: ${m.content}`).join("\n\n"));
188
+ } catch {
189
+ completeThrew = true;
190
+ break;
191
+ }
192
+ messages.push({ role: "assistant", content: reply });
193
+ const action = parseAction(reply);
194
+ if (!action) {
195
+ messages.push({
196
+ role: "user",
197
+ content: "Observation: Use exactly one valid action: search, note, or finish. Respond with the next action only."
198
+ });
199
+ continue;
200
+ }
201
+ iterationsWithValidAction += 1;
202
+ if (action.type === "finish") {
203
+ break;
204
+ }
205
+ if (action.type === "search") {
206
+ const result = await input.executor.search({
207
+ keywords: action.keywords,
208
+ dateFrom: action.dateFrom ?? input.dateFrom,
209
+ dateTo: action.dateTo ?? input.dateTo
210
+ });
211
+ lastHits = result.candidates.filter((c) => !excludedIds.has(c.id)).slice(0, opts.searchTopK);
212
+ for (const hit of lastHits) {
213
+ excludedIds.add(hit.id);
214
+ }
215
+ searches += 1;
216
+ messages.push({ role: "user", content: buildObservationPrompt(lastHits) });
217
+ continue;
218
+ }
219
+ if (action.type === "note") {
220
+ let saved = 0;
221
+ for (const index of action.indices) {
222
+ if (index >= 1 && index <= lastHits.length) {
223
+ const hit = lastHits[index - 1];
224
+ if (!evidence.has(hit.id)) {
225
+ evidence.set(hit.id, hit);
226
+ saved += 1;
227
+ }
228
+ }
229
+ }
230
+ notes += saved;
231
+ messages.push({
232
+ role: "user",
233
+ content: `Observation: Saved ${saved} new result(s). Total notes: ${evidence.size}.
234
+ Respond with the next action only.`
235
+ });
236
+ }
237
+ }
238
+ let fallbackRan = false;
239
+ if (evidence.size === 0 && opts.fallbackToBaseline) {
240
+ fallbackRan = true;
241
+ if (lastHits.length > 0) {
242
+ for (const hit of lastHits) {
243
+ if (!evidence.has(hit.id)) {
244
+ evidence.set(hit.id, hit);
245
+ }
246
+ }
247
+ } else {
248
+ const baseline = await input.executor.search({
249
+ keywords: deriveKeywordsFromQuery(input.query),
250
+ dateFrom: input.dateFrom,
251
+ dateTo: input.dateTo
252
+ });
253
+ searches += 1;
254
+ for (const hit of baseline.candidates.slice(0, opts.searchTopK)) {
255
+ if (!evidence.has(hit.id)) {
256
+ evidence.set(hit.id, hit);
257
+ }
258
+ }
259
+ }
260
+ }
261
+ lastDegraded = completeThrew || iterationsWithValidAction === 0 || fallbackRan;
262
+ return {
263
+ evidence: Array.from(evidence.values()),
264
+ stats: { iterations, searches, notes }
265
+ };
266
+ }
267
+ };
268
+ }
269
+
270
+ // src/search/query-rewriter.ts
271
+ var SYSTEM_PROMPT2 = `You are a memory retrieval assistant.
272
+
273
+ The memory store contains a user's past messages, written in the first person (e.g. "I told you about my sister's wedding", "I prefer dark mode").
274
+
275
+ Your job is NOT to answer the question. Your job is to rewrite the assistant's question into a short, natural question that the USER would ask their own memory log to find the relevant entry.
276
+
277
+ Rules:
278
+ - Use first person: "Did I tell you about ...?", "What did I say about ...?", "Have I mentioned ...?"
279
+ - Do NOT address the user as "you".
280
+ - Do NOT answer the question.
281
+ - Output each rephrasing on its own line, prefixed with "- ".
282
+ - Keep each rephrasing under 20 words.
283
+ - Output exactly the requested number of lines.`;
284
+ function buildPrompt(query, numVariants) {
285
+ const label = numVariants === 1 ? "1 alternative rephrasing" : `${numVariants} alternative rephrasings`;
286
+ return `${SYSTEM_PROMPT2}
287
+
288
+ Output exactly ${label}.
289
+
290
+ Example:
291
+ Question: What is the name of my cat?
292
+ - Did I tell you the name of my cat?
293
+
294
+ Question: ${query}
295
+ Output:`;
296
+ }
297
+ function sanitizeLine(text) {
298
+ return text.replace(/^\s*["'`]+|["'`]+\s*$/g, "").replace(/^Rewritten:\s*/i, "").trim();
299
+ }
300
+ function parseVariants(raw, maxVariants, original) {
301
+ const lines = raw.split(/\r?\n/).map((line) => sanitizeLine(line.replace(/^\s*-\s+/, ""))).filter((line) => line.length > 0);
302
+ if (lines.length === 0) return [];
303
+ const seen = /* @__PURE__ */ new Set([original.toLowerCase()]);
304
+ const variants = [];
305
+ for (const line of lines) {
306
+ if (variants.length >= maxVariants) break;
307
+ const key = line.toLowerCase();
308
+ if (seen.has(key)) continue;
309
+ seen.add(key);
310
+ variants.push(line);
311
+ }
312
+ return variants;
313
+ }
314
+ function createUserVoiceRewriter(options) {
315
+ const { complete, maxVariants = 1, disabled = false } = options;
316
+ const wantedVariants = Math.max(0, Math.floor(maxVariants));
317
+ let lastDegraded = false;
318
+ return {
319
+ async rewrite(input) {
320
+ if (disabled || !input.query || !input.query.trim()) {
321
+ lastDegraded = false;
322
+ return [input.query];
323
+ }
324
+ const original = input.query.trim();
325
+ if (wantedVariants === 0) {
326
+ lastDegraded = false;
327
+ return [original];
328
+ }
329
+ try {
330
+ const raw = await complete(buildPrompt(original, wantedVariants));
331
+ const variants = parseVariants(raw, wantedVariants, original);
332
+ if (variants.length === 0) {
333
+ lastDegraded = true;
334
+ return [original];
335
+ }
336
+ lastDegraded = false;
337
+ return [original, ...variants];
338
+ } catch {
339
+ lastDegraded = true;
340
+ return [original];
341
+ }
342
+ },
343
+ lastDegraded() {
344
+ return lastDegraded;
345
+ }
346
+ };
347
+ }
348
+
10
349
  // src/storage/postgres-raw-message-factory.ts
11
350
  var factory = null;
12
351
  async function resolvePostgresFactory(env) {
@@ -158,7 +497,11 @@ function parseUnifiedArgs(argv) {
158
497
  insightsBackend: env.INSIGHTS_BACKEND ?? "none",
159
498
  insightsCollection: env.INSIGHTS_COLLECTION ?? "opencontext_insights",
160
499
  knowledgeBackend: env.KNOWLEDGE_BACKEND ?? "none",
161
- knowledgeCollection: env.KNOWLEDGE_COLLECTION ?? "opencontext_knowledge"
500
+ knowledgeCollection: env.KNOWLEDGE_COLLECTION ?? "opencontext_knowledge",
501
+ reasoning: env.REASONING === "1" || env.REASONING === "true",
502
+ reasoningBaseUrl: env.OPENCONTEXT_LLM_BASE_URL,
503
+ reasoningModel: env.OPENCONTEXT_LLM_MODEL,
504
+ reasoningTimeoutMs: env.OPENCONTEXT_LLM_TIMEOUT_MS ? Number.parseInt(env.OPENCONTEXT_LLM_TIMEOUT_MS, 10) : void 0
162
505
  };
163
506
  for (let i = 0; i < argv.length; i += 1) {
164
507
  const arg = argv[i];
@@ -193,6 +536,21 @@ function parseUnifiedArgs(argv) {
193
536
  case "--knowledge-collection":
194
537
  args.knowledgeCollection = takeValue();
195
538
  break;
539
+ case "--reasoning":
540
+ args.reasoning = true;
541
+ break;
542
+ case "--no-reasoning":
543
+ args.reasoning = false;
544
+ break;
545
+ case "--reasoning-base-url":
546
+ args.reasoningBaseUrl = takeValue();
547
+ break;
548
+ case "--reasoning-model":
549
+ args.reasoningModel = takeValue();
550
+ break;
551
+ case "--reasoning-timeout-ms":
552
+ args.reasoningTimeoutMs = Number.parseInt(takeValue(), 10);
553
+ break;
196
554
  }
197
555
  }
198
556
  for (const [name, value] of [
@@ -366,6 +724,52 @@ async function buildUnified(args) {
366
724
  };
367
725
  log(`knowledge backend wired via chroma (collection=${args.knowledgeCollection})`);
368
726
  }
727
+ if (args.reasoning) {
728
+ const apiKey = process.env.OPENCONTEXT_LLM_API_KEY;
729
+ if (!apiKey) {
730
+ throw new Error(
731
+ "--reasoning requires OPENCONTEXT_LLM_API_KEY (and ideally OPENCONTEXT_LLM_BASE_URL / OPENCONTEXT_LLM_MODEL) in the environment"
732
+ );
733
+ }
734
+ const baseUrl = args.reasoningBaseUrl ?? process.env.OPENCONTEXT_LLM_BASE_URL ?? "https://openrouter.ai/api/v1";
735
+ const model = args.reasoningModel ?? process.env.OPENCONTEXT_LLM_MODEL ?? "openai/gpt-4o-mini";
736
+ const timeoutMs = args.reasoningTimeoutMs ?? 3e4;
737
+ const complete = async (prompt) => {
738
+ const controller = new AbortController();
739
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
740
+ timer.unref?.();
741
+ try {
742
+ const res = await fetch(`${baseUrl}/chat/completions`, {
743
+ method: "POST",
744
+ headers: {
745
+ "content-type": "application/json",
746
+ authorization: `Bearer ${apiKey}`,
747
+ "HTTP-Referer": process.env.NEXT_PUBLIC_APP_URL ?? "https://opencontext.ai",
748
+ "X-Title": "opencontext AI"
749
+ },
750
+ body: JSON.stringify({
751
+ model,
752
+ messages: [{ role: "user", content: prompt }],
753
+ temperature: 0
754
+ }),
755
+ signal: controller.signal
756
+ });
757
+ if (!res.ok) throw new Error(`reasoning LLM ${res.status}: ${await res.text()}`);
758
+ const body = await res.json();
759
+ const text = body.choices?.[0]?.message?.content?.trim();
760
+ if (!text) throw new Error("reasoning LLM response missing choices[0].message.content");
761
+ return text;
762
+ } finally {
763
+ clearTimeout(timer);
764
+ }
765
+ };
766
+ const queryRewriter = createUserVoiceRewriter({ complete });
767
+ const iterativePlanner = createIterativeRecallPlanner({ complete });
768
+ if (!unified.reasoning) unified.reasoning = {};
769
+ unified.reasoning.queryRewriter = queryRewriter;
770
+ unified.reasoning.iterativePlanner = iterativePlanner;
771
+ log(`reasoning wired (model=${model}, baseUrl=${baseUrl})`);
772
+ }
369
773
  return unified;
370
774
  }
371
775
  function printUnifiedHelp() {
@@ -388,7 +792,26 @@ Cross-source search (wires unified.searchKnowledge / searchInsights / searchRawM
388
792
  --knowledge-backend <name> chroma | none
389
793
  (env: KNOWLEDGE_BACKEND, default: none)
390
794
  --knowledge-collection <name> Chroma collection (default: opencontext_knowledge)
391
- Note: the chroma backends dynamically import @melandlabs/ai-rag.`);
795
+ Note: the chroma backends dynamically import @melandlabs/ai-rag.
796
+
797
+ Reasoning (wires unified.reasoning.{queryRewriter, iterativePlanner}):
798
+ --reasoning Enable the LLM reasoning layer so /v1/search and
799
+ memory.search can honor reasoningStrategy:
800
+ "rewrite" \u2014 first-person memory-check rephrase
801
+ "iterative" \u2014 planner that searches, notes evidence,
802
+ searches again
803
+ (env: REASONING=1, default: off)
804
+ --no-reasoning Explicitly disable even if REASONING=1 is set.
805
+ --reasoning-base-url <url> OpenAI-compatible base URL for the reasoning LLM.
806
+ (env: OPENCONTEXT_LLM_BASE_URL, default: https://openrouter.ai/api/v1)
807
+ --reasoning-model <name> Reasoning LLM model identifier.
808
+ (env: OPENCONTEXT_LLM_MODEL, default: openai/gpt-4o-mini)
809
+ --reasoning-timeout-ms <int> Per-request timeout (default: 30000).
810
+
811
+ Required env when --reasoning is set:
812
+ OPENCONTEXT_LLM_API_KEY Bearer token (no default)
813
+ OPENCONTEXT_LLM_BASE_URL (optional) overrides --reasoning-base-url
814
+ OPENCONTEXT_LLM_MODEL (optional) overrides --reasoning-model`);
392
815
  }
393
816
 
394
817
  export { buildUnified, parseUnifiedArgs, printUnifiedHelp };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@melandlabs/memory-store",
3
- "version": "1.1.6",
3
+ "version": "1.1.7",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist",
@@ -60,15 +60,15 @@
60
60
  "@modelcontextprotocol/sdk": "^1.25.3",
61
61
  "hono": "^4.6.14",
62
62
  "zod": "^4.3.6",
63
- "@melandlabs/ai": "0.9.0",
64
- "@melandlabs/contracts": "0.6.0",
63
+ "@melandlabs/ai": "0.9.1",
65
64
  "@melandlabs/env-config": "0.4.0",
65
+ "@melandlabs/rag": "0.3.0",
66
+ "@melandlabs/okf": "0.2.1",
67
+ "@melandlabs/contracts": "0.6.0",
66
68
  "@melandlabs/memory-consolidation": "0.5.2",
67
- "@melandlabs/okf": "0.2.0",
68
- "@melandlabs/sqlite": "0.5.1",
69
- "@melandlabs/vsa": "0.3.0",
70
69
  "@melandlabs/shared": "0.4.0",
71
- "@melandlabs/rag": "0.3.0"
70
+ "@melandlabs/vsa": "0.3.0",
71
+ "@melandlabs/sqlite": "0.5.2"
72
72
  },
73
73
  "peerDependencies": {
74
74
  "@melandlabs/ai-rag": "0.2.9",