@prometheus-ai/memory 0.5.0

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 (128) hide show
  1. package/README.md +107 -0
  2. package/dist/types/cli.d.ts +35 -0
  3. package/dist/types/config.d.ts +77 -0
  4. package/dist/types/core/aaak.d.ts +55 -0
  5. package/dist/types/core/annotations.d.ts +75 -0
  6. package/dist/types/core/banks.d.ts +33 -0
  7. package/dist/types/core/beam/consolidate.d.ts +32 -0
  8. package/dist/types/core/beam/helpers.d.ts +76 -0
  9. package/dist/types/core/beam/index.d.ts +59 -0
  10. package/dist/types/core/beam/recall.d.ts +32 -0
  11. package/dist/types/core/beam/schema.d.ts +2 -0
  12. package/dist/types/core/beam/store.d.ts +35 -0
  13. package/dist/types/core/beam/types.d.ts +233 -0
  14. package/dist/types/core/binary-vectors.d.ts +54 -0
  15. package/dist/types/core/chat-normalize.d.ts +13 -0
  16. package/dist/types/core/content-sanitizer.d.ts +18 -0
  17. package/dist/types/core/cost-log.d.ts +13 -0
  18. package/dist/types/core/embeddings.d.ts +44 -0
  19. package/dist/types/core/entities.d.ts +7 -0
  20. package/dist/types/core/episodic-graph.d.ts +89 -0
  21. package/dist/types/core/extraction/client.d.ts +31 -0
  22. package/dist/types/core/extraction/diagnostics.d.ts +51 -0
  23. package/dist/types/core/extraction/prompts.d.ts +2 -0
  24. package/dist/types/core/extraction.d.ts +6 -0
  25. package/dist/types/core/index.d.ts +4 -0
  26. package/dist/types/core/llm-backends.d.ts +21 -0
  27. package/dist/types/core/local-llm.d.ts +15 -0
  28. package/dist/types/core/memory.d.ts +160 -0
  29. package/dist/types/core/migrations/e6-triplestore-split.d.ts +17 -0
  30. package/dist/types/core/migrations/index.d.ts +1 -0
  31. package/dist/types/core/mmr.d.ts +8 -0
  32. package/dist/types/core/orchestrator.d.ts +20 -0
  33. package/dist/types/core/patterns.d.ts +61 -0
  34. package/dist/types/core/plugins.d.ts +109 -0
  35. package/dist/types/core/polyphonic-recall.d.ts +66 -0
  36. package/dist/types/core/query-cache.d.ts +46 -0
  37. package/dist/types/core/query-intent.d.ts +20 -0
  38. package/dist/types/core/recall-diagnostics.d.ts +48 -0
  39. package/dist/types/core/runtime-options.d.ts +68 -0
  40. package/dist/types/core/shmr.d.ts +56 -0
  41. package/dist/types/core/streaming.d.ts +136 -0
  42. package/dist/types/core/synonyms.d.ts +46 -0
  43. package/dist/types/core/temporal-parser.d.ts +16 -0
  44. package/dist/types/core/token-counter.d.ts +8 -0
  45. package/dist/types/core/triples.d.ts +63 -0
  46. package/dist/types/core/typed-memory.d.ts +39 -0
  47. package/dist/types/core/vector-math.d.ts +1 -0
  48. package/dist/types/core/veracity-consolidation.d.ts +60 -0
  49. package/dist/types/core/weibull.d.ts +96 -0
  50. package/dist/types/db.d.ts +16 -0
  51. package/dist/types/diagnose.d.ts +24 -0
  52. package/dist/types/dr/index.d.ts +1 -0
  53. package/dist/types/dr/recovery.d.ts +68 -0
  54. package/dist/types/index.d.ts +5 -0
  55. package/dist/types/mcp-server.d.ts +40 -0
  56. package/dist/types/mcp-tools.d.ts +484 -0
  57. package/dist/types/migrations/e6-triplestore-split.d.ts +1 -0
  58. package/dist/types/migrations/index.d.ts +1 -0
  59. package/dist/types/types.d.ts +145 -0
  60. package/dist/types/util/datetime.d.ts +8 -0
  61. package/dist/types/util/env.d.ts +10 -0
  62. package/dist/types/util/ids.d.ts +3 -0
  63. package/dist/types/util/lru.d.ts +12 -0
  64. package/dist/types/util/regex.d.ts +10 -0
  65. package/package.json +85 -0
  66. package/src/cli.ts +398 -0
  67. package/src/config.ts +326 -0
  68. package/src/core/aaak.ts +142 -0
  69. package/src/core/annotations.ts +457 -0
  70. package/src/core/banks.ts +133 -0
  71. package/src/core/beam/consolidate.ts +965 -0
  72. package/src/core/beam/helpers.ts +977 -0
  73. package/src/core/beam/index.ts +353 -0
  74. package/src/core/beam/recall.ts +1100 -0
  75. package/src/core/beam/schema.ts +423 -0
  76. package/src/core/beam/store.ts +829 -0
  77. package/src/core/beam/types.ts +268 -0
  78. package/src/core/binary-vectors.ts +317 -0
  79. package/src/core/chat-normalize.ts +160 -0
  80. package/src/core/content-sanitizer.ts +136 -0
  81. package/src/core/cost-log.ts +103 -0
  82. package/src/core/embeddings.ts +423 -0
  83. package/src/core/entities.ts +259 -0
  84. package/src/core/episodic-graph.ts +708 -0
  85. package/src/core/extraction/client.ts +162 -0
  86. package/src/core/extraction/diagnostics.ts +193 -0
  87. package/src/core/extraction/prompts.ts +31 -0
  88. package/src/core/extraction.ts +335 -0
  89. package/src/core/index.ts +30 -0
  90. package/src/core/llm-backends.ts +51 -0
  91. package/src/core/local-llm.ts +436 -0
  92. package/src/core/memory.ts +630 -0
  93. package/src/core/migrations/e6-triplestore-split.ts +211 -0
  94. package/src/core/migrations/index.ts +1 -0
  95. package/src/core/mmr.ts +71 -0
  96. package/src/core/orchestrator.ts +62 -0
  97. package/src/core/patterns.ts +484 -0
  98. package/src/core/plugins.ts +375 -0
  99. package/src/core/polyphonic-recall.ts +563 -0
  100. package/src/core/query-cache.ts +354 -0
  101. package/src/core/query-intent.ts +139 -0
  102. package/src/core/recall-diagnostics.ts +157 -0
  103. package/src/core/runtime-options.ts +119 -0
  104. package/src/core/shmr.ts +460 -0
  105. package/src/core/streaming.ts +419 -0
  106. package/src/core/synonyms.ts +197 -0
  107. package/src/core/temporal-parser.ts +363 -0
  108. package/src/core/token-counter.ts +30 -0
  109. package/src/core/triples.ts +454 -0
  110. package/src/core/typed-memory.ts +407 -0
  111. package/src/core/vector-math.ts +23 -0
  112. package/src/core/veracity-consolidation.ts +477 -0
  113. package/src/core/weibull.ts +124 -0
  114. package/src/db.ts +128 -0
  115. package/src/diagnose.ts +174 -0
  116. package/src/dr/index.ts +1 -0
  117. package/src/dr/recovery.ts +405 -0
  118. package/src/index.ts +33 -0
  119. package/src/mcp-server.ts +155 -0
  120. package/src/mcp-tools.ts +970 -0
  121. package/src/migrations/e6-triplestore-split.ts +1 -0
  122. package/src/migrations/index.ts +1 -0
  123. package/src/types.ts +157 -0
  124. package/src/util/datetime.ts +69 -0
  125. package/src/util/env.ts +65 -0
  126. package/src/util/ids.ts +19 -0
  127. package/src/util/lru.ts +48 -0
  128. package/src/util/regex.ts +165 -0
@@ -0,0 +1,353 @@
1
+ import type { Database } from "bun:sqlite";
2
+ import { existsSync } from "node:fs";
3
+ import { ftsWeight, importanceWeight, vectorWeight } from "../../config";
4
+ import { closeQuietly, openDatabase } from "../../db";
5
+ import { AnnotationStore } from "../annotations";
6
+ import { EpisodicGraph } from "../episodic-graph";
7
+ import { hasPendingMigration, migrate as migrateTriplestoreSplit } from "../migrations/e6-triplestore-split";
8
+ import {
9
+ consolidateToEpisodic,
10
+ degradeEpisodic,
11
+ detectLanguage,
12
+ extractAndStoreFacts,
13
+ getConsolidationLog,
14
+ getContaminated,
15
+ getEpisodicStats,
16
+ getMemoriaStats,
17
+ health,
18
+ memoriaRetrieve,
19
+ sleep,
20
+ sleepAllSessions,
21
+ } from "./consolidate";
22
+ import { factRecall, formatContext, recall, recallEnhanced } from "./recall";
23
+ import { initBeam } from "./schema";
24
+ import {
25
+ exportToDict,
26
+ forgetWorking,
27
+ get,
28
+ getContext,
29
+ getGlobalWorkingStats,
30
+ getWorkingStats,
31
+ importFromDict,
32
+ invalidate,
33
+ remember,
34
+ rememberBatch,
35
+ scratchpadClear,
36
+ scratchpadRead,
37
+ scratchpadWrite,
38
+ updateWorking,
39
+ } from "./store";
40
+ import type {
41
+ BeamCaches,
42
+ BeamConfig,
43
+ BeamEvent,
44
+ BeamMemoryOptions,
45
+ BeamMemoryState,
46
+ BeamStats,
47
+ ImportStats,
48
+ MemoriaRetrieveResult,
49
+ Metadata,
50
+ RecallEnhancedOptions,
51
+ RecallOptions,
52
+ RecallResult,
53
+ RememberBatchItem,
54
+ RememberBatchOptions,
55
+ RememberOptions,
56
+ SleepResult,
57
+ } from "./types";
58
+
59
+ export { initBeam } from "./schema";
60
+ export type * from "./types";
61
+
62
+ const DEFAULT_CONFIG: BeamConfig = {
63
+ workingMemoryLimit: 1000,
64
+ workingMemoryTtlHours: 24,
65
+ recencyHalflifeHours: 72,
66
+ vecWeight: 0.5,
67
+ ftsWeight: 0.3,
68
+ importanceWeight: 0.2,
69
+ useCloud: false,
70
+ localLlmEnabled: false,
71
+ };
72
+
73
+ function normalizeConfig(options: BeamMemoryOptions): BeamConfig {
74
+ const configured = options.config ?? {};
75
+ const useCloud = options.useCloud ?? configured.useCloud ?? DEFAULT_CONFIG.useCloud;
76
+ return {
77
+ workingMemoryLimit: configured.workingMemoryLimit ?? DEFAULT_CONFIG.workingMemoryLimit,
78
+ workingMemoryTtlHours: configured.workingMemoryTtlHours ?? DEFAULT_CONFIG.workingMemoryTtlHours,
79
+ recencyHalflifeHours: configured.recencyHalflifeHours ?? DEFAULT_CONFIG.recencyHalflifeHours,
80
+ vecWeight: configured.vecWeight ?? vectorWeight(),
81
+ ftsWeight: configured.ftsWeight ?? ftsWeight(),
82
+ importanceWeight: configured.importanceWeight ?? importanceWeight(),
83
+ useCloud,
84
+ localLlmEnabled: configured.localLlmEnabled ?? DEFAULT_CONFIG.localLlmEnabled,
85
+ };
86
+ }
87
+ function autoMigrateAnnotations(db: Database, dbPath: string | undefined): void {
88
+ if (dbPath === undefined || dbPath === ":memory:" || !existsSync(dbPath)) return;
89
+ if (!hasPendingMigration(db)) return;
90
+ if (process.env.PROMETHEUS_MEMORY_AUTO_MIGRATE === "0") {
91
+ const row = db
92
+ .query(
93
+ "SELECT COUNT(*) AS count FROM triples WHERE predicate IN ('mentions', 'fact', 'occurred_on', 'has_source')",
94
+ )
95
+ .get() as { count: number };
96
+ console.warn(
97
+ `PROMETHEUS_MEMORY_AUTO_MIGRATE=0: ${row.count} annotation rows pending; run scripts/migrate_triplestore_split.py manually.`,
98
+ );
99
+ return;
100
+ }
101
+ migrateTriplestoreSplit({ dbPath, dryRun: false, backup: true, logFn: () => {} });
102
+ }
103
+
104
+ export class BeamMemory implements BeamMemoryState {
105
+ readonly db: Database;
106
+ readonly dbPath?: string;
107
+ readonly sessionId: string;
108
+ readonly authorId: string | null;
109
+ readonly authorType: string | null;
110
+ readonly channelId: string;
111
+ readonly useCloud: boolean;
112
+ readonly eventEmitter?: (event: BeamEvent) => void;
113
+ readonly pluginManager: BeamMemoryState["pluginManager"];
114
+ readonly annotations: BeamMemoryState["annotations"];
115
+ readonly triples: BeamMemoryState["triples"];
116
+ readonly episodicGraph: unknown | null;
117
+ readonly veracityConsolidator: unknown | null;
118
+ readonly caches: BeamCaches;
119
+ readonly config: BeamConfig;
120
+ readonly pendingExtractions: Set<Promise<void>> = new Set();
121
+ #closed = false;
122
+
123
+ constructor(options?: BeamMemoryOptions);
124
+ constructor(
125
+ sessionId?: string,
126
+ dbPath?: string,
127
+ authorId?: string | null,
128
+ authorType?: string | null,
129
+ channelId?: string | null,
130
+ useCloud?: boolean,
131
+ eventEmitter?: (event: BeamEvent) => void,
132
+ );
133
+ constructor(
134
+ optionsOrSessionId: BeamMemoryOptions | string = {},
135
+ dbPath?: string,
136
+ authorId?: string | null,
137
+ authorType?: string | null,
138
+ channelId?: string | null,
139
+ useCloud?: boolean,
140
+ eventEmitter?: (event: BeamEvent) => void,
141
+ ) {
142
+ const options: BeamMemoryOptions =
143
+ typeof optionsOrSessionId === "string"
144
+ ? {
145
+ sessionId: optionsOrSessionId,
146
+ dbPath,
147
+ authorId,
148
+ authorType,
149
+ channelId,
150
+ useCloud,
151
+ eventEmitter,
152
+ }
153
+ : optionsOrSessionId;
154
+ this.sessionId = options.sessionId ?? "default";
155
+ this.authorId = options.authorId ?? null;
156
+ this.authorType = options.authorType ?? null;
157
+ this.channelId = options.channelId ?? this.sessionId;
158
+ this.dbPath = options.dbPath;
159
+ this.config = normalizeConfig(options);
160
+ this.useCloud = this.config.useCloud;
161
+ this.eventEmitter = options.eventEmitter;
162
+ this.pluginManager = options.pluginManager ?? null;
163
+ this.db = openDatabase(this.dbPath);
164
+ initBeam(this.db);
165
+ autoMigrateAnnotations(this.db, this.dbPath);
166
+ if (options.annotations !== undefined) {
167
+ this.annotations = options.annotations;
168
+ } else {
169
+ const annotationStore = new AnnotationStore({ db: this.db, dbPath: this.dbPath });
170
+ this.annotations = {
171
+ add: (memoryId, kind, value, writeOptions) =>
172
+ annotationStore.add(memoryId, kind, value, writeOptions?.source, writeOptions?.confidence),
173
+ addMany: (memoryId, kind, values, writeOptions) =>
174
+ annotationStore.addMany(memoryId, kind, values, writeOptions?.source, writeOptions?.confidence),
175
+ queryByMemory: (memoryId, kind) => annotationStore.queryByMemory(memoryId, kind),
176
+ queryByKind: (kind, value) => annotationStore.queryByKind(kind, { value }),
177
+ getDistinctValues: kind => annotationStore.getDistinctValues(kind),
178
+ };
179
+ }
180
+ this.triples = options.triples ?? null;
181
+ this.episodicGraph = new EpisodicGraph({ db: this.db, dbPath: this.dbPath });
182
+ this.veracityConsolidator = null;
183
+ this.caches = {
184
+ timestampParse: new Map<string, Date>(),
185
+ extractionBuffer: [],
186
+ };
187
+ }
188
+
189
+ close(): void {
190
+ if (this.#closed) {
191
+ return;
192
+ }
193
+ this.#closed = true;
194
+ closeQuietly(this.db);
195
+ }
196
+
197
+ async flushExtractions(): Promise<void> {
198
+ while (this.pendingExtractions.size > 0) {
199
+ await Promise.allSettled([...this.pendingExtractions]);
200
+ }
201
+ }
202
+
203
+ remember(content: string, options: RememberOptions = {}): string {
204
+ return remember(this, content, options);
205
+ }
206
+
207
+ rememberBatch(items: readonly RememberBatchItem[], options: RememberBatchOptions = {}): string[] {
208
+ return rememberBatch(this, items, options);
209
+ }
210
+
211
+ getContext(limit = 10): unknown[] {
212
+ return getContext(this, limit);
213
+ }
214
+
215
+ invalidate(memoryId: string, replacementId: string | null = null): boolean {
216
+ return invalidate(this, memoryId, replacementId);
217
+ }
218
+
219
+ getWorkingStats(
220
+ authorId: string | null = null,
221
+ authorType: string | null = null,
222
+ channelId: string | null = null,
223
+ ): BeamStats {
224
+ return getWorkingStats(this, authorId, authorType, channelId);
225
+ }
226
+
227
+ getGlobalWorkingStats(): BeamStats {
228
+ return getGlobalWorkingStats(this);
229
+ }
230
+
231
+ updateWorking(memoryId: string, content: string | null = null, importance: number | null = null): boolean {
232
+ return updateWorking(this, memoryId, content, importance);
233
+ }
234
+
235
+ get(memoryId: string): unknown | null {
236
+ return get(this, memoryId);
237
+ }
238
+
239
+ forgetWorking(memoryId: string): boolean {
240
+ return forgetWorking(this, memoryId);
241
+ }
242
+
243
+ consolidateToEpisodic(
244
+ summary: string,
245
+ sourceWmIds: readonly string[],
246
+ source = "consolidation",
247
+ importance = 0.6,
248
+ ): string {
249
+ return consolidateToEpisodic(this, summary, sourceWmIds, source, importance);
250
+ }
251
+
252
+ detectLanguage(text: string): string {
253
+ return detectLanguage(this, text);
254
+ }
255
+
256
+ extractAndStoreFacts(
257
+ content: string,
258
+ messageIdx = 0,
259
+ sourceMemoryId: string | null = null,
260
+ ): Record<string, unknown> {
261
+ return extractAndStoreFacts(this, content, messageIdx, sourceMemoryId);
262
+ }
263
+
264
+ memoriaRetrieve(query: string, ability: string | null = null, topK = 10): MemoriaRetrieveResult {
265
+ return memoriaRetrieve(this, query, ability, topK);
266
+ }
267
+
268
+ recall(query: string, topK = 40, options: RecallOptions = {}): Promise<RecallResult[]> {
269
+ return recall(this, query, topK, options);
270
+ }
271
+
272
+ recallEnhanced(query: string, topK = 40, options: RecallEnhancedOptions = {}): Promise<RecallResult[]> {
273
+ return recallEnhanced(this, query, topK, options);
274
+ }
275
+
276
+ formatContext(results: readonly RecallResult[], format = "bullet"): string {
277
+ return formatContext(this, results, format);
278
+ }
279
+
280
+ factRecall(query: string, topK = 30): RecallResult[] {
281
+ return factRecall(this, query, topK);
282
+ }
283
+
284
+ getEpisodicStats(
285
+ authorId: string | null = null,
286
+ authorType: string | null = null,
287
+ channelId: string | null = null,
288
+ ): BeamStats {
289
+ return getEpisodicStats(this, authorId, authorType, channelId);
290
+ }
291
+
292
+ getMemoriaStats(): BeamStats {
293
+ return getMemoriaStats(this);
294
+ }
295
+
296
+ scratchpadWrite(content: string): string {
297
+ return scratchpadWrite(this, content);
298
+ }
299
+
300
+ scratchpadRead(): unknown[] {
301
+ return scratchpadRead(this);
302
+ }
303
+
304
+ scratchpadClear(): void {
305
+ scratchpadClear(this);
306
+ }
307
+
308
+ degradeEpisodic(dryRun = false): Record<string, unknown> {
309
+ return degradeEpisodic(this, dryRun);
310
+ }
311
+
312
+ getContaminated(limit = 50, minImportance = 0.0): unknown[] {
313
+ return getContaminated(this, limit, minImportance);
314
+ }
315
+
316
+ health(staleThresholdHours = 24.0): Record<string, unknown> {
317
+ return health(this, staleThresholdHours);
318
+ }
319
+
320
+ sleep(dryRun = false): SleepResult {
321
+ return sleep(this, dryRun);
322
+ }
323
+
324
+ sleepAllSessions(dryRun = false): SleepResult {
325
+ return sleepAllSessions(this, dryRun);
326
+ }
327
+
328
+ getConsolidationLog(limit = 10): unknown[] {
329
+ return getConsolidationLog(this, limit);
330
+ }
331
+
332
+ exportToDict(): Record<string, unknown> {
333
+ return exportToDict(this);
334
+ }
335
+
336
+ importFromDict(data: Record<string, unknown>, force = false): ImportStats {
337
+ return importFromDict(this, data, force);
338
+ }
339
+ protected emitEvent(type: string, data: Omit<BeamEvent, "type" | "sessionId" | "timestamp"> = {}): void {
340
+ const event: BeamEvent = {
341
+ ...data,
342
+ type,
343
+ sessionId: this.sessionId,
344
+ timestamp: new Date().toISOString(),
345
+ };
346
+ this.eventEmitter?.(event);
347
+ void this.pluginManager?.emit?.(event);
348
+ }
349
+
350
+ protected metadataJson(metadata: Metadata | null | undefined): string | null {
351
+ return metadata == null ? null : JSON.stringify(metadata);
352
+ }
353
+ }