@mnemonic-ai/core 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.
Files changed (47) hide show
  1. package/dist/chunk-5Z46NSNR.js +228 -0
  2. package/dist/chunk-5Z46NSNR.js.map +1 -0
  3. package/dist/chunk-CZDK53NR.js +24 -0
  4. package/dist/chunk-CZDK53NR.js.map +1 -0
  5. package/dist/chunk-L7SCUMC3.js +53 -0
  6. package/dist/chunk-L7SCUMC3.js.map +1 -0
  7. package/dist/chunk-M3IZJTMM.js +474 -0
  8. package/dist/chunk-M3IZJTMM.js.map +1 -0
  9. package/dist/chunk-NA7L5FQN.js +1581 -0
  10. package/dist/chunk-NA7L5FQN.js.map +1 -0
  11. package/dist/chunk-OEEEWS2M.js +375 -0
  12. package/dist/chunk-OEEEWS2M.js.map +1 -0
  13. package/dist/chunk-YZW6DYUY.js +46 -0
  14. package/dist/chunk-YZW6DYUY.js.map +1 -0
  15. package/dist/cli/main.cjs +1827 -0
  16. package/dist/cli/main.cjs.map +1 -0
  17. package/dist/cli/main.d.cts +1 -0
  18. package/dist/cli/main.d.ts +1 -0
  19. package/dist/cli/main.js +84 -0
  20. package/dist/cli/main.js.map +1 -0
  21. package/dist/client-b2Xhkqdl.d.cts +409 -0
  22. package/dist/client-b2Xhkqdl.d.ts +409 -0
  23. package/dist/index.cjs +2547 -0
  24. package/dist/index.cjs.map +1 -0
  25. package/dist/index.d.cts +309 -0
  26. package/dist/index.d.ts +309 -0
  27. package/dist/index.js +160 -0
  28. package/dist/index.js.map +1 -0
  29. package/dist/local-MYLINANE.js +7 -0
  30. package/dist/local-MYLINANE.js.map +1 -0
  31. package/dist/mcp/main.cjs +2775 -0
  32. package/dist/mcp/main.cjs.map +1 -0
  33. package/dist/mcp/main.d.cts +1 -0
  34. package/dist/mcp/main.d.ts +1 -0
  35. package/dist/mcp/main.js +31 -0
  36. package/dist/mcp/main.js.map +1 -0
  37. package/dist/mcp/server.cjs +2765 -0
  38. package/dist/mcp/server.cjs.map +1 -0
  39. package/dist/mcp/server.d.cts +23 -0
  40. package/dist/mcp/server.d.ts +23 -0
  41. package/dist/mcp/server.js +12 -0
  42. package/dist/mcp/server.js.map +1 -0
  43. package/dist/openai-GDIC3YVT.js +7 -0
  44. package/dist/openai-GDIC3YVT.js.map +1 -0
  45. package/dist/postgres-GQ6DZDBW.js +8 -0
  46. package/dist/postgres-GQ6DZDBW.js.map +1 -0
  47. package/package.json +117 -0
@@ -0,0 +1,409 @@
1
+ /**
2
+ * Core memory data structures.
3
+ */
4
+ /** Built-in tier constants. Custom tiers can be registered via MnemonicConfig. */
5
+ declare const MemoryTier: {
6
+ readonly IDENTITY: "identity";
7
+ readonly PROCEDURAL: "procedural";
8
+ readonly STRUCTURAL: "structural";
9
+ readonly EPISODIC: "episodic";
10
+ readonly TRANSIENT: "transient";
11
+ };
12
+ type MemoryTier = (typeof MemoryTier)[keyof typeof MemoryTier];
13
+ /** Options for constructing a Memory. Only `content` is required. */
14
+ interface MemoryInit {
15
+ content: string;
16
+ id?: string;
17
+ tier?: string;
18
+ source?: string;
19
+ actor?: string;
20
+ sessionId?: string | null;
21
+ createdAt?: Date;
22
+ lastAccessedAt?: Date;
23
+ accessCount?: number;
24
+ importance?: number;
25
+ supersededBy?: string | null;
26
+ contradictedBy?: string | null;
27
+ embedding?: number[] | null;
28
+ metadata?: Record<string, unknown>;
29
+ linkedIds?: string[];
30
+ agentId?: string;
31
+ shared?: boolean;
32
+ charsPerToken?: number;
33
+ }
34
+ /** A single unit of agent memory. */
35
+ declare class Memory {
36
+ readonly content: string;
37
+ readonly id: string;
38
+ tier: string;
39
+ source: string;
40
+ actor: string;
41
+ sessionId: string | null;
42
+ createdAt: Date;
43
+ lastAccessedAt: Date;
44
+ accessCount: number;
45
+ importance: number;
46
+ supersededBy: string | null;
47
+ contradictedBy: string | null;
48
+ embedding: number[] | null;
49
+ metadata: Record<string, unknown>;
50
+ linkedIds: string[];
51
+ agentId: string;
52
+ shared: boolean;
53
+ private _charsPerToken;
54
+ constructor(init: MemoryInit);
55
+ /** The tier as a plain string, regardless of whether it was set as an enum. */
56
+ get tierName(): string;
57
+ /** Rough token count using configurable chars-per-token ratio. */
58
+ get tokenEstimate(): number;
59
+ /** Record an access. */
60
+ touch(): void;
61
+ }
62
+ /** A directed relationship between two memories.
63
+ * Known relations: "related_to", "contradicts", "elaborates", "supersedes", "consolidates".
64
+ */
65
+ interface MemoryEdge {
66
+ sourceId: string;
67
+ targetId: string;
68
+ relation: string;
69
+ weight: number;
70
+ createdAt: Date;
71
+ }
72
+ /**
73
+ * A pair of memory IDs with their cosine similarity score.
74
+ * Used by findSimilarPairs() to return sparse above-threshold pairs
75
+ * without transferring full embedding vectors from the database.
76
+ */
77
+ interface SimilarPair {
78
+ idA: string;
79
+ idB: string;
80
+ similarity: number;
81
+ }
82
+ /** Create a MemoryEdge with defaults. */
83
+ declare function createEdge(sourceId: string, targetId: string, relation: string, weight?: number): MemoryEdge;
84
+
85
+ /**
86
+ * Centralised configuration for all Mnemonic tunables.
87
+ */
88
+
89
+ interface ScorerConfig {
90
+ weightRecency: number;
91
+ weightFrequency: number;
92
+ weightLinks: number;
93
+ weightBase: number;
94
+ frequencyLogCap: number;
95
+ linkSaturation: number;
96
+ supersessionPenalty: number;
97
+ contradictionPenalty: number;
98
+ consolidationPenalty: number;
99
+ tierBaseScores: Record<string, number>;
100
+ }
101
+ interface ClassifierConfig {
102
+ extraPatterns: Record<string, string[]>;
103
+ episodicMinWords: number;
104
+ customClassifier: ((content: string, source: string, actor: string) => string) | null;
105
+ }
106
+ interface LinkerConfig {
107
+ similarityThreshold: number;
108
+ maxLinks: number;
109
+ keywordPenalty: number;
110
+ contradictionThreshold: number;
111
+ elaborationThreshold: number;
112
+ supersessionThreshold: number;
113
+ negationWords: Set<string>;
114
+ customRelationFn: ((a: Memory, b: Memory, similarity: number) => string) | null;
115
+ }
116
+ type SortOrder = "chronological" | "importance" | "relevance" | ((a: Memory, b: Memory) => number);
117
+ interface AssemblerConfig {
118
+ defaultMaxTokens: number;
119
+ diversityStrength: number;
120
+ sortOrder: SortOrder;
121
+ minRelevance: number;
122
+ }
123
+ interface ConsolidationConfig {
124
+ minClusterSize: number;
125
+ similarityThreshold: number;
126
+ maxContentLength: number;
127
+ prefix: string;
128
+ sourceName: string;
129
+ actorName: string;
130
+ /**
131
+ * Custom summary function replacing the default semicolon-join.
132
+ * Receives original memory content strings, returns a summary string.
133
+ * May be sync or async. When null/undefined, the default join is used.
134
+ */
135
+ summarizer?: ((contents: string[]) => Promise<string> | string) | null;
136
+ /** Max candidates for brute-force pairwise similarity (SQLite/default). */
137
+ maxCandidates: number;
138
+ /** Max nearest neighbors per candidate in LATERAL/vector index (Postgres/Neo4j). */
139
+ maxNeighborsPerCandidate: number;
140
+ }
141
+ interface PromotionConfig {
142
+ transientToEpisodicAccesses: number;
143
+ episodicToStructuralAccesses: number;
144
+ structuralToIdentityAccesses: number;
145
+ proceduralToIdentityAccesses: number;
146
+ demotionImportanceThreshold: number;
147
+ }
148
+ declare class SalienceSignal {
149
+ readonly name: string;
150
+ readonly patterns: string[];
151
+ readonly boost: number;
152
+ private _compiled;
153
+ constructor(name: string, patterns: string[], boost: number);
154
+ scan(text: string): boolean;
155
+ }
156
+ declare const BUILTIN_SALIENCE_SIGNALS: SalienceSignal[];
157
+ interface SalienceConfig {
158
+ enabled: boolean;
159
+ maxBoost: number;
160
+ signals: SalienceSignal[];
161
+ }
162
+ interface TierDefinition {
163
+ name: string;
164
+ defaultHalfLifeDays: number;
165
+ description: string;
166
+ }
167
+ declare const BUILTIN_TIERS: TierDefinition[];
168
+ declare class MnemonicConfig {
169
+ scorer: ScorerConfig;
170
+ classifier: ClassifierConfig;
171
+ linker: LinkerConfig;
172
+ assembler: AssemblerConfig;
173
+ consolidation: ConsolidationConfig;
174
+ promotion: PromotionConfig;
175
+ salience: SalienceConfig;
176
+ charsPerToken: number;
177
+ defaultTier: string;
178
+ embeddingSearchLimit: number;
179
+ private _tiers;
180
+ constructor(overrides?: Partial<{
181
+ scorer: Partial<ScorerConfig>;
182
+ classifier: Partial<ClassifierConfig>;
183
+ linker: Partial<LinkerConfig>;
184
+ assembler: Partial<AssemblerConfig>;
185
+ consolidation: Partial<ConsolidationConfig>;
186
+ promotion: Partial<PromotionConfig>;
187
+ salience: Partial<SalienceConfig>;
188
+ charsPerToken: number;
189
+ defaultTier: string;
190
+ embeddingSearchLimit: number;
191
+ }>);
192
+ registerTier(tier: TierDefinition): void;
193
+ getTier(name: string): TierDefinition;
194
+ tierNames(): string[];
195
+ halfLifeDays(tierName: string): number;
196
+ }
197
+
198
+ /**
199
+ * Abstract interface for embedding providers.
200
+ */
201
+ /** Interface for producing vector embeddings from text. */
202
+ interface BaseEmbedder {
203
+ /** Return a dense vector for text. */
204
+ embed(text: string): Promise<number[]>;
205
+ /** Return dense vectors for a batch of texts. */
206
+ embedBatch(texts: string[]): Promise<number[][]>;
207
+ /** Dimensionality of the embeddings produced. */
208
+ readonly dimension: number;
209
+ }
210
+
211
+ /**
212
+ * Abstract base interface for memory stores.
213
+ */
214
+
215
+ /** Options for agent-scoped store operations. */
216
+ interface AgentFilterOptions {
217
+ agentId?: string;
218
+ includeShared?: boolean;
219
+ tier?: string;
220
+ /** Cap the result set at the database level. */
221
+ limit?: number;
222
+ }
223
+ /** Synchronous interface for storage backends (e.g. SQLite). */
224
+ interface BaseStore {
225
+ /** Create tables / indexes if they don't exist. */
226
+ initialize(): void;
227
+ /** Release resources (close connections, etc.). */
228
+ close(): void;
229
+ /** Persist a single memory (insert or update). */
230
+ save(memory: Memory): void;
231
+ /** Retrieve a memory by ID. */
232
+ get(memoryId: string): Memory | null;
233
+ /** Return memories. When agentId is provided, returns own + shared. */
234
+ listAll(options?: AgentFilterOptions): Memory[];
235
+ /** Remove a memory by ID and its edges. */
236
+ delete(memoryId: string): void;
237
+ /** Delete memories older than ageMs milliseconds. Returns count deleted. */
238
+ deleteOlderThan(ageMs: number, tier?: string, options?: AgentFilterOptions): number;
239
+ /** Persist a relationship edge. */
240
+ saveEdge(edge: MemoryEdge): void;
241
+ /** Return all edges where memoryId is source or target. */
242
+ getEdges(memoryId: string): MemoryEdge[];
243
+ /** Return memories closest to embedding (approximate nearest-neighbour). */
244
+ searchByEmbedding(embedding: number[], limit?: number, options?: AgentFilterOptions): Memory[];
245
+ /**
246
+ * Return memory pairs whose cosine similarity >= threshold.
247
+ *
248
+ * This is a bounded, approximate search. `maxCandidates` caps the number of
249
+ * embeddings considered, and `maxNeighborsPerCandidate` limits per-row
250
+ * neighbors in DB-pushed implementations. Results may not include all
251
+ * qualifying pairs in the store.
252
+ */
253
+ findSimilarPairs(options?: {
254
+ threshold?: number;
255
+ agentId?: string;
256
+ tier?: string;
257
+ maxCandidates?: number;
258
+ maxNeighborsPerCandidate?: number;
259
+ }): SimilarPair[];
260
+ /** Read a key-value metadata entry. */
261
+ getMeta(key: string): string | null;
262
+ /** Write a key-value metadata entry (upsert). */
263
+ setMeta(key: string, value: string): void;
264
+ }
265
+
266
+ /**
267
+ * Async mirror of BaseStore for networked backends (Postgres, Neo4j).
268
+ */
269
+
270
+ /** Asynchronous interface for networked storage backends. */
271
+ interface AsyncBaseStore {
272
+ initialize(): Promise<void>;
273
+ close(): Promise<void>;
274
+ save(memory: Memory): Promise<void>;
275
+ get(memoryId: string): Promise<Memory | null>;
276
+ listAll(options?: AgentFilterOptions): Promise<Memory[]>;
277
+ delete(memoryId: string): Promise<void>;
278
+ deleteOlderThan(ageMs: number, tier?: string, options?: AgentFilterOptions): Promise<number>;
279
+ saveEdge(edge: MemoryEdge): Promise<void>;
280
+ getEdges(memoryId: string): Promise<MemoryEdge[]>;
281
+ searchByEmbedding(embedding: number[], limit?: number, options?: AgentFilterOptions): Promise<Memory[]>;
282
+ findSimilarPairs(options?: {
283
+ threshold?: number;
284
+ agentId?: string;
285
+ tier?: string;
286
+ maxCandidates?: number;
287
+ maxNeighborsPerCandidate?: number;
288
+ }): Promise<SimilarPair[]>;
289
+ getMeta(key: string): Promise<string | null>;
290
+ setMeta(key: string, value: string): Promise<void>;
291
+ }
292
+
293
+ /**
294
+ * Top-level Mnemonic client — the public API surface.
295
+ */
296
+
297
+ type StoreFactory = (uri: string, embeddingDim?: number) => BaseStore | AsyncBaseStore | Promise<AsyncBaseStore>;
298
+ /**
299
+ * Register a store factory for a URI scheme.
300
+ *
301
+ * The factory receives the full URI and the embedding dimension (if known).
302
+ * Must return a BaseStore or AsyncBaseStore.
303
+ * Throws if `scheme` is already registered (pass `overwrite: true` to replace).
304
+ *
305
+ * @example
306
+ * ```ts
307
+ * registerStore("neo4j", (uri, dim) => new Neo4jStore({ uri, embeddingDim: dim }));
308
+ * new Mnemonic({ store: "neo4j://localhost" }); // now works
309
+ * ```
310
+ */
311
+ declare function registerStore(scheme: string, factory: StoreFactory, options?: {
312
+ overwrite?: boolean;
313
+ }): void;
314
+ interface AddOptions {
315
+ source?: string;
316
+ actor?: string;
317
+ tier?: string;
318
+ sessionId?: string;
319
+ metadata?: Record<string, unknown>;
320
+ shared?: boolean;
321
+ }
322
+ interface RecallOptions {
323
+ maxTokens?: number;
324
+ minRelevance?: number;
325
+ header?: string;
326
+ }
327
+ interface ForgetOptions {
328
+ olderThan?: string;
329
+ tier?: string;
330
+ belowImportance?: number;
331
+ }
332
+ interface StatsResult {
333
+ totalMemories: number;
334
+ totalTokens: number;
335
+ byTier: Record<string, number>;
336
+ agentId: string;
337
+ }
338
+ declare class Mnemonic {
339
+ private _config;
340
+ private _store;
341
+ private _embedder;
342
+ private _autoClassify;
343
+ private _agentId;
344
+ private _resolvedAgentId;
345
+ private _initPromise;
346
+ constructor(options?: {
347
+ store?: string | BaseStore | AsyncBaseStore;
348
+ embedder?: BaseEmbedder | null;
349
+ autoClassify?: boolean;
350
+ config?: MnemonicConfig;
351
+ agentId?: string;
352
+ });
353
+ get config(): MnemonicConfig;
354
+ /** The underlying async store. */
355
+ get store(): AsyncBaseStore;
356
+ /** The embedder (if configured). */
357
+ get embedder(): BaseEmbedder | null;
358
+ /** The resolved agent ID (available after init()). */
359
+ get agentId(): string;
360
+ /**
361
+ * Initialize the store and resolve agent identity. Must be called before use.
362
+ * Pass `{ skipStoreInit: true }` when reusing an already-initialized store
363
+ * (e.g. creating per-agent clients that share a single backend).
364
+ */
365
+ init(options?: {
366
+ skipStoreInit?: boolean;
367
+ }): Promise<void>;
368
+ private _resolveAgentId;
369
+ private _ensureInitialized;
370
+ /** Return only memories owned by this agent (excludes shared from others). */
371
+ private _ownMemories;
372
+ private static _contentHash;
373
+ /**
374
+ * Store a memory with automatic classification and linking.
375
+ * If identical content already exists for this agent, returns the existing memory.
376
+ */
377
+ add(content: string, options?: AddOptions): Promise<Memory>;
378
+ private _assemble;
379
+ /** Retrieve optimised context for a given query within a token budget. */
380
+ recall(query: string, options?: RecallOptions): Promise<string>;
381
+ /** Like recall but returns the raw Memory objects. */
382
+ recallMemories(query: string, options?: {
383
+ maxTokens?: number;
384
+ minRelevance?: number;
385
+ }): Promise<Memory[]>;
386
+ /** Delete memories matching the given criteria. Returns count deleted. */
387
+ forget(options?: ForgetOptions): Promise<number>;
388
+ /**
389
+ * Merge similar episodic memories into higher-tier summaries.
390
+ *
391
+ * Originals are kept alive but deprioritised via a scoring penalty
392
+ * and `consolidated_into` metadata. A `consolidates` edge links
393
+ * the summary to each original for graph traversal.
394
+ */
395
+ consolidate(): Promise<number>;
396
+ /** Run the tier promotion/demotion pipeline on own memories. */
397
+ promote(): Promise<number>;
398
+ /** Re-run the linker across all memories to retroactively set edges. */
399
+ relink(): Promise<number>;
400
+ /** Return aggregate statistics about own memories. */
401
+ stats(): Promise<StatsResult>;
402
+ /** Make a memory visible to all agents. */
403
+ share(memoryId: string): Promise<Memory>;
404
+ /** Make a memory private (only visible to owner). */
405
+ unshare(memoryId: string): Promise<Memory>;
406
+ private _applyTierResults;
407
+ }
408
+
409
+ export { type AsyncBaseStore as A, type BaseStore as B, type ClassifierConfig as C, type ForgetOptions as F, type LinkerConfig as L, Mnemonic as M, type PromotionConfig as P, type RecallOptions as R, type SimilarPair as S, type TierDefinition as T, Memory as a, type AgentFilterOptions as b, type MemoryEdge as c, type BaseEmbedder as d, MnemonicConfig as e, type SalienceConfig as f, type AddOptions as g, type AssemblerConfig as h, BUILTIN_SALIENCE_SIGNALS as i, BUILTIN_TIERS as j, type ConsolidationConfig as k, type MemoryInit as l, MemoryTier as m, SalienceSignal as n, type ScorerConfig as o, type SortOrder as p, type StatsResult as q, type StoreFactory as r, createEdge as s, registerStore as t };