@mzhub/mem-ts 0.1.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.
- package/README.md +335 -0
- package/dist/BaseAdapter-BoRh1T7O.d.mts +75 -0
- package/dist/BaseAdapter-CQVX-gcA.d.ts +75 -0
- package/dist/BaseProvider-CEoiLGj5.d.ts +34 -0
- package/dist/BaseProvider-edMh_R9t.d.mts +34 -0
- package/dist/adapters/index.d.mts +259 -0
- package/dist/adapters/index.d.ts +259 -0
- package/dist/adapters/index.js +1570 -0
- package/dist/adapters/index.js.map +1 -0
- package/dist/adapters/index.mjs +1542 -0
- package/dist/adapters/index.mjs.map +1 -0
- package/dist/index-Ci5Q9G9H.d.mts +289 -0
- package/dist/index-Dl-Q2au9.d.ts +289 -0
- package/dist/index.d.mts +1206 -0
- package/dist/index.d.ts +1206 -0
- package/dist/index.js +5126 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +5058 -0
- package/dist/index.mjs.map +1 -0
- package/dist/middleware/index.d.mts +4 -0
- package/dist/middleware/index.d.ts +4 -0
- package/dist/middleware/index.js +63 -0
- package/dist/middleware/index.js.map +1 -0
- package/dist/middleware/index.mjs +59 -0
- package/dist/middleware/index.mjs.map +1 -0
- package/dist/providers/index.d.mts +96 -0
- package/dist/providers/index.d.ts +96 -0
- package/dist/providers/index.js +379 -0
- package/dist/providers/index.js.map +1 -0
- package/dist/providers/index.mjs +370 -0
- package/dist/providers/index.mjs.map +1 -0
- package/dist/types-G9qmfSeZ.d.mts +260 -0
- package/dist/types-G9qmfSeZ.d.ts +260 -0
- package/logo.png +0 -0
- package/package.json +114 -0
package/dist/index.d.mts
ADDED
|
@@ -0,0 +1,1206 @@
|
|
|
1
|
+
export { b as MemoryMiddlewareOptions, M as MemoryOS, a as MemoryOSConfig, c as createMemoryMiddleware, d as digestAfterResponse, w as withMemory } from './index-Ci5Q9G9H.mjs';
|
|
2
|
+
import { f as MemoryOperation, M as MemoryFact, E as ExtractionResult, H as HydrateOptions, d as HydratedContext, S as Session, F as FactFilter, C as ConversationExchange } from './types-G9qmfSeZ.mjs';
|
|
3
|
+
export { a as CompletionOptions, b as CompletionResult, h as MemoryOSEvents, c as MemoryOSOptions, g as Message, P as ProviderConfig, e as ProviderName } from './types-G9qmfSeZ.mjs';
|
|
4
|
+
import { B as BaseAdapter } from './BaseAdapter-BoRh1T7O.mjs';
|
|
5
|
+
export { InMemoryAdapter, JSONFileAdapter, JSONFileAdapterConfig, MongoDBAdapter, MongoDBAdapterConfig, PostgresAdapter, PostgresAdapterConfig, UpstashRedisAdapter, UpstashRedisAdapterConfig } from './adapters/index.mjs';
|
|
6
|
+
export { AnthropicProvider, CerebrasProvider, GeminiProvider, GroqProvider, OpenAIProvider, createProvider, getAvailableProviders } from './providers/index.mjs';
|
|
7
|
+
import { B as BaseProvider } from './BaseProvider-edMh_R9t.mjs';
|
|
8
|
+
|
|
9
|
+
interface ConflictResolutionResult {
|
|
10
|
+
/** Operations to apply after conflict resolution */
|
|
11
|
+
resolvedOperations: MemoryOperation[];
|
|
12
|
+
/** Conflicts that were detected and resolved */
|
|
13
|
+
conflicts: Array<{
|
|
14
|
+
existingFact: MemoryFact;
|
|
15
|
+
newOperation: MemoryOperation;
|
|
16
|
+
resolution: "replace" | "keep_both" | "merge" | "ignore";
|
|
17
|
+
}>;
|
|
18
|
+
}
|
|
19
|
+
type ConflictStrategy = "latest" | "keep_both" | "merge";
|
|
20
|
+
/**
|
|
21
|
+
* Resolves conflicts between new operations and existing facts.
|
|
22
|
+
* Implements the conflict resolution logic for the memory graph.
|
|
23
|
+
*/
|
|
24
|
+
declare class ConflictResolver {
|
|
25
|
+
private strategy;
|
|
26
|
+
constructor(strategy?: ConflictStrategy);
|
|
27
|
+
/**
|
|
28
|
+
* Resolve conflicts between new operations and existing facts
|
|
29
|
+
*/
|
|
30
|
+
resolve(userId: string, operations: MemoryOperation[], adapter: BaseAdapter): Promise<ConflictResolutionResult>;
|
|
31
|
+
/**
|
|
32
|
+
* Check if a predicate should allow multiple values
|
|
33
|
+
* (e.g., USES_TECH can have multiple values, but LOCATION should not)
|
|
34
|
+
*/
|
|
35
|
+
isMultiValuePredicate(predicate: string): boolean;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
interface ExtractorWorkerConfig {
|
|
39
|
+
/** Minimum confidence threshold for facts (0-1) */
|
|
40
|
+
minConfidence?: number;
|
|
41
|
+
/** Conflict resolution strategy */
|
|
42
|
+
conflictStrategy?: ConflictStrategy;
|
|
43
|
+
/** Enable debug logging */
|
|
44
|
+
debug?: boolean;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* The "Slow Brain" - Background worker that extracts facts from conversations.
|
|
48
|
+
* Runs asynchronously after responses are sent to users.
|
|
49
|
+
*/
|
|
50
|
+
declare class ExtractorWorker {
|
|
51
|
+
private provider;
|
|
52
|
+
private adapter;
|
|
53
|
+
private conflictResolver;
|
|
54
|
+
private minConfidence;
|
|
55
|
+
private debug;
|
|
56
|
+
private queue;
|
|
57
|
+
private processing;
|
|
58
|
+
constructor(provider: BaseProvider, adapter: BaseAdapter, config?: ExtractorWorkerConfig);
|
|
59
|
+
/**
|
|
60
|
+
* Queue a conversation exchange for background extraction.
|
|
61
|
+
* This method returns immediately (non-blocking).
|
|
62
|
+
*/
|
|
63
|
+
enqueue(userId: string, sessionId: string, userMessage: string, assistantResponse: string): void;
|
|
64
|
+
/**
|
|
65
|
+
* Process the extraction queue
|
|
66
|
+
*/
|
|
67
|
+
private processQueue;
|
|
68
|
+
/**
|
|
69
|
+
* Process a single extraction task
|
|
70
|
+
*/
|
|
71
|
+
private processTask;
|
|
72
|
+
/**
|
|
73
|
+
* Apply memory operations to the storage adapter
|
|
74
|
+
*/
|
|
75
|
+
private applyOperations;
|
|
76
|
+
/**
|
|
77
|
+
* Extract facts immediately (synchronous, for testing)
|
|
78
|
+
*/
|
|
79
|
+
extractNow(userId: string, sessionId: string, userMessage: string, assistantResponse: string): Promise<ExtractionResult>;
|
|
80
|
+
/**
|
|
81
|
+
* Get the current queue length
|
|
82
|
+
*/
|
|
83
|
+
getQueueLength(): number;
|
|
84
|
+
/**
|
|
85
|
+
* Check if the worker is currently processing
|
|
86
|
+
*/
|
|
87
|
+
isProcessing(): boolean;
|
|
88
|
+
/**
|
|
89
|
+
* Wait for all queued tasks to complete
|
|
90
|
+
*/
|
|
91
|
+
drain(): Promise<void>;
|
|
92
|
+
/**
|
|
93
|
+
* Get effective importance for an operation.
|
|
94
|
+
* Auto-escalates safety-critical predicates (allergies, medical, boundaries).
|
|
95
|
+
*/
|
|
96
|
+
private getEffectiveImportance;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
interface ContextHydratorConfig {
|
|
100
|
+
/** Maximum number of facts to include in context */
|
|
101
|
+
maxFacts?: number;
|
|
102
|
+
/** Maximum number of recent messages to include */
|
|
103
|
+
maxHistory?: number;
|
|
104
|
+
/** Format style for compiled prompt */
|
|
105
|
+
formatStyle?: "natural" | "structured" | "minimal";
|
|
106
|
+
/** Minimum confidence threshold for facts (0-1) */
|
|
107
|
+
minConfidence?: number;
|
|
108
|
+
/** Wrap context in safety tags to prevent injection */
|
|
109
|
+
safeMode?: boolean;
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* The "Fast Brain" - Builds compiled context for LLM injection.
|
|
113
|
+
* Runs synchronously before each LLM call.
|
|
114
|
+
*/
|
|
115
|
+
declare class ContextHydrator {
|
|
116
|
+
private adapter;
|
|
117
|
+
private config;
|
|
118
|
+
constructor(adapter: BaseAdapter, config?: ContextHydratorConfig);
|
|
119
|
+
/**
|
|
120
|
+
* Hydrate context for a user based on their message.
|
|
121
|
+
*
|
|
122
|
+
* Uses the "Amygdala pattern":
|
|
123
|
+
* 1. CRITICAL facts (importance >= 9) are ALWAYS included
|
|
124
|
+
* 2. Remaining budget filled with recent, high-confidence facts
|
|
125
|
+
*/
|
|
126
|
+
hydrate(userId: string, _message: string, options?: HydrateOptions): Promise<HydratedContext>;
|
|
127
|
+
/**
|
|
128
|
+
* Record fact access for Hebbian learning (strengthens frequently used facts)
|
|
129
|
+
*/
|
|
130
|
+
private recordAccess;
|
|
131
|
+
/**
|
|
132
|
+
* Compile facts and history into a prompt string
|
|
133
|
+
*/
|
|
134
|
+
private compilePrompt;
|
|
135
|
+
/**
|
|
136
|
+
* Natural language format (default)
|
|
137
|
+
*/
|
|
138
|
+
private compileNatural;
|
|
139
|
+
/**
|
|
140
|
+
* Structured format (for debugging or specific use cases)
|
|
141
|
+
*/
|
|
142
|
+
private compileStructured;
|
|
143
|
+
/**
|
|
144
|
+
* Minimal format (just facts, no history)
|
|
145
|
+
*/
|
|
146
|
+
private compileMinimal;
|
|
147
|
+
/**
|
|
148
|
+
* Convert a fact to natural language
|
|
149
|
+
*/
|
|
150
|
+
private factToNaturalLanguage;
|
|
151
|
+
/**
|
|
152
|
+
* Group facts by subject
|
|
153
|
+
*/
|
|
154
|
+
private groupFactsBySubject;
|
|
155
|
+
/**
|
|
156
|
+
* Truncate text to a maximum length
|
|
157
|
+
*/
|
|
158
|
+
private truncate;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Configuration for semantic cache
|
|
163
|
+
*/
|
|
164
|
+
interface SemanticCacheConfig {
|
|
165
|
+
/** Maximum cache size per user */
|
|
166
|
+
maxSize?: number;
|
|
167
|
+
/** TTL in milliseconds (default: 5 minutes) */
|
|
168
|
+
ttlMs?: number;
|
|
169
|
+
/** Similarity threshold for cache hit (0-1) */
|
|
170
|
+
similarityThreshold?: number;
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* In-memory semantic cache for reducing redundant hydrations.
|
|
174
|
+
* Uses simple string similarity for matching - can be extended with embeddings.
|
|
175
|
+
*/
|
|
176
|
+
declare class SemanticCache {
|
|
177
|
+
private cache;
|
|
178
|
+
private config;
|
|
179
|
+
private stats;
|
|
180
|
+
constructor(config?: SemanticCacheConfig);
|
|
181
|
+
/**
|
|
182
|
+
* Try to get a cached context for a query
|
|
183
|
+
*/
|
|
184
|
+
get(userId: string, query: string): HydratedContext | null;
|
|
185
|
+
/**
|
|
186
|
+
* Store a context in the cache
|
|
187
|
+
*/
|
|
188
|
+
set(userId: string, query: string, context: HydratedContext): void;
|
|
189
|
+
/**
|
|
190
|
+
* Invalidate cache for a user (call after digest)
|
|
191
|
+
*/
|
|
192
|
+
invalidate(userId: string): void;
|
|
193
|
+
/**
|
|
194
|
+
* Clear all cache entries
|
|
195
|
+
*/
|
|
196
|
+
clear(): void;
|
|
197
|
+
/**
|
|
198
|
+
* Get cache statistics
|
|
199
|
+
*/
|
|
200
|
+
getStats(): {
|
|
201
|
+
hits: number;
|
|
202
|
+
misses: number;
|
|
203
|
+
evictions: number;
|
|
204
|
+
hitRate: number;
|
|
205
|
+
};
|
|
206
|
+
/**
|
|
207
|
+
* Calculate simple string similarity using Jaccard index on word tokens
|
|
208
|
+
*/
|
|
209
|
+
private calculateSimilarity;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Token economics utilities for mem-ts.
|
|
214
|
+
* Provides token estimation, compression, and analytics.
|
|
215
|
+
*/
|
|
216
|
+
/**
|
|
217
|
+
* Token usage statistics
|
|
218
|
+
*/
|
|
219
|
+
interface TokenUsage {
|
|
220
|
+
inputTokens: number;
|
|
221
|
+
outputTokens: number;
|
|
222
|
+
totalTokens: number;
|
|
223
|
+
estimatedCost?: number;
|
|
224
|
+
}
|
|
225
|
+
/**
|
|
226
|
+
* Token analytics over time
|
|
227
|
+
*/
|
|
228
|
+
interface TokenAnalytics {
|
|
229
|
+
totalInputTokens: number;
|
|
230
|
+
totalOutputTokens: number;
|
|
231
|
+
totalCalls: number;
|
|
232
|
+
averageInputTokens: number;
|
|
233
|
+
averageOutputTokens: number;
|
|
234
|
+
tokensSavedByCache: number;
|
|
235
|
+
tokensSavedByCompression: number;
|
|
236
|
+
estimatedSavings: number;
|
|
237
|
+
}
|
|
238
|
+
/**
|
|
239
|
+
* Pricing per 1M tokens (approximate, as of late 2024)
|
|
240
|
+
*/
|
|
241
|
+
declare const TOKEN_PRICING: Record<string, {
|
|
242
|
+
input: number;
|
|
243
|
+
output: number;
|
|
244
|
+
}>;
|
|
245
|
+
/**
|
|
246
|
+
* Estimate token count for a string.
|
|
247
|
+
* Uses a simple heuristic: ~4 characters per token for English text.
|
|
248
|
+
* For more accurate counts, use tiktoken or similar.
|
|
249
|
+
*/
|
|
250
|
+
declare function estimateTokens(text: string): number;
|
|
251
|
+
/**
|
|
252
|
+
* Estimate cost for a given token usage
|
|
253
|
+
*/
|
|
254
|
+
declare function estimateCost(usage: {
|
|
255
|
+
inputTokens: number;
|
|
256
|
+
outputTokens: number;
|
|
257
|
+
}, model: string): number;
|
|
258
|
+
/**
|
|
259
|
+
* Token analytics tracker
|
|
260
|
+
*/
|
|
261
|
+
declare class TokenTracker {
|
|
262
|
+
private usages;
|
|
263
|
+
private tokensSavedByCache;
|
|
264
|
+
private tokensSavedByCompression;
|
|
265
|
+
private model;
|
|
266
|
+
constructor(model?: string);
|
|
267
|
+
/**
|
|
268
|
+
* Record a token usage
|
|
269
|
+
*/
|
|
270
|
+
record(usage: {
|
|
271
|
+
inputTokens: number;
|
|
272
|
+
outputTokens: number;
|
|
273
|
+
}): void;
|
|
274
|
+
/**
|
|
275
|
+
* Record tokens saved by cache hit
|
|
276
|
+
*/
|
|
277
|
+
recordCacheSavings(tokens: number): void;
|
|
278
|
+
/**
|
|
279
|
+
* Record tokens saved by compression
|
|
280
|
+
*/
|
|
281
|
+
recordCompressionSavings(originalTokens: number, compressedTokens: number): void;
|
|
282
|
+
/**
|
|
283
|
+
* Get analytics summary
|
|
284
|
+
*/
|
|
285
|
+
getAnalytics(): TokenAnalytics;
|
|
286
|
+
/**
|
|
287
|
+
* Reset analytics
|
|
288
|
+
*/
|
|
289
|
+
reset(): void;
|
|
290
|
+
}
|
|
291
|
+
/**
|
|
292
|
+
* Compress conversation history by summarizing older messages.
|
|
293
|
+
* Returns a compressed conversation array.
|
|
294
|
+
*/
|
|
295
|
+
declare function compressConversation(messages: Array<{
|
|
296
|
+
role: string;
|
|
297
|
+
content: string;
|
|
298
|
+
}>, options?: {
|
|
299
|
+
keepRecent?: number;
|
|
300
|
+
maxSummaryTokens?: number;
|
|
301
|
+
}): {
|
|
302
|
+
messages: Array<{
|
|
303
|
+
role: string;
|
|
304
|
+
content: string;
|
|
305
|
+
}>;
|
|
306
|
+
originalTokens: number;
|
|
307
|
+
compressedTokens: number;
|
|
308
|
+
};
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* Event types for MemoryOS
|
|
312
|
+
*/
|
|
313
|
+
interface MemoryEvents {
|
|
314
|
+
"fact:created": {
|
|
315
|
+
fact: MemoryFact;
|
|
316
|
+
userId: string;
|
|
317
|
+
};
|
|
318
|
+
"fact:updated": {
|
|
319
|
+
fact: MemoryFact;
|
|
320
|
+
oldFact: MemoryFact;
|
|
321
|
+
userId: string;
|
|
322
|
+
};
|
|
323
|
+
"fact:deleted": {
|
|
324
|
+
fact: MemoryFact;
|
|
325
|
+
reason?: string;
|
|
326
|
+
userId: string;
|
|
327
|
+
};
|
|
328
|
+
"session:start": {
|
|
329
|
+
session: Session;
|
|
330
|
+
};
|
|
331
|
+
"session:end": {
|
|
332
|
+
session: Session;
|
|
333
|
+
};
|
|
334
|
+
"extraction:start": {
|
|
335
|
+
userId: string;
|
|
336
|
+
sessionId: string;
|
|
337
|
+
};
|
|
338
|
+
"extraction:complete": {
|
|
339
|
+
result: ExtractionResult;
|
|
340
|
+
userId: string;
|
|
341
|
+
sessionId: string;
|
|
342
|
+
};
|
|
343
|
+
"hydration:start": {
|
|
344
|
+
userId: string;
|
|
345
|
+
message: string;
|
|
346
|
+
};
|
|
347
|
+
"hydration:complete": {
|
|
348
|
+
userId: string;
|
|
349
|
+
factsCount: number;
|
|
350
|
+
fromCache: boolean;
|
|
351
|
+
};
|
|
352
|
+
"cache:hit": {
|
|
353
|
+
userId: string;
|
|
354
|
+
query: string;
|
|
355
|
+
};
|
|
356
|
+
"cache:miss": {
|
|
357
|
+
userId: string;
|
|
358
|
+
query: string;
|
|
359
|
+
};
|
|
360
|
+
error: {
|
|
361
|
+
error: Error;
|
|
362
|
+
context?: string;
|
|
363
|
+
};
|
|
364
|
+
}
|
|
365
|
+
type EventHandler<T> = (data: T) => void;
|
|
366
|
+
/**
|
|
367
|
+
* Simple event emitter for MemoryOS events.
|
|
368
|
+
* Provides type-safe event handling.
|
|
369
|
+
*/
|
|
370
|
+
declare class MemoryEventEmitter {
|
|
371
|
+
private handlers;
|
|
372
|
+
/**
|
|
373
|
+
* Subscribe to an event
|
|
374
|
+
*/
|
|
375
|
+
on<K extends keyof MemoryEvents>(event: K, handler: EventHandler<MemoryEvents[K]>): () => void;
|
|
376
|
+
/**
|
|
377
|
+
* Subscribe to an event once
|
|
378
|
+
*/
|
|
379
|
+
once<K extends keyof MemoryEvents>(event: K, handler: EventHandler<MemoryEvents[K]>): () => void;
|
|
380
|
+
/**
|
|
381
|
+
* Emit an event
|
|
382
|
+
*/
|
|
383
|
+
emit<K extends keyof MemoryEvents>(event: K, data: MemoryEvents[K]): void;
|
|
384
|
+
/**
|
|
385
|
+
* Remove all handlers for an event
|
|
386
|
+
*/
|
|
387
|
+
off<K extends keyof MemoryEvents>(event: K): void;
|
|
388
|
+
/**
|
|
389
|
+
* Remove all handlers
|
|
390
|
+
*/
|
|
391
|
+
removeAllListeners(): void;
|
|
392
|
+
/**
|
|
393
|
+
* Get handler count for an event
|
|
394
|
+
*/
|
|
395
|
+
listenerCount<K extends keyof MemoryEvents>(event: K): number;
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Security utilities for mem-ts.
|
|
400
|
+
* Protects against prompt injection and data poisoning.
|
|
401
|
+
*/
|
|
402
|
+
interface SecurityConfig {
|
|
403
|
+
/** Enable prompt injection detection */
|
|
404
|
+
detectInjection?: boolean;
|
|
405
|
+
/** Block facts that contain injection patterns */
|
|
406
|
+
blockInjectedFacts?: boolean;
|
|
407
|
+
/** Detect PII in facts */
|
|
408
|
+
detectPii?: boolean;
|
|
409
|
+
/** Redact PII before storing */
|
|
410
|
+
redactPii?: boolean;
|
|
411
|
+
/** Custom patterns to block */
|
|
412
|
+
customBlockPatterns?: RegExp[];
|
|
413
|
+
}
|
|
414
|
+
interface SecurityCheckResult {
|
|
415
|
+
safe: boolean;
|
|
416
|
+
issues: Array<{
|
|
417
|
+
type: "injection" | "pii" | "custom";
|
|
418
|
+
description: string;
|
|
419
|
+
location?: string;
|
|
420
|
+
}>;
|
|
421
|
+
sanitized?: string;
|
|
422
|
+
}
|
|
423
|
+
/**
|
|
424
|
+
* Security scanner for memory content
|
|
425
|
+
*/
|
|
426
|
+
declare class SecurityScanner {
|
|
427
|
+
private config;
|
|
428
|
+
constructor(config?: SecurityConfig);
|
|
429
|
+
/**
|
|
430
|
+
* Scan text for security issues
|
|
431
|
+
*/
|
|
432
|
+
scan(text: string): SecurityCheckResult;
|
|
433
|
+
/**
|
|
434
|
+
* Check if a fact is safe to store
|
|
435
|
+
*/
|
|
436
|
+
isSafeToStore(fact: {
|
|
437
|
+
subject: string;
|
|
438
|
+
predicate: string;
|
|
439
|
+
object: string;
|
|
440
|
+
}): SecurityCheckResult;
|
|
441
|
+
}
|
|
442
|
+
/**
|
|
443
|
+
* Wrap memory context in XML tags to instruct the LLM to treat it as data.
|
|
444
|
+
* This is a mitigation against prompt injection via memory.
|
|
445
|
+
*/
|
|
446
|
+
declare function wrapContextSafely(context: string): string;
|
|
447
|
+
/**
|
|
448
|
+
* Sanitize a string for safe storage
|
|
449
|
+
*/
|
|
450
|
+
declare function sanitizeForStorage(text: string): string;
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Budget management for mem-ts.
|
|
454
|
+
* Prevents runaway costs from infinite loops or abuse.
|
|
455
|
+
*/
|
|
456
|
+
interface BudgetConfig {
|
|
457
|
+
/** Maximum tokens per user per day for background processing */
|
|
458
|
+
maxTokensPerUserPerDay?: number;
|
|
459
|
+
/** Maximum extraction calls per user per day */
|
|
460
|
+
maxExtractionsPerUserPerDay?: number;
|
|
461
|
+
/** Maximum facts per user (to prevent storage abuse) */
|
|
462
|
+
maxFactsPerUser?: number;
|
|
463
|
+
/** Maximum conversations stored per user */
|
|
464
|
+
maxConversationsPerUser?: number;
|
|
465
|
+
/** Cooldown between extractions in ms (prevents rapid-fire) */
|
|
466
|
+
extractionCooldownMs?: number;
|
|
467
|
+
}
|
|
468
|
+
/**
|
|
469
|
+
* Budget manager to prevent runaway costs and abuse.
|
|
470
|
+
*/
|
|
471
|
+
declare class BudgetManager {
|
|
472
|
+
private config;
|
|
473
|
+
private userBudgets;
|
|
474
|
+
constructor(config?: BudgetConfig);
|
|
475
|
+
private getToday;
|
|
476
|
+
private getUserState;
|
|
477
|
+
/**
|
|
478
|
+
* Check if a user can perform an extraction
|
|
479
|
+
*/
|
|
480
|
+
canExtract(userId: string): {
|
|
481
|
+
allowed: boolean;
|
|
482
|
+
reason?: string;
|
|
483
|
+
};
|
|
484
|
+
/**
|
|
485
|
+
* Check if a user has token budget remaining
|
|
486
|
+
*/
|
|
487
|
+
canUseTokens(userId: string, estimatedTokens: number): {
|
|
488
|
+
allowed: boolean;
|
|
489
|
+
reason?: string;
|
|
490
|
+
};
|
|
491
|
+
/**
|
|
492
|
+
* Record an extraction
|
|
493
|
+
*/
|
|
494
|
+
recordExtraction(userId: string): void;
|
|
495
|
+
/**
|
|
496
|
+
* Record token usage
|
|
497
|
+
*/
|
|
498
|
+
recordTokens(userId: string, tokens: number): void;
|
|
499
|
+
/**
|
|
500
|
+
* Get remaining budget for a user
|
|
501
|
+
*/
|
|
502
|
+
getRemainingBudget(userId: string): {
|
|
503
|
+
tokensRemaining: number;
|
|
504
|
+
extractionsRemaining: number;
|
|
505
|
+
};
|
|
506
|
+
/**
|
|
507
|
+
* Get max facts allowed per user
|
|
508
|
+
*/
|
|
509
|
+
getMaxFactsPerUser(): number;
|
|
510
|
+
/**
|
|
511
|
+
* Get max conversations allowed per user
|
|
512
|
+
*/
|
|
513
|
+
getMaxConversationsPerUser(): number;
|
|
514
|
+
/**
|
|
515
|
+
* Reset a user's budget (for testing or admin override)
|
|
516
|
+
*/
|
|
517
|
+
resetUserBudget(userId: string): void;
|
|
518
|
+
/**
|
|
519
|
+
* Get current usage stats for a user
|
|
520
|
+
*/
|
|
521
|
+
getUsageStats(userId: string): {
|
|
522
|
+
tokensUsedToday: number;
|
|
523
|
+
extractionsToday: number;
|
|
524
|
+
tokensRemaining: number;
|
|
525
|
+
extractionsRemaining: number;
|
|
526
|
+
};
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/**
|
|
530
|
+
* Memory decay utilities for mem-ts.
|
|
531
|
+
* Prevents the "stalker effect" by forgetting irrelevant facts over time.
|
|
532
|
+
*/
|
|
533
|
+
|
|
534
|
+
interface DecayConfig {
|
|
535
|
+
/** Enable automatic decay */
|
|
536
|
+
enabled?: boolean;
|
|
537
|
+
/** Default TTL for facts in days (null = never expire) */
|
|
538
|
+
defaultTtlDays?: number | null;
|
|
539
|
+
/** TTL for low-weight facts (confidence < 0.5) in days */
|
|
540
|
+
lowWeightTtlDays?: number;
|
|
541
|
+
/** Predicates that should never decay (e.g., NAME, ALLERGY) */
|
|
542
|
+
permanentPredicates?: string[];
|
|
543
|
+
/** Predicates that should decay quickly (e.g., WEARING, CURRENT_MOOD) */
|
|
544
|
+
ephemeralPredicates?: string[];
|
|
545
|
+
/** TTL for ephemeral predicates in hours */
|
|
546
|
+
ephemeralTtlHours?: number;
|
|
547
|
+
/** Minimum reinforcement count to become "permanent" */
|
|
548
|
+
reinforcementThreshold?: number;
|
|
549
|
+
}
|
|
550
|
+
interface FactWithDecay extends MemoryFact {
|
|
551
|
+
/** Number of times this fact has been reinforced (mentioned again) */
|
|
552
|
+
reinforcementCount?: number;
|
|
553
|
+
/** Last time the fact was reinforced */
|
|
554
|
+
lastReinforcedAt?: Date;
|
|
555
|
+
/** Calculated decay weight (0-1, where 0 = should be deleted) */
|
|
556
|
+
decayWeight?: number;
|
|
557
|
+
/** Calculated expiry time */
|
|
558
|
+
expiresAt?: Date | null;
|
|
559
|
+
}
|
|
560
|
+
/**
|
|
561
|
+
* Decay manager for memory facts
|
|
562
|
+
*/
|
|
563
|
+
declare class DecayManager {
|
|
564
|
+
private config;
|
|
565
|
+
constructor(config?: DecayConfig);
|
|
566
|
+
/**
|
|
567
|
+
* Calculate decay weight for a fact (0-1, where 0 = should be deleted)
|
|
568
|
+
*/
|
|
569
|
+
calculateDecayWeight(fact: FactWithDecay): number;
|
|
570
|
+
/**
|
|
571
|
+
* Calculate expiry date for a fact
|
|
572
|
+
*/
|
|
573
|
+
calculateExpiryDate(fact: FactWithDecay): Date | null;
|
|
574
|
+
/**
|
|
575
|
+
* Check if a fact should be pruned
|
|
576
|
+
*/
|
|
577
|
+
shouldPrune(fact: FactWithDecay): boolean;
|
|
578
|
+
/**
|
|
579
|
+
* Filter facts by decay weight threshold
|
|
580
|
+
*/
|
|
581
|
+
filterByWeight(facts: FactWithDecay[], minWeight?: number): FactWithDecay[];
|
|
582
|
+
/**
|
|
583
|
+
* Get facts that should be pruned
|
|
584
|
+
*/
|
|
585
|
+
getFactsToPrune(facts: FactWithDecay[]): FactWithDecay[];
|
|
586
|
+
/**
|
|
587
|
+
* Check if a predicate is permanent (never decays)
|
|
588
|
+
*/
|
|
589
|
+
isPermanent(predicate: string): boolean;
|
|
590
|
+
/**
|
|
591
|
+
* Check if a predicate is ephemeral (decays quickly)
|
|
592
|
+
*/
|
|
593
|
+
isEphemeral(predicate: string): boolean;
|
|
594
|
+
/**
|
|
595
|
+
* Add a predicate to permanent list
|
|
596
|
+
*/
|
|
597
|
+
addPermanentPredicate(predicate: string): void;
|
|
598
|
+
/**
|
|
599
|
+
* Add a predicate to ephemeral list
|
|
600
|
+
*/
|
|
601
|
+
addEphemeralPredicate(predicate: string): void;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
/**
|
|
605
|
+
* Auto-summarization manager for mem-ts.
|
|
606
|
+
* Triggers conversation summarization after a threshold of messages.
|
|
607
|
+
*/
|
|
608
|
+
|
|
609
|
+
interface AutoSummarizeConfig {
|
|
610
|
+
/** Enable auto-summarization */
|
|
611
|
+
enabled?: boolean;
|
|
612
|
+
/** Number of messages before triggering summarization */
|
|
613
|
+
threshold?: number;
|
|
614
|
+
/** Maximum summary length in characters */
|
|
615
|
+
maxSummaryLength?: number;
|
|
616
|
+
}
|
|
617
|
+
/**
|
|
618
|
+
* Auto-summarization manager
|
|
619
|
+
*/
|
|
620
|
+
declare class AutoSummarizer {
|
|
621
|
+
private adapter;
|
|
622
|
+
private provider;
|
|
623
|
+
private config;
|
|
624
|
+
private messageCounters;
|
|
625
|
+
constructor(adapter: BaseAdapter, provider: BaseProvider | null, config?: AutoSummarizeConfig);
|
|
626
|
+
/**
|
|
627
|
+
* Record a message and check if summarization should trigger
|
|
628
|
+
*/
|
|
629
|
+
recordMessage(userId: string, sessionId: string): Promise<boolean>;
|
|
630
|
+
/**
|
|
631
|
+
* Summarize a session's conversation history
|
|
632
|
+
*/
|
|
633
|
+
summarizeSession(userId: string, sessionId: string): Promise<string | null>;
|
|
634
|
+
/**
|
|
635
|
+
* Get current message count for a session
|
|
636
|
+
*/
|
|
637
|
+
getMessageCount(userId: string, sessionId: string): number;
|
|
638
|
+
/**
|
|
639
|
+
* Reset message counter for a session
|
|
640
|
+
*/
|
|
641
|
+
resetCounter(userId: string, sessionId: string): void;
|
|
642
|
+
/**
|
|
643
|
+
* Force summarization regardless of count
|
|
644
|
+
*/
|
|
645
|
+
forceSummarize(userId: string, sessionId: string): Promise<string | null>;
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
/**
|
|
649
|
+
* Tiered storage adapter for mem-ts.
|
|
650
|
+
* Manages automatic data flow between hot, warm, and cold storage tiers.
|
|
651
|
+
*/
|
|
652
|
+
|
|
653
|
+
interface TieredAdapterConfig {
|
|
654
|
+
/** Hot storage (fast, limited) - e.g., Redis, in-memory */
|
|
655
|
+
hotAdapter: BaseAdapter;
|
|
656
|
+
/** Cold storage (slow, unlimited) - e.g., Postgres, MongoDB */
|
|
657
|
+
coldAdapter: BaseAdapter;
|
|
658
|
+
/** Maximum facts to keep in hot storage per user */
|
|
659
|
+
hotFactLimit?: number;
|
|
660
|
+
/** Maximum conversations to keep in hot storage per user */
|
|
661
|
+
hotConversationLimit?: number;
|
|
662
|
+
/** Automatically promote frequently accessed facts to hot */
|
|
663
|
+
autoPromote?: boolean;
|
|
664
|
+
/** Automatically demote old facts to cold */
|
|
665
|
+
autoDemote?: boolean;
|
|
666
|
+
}
|
|
667
|
+
/**
|
|
668
|
+
* Tiered storage adapter that manages hot (fast) and cold (persistent) storage.
|
|
669
|
+
*
|
|
670
|
+
* Hot tier: Recent/frequently accessed data for fast retrieval
|
|
671
|
+
* Cold tier: Long-term persistent storage
|
|
672
|
+
*
|
|
673
|
+
* Read path: Hot first, fall back to cold, promote on access
|
|
674
|
+
* Write path: Write to both (hot for speed, cold for durability)
|
|
675
|
+
*/
|
|
676
|
+
declare class TieredAdapter extends BaseAdapter {
|
|
677
|
+
private hot;
|
|
678
|
+
private cold;
|
|
679
|
+
private config;
|
|
680
|
+
constructor(config: TieredAdapterConfig);
|
|
681
|
+
initialize(): Promise<void>;
|
|
682
|
+
close(): Promise<void>;
|
|
683
|
+
getFacts(userId: string, filter?: FactFilter): Promise<MemoryFact[]>;
|
|
684
|
+
getFactById(userId: string, factId: string): Promise<MemoryFact | null>;
|
|
685
|
+
upsertFact(userId: string, fact: Omit<MemoryFact, "id" | "createdAt" | "updatedAt">): Promise<MemoryFact>;
|
|
686
|
+
updateFact(userId: string, factId: string, updates: Partial<MemoryFact>): Promise<MemoryFact>;
|
|
687
|
+
deleteFact(userId: string, factId: string, reason?: string): Promise<void>;
|
|
688
|
+
hardDeleteFact(userId: string, factId: string): Promise<void>;
|
|
689
|
+
getConversationHistory(userId: string, limit?: number, sessionId?: string): Promise<ConversationExchange[]>;
|
|
690
|
+
saveConversation(userId: string, exchange: Omit<ConversationExchange, "id">): Promise<ConversationExchange>;
|
|
691
|
+
getSessions(userId: string, limit?: number): Promise<Session[]>;
|
|
692
|
+
getSession(userId: string, sessionId: string): Promise<Session | null>;
|
|
693
|
+
createSession(userId: string): Promise<Session>;
|
|
694
|
+
endSession(userId: string, sessionId: string, summary?: string): Promise<Session>;
|
|
695
|
+
private promoteFactsToHot;
|
|
696
|
+
private demoteOldFacts;
|
|
697
|
+
private demoteOldConversations;
|
|
698
|
+
/**
|
|
699
|
+
* Manually promote a fact to hot storage
|
|
700
|
+
*/
|
|
701
|
+
promoteToHot(userId: string, factId: string): Promise<void>;
|
|
702
|
+
/**
|
|
703
|
+
* Manually demote a fact from hot storage
|
|
704
|
+
*/
|
|
705
|
+
demoteFromHot(userId: string, factId: string): Promise<void>;
|
|
706
|
+
/**
|
|
707
|
+
* Sync all facts from cold to hot for a user (cache warming)
|
|
708
|
+
*/
|
|
709
|
+
warmCache(userId: string): Promise<void>;
|
|
710
|
+
/**
|
|
711
|
+
* Get storage statistics
|
|
712
|
+
*/
|
|
713
|
+
getStorageStats(userId: string): Promise<{
|
|
714
|
+
hotFacts: number;
|
|
715
|
+
coldFacts: number;
|
|
716
|
+
hotConversations: number;
|
|
717
|
+
coldConversations: number;
|
|
718
|
+
}>;
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
/**
|
|
722
|
+
* Embeddings support for mem-ts.
|
|
723
|
+
* Provides vector embeddings for semantic search.
|
|
724
|
+
*/
|
|
725
|
+
interface EmbeddingConfig {
|
|
726
|
+
/** Embedding provider */
|
|
727
|
+
provider: "openai" | "cohere" | "local";
|
|
728
|
+
/** API key (for cloud providers) */
|
|
729
|
+
apiKey?: string;
|
|
730
|
+
/** Model to use */
|
|
731
|
+
model?: string;
|
|
732
|
+
/** Embedding dimensions */
|
|
733
|
+
dimensions?: number;
|
|
734
|
+
}
|
|
735
|
+
interface EmbeddingResult {
|
|
736
|
+
/** The embedding vector */
|
|
737
|
+
vector: number[];
|
|
738
|
+
/** Token count */
|
|
739
|
+
tokens: number;
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* Embedding provider interface
|
|
743
|
+
*/
|
|
744
|
+
declare abstract class BaseEmbeddingProvider {
|
|
745
|
+
protected config: EmbeddingConfig;
|
|
746
|
+
constructor(config: EmbeddingConfig);
|
|
747
|
+
abstract embed(text: string): Promise<EmbeddingResult>;
|
|
748
|
+
abstract embedBatch(texts: string[]): Promise<EmbeddingResult[]>;
|
|
749
|
+
abstract getDimensions(): number;
|
|
750
|
+
}
|
|
751
|
+
/**
|
|
752
|
+
* OpenAI embedding provider
|
|
753
|
+
*/
|
|
754
|
+
declare class OpenAIEmbeddingProvider extends BaseEmbeddingProvider {
|
|
755
|
+
private model;
|
|
756
|
+
private dimensions;
|
|
757
|
+
constructor(config: EmbeddingConfig);
|
|
758
|
+
embed(text: string): Promise<EmbeddingResult>;
|
|
759
|
+
embedBatch(texts: string[]): Promise<EmbeddingResult[]>;
|
|
760
|
+
getDimensions(): number;
|
|
761
|
+
}
|
|
762
|
+
/**
|
|
763
|
+
* Calculate cosine similarity between two vectors
|
|
764
|
+
*/
|
|
765
|
+
declare function cosineSimilarity(a: number[], b: number[]): number;
|
|
766
|
+
/**
|
|
767
|
+
* Find top-k most similar vectors
|
|
768
|
+
*/
|
|
769
|
+
declare function findTopK(query: number[], candidates: Array<{
|
|
770
|
+
id: string;
|
|
771
|
+
vector: number[];
|
|
772
|
+
}>, k: number): Array<{
|
|
773
|
+
id: string;
|
|
774
|
+
similarity: number;
|
|
775
|
+
}>;
|
|
776
|
+
/**
|
|
777
|
+
* In-memory vector store for simple use cases
|
|
778
|
+
*/
|
|
779
|
+
declare class InMemoryVectorStore {
|
|
780
|
+
private vectors;
|
|
781
|
+
/**
|
|
782
|
+
* Store a vector for a user
|
|
783
|
+
*/
|
|
784
|
+
store(userId: string, id: string, vector: number[]): void;
|
|
785
|
+
/**
|
|
786
|
+
* Search for similar vectors
|
|
787
|
+
*/
|
|
788
|
+
search(userId: string, query: number[], k?: number): Array<{
|
|
789
|
+
id: string;
|
|
790
|
+
similarity: number;
|
|
791
|
+
}>;
|
|
792
|
+
/**
|
|
793
|
+
* Delete a vector
|
|
794
|
+
*/
|
|
795
|
+
delete(userId: string, id: string): void;
|
|
796
|
+
/**
|
|
797
|
+
* Clear all vectors for a user
|
|
798
|
+
*/
|
|
799
|
+
clear(userId: string): void;
|
|
800
|
+
/**
|
|
801
|
+
* Get vector count for a user
|
|
802
|
+
*/
|
|
803
|
+
count(userId: string): number;
|
|
804
|
+
}
|
|
805
|
+
/**
|
|
806
|
+
* Create an embedding provider
|
|
807
|
+
*/
|
|
808
|
+
declare function createEmbeddingProvider(config: EmbeddingConfig): BaseEmbeddingProvider;
|
|
809
|
+
|
|
810
|
+
/**
|
|
811
|
+
* Deep Sleep Worker - "Sleep Synthesis" for pattern recognition.
|
|
812
|
+
*
|
|
813
|
+
* Runs on a schedule (not per-message) to find higher-level patterns
|
|
814
|
+
* across multiple conversations over time.
|
|
815
|
+
*
|
|
816
|
+
* Biological analogy: During sleep, the brain consolidates memories
|
|
817
|
+
* and connects dots between experiences that happened days apart.
|
|
818
|
+
*/
|
|
819
|
+
|
|
820
|
+
interface DeepSleepConfig {
|
|
821
|
+
/** Hours to look back for recent facts (default: 24) */
|
|
822
|
+
lookbackHours?: number;
|
|
823
|
+
/** Minimum facts needed to trigger synthesis (default: 3) */
|
|
824
|
+
minFactsForSynthesis?: number;
|
|
825
|
+
/** Maximum new insights to generate (default: 5) */
|
|
826
|
+
maxInsights?: number;
|
|
827
|
+
/** Minimum confidence for synthesized insights (default: 0.7) */
|
|
828
|
+
minInsightConfidence?: number;
|
|
829
|
+
/** Enable debug logging */
|
|
830
|
+
debug?: boolean;
|
|
831
|
+
}
|
|
832
|
+
/**
|
|
833
|
+
* Deep Sleep Worker - Scheduled batch synthesis for pattern recognition.
|
|
834
|
+
*
|
|
835
|
+
* Call `runSynthesisCycle(userId)` on a schedule (e.g., nightly cron).
|
|
836
|
+
*/
|
|
837
|
+
declare class DeepSleepWorker {
|
|
838
|
+
private provider;
|
|
839
|
+
private adapter;
|
|
840
|
+
private config;
|
|
841
|
+
constructor(provider: BaseProvider, adapter: BaseAdapter, config?: DeepSleepConfig);
|
|
842
|
+
/**
|
|
843
|
+
* Run a synthesis cycle for a user.
|
|
844
|
+
* Meant to be called on a schedule (e.g., nightly).
|
|
845
|
+
*/
|
|
846
|
+
runSynthesisCycle(userId: string): Promise<MemoryOperation[]>;
|
|
847
|
+
/**
|
|
848
|
+
* Run synthesis for all active users.
|
|
849
|
+
* Call this from a cron job for batch processing.
|
|
850
|
+
*/
|
|
851
|
+
runGlobalCycle(userIds: string[]): Promise<Map<string, MemoryOperation[]>>;
|
|
852
|
+
private buildPrompt;
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* Memory Consolidation Worker
|
|
857
|
+
*
|
|
858
|
+
* Implements the three-stage memory model:
|
|
859
|
+
* - Short-term: Just learned, may not persist (< 1 hour, < 2 accesses)
|
|
860
|
+
* - Working: Being actively used (1-24 hours, 2-5 accesses)
|
|
861
|
+
* - Long-term: Consolidated through reinforcement (> 24 hours, > 5 accesses)
|
|
862
|
+
*
|
|
863
|
+
* Facts progress through stages based on time and access patterns.
|
|
864
|
+
*/
|
|
865
|
+
|
|
866
|
+
interface ConsolidationConfig {
|
|
867
|
+
/** Hours before short-term can become working (default: 1) */
|
|
868
|
+
shortTermHours?: number;
|
|
869
|
+
/** Hours before working can become long-term (default: 24) */
|
|
870
|
+
workingHours?: number;
|
|
871
|
+
/** Access count to promote short-term → working (default: 2) */
|
|
872
|
+
workingAccessThreshold?: number;
|
|
873
|
+
/** Access count to promote working → long-term (default: 5) */
|
|
874
|
+
longTermAccessThreshold?: number;
|
|
875
|
+
/** Enable debug logging */
|
|
876
|
+
debug?: boolean;
|
|
877
|
+
}
|
|
878
|
+
type MemoryStage = "short-term" | "working" | "long-term";
|
|
879
|
+
/**
|
|
880
|
+
* Manages memory consolidation through the three-stage model.
|
|
881
|
+
*/
|
|
882
|
+
declare class ConsolidationWorker {
|
|
883
|
+
private adapter;
|
|
884
|
+
private config;
|
|
885
|
+
constructor(adapter: BaseAdapter, config?: ConsolidationConfig);
|
|
886
|
+
/**
|
|
887
|
+
* Determine what stage a fact should be in based on age and access.
|
|
888
|
+
*/
|
|
889
|
+
determineStage(fact: MemoryFact): MemoryStage;
|
|
890
|
+
/**
|
|
891
|
+
* Run consolidation for a user's facts.
|
|
892
|
+
* Promotes facts through stages based on age and access patterns.
|
|
893
|
+
*/
|
|
894
|
+
consolidate(userId: string): Promise<{
|
|
895
|
+
promoted: number;
|
|
896
|
+
demoted: number;
|
|
897
|
+
unchanged: number;
|
|
898
|
+
}>;
|
|
899
|
+
/**
|
|
900
|
+
* Get facts filtered by memory stage.
|
|
901
|
+
*/
|
|
902
|
+
getFactsByStage(userId: string, stage: MemoryStage): Promise<MemoryFact[]>;
|
|
903
|
+
/**
|
|
904
|
+
* Automatically prune short-term facts that haven't been accessed.
|
|
905
|
+
* Call this periodically to clean up ephemeral memories.
|
|
906
|
+
*/
|
|
907
|
+
pruneShortTerm(userId: string, maxAgeHours?: number): Promise<number>;
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/**
|
|
911
|
+
* Contradiction Detection
|
|
912
|
+
*
|
|
913
|
+
* Detects when new facts conflict with existing facts in real-time.
|
|
914
|
+
* Can be used to:
|
|
915
|
+
* 1. Automatically resolve conflicts
|
|
916
|
+
* 2. Flag for user clarification
|
|
917
|
+
* 3. Emit events for logging/debugging
|
|
918
|
+
*/
|
|
919
|
+
|
|
920
|
+
interface ContradictionConfig {
|
|
921
|
+
/** Whether to auto-resolve contradictions (default: true) */
|
|
922
|
+
autoResolve?: boolean;
|
|
923
|
+
/** Use LLM to detect semantic contradictions (default: false) */
|
|
924
|
+
useLLM?: boolean;
|
|
925
|
+
/** Enable debug logging */
|
|
926
|
+
debug?: boolean;
|
|
927
|
+
}
|
|
928
|
+
interface Contradiction {
|
|
929
|
+
/** The new fact attempting to be stored */
|
|
930
|
+
newFact: MemoryOperation;
|
|
931
|
+
/** The existing fact it conflicts with */
|
|
932
|
+
existingFact: MemoryFact;
|
|
933
|
+
/** Type of contradiction */
|
|
934
|
+
type: "direct" | "semantic" | "temporal";
|
|
935
|
+
/** Confidence that this is a real contradiction (0-1) */
|
|
936
|
+
confidence: number;
|
|
937
|
+
/** Description of the contradiction */
|
|
938
|
+
description: string;
|
|
939
|
+
}
|
|
940
|
+
interface ContradictionResult {
|
|
941
|
+
/** Whether contradictions were found */
|
|
942
|
+
hasContradictions: boolean;
|
|
943
|
+
/** List of detected contradictions */
|
|
944
|
+
contradictions: Contradiction[];
|
|
945
|
+
/** Suggested resolution */
|
|
946
|
+
resolution?: "replace" | "keep" | "merge" | "clarify";
|
|
947
|
+
}
|
|
948
|
+
/**
|
|
949
|
+
* Detects contradictions between new and existing facts.
|
|
950
|
+
*/
|
|
951
|
+
declare class ContradictionDetector {
|
|
952
|
+
private adapter;
|
|
953
|
+
private provider?;
|
|
954
|
+
private config;
|
|
955
|
+
constructor(adapter: BaseAdapter, provider?: BaseProvider, config?: ContradictionConfig);
|
|
956
|
+
/**
|
|
957
|
+
* Check if a new operation contradicts existing facts.
|
|
958
|
+
*/
|
|
959
|
+
check(userId: string, operation: MemoryOperation): Promise<ContradictionResult>;
|
|
960
|
+
/**
|
|
961
|
+
* Analyze if two facts are truly contradictory.
|
|
962
|
+
*/
|
|
963
|
+
private analyzeContradiction;
|
|
964
|
+
/**
|
|
965
|
+
* Use LLM to detect semantic contradictions.
|
|
966
|
+
*/
|
|
967
|
+
private checkSemanticContradiction;
|
|
968
|
+
/**
|
|
969
|
+
* Check multiple operations at once.
|
|
970
|
+
*/
|
|
971
|
+
checkBatch(userId: string, operations: MemoryOperation[]): Promise<Map<number, ContradictionResult>>;
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
/**
|
|
975
|
+
* Association Engine - Knowledge Graph Links
|
|
976
|
+
*
|
|
977
|
+
* Creates and manages links between related facts.
|
|
978
|
+
* Enables richer context by connecting:
|
|
979
|
+
* - "likes hiking" → "likes outdoors"
|
|
980
|
+
* - "works at Google" → "is an engineer"
|
|
981
|
+
*/
|
|
982
|
+
|
|
983
|
+
interface AssociationConfig {
|
|
984
|
+
/** Minimum similarity score to auto-link (default: 0.7) */
|
|
985
|
+
similarityThreshold?: number;
|
|
986
|
+
/** Maximum associations per fact (default: 5) */
|
|
987
|
+
maxAssociations?: number;
|
|
988
|
+
/** Use LLM to find semantic relationships (default: false) */
|
|
989
|
+
useLLM?: boolean;
|
|
990
|
+
/** Enable debug logging */
|
|
991
|
+
debug?: boolean;
|
|
992
|
+
}
|
|
993
|
+
interface Association {
|
|
994
|
+
/** Source fact ID */
|
|
995
|
+
fromFactId: string;
|
|
996
|
+
/** Target fact ID */
|
|
997
|
+
toFactId: string;
|
|
998
|
+
/** Type of relationship */
|
|
999
|
+
relationship: "similar" | "implies" | "contradicts" | "related" | "causes";
|
|
1000
|
+
/** Strength of association (0-1) */
|
|
1001
|
+
strength: number;
|
|
1002
|
+
}
|
|
1003
|
+
/**
|
|
1004
|
+
* Manages associations (links) between facts.
|
|
1005
|
+
*/
|
|
1006
|
+
declare class AssociationEngine {
|
|
1007
|
+
private adapter;
|
|
1008
|
+
private provider?;
|
|
1009
|
+
private config;
|
|
1010
|
+
constructor(adapter: BaseAdapter, provider?: BaseProvider, config?: AssociationConfig);
|
|
1011
|
+
/**
|
|
1012
|
+
* Manually link two facts together.
|
|
1013
|
+
*/
|
|
1014
|
+
linkFacts(userId: string, factIdA: string, factIdB: string, relationship?: Association["relationship"]): Promise<void>;
|
|
1015
|
+
/**
|
|
1016
|
+
* Find all facts related to a given fact.
|
|
1017
|
+
*/
|
|
1018
|
+
findRelated(userId: string, factId: string): Promise<MemoryFact[]>;
|
|
1019
|
+
/**
|
|
1020
|
+
* Automatically find and link similar facts using embeddings.
|
|
1021
|
+
*/
|
|
1022
|
+
autoLink(userId: string): Promise<number>;
|
|
1023
|
+
/**
|
|
1024
|
+
* Use LLM to find deeper relationships between facts.
|
|
1025
|
+
*/
|
|
1026
|
+
findSemanticRelationships(userId: string): Promise<Association[]>;
|
|
1027
|
+
/**
|
|
1028
|
+
* Get the full knowledge graph for a user.
|
|
1029
|
+
*/
|
|
1030
|
+
getGraph(userId: string): Promise<{
|
|
1031
|
+
nodes: MemoryFact[];
|
|
1032
|
+
edges: Array<{
|
|
1033
|
+
from: string;
|
|
1034
|
+
to: string;
|
|
1035
|
+
}>;
|
|
1036
|
+
}>;
|
|
1037
|
+
}
|
|
1038
|
+
|
|
1039
|
+
/**
|
|
1040
|
+
* Predictive Engine - Behavioral Pattern Detection
|
|
1041
|
+
*
|
|
1042
|
+
* Detects temporal and behavioral patterns in user interactions:
|
|
1043
|
+
* - "User usually asks about X on Mondays"
|
|
1044
|
+
* - "User tends to discuss work topics in mornings"
|
|
1045
|
+
* - "User often follows up on topic Y after topic X"
|
|
1046
|
+
*/
|
|
1047
|
+
|
|
1048
|
+
interface PredictionConfig {
|
|
1049
|
+
/** Minimum occurrences to consider a pattern (default: 3) */
|
|
1050
|
+
minOccurrences?: number;
|
|
1051
|
+
/** Days to look back for patterns (default: 30) */
|
|
1052
|
+
lookbackDays?: number;
|
|
1053
|
+
/** Enable debug logging */
|
|
1054
|
+
debug?: boolean;
|
|
1055
|
+
}
|
|
1056
|
+
interface BehaviorPattern {
|
|
1057
|
+
/** Type of pattern */
|
|
1058
|
+
type: "temporal" | "sequential" | "topical";
|
|
1059
|
+
/** Description of the pattern */
|
|
1060
|
+
description: string;
|
|
1061
|
+
/** Confidence score (0-1) */
|
|
1062
|
+
confidence: number;
|
|
1063
|
+
/** Supporting evidence */
|
|
1064
|
+
occurrences: number;
|
|
1065
|
+
/** Day of week (0-6) for temporal patterns */
|
|
1066
|
+
dayOfWeek?: number;
|
|
1067
|
+
/** Hour of day (0-23) for temporal patterns */
|
|
1068
|
+
hourOfDay?: number;
|
|
1069
|
+
/** Topic/predicate involved */
|
|
1070
|
+
topic?: string;
|
|
1071
|
+
}
|
|
1072
|
+
interface Prediction {
|
|
1073
|
+
/** What we predict the user might do/ask */
|
|
1074
|
+
prediction: string;
|
|
1075
|
+
/** Based on which pattern */
|
|
1076
|
+
basedOn: BehaviorPattern;
|
|
1077
|
+
/** Confidence score (0-1) */
|
|
1078
|
+
confidence: number;
|
|
1079
|
+
/** Suggested proactive action */
|
|
1080
|
+
suggestedAction?: string;
|
|
1081
|
+
}
|
|
1082
|
+
/**
|
|
1083
|
+
* Analyzes user behavior to detect patterns and make predictions.
|
|
1084
|
+
*/
|
|
1085
|
+
declare class PredictiveEngine {
|
|
1086
|
+
private adapter;
|
|
1087
|
+
private provider?;
|
|
1088
|
+
private config;
|
|
1089
|
+
constructor(adapter: BaseAdapter, provider?: BaseProvider, config?: PredictionConfig);
|
|
1090
|
+
/**
|
|
1091
|
+
* Analyze a user's behavior patterns.
|
|
1092
|
+
*/
|
|
1093
|
+
analyzePatterns(userId: string): Promise<BehaviorPattern[]>;
|
|
1094
|
+
/**
|
|
1095
|
+
* Analyze when user tends to interact.
|
|
1096
|
+
*/
|
|
1097
|
+
private analyzeTemporalPatterns;
|
|
1098
|
+
/**
|
|
1099
|
+
* Analyze what topics user engages with most.
|
|
1100
|
+
*/
|
|
1101
|
+
private analyzeTopicPatterns;
|
|
1102
|
+
/**
|
|
1103
|
+
* Get predictions for what user might need/ask next.
|
|
1104
|
+
*/
|
|
1105
|
+
getPredictions(userId: string, _currentContext?: string): Promise<Prediction[]>;
|
|
1106
|
+
/**
|
|
1107
|
+
* Use LLM for deeper behavioral analysis.
|
|
1108
|
+
*/
|
|
1109
|
+
analyzeWithLLM(userId: string): Promise<BehaviorPattern[]>;
|
|
1110
|
+
}
|
|
1111
|
+
|
|
1112
|
+
/**
|
|
1113
|
+
* Hierarchical Memory Manager (HMM)
|
|
1114
|
+
*
|
|
1115
|
+
* Implements the 4-level Memory Pyramid:
|
|
1116
|
+
*
|
|
1117
|
+
* Level 4: Core Beliefs (BIOS)
|
|
1118
|
+
* - Always loaded, never forgotten
|
|
1119
|
+
* - Allergies, identity, safety rules
|
|
1120
|
+
*
|
|
1121
|
+
* Level 3: Patterns (Wisdom)
|
|
1122
|
+
* - Synthesized from multiple Level 2 facts
|
|
1123
|
+
* - "User is health-conscious" instead of 50 food facts
|
|
1124
|
+
*
|
|
1125
|
+
* Level 2: Facts (Knowledge)
|
|
1126
|
+
* - The standard discrete facts
|
|
1127
|
+
* - Subject-Predicate-Object triples
|
|
1128
|
+
*
|
|
1129
|
+
* Level 1: Raw Logs (Stream)
|
|
1130
|
+
* - Ephemeral conversation buffer
|
|
1131
|
+
* - Auto-flushed after extraction
|
|
1132
|
+
*
|
|
1133
|
+
* This is an OPTIONAL wrapper - you can use mem-ts without HMM.
|
|
1134
|
+
*/
|
|
1135
|
+
|
|
1136
|
+
type MemoryLevel = "raw_log" | "fact" | "pattern" | "core_belief";
|
|
1137
|
+
interface HierarchicalConfig {
|
|
1138
|
+
/** Enable HMM mode (default: false for backwards compatibility) */
|
|
1139
|
+
enabled?: boolean;
|
|
1140
|
+
/** Maximum raw logs to keep before flushing (default: 20) */
|
|
1141
|
+
maxRawLogs?: number;
|
|
1142
|
+
/** Minimum facts needed to synthesize a pattern (default: 3) */
|
|
1143
|
+
minFactsForPattern?: number;
|
|
1144
|
+
/** Hours before promoting patterns to core beliefs (default: 168 = 1 week) */
|
|
1145
|
+
coreBeliefHours?: number;
|
|
1146
|
+
/** Enable debug logging */
|
|
1147
|
+
debug?: boolean;
|
|
1148
|
+
}
|
|
1149
|
+
/**
|
|
1150
|
+
* Hierarchical Memory Manager - Optional HMM mode for mem-ts
|
|
1151
|
+
*/
|
|
1152
|
+
declare class HierarchicalMemory {
|
|
1153
|
+
private adapter;
|
|
1154
|
+
private provider?;
|
|
1155
|
+
private config;
|
|
1156
|
+
constructor(adapter: BaseAdapter, provider?: BaseProvider, config?: HierarchicalConfig);
|
|
1157
|
+
/**
|
|
1158
|
+
* Get facts by memory level.
|
|
1159
|
+
*/
|
|
1160
|
+
getByLevel(userId: string, level: MemoryLevel): Promise<MemoryFact[]>;
|
|
1161
|
+
/**
|
|
1162
|
+
* Hierarchical retrieval - top-down query.
|
|
1163
|
+
* 1. Always load core beliefs
|
|
1164
|
+
* 2. Check patterns for context
|
|
1165
|
+
* 3. Load specific facts only if needed
|
|
1166
|
+
*/
|
|
1167
|
+
hydrateHierarchical(userId: string, maxFacts?: number): Promise<{
|
|
1168
|
+
coreBeliefs: MemoryFact[];
|
|
1169
|
+
patterns: MemoryFact[];
|
|
1170
|
+
facts: MemoryFact[];
|
|
1171
|
+
totalTokens: number;
|
|
1172
|
+
}>;
|
|
1173
|
+
/**
|
|
1174
|
+
* Compile hierarchical context into a prompt.
|
|
1175
|
+
*/
|
|
1176
|
+
compileHierarchicalPrompt(coreBeliefs: MemoryFact[], patterns: MemoryFact[], facts: MemoryFact[]): string;
|
|
1177
|
+
/**
|
|
1178
|
+
* Promote fact to core_belief level.
|
|
1179
|
+
*/
|
|
1180
|
+
promoteToCore(userId: string, factId: string, reason?: string): Promise<void>;
|
|
1181
|
+
/**
|
|
1182
|
+
* Synthesize patterns from facts using LLM.
|
|
1183
|
+
* This is the "Deep Sleep" compression step.
|
|
1184
|
+
*/
|
|
1185
|
+
synthesizePatterns(userId: string): Promise<{
|
|
1186
|
+
patternsCreated: number;
|
|
1187
|
+
promotions: number;
|
|
1188
|
+
factsCompressed: number;
|
|
1189
|
+
}>;
|
|
1190
|
+
/**
|
|
1191
|
+
* Flush raw logs - extract facts and delete.
|
|
1192
|
+
*/
|
|
1193
|
+
flushRawLogs(userId: string): Promise<number>;
|
|
1194
|
+
/**
|
|
1195
|
+
* Get compression statistics - shows efficiency of HMM.
|
|
1196
|
+
*/
|
|
1197
|
+
getCompressionStats(userId: string): Promise<{
|
|
1198
|
+
rawLogs: number;
|
|
1199
|
+
facts: number;
|
|
1200
|
+
patterns: number;
|
|
1201
|
+
coreBeliefs: number;
|
|
1202
|
+
compressionRatio: number;
|
|
1203
|
+
}>;
|
|
1204
|
+
}
|
|
1205
|
+
|
|
1206
|
+
export { type Association, type AssociationConfig, AssociationEngine, type AutoSummarizeConfig, AutoSummarizer, BaseAdapter, BaseProvider, type BehaviorPattern, type BudgetConfig, BudgetManager, ConflictResolver, type ConflictStrategy, type ConsolidationConfig, ConsolidationWorker, ContextHydrator, type Contradiction, type ContradictionConfig, ContradictionDetector, type ContradictionResult, ConversationExchange, type DecayConfig, DecayManager, type DeepSleepConfig, DeepSleepWorker, type EmbeddingConfig, type EmbeddingResult, ExtractionResult, ExtractorWorker, FactFilter, type FactWithDecay, type HierarchicalConfig, HierarchicalMemory, HydrateOptions, HydratedContext, InMemoryVectorStore, MemoryEventEmitter, type MemoryEvents, MemoryFact, type MemoryLevel, MemoryOperation, OpenAIEmbeddingProvider, type Prediction, type PredictionConfig, PredictiveEngine, type SecurityCheckResult, type SecurityConfig, SecurityScanner, SemanticCache, type SemanticCacheConfig, Session, TOKEN_PRICING, TieredAdapter, type TieredAdapterConfig, type TokenAnalytics, TokenTracker, type TokenUsage, compressConversation, cosineSimilarity, createEmbeddingProvider, estimateCost, estimateTokens, findTopK, sanitizeForStorage, wrapContextSafely };
|