mnemocyte 0.0.6 → 0.0.8
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 +63 -1
- package/dist/index.d.mts +518 -4
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +621 -165
- package/dist/index.mjs.map +1 -1
- package/package.json +11 -15
package/dist/index.d.mts
CHANGED
|
@@ -1,160 +1,674 @@
|
|
|
1
1
|
//#region src/types.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Discriminator describing what kind of memory a {@link Memory} represents.
|
|
4
|
+
*
|
|
5
|
+
* - `"fact"` — a stable, objective statement.
|
|
6
|
+
* - `"preference"` — a user/entity preference that should bias future responses.
|
|
7
|
+
* - `"instruction"` — a directive the agent should follow.
|
|
8
|
+
* - `"backstory"` — long-lived background context about the entity.
|
|
9
|
+
* - `"episode"` — a discrete past event.
|
|
10
|
+
* - `"session"` — short-lived context tied to a single session.
|
|
11
|
+
*
|
|
12
|
+
* @defaultValue `"fact"` when omitted on {@link RememberInput}.
|
|
13
|
+
*/
|
|
2
14
|
type MemoryType = "fact" | "preference" | "instruction" | "backstory" | "episode" | "session";
|
|
15
|
+
/**
|
|
16
|
+
* Relative importance assigned to a memory. Influences retrieval ranking
|
|
17
|
+
* via the `importance` score component.
|
|
18
|
+
*
|
|
19
|
+
* @defaultValue `"normal"` when omitted on {@link RememberInput}.
|
|
20
|
+
*/
|
|
3
21
|
type ImportanceLevel = "low" | "normal" | "high" | "critical";
|
|
22
|
+
/**
|
|
23
|
+
* Output format produced by {@link MnemocyteClient.buildContext}.
|
|
24
|
+
*
|
|
25
|
+
* - `"markdown"` — headings + bullet list (default; LLM-friendly).
|
|
26
|
+
* - `"plain"` — newline-separated plain text.
|
|
27
|
+
* - `"xml"` — structured tags, useful for models that parse XML reliably.
|
|
28
|
+
*
|
|
29
|
+
* @defaultValue `"markdown"`
|
|
30
|
+
*/
|
|
4
31
|
type ContextFormat = "markdown" | "plain" | "xml";
|
|
32
|
+
/**
|
|
33
|
+
* Identifies which backend a {@link MnemocyteClient} is using.
|
|
34
|
+
*
|
|
35
|
+
* Selected automatically by {@link createMnemocyte} based on whether
|
|
36
|
+
* {@link MnemocyteConfig.databaseUrl} was provided.
|
|
37
|
+
*/
|
|
38
|
+
type MnemocyteBackend = "in-memory" | "postgres";
|
|
39
|
+
/**
|
|
40
|
+
* The set of public {@link MnemocyteClient} methods that emit
|
|
41
|
+
* {@link MnemocyteObservation} events through {@link ObservabilityConfig.onEvent}.
|
|
42
|
+
*/
|
|
43
|
+
type MnemocyteOperation = "remember" | "rememberMany" | "recall" | "buildContext" | "forget" | "forgetAll" | "prune" | "stats" | "close";
|
|
44
|
+
/**
|
|
45
|
+
* Lifecycle phase of a {@link MnemocyteObservation}.
|
|
46
|
+
*
|
|
47
|
+
* Every operation emits exactly one `"start"` event and exactly one of
|
|
48
|
+
* `"success"` or `"error"` once it settles.
|
|
49
|
+
*/
|
|
50
|
+
type MnemocyteObservationPhase = "start" | "success" | "error";
|
|
51
|
+
/**
|
|
52
|
+
* A single observability event emitted by a {@link MnemocyteClient}.
|
|
53
|
+
*
|
|
54
|
+
* Delivered to {@link ObservabilityConfig.onEvent} for tracing, metrics,
|
|
55
|
+
* and structured logging.
|
|
56
|
+
*/
|
|
57
|
+
interface MnemocyteObservation {
|
|
58
|
+
/** Operation that produced this event. */
|
|
59
|
+
operation: MnemocyteOperation;
|
|
60
|
+
/** Lifecycle phase: `"start"`, `"success"`, or `"error"`. */
|
|
61
|
+
phase: MnemocyteObservationPhase;
|
|
62
|
+
/** Backend handling the operation. */
|
|
63
|
+
backend: MnemocyteBackend;
|
|
64
|
+
/** Wall-clock timestamp of this event. */
|
|
65
|
+
timestamp: Date;
|
|
66
|
+
/** Elapsed milliseconds since the `"start"` event. Present on `"success"` / `"error"`. */
|
|
67
|
+
durationMs?: number;
|
|
68
|
+
/** Entity ID associated with the operation, when applicable. */
|
|
69
|
+
entityId?: string;
|
|
70
|
+
/** Memory ID associated with the operation, when applicable. */
|
|
71
|
+
memoryId?: string;
|
|
72
|
+
/** Number of items processed (e.g. memories returned, batch size). */
|
|
73
|
+
count?: number;
|
|
74
|
+
/** Thrown value. Present only on `"error"`. */
|
|
75
|
+
error?: unknown;
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Hooks for observing client activity.
|
|
79
|
+
*
|
|
80
|
+
* Exceptions thrown by {@link ObservabilityConfig.onEvent} are swallowed so
|
|
81
|
+
* that telemetry never affects application logic.
|
|
82
|
+
*/
|
|
83
|
+
interface ObservabilityConfig {
|
|
84
|
+
/**
|
|
85
|
+
* Called for every lifecycle event of every operation. Receives a single
|
|
86
|
+
* {@link MnemocyteObservation}. May be sync or async; the operation will
|
|
87
|
+
* not be delayed waiting for slow async hooks beyond the awaited dispatch.
|
|
88
|
+
*/
|
|
89
|
+
onEvent?: (event: MnemocyteObservation) => void | Promise<void>;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Production-hardening knobs applied to outbound provider calls
|
|
93
|
+
* (currently the {@link Embedder}). Mnemocyte applies a timeout, retries
|
|
94
|
+
* on transient failures, and forwards `AbortSignal` cancellation to each
|
|
95
|
+
* attempt. Every field is optional with conservative defaults; the
|
|
96
|
+
* defaults disable retries and timeouts so existing setups are
|
|
97
|
+
* unaffected unless they opt in.
|
|
98
|
+
*/
|
|
99
|
+
interface ProviderResilienceConfig {
|
|
100
|
+
/**
|
|
101
|
+
* Maximum time, in milliseconds, that a single provider attempt may
|
|
102
|
+
* run before a {@link MnemocyteError} with code `"TIMEOUT"` is thrown.
|
|
103
|
+
* Defaults to `0` which disables the timeout.
|
|
104
|
+
*/
|
|
105
|
+
timeoutMs?: number;
|
|
106
|
+
/**
|
|
107
|
+
* Maximum number of retry attempts after the initial call. `0`
|
|
108
|
+
* disables retries (default).
|
|
109
|
+
*/
|
|
110
|
+
retries?: number;
|
|
111
|
+
/** Base backoff delay (ms) used before the first retry. Defaults to `100`. */
|
|
112
|
+
baseDelayMs?: number;
|
|
113
|
+
/** Maximum backoff delay (ms) used between retries. Defaults to `2000`. */
|
|
114
|
+
maxDelayMs?: number;
|
|
115
|
+
/**
|
|
116
|
+
* Optional predicate deciding whether `error` should trigger a retry.
|
|
117
|
+
* Receives the thrown value and the 1-indexed `attempt` number that
|
|
118
|
+
* just failed. When omitted, a conservative built-in heuristic is used
|
|
119
|
+
* that retries on common transient indicators (network errors, 5xx
|
|
120
|
+
* responses, rate-limit hints) and never retries `"VALIDATION"`,
|
|
121
|
+
* `"CONFIG"`, or `"ABORTED"` {@link MnemocyteError}s.
|
|
122
|
+
*/
|
|
123
|
+
shouldRetry?: (error: unknown, attempt: number) => boolean;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Configuration passed to {@link createMnemocyte}.
|
|
127
|
+
*/
|
|
5
128
|
interface MnemocyteConfig {
|
|
129
|
+
/**
|
|
130
|
+
* Postgres connection string. When set, the client uses the Postgres
|
|
131
|
+
* backend (requires the `pgvector` extension and the bundled migration).
|
|
132
|
+
* When omitted, an in-memory backend is used.
|
|
133
|
+
*/
|
|
6
134
|
databaseUrl?: string;
|
|
135
|
+
/** Required embedder used to vectorise content for storage and retrieval. */
|
|
7
136
|
embedder: Embedder;
|
|
137
|
+
/** Default values applied to {@link RecallInput} when properties are omitted. */
|
|
8
138
|
defaults?: {
|
|
9
|
-
limit?: number;
|
|
139
|
+
/** Default `limit` for {@link MnemocyteClient.recall}. */limit?: number; /** Default `minScore` cutoff for {@link MnemocyteClient.recall}. */
|
|
10
140
|
minScore?: number;
|
|
11
141
|
};
|
|
142
|
+
/** Retrieval-ranking tuning. See {@link RetrievalConfig}. */
|
|
12
143
|
retrieval?: RetrievalConfig;
|
|
144
|
+
/** Observability hooks. See {@link ObservabilityConfig}. */
|
|
145
|
+
observability?: ObservabilityConfig;
|
|
146
|
+
/**
|
|
147
|
+
* Production-hardening knobs for outbound provider calls
|
|
148
|
+
* (timeouts, retries, abort propagation). See
|
|
149
|
+
* {@link ProviderResilienceConfig}.
|
|
150
|
+
*/
|
|
151
|
+
provider?: ProviderResilienceConfig;
|
|
13
152
|
}
|
|
153
|
+
/**
|
|
154
|
+
* Pluggable embedding provider. Wraps an external embedding API
|
|
155
|
+
* (e.g. OpenAI, Cohere, a local model) in a small interface.
|
|
156
|
+
*
|
|
157
|
+
* Mnemocyte records {@link Embedder.model} and {@link Embedder.dimensions}
|
|
158
|
+
* on every stored memory and uses them to detect incompatible vectors
|
|
159
|
+
* (e.g. when the model is swapped).
|
|
160
|
+
*/
|
|
14
161
|
interface Embedder {
|
|
162
|
+
/** Stable identifier for the underlying model (e.g. `"text-embedding-3-small"`). */
|
|
15
163
|
readonly model: string;
|
|
164
|
+
/** Dimensionality of vectors returned by {@link Embedder.embed}. */
|
|
16
165
|
readonly dimensions: number;
|
|
17
|
-
|
|
166
|
+
/**
|
|
167
|
+
* Embed one or more texts. Implementations MUST return one vector per
|
|
168
|
+
* input, in the same order, each of length {@link Embedder.dimensions}.
|
|
169
|
+
*
|
|
170
|
+
* The optional `options.signal` is forwarded by Mnemocyte when the
|
|
171
|
+
* caller passes a `signal` on a {@link RememberInput} / {@link RecallInput}
|
|
172
|
+
* / {@link BuildContextInput}, or when Mnemocyte's own provider timeout
|
|
173
|
+
* fires. Implementations that integrate with `fetch` should forward
|
|
174
|
+
* the signal to it so requests can be cancelled promptly.
|
|
175
|
+
*/
|
|
176
|
+
embed(texts: readonly string[], options?: {
|
|
177
|
+
signal?: AbortSignal;
|
|
178
|
+
}): Promise<number[][]>;
|
|
18
179
|
}
|
|
180
|
+
/**
|
|
181
|
+
* A persisted memory record as returned by the client.
|
|
182
|
+
*
|
|
183
|
+
* Memories are immutable from the caller's perspective; updates produce a
|
|
184
|
+
* new memory and link the previous one via {@link Memory.supersededBy}.
|
|
185
|
+
*/
|
|
19
186
|
interface Memory {
|
|
187
|
+
/** Unique identifier (UUID for Postgres backend). */
|
|
20
188
|
id: string;
|
|
189
|
+
/** Owning entity — typically a user, agent, or session ID. */
|
|
21
190
|
entityId: string;
|
|
191
|
+
/** Raw textual content of the memory. */
|
|
22
192
|
content: string;
|
|
193
|
+
/** Discriminator describing the kind of memory. */
|
|
23
194
|
type: MemoryType;
|
|
195
|
+
/** Relative importance assigned at write time. */
|
|
24
196
|
importance: ImportanceLevel;
|
|
197
|
+
/** Free-form tags used for filtering on {@link RecallInput.tags}. */
|
|
25
198
|
tags: string[];
|
|
199
|
+
/** Optional human-readable source attribution (e.g. `"chat:2024-04-12"`). */
|
|
26
200
|
source: string | null;
|
|
201
|
+
/** Arbitrary user-provided metadata persisted alongside the memory. */
|
|
27
202
|
metadata: Record<string, unknown>;
|
|
203
|
+
/** Confidence in `[0, 1]`. Used in retrieval ranking. */
|
|
28
204
|
confidence: number;
|
|
205
|
+
/** {@link Embedder.model} value at write time. */
|
|
29
206
|
embeddingModel: string;
|
|
207
|
+
/** {@link Embedder.dimensions} value at write time. */
|
|
30
208
|
embeddingDimensions: number;
|
|
209
|
+
/** ID of the memory that supersedes this one, or `null` if active. */
|
|
31
210
|
supersededBy: string | null;
|
|
211
|
+
/** Optional expiry; expired memories are filtered out by default. */
|
|
32
212
|
expiresAt: Date | null;
|
|
213
|
+
/** Last time this memory was returned by {@link MnemocyteClient.recall}. */
|
|
33
214
|
lastAccessedAt: Date | null;
|
|
215
|
+
/** Cumulative number of times this memory has been recalled. */
|
|
34
216
|
accessCount: number;
|
|
217
|
+
/** Creation timestamp. */
|
|
35
218
|
createdAt: Date;
|
|
219
|
+
/** Most recent update timestamp. */
|
|
36
220
|
updatedAt: Date;
|
|
37
221
|
}
|
|
222
|
+
/**
|
|
223
|
+
* Per-component scores produced during retrieval ranking. Each value is
|
|
224
|
+
* normalised to `[0, 1]` before being combined via
|
|
225
|
+
* {@link RetrievalScoreWeights}.
|
|
226
|
+
*/
|
|
38
227
|
interface RetrievalScores {
|
|
228
|
+
/** Cosine similarity between the query embedding and the memory embedding. */
|
|
39
229
|
vector: number;
|
|
230
|
+
/** Token-overlap (lexical) score between query and memory content. */
|
|
40
231
|
lexical: number;
|
|
232
|
+
/** Time-decay score based on {@link RetrievalConfig.recencyHalfLifeDays}. */
|
|
41
233
|
recency: number;
|
|
234
|
+
/** Pass-through of the memory's stored `confidence`. */
|
|
42
235
|
confidence: number;
|
|
236
|
+
/** Saturating score derived from `accessCount`. */
|
|
43
237
|
access: number;
|
|
238
|
+
/** Score derived from {@link ImportanceLevel}. */
|
|
44
239
|
importance: number;
|
|
45
240
|
}
|
|
241
|
+
/**
|
|
242
|
+
* Optional overrides for the per-component retrieval weights. Missing keys
|
|
243
|
+
* fall back to library defaults. Weights need not sum to 1; the final
|
|
244
|
+
* score is computed as a weighted sum of {@link RetrievalScores}.
|
|
245
|
+
*/
|
|
46
246
|
interface RetrievalScoreWeights {
|
|
247
|
+
/** Weight applied to {@link RetrievalScores.vector}. */
|
|
47
248
|
vector?: number;
|
|
249
|
+
/** Weight applied to {@link RetrievalScores.lexical}. */
|
|
48
250
|
lexical?: number;
|
|
251
|
+
/** Weight applied to {@link RetrievalScores.recency}. */
|
|
49
252
|
recency?: number;
|
|
253
|
+
/** Weight applied to {@link RetrievalScores.confidence}. */
|
|
50
254
|
confidence?: number;
|
|
255
|
+
/** Weight applied to {@link RetrievalScores.access}. */
|
|
51
256
|
access?: number;
|
|
257
|
+
/** Weight applied to {@link RetrievalScores.importance}. */
|
|
52
258
|
importance?: number;
|
|
53
259
|
}
|
|
260
|
+
/**
|
|
261
|
+
* Retrieval-ranking tuning. All fields are optional; sensible defaults are
|
|
262
|
+
* used for any field that is omitted.
|
|
263
|
+
*/
|
|
54
264
|
interface RetrievalConfig {
|
|
265
|
+
/** Per-component score weights. See {@link RetrievalScoreWeights}. */
|
|
55
266
|
weights?: RetrievalScoreWeights;
|
|
267
|
+
/** Half-life (days) for the time-decay recency component. */
|
|
56
268
|
recencyHalfLifeDays?: number;
|
|
269
|
+
/** Access count at which the access score is considered saturated. */
|
|
57
270
|
accessSaturation?: number;
|
|
271
|
+
/**
|
|
272
|
+
* Multiplier applied to {@link RecallInput.limit} to determine how many
|
|
273
|
+
* candidates are fetched from the underlying store before re-ranking.
|
|
274
|
+
*/
|
|
58
275
|
candidateMultiplier?: number;
|
|
59
276
|
}
|
|
277
|
+
/**
|
|
278
|
+
* Detailed scoring breakdown attached to each {@link MemoryWithScore} when
|
|
279
|
+
* {@link RecallInput.explain} is `true`. Useful for debugging ranking and
|
|
280
|
+
* tuning {@link RetrievalConfig}.
|
|
281
|
+
*/
|
|
60
282
|
interface RetrievalExplanation {
|
|
283
|
+
/** Raw vector similarity in `[0, 1]`. */
|
|
61
284
|
vectorScore: number;
|
|
285
|
+
/** Raw lexical-overlap score in `[0, 1]`. */
|
|
62
286
|
lexicalScore: number;
|
|
287
|
+
/** Raw recency score in `[0, 1]`. */
|
|
63
288
|
recencyScore: number;
|
|
289
|
+
/** Raw confidence score in `[0, 1]`. */
|
|
64
290
|
confidenceScore: number;
|
|
291
|
+
/** Raw access score in `[0, 1]`. */
|
|
65
292
|
accessScore: number;
|
|
293
|
+
/** Raw importance score in `[0, 1]`. */
|
|
66
294
|
importanceScore: number;
|
|
295
|
+
/** Additive multiplier applied for high-importance memories. */
|
|
67
296
|
importanceBoost: number;
|
|
297
|
+
/** Effective weights used for this query (defaults filled in). */
|
|
68
298
|
weights: Required<RetrievalScoreWeights>;
|
|
299
|
+
/** Final combined score — same value as {@link MemoryWithScore.score}. */
|
|
69
300
|
finalScore: number;
|
|
70
301
|
}
|
|
302
|
+
/**
|
|
303
|
+
* A {@link Memory} returned by {@link MnemocyteClient.recall}, annotated
|
|
304
|
+
* with retrieval scores.
|
|
305
|
+
*/
|
|
71
306
|
interface MemoryWithScore extends Memory {
|
|
307
|
+
/** Final combined relevance score. Higher is better. */
|
|
72
308
|
score: number;
|
|
309
|
+
/** Per-component scores that produced {@link MemoryWithScore.score}. */
|
|
73
310
|
scores: RetrievalScores;
|
|
311
|
+
/**
|
|
312
|
+
* Full scoring breakdown when {@link RecallInput.explain} is `true`,
|
|
313
|
+
* `null` otherwise.
|
|
314
|
+
*/
|
|
74
315
|
explanation: RetrievalExplanation | null;
|
|
75
316
|
}
|
|
317
|
+
/**
|
|
318
|
+
* Input for {@link MnemocyteClient.remember} and
|
|
319
|
+
* {@link MnemocyteClient.rememberMany}.
|
|
320
|
+
*/
|
|
76
321
|
interface RememberInput {
|
|
322
|
+
/** Owning entity ID (e.g. user, agent, or session). */
|
|
77
323
|
entityId: string;
|
|
324
|
+
/** Raw textual content to store. Must be non-empty. */
|
|
78
325
|
content: string;
|
|
326
|
+
/** Memory kind. @defaultValue `"fact"` */
|
|
79
327
|
type?: MemoryType;
|
|
328
|
+
/** Relative importance. @defaultValue `"normal"` */
|
|
80
329
|
importance?: ImportanceLevel;
|
|
330
|
+
/** Free-form tags used for later filtering. */
|
|
81
331
|
tags?: string[];
|
|
332
|
+
/** Optional human-readable source attribution. */
|
|
82
333
|
source?: string;
|
|
334
|
+
/** Arbitrary metadata persisted alongside the memory. */
|
|
83
335
|
metadata?: Record<string, unknown>;
|
|
336
|
+
/** Confidence in `[0, 1]`. @defaultValue `1` */
|
|
84
337
|
confidence?: number;
|
|
338
|
+
/** Optional expiry; expired memories are filtered out by default. */
|
|
85
339
|
expiresAt?: Date;
|
|
340
|
+
/**
|
|
341
|
+
* Optional cancellation signal. Forwarded to the embedder; when
|
|
342
|
+
* aborted, the operation throws a {@link MnemocyteError} with code
|
|
343
|
+
* `"ABORTED"`.
|
|
344
|
+
*/
|
|
345
|
+
signal?: AbortSignal;
|
|
86
346
|
}
|
|
347
|
+
/**
|
|
348
|
+
* Input for {@link MnemocyteClient.recall}.
|
|
349
|
+
*/
|
|
87
350
|
interface RecallInput {
|
|
351
|
+
/** Owning entity ID to search within. */
|
|
88
352
|
entityId: string;
|
|
353
|
+
/** Free-text query; embedded and matched against stored memories. */
|
|
89
354
|
query: string;
|
|
355
|
+
/** Maximum number of results. Falls back to {@link MnemocyteConfig.defaults}. */
|
|
90
356
|
limit?: number;
|
|
357
|
+
/** Minimum final score required for a memory to be returned. */
|
|
91
358
|
minScore?: number;
|
|
359
|
+
/** Restrict results to these memory types. */
|
|
92
360
|
types?: MemoryType[];
|
|
361
|
+
/** Require results to include all of these tags. */
|
|
93
362
|
tags?: string[];
|
|
363
|
+
/** Only include memories created strictly before this date. */
|
|
94
364
|
before?: Date;
|
|
365
|
+
/** Only include memories created strictly after this date. */
|
|
95
366
|
after?: Date;
|
|
367
|
+
/** Include memories that have been superseded. @defaultValue `false` */
|
|
96
368
|
includeSuperseded?: boolean;
|
|
369
|
+
/** Include memories whose `expiresAt` has passed. @defaultValue `false` */
|
|
97
370
|
includeExpired?: boolean;
|
|
371
|
+
/** Populate {@link MemoryWithScore.explanation} on each result. @defaultValue `false` */
|
|
98
372
|
explain?: boolean;
|
|
373
|
+
/**
|
|
374
|
+
* Optional cancellation signal. Forwarded to the embedder; when
|
|
375
|
+
* aborted, the operation throws a {@link MnemocyteError} with code
|
|
376
|
+
* `"ABORTED"`.
|
|
377
|
+
*/
|
|
378
|
+
signal?: AbortSignal;
|
|
99
379
|
}
|
|
380
|
+
/**
|
|
381
|
+
* Pluggable token counter used by {@link MnemocyteClient.buildContext} to
|
|
382
|
+
* enforce {@link BuildContextInput.maxTokens}. Plug in your model's real
|
|
383
|
+
* tokenizer (e.g. `tiktoken`) for accurate budgeting; a simple word-based
|
|
384
|
+
* heuristic is used when omitted.
|
|
385
|
+
*/
|
|
100
386
|
interface TokenCounter {
|
|
387
|
+
/** Return the number of tokens in `text`. */
|
|
101
388
|
count(text: string): number;
|
|
102
389
|
}
|
|
390
|
+
/**
|
|
391
|
+
* Input for {@link MnemocyteClient.buildContext}, which renders relevant
|
|
392
|
+
* memories into a prompt-ready string.
|
|
393
|
+
*/
|
|
103
394
|
interface BuildContextInput {
|
|
395
|
+
/** Owning entity ID to search within. */
|
|
104
396
|
entityId: string;
|
|
397
|
+
/** Free-text query used to select relevant memories. */
|
|
105
398
|
query: string;
|
|
399
|
+
/** Output format. @defaultValue `"markdown"` */
|
|
106
400
|
format?: ContextFormat;
|
|
401
|
+
/** Optional token budget; memories are dropped from the tail until the budget fits. */
|
|
107
402
|
maxTokens?: number;
|
|
403
|
+
/** Maximum number of memories to consider. */
|
|
108
404
|
limit?: number;
|
|
405
|
+
/** Minimum retrieval score required. */
|
|
109
406
|
minScore?: number;
|
|
407
|
+
/** Restrict to these memory types. */
|
|
110
408
|
types?: MemoryType[];
|
|
409
|
+
/** Require results to include all of these tags. */
|
|
111
410
|
tags?: string[];
|
|
411
|
+
/** Include superseded memories. @defaultValue `false` */
|
|
112
412
|
includeSuperseded?: boolean;
|
|
413
|
+
/** Include expired memories. @defaultValue `false` */
|
|
113
414
|
includeExpired?: boolean;
|
|
415
|
+
/** Tokenizer used to enforce {@link BuildContextInput.maxTokens}. */
|
|
114
416
|
tokenCounter?: TokenCounter;
|
|
417
|
+
/**
|
|
418
|
+
* Optional cancellation signal. Forwarded to the underlying recall
|
|
419
|
+
* call and embedder; when aborted, the operation throws a
|
|
420
|
+
* {@link MnemocyteError} with code `"ABORTED"`.
|
|
421
|
+
*/
|
|
422
|
+
signal?: AbortSignal;
|
|
423
|
+
}
|
|
424
|
+
/**
|
|
425
|
+
* Input for {@link MnemocyteClient.prune}. All fields are optional, but
|
|
426
|
+
* at least one selector must be set; calling `prune({})` is rejected with
|
|
427
|
+
* a `"VALIDATION"` {@link MnemocyteError} so memories cannot be deleted
|
|
428
|
+
* accidentally. Specified filters are combined with AND semantics.
|
|
429
|
+
*/
|
|
430
|
+
interface PruneInput {
|
|
431
|
+
/** Restrict pruning to a single entity. */
|
|
432
|
+
entityId?: string;
|
|
433
|
+
/** Match memories whose `expiresAt` is in the past. */
|
|
434
|
+
expired?: boolean;
|
|
435
|
+
/** Match memories that have been superseded (`supersededBy !== null`). */
|
|
436
|
+
superseded?: boolean;
|
|
437
|
+
/** Match memories created strictly before this date. */
|
|
438
|
+
createdBefore?: Date;
|
|
439
|
+
/**
|
|
440
|
+
* Match memories whose `lastAccessedAt` is `null` or strictly before
|
|
441
|
+
* this date. Useful for evicting "cold" memories.
|
|
442
|
+
*/
|
|
443
|
+
notAccessedSince?: Date;
|
|
444
|
+
/** Restrict pruning to these memory types. */
|
|
445
|
+
types?: MemoryType[];
|
|
446
|
+
/**
|
|
447
|
+
* Require memories to include all of these tags. Empty array is
|
|
448
|
+
* treated as no tag filter.
|
|
449
|
+
*/
|
|
450
|
+
tags?: string[];
|
|
451
|
+
/**
|
|
452
|
+
* Match memories whose `importance` is at or below this level. For
|
|
453
|
+
* example, `"normal"` prunes `"low"` and `"normal"` but never `"high"`
|
|
454
|
+
* or `"critical"`. Useful for evicting low-value memories first.
|
|
455
|
+
*/
|
|
456
|
+
maxImportance?: ImportanceLevel;
|
|
457
|
+
/**
|
|
458
|
+
* If `true`, count what would be pruned without deleting anything.
|
|
459
|
+
* @defaultValue `false`
|
|
460
|
+
*/
|
|
461
|
+
dryRun?: boolean;
|
|
462
|
+
/** Optional cancellation signal. */
|
|
463
|
+
signal?: AbortSignal;
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Result returned by {@link MnemocyteClient.prune}.
|
|
467
|
+
*/
|
|
468
|
+
interface PruneResult {
|
|
469
|
+
/** Number of memories that matched the prune filter. */
|
|
470
|
+
matchedCount: number;
|
|
471
|
+
/**
|
|
472
|
+
* Number of memories actually deleted. Equals `matchedCount` for
|
|
473
|
+
* normal runs and `0` for `dryRun` runs.
|
|
474
|
+
*/
|
|
475
|
+
deletedCount: number;
|
|
476
|
+
/** `true` when {@link PruneInput.dryRun} was set. */
|
|
477
|
+
dryRun: boolean;
|
|
115
478
|
}
|
|
479
|
+
/**
|
|
480
|
+
* Stats for a single entity, returned by
|
|
481
|
+
* {@link MnemocyteClient.stats} when an `entityId` is provided.
|
|
482
|
+
*/
|
|
116
483
|
interface EntityStats {
|
|
484
|
+
/** The entity these stats describe. */
|
|
117
485
|
entityId: string;
|
|
486
|
+
/** Total number of memories ever stored for this entity. */
|
|
118
487
|
memoryCount: number;
|
|
488
|
+
/** Memories that are neither expired nor superseded. */
|
|
119
489
|
activeMemoryCount: number;
|
|
490
|
+
/** Memories whose `expiresAt` has passed. */
|
|
120
491
|
expiredMemoryCount: number;
|
|
492
|
+
/** Memories that have been superseded by a newer one. */
|
|
121
493
|
supersededMemoryCount: number;
|
|
122
494
|
}
|
|
495
|
+
/**
|
|
496
|
+
* Stats aggregated across all entities, returned by
|
|
497
|
+
* {@link MnemocyteClient.stats} when no `entityId` is provided.
|
|
498
|
+
*/
|
|
123
499
|
interface GlobalStats {
|
|
500
|
+
/** Number of distinct entities with at least one memory. */
|
|
124
501
|
entityCount: number;
|
|
502
|
+
/** Total number of memories across all entities. */
|
|
125
503
|
memoryCount: number;
|
|
504
|
+
/** Memories that are neither expired nor superseded. */
|
|
126
505
|
activeMemoryCount: number;
|
|
506
|
+
/** Memories whose `expiresAt` has passed. */
|
|
127
507
|
expiredMemoryCount: number;
|
|
508
|
+
/** Memories that have been superseded by a newer one. */
|
|
128
509
|
supersededMemoryCount: number;
|
|
129
510
|
}
|
|
511
|
+
/**
|
|
512
|
+
* The Mnemocyte client. Returned by {@link createMnemocyte}.
|
|
513
|
+
*
|
|
514
|
+
* Every method may throw {@link MnemocyteError}; use {@link isMnemocyteError}
|
|
515
|
+
* to narrow caught values.
|
|
516
|
+
*/
|
|
130
517
|
interface MnemocyteClient {
|
|
518
|
+
/**
|
|
519
|
+
* Persist a single memory and return the stored record.
|
|
520
|
+
*
|
|
521
|
+
* @throws {MnemocyteError} `"VALIDATION"` for invalid input, `"EMBEDDING"`
|
|
522
|
+
* if the embedder fails, `"DB"` for storage failures.
|
|
523
|
+
*/
|
|
131
524
|
remember(input: RememberInput): Promise<Memory>;
|
|
525
|
+
/**
|
|
526
|
+
* Persist multiple memories in one round-trip. Returns the stored records
|
|
527
|
+
* in the same order as `inputs`.
|
|
528
|
+
*/
|
|
132
529
|
rememberMany(inputs: readonly RememberInput[]): Promise<Memory[]>;
|
|
530
|
+
/**
|
|
531
|
+
* Retrieve the most relevant memories for `input.query`, ranked by the
|
|
532
|
+
* configured {@link RetrievalConfig}.
|
|
533
|
+
*/
|
|
133
534
|
recall(input: RecallInput): Promise<MemoryWithScore[]>;
|
|
535
|
+
/**
|
|
536
|
+
* Build a prompt-ready context string from the most relevant memories.
|
|
537
|
+
* Respects {@link BuildContextInput.maxTokens} when supplied.
|
|
538
|
+
*/
|
|
134
539
|
buildContext(input: BuildContextInput): Promise<string>;
|
|
540
|
+
/**
|
|
541
|
+
* Delete a specific memory belonging to `entityId`.
|
|
542
|
+
*
|
|
543
|
+
* @throws {MnemocyteError} `"NOT_FOUND"` if the memory does not exist
|
|
544
|
+
* or does not belong to `entityId`.
|
|
545
|
+
*/
|
|
135
546
|
forget(input: {
|
|
136
547
|
entityId: string;
|
|
137
548
|
memoryId: string;
|
|
138
549
|
}): Promise<void>;
|
|
550
|
+
/** Delete every memory belonging to `entityId`. */
|
|
139
551
|
forgetAll(input: {
|
|
140
552
|
entityId: string;
|
|
141
553
|
}): Promise<void>;
|
|
554
|
+
/**
|
|
555
|
+
* Bulk-delete memories matching the filters on {@link PruneInput}.
|
|
556
|
+
*
|
|
557
|
+
* At least one filter must be specified; an empty input throws a
|
|
558
|
+
* `"VALIDATION"` {@link MnemocyteError} to avoid accidental full
|
|
559
|
+
* deletion. Pass `dryRun: true` to count without deleting.
|
|
560
|
+
*
|
|
561
|
+
* @example Evict expired or stale memories for an entity
|
|
562
|
+
* ```ts
|
|
563
|
+
* await client.prune({
|
|
564
|
+
* entityId: "user_123",
|
|
565
|
+
* expired: true,
|
|
566
|
+
* });
|
|
567
|
+
*
|
|
568
|
+
* await client.prune({
|
|
569
|
+
* notAccessedSince: new Date(Date.now() - 30 * 24 * 3600 * 1000),
|
|
570
|
+
* maxImportance: "normal",
|
|
571
|
+
* });
|
|
572
|
+
* ```
|
|
573
|
+
*/
|
|
574
|
+
prune(input: PruneInput): Promise<PruneResult>;
|
|
575
|
+
/**
|
|
576
|
+
* Return statistics. With an `entityId`, returns {@link EntityStats};
|
|
577
|
+
* without one, returns {@link GlobalStats}.
|
|
578
|
+
*/
|
|
142
579
|
stats(input?: {
|
|
143
580
|
entityId?: string;
|
|
144
581
|
}): Promise<EntityStats | GlobalStats>;
|
|
582
|
+
/**
|
|
583
|
+
* Release any underlying resources (e.g. the Postgres connection pool).
|
|
584
|
+
* Safe to call multiple times. The client must not be used afterward.
|
|
585
|
+
*/
|
|
145
586
|
close(): Promise<void>;
|
|
146
587
|
}
|
|
147
588
|
//#endregion
|
|
148
589
|
//#region src/client.d.ts
|
|
590
|
+
/**
|
|
591
|
+
* Create a Mnemocyte client.
|
|
592
|
+
*
|
|
593
|
+
* When {@link MnemocyteConfig.databaseUrl} is provided, a Postgres-backed
|
|
594
|
+
* client is returned (requires the `pgvector` extension and the bundled
|
|
595
|
+
* migration applied). Otherwise an in-memory client is returned, intended
|
|
596
|
+
* for tests, demos, and short-lived processes.
|
|
597
|
+
*
|
|
598
|
+
* The returned client owns any underlying resources (e.g. the Postgres
|
|
599
|
+
* connection pool). Call {@link MnemocyteClient.close} when finished to
|
|
600
|
+
* release them.
|
|
601
|
+
*
|
|
602
|
+
* @param config - Client configuration. {@link MnemocyteConfig.embedder} is required.
|
|
603
|
+
* @returns A {@link MnemocyteClient} instance.
|
|
604
|
+
* @throws {MnemocyteError} With code `"CONFIG"` if `embedder` is missing or invalid,
|
|
605
|
+
* or `"VALIDATION"` if `databaseUrl` is provided but empty.
|
|
606
|
+
*
|
|
607
|
+
* @example Postgres-backed client
|
|
608
|
+
* ```ts
|
|
609
|
+
* const client = createMnemocyte({
|
|
610
|
+
* databaseUrl: process.env.DATABASE_URL,
|
|
611
|
+
* embedder,
|
|
612
|
+
* });
|
|
613
|
+
* ```
|
|
614
|
+
*/
|
|
149
615
|
declare function createMnemocyte(config: MnemocyteConfig): MnemocyteClient;
|
|
150
616
|
//#endregion
|
|
151
617
|
//#region src/errors.d.ts
|
|
152
|
-
|
|
618
|
+
/**
|
|
619
|
+
* Stable, machine-readable error code attached to every {@link MnemocyteError}.
|
|
620
|
+
*
|
|
621
|
+
* - `"CONFIG"` — invalid client configuration (e.g. missing or malformed embedder).
|
|
622
|
+
* - `"VALIDATION"` — invalid argument passed to a client method.
|
|
623
|
+
* - `"DB"` — Postgres or driver-level failure.
|
|
624
|
+
* - `"EMBEDDING"` — embedder threw or returned an invalid vector.
|
|
625
|
+
* - `"NOT_FOUND"` — referenced memory or entity does not exist.
|
|
626
|
+
* - `"MIGRATION"` — schema/migration check failed against the target database.
|
|
627
|
+
* - `"TIMEOUT"` — a provider call exceeded its configured timeout.
|
|
628
|
+
* - `"ABORTED"` — the operation was cancelled via an `AbortSignal`.
|
|
629
|
+
*/
|
|
630
|
+
type MnemocyteErrorCode = "CONFIG" | "VALIDATION" | "DB" | "EMBEDDING" | "NOT_FOUND" | "MIGRATION" | "TIMEOUT" | "ABORTED";
|
|
631
|
+
/**
|
|
632
|
+
* Error type thrown by every public Mnemocyte API.
|
|
633
|
+
*
|
|
634
|
+
* Use the {@link MnemocyteError.code} property — not the message — to branch
|
|
635
|
+
* on failure modes, or call {@link isMnemocyteError} as a type guard when
|
|
636
|
+
* working with `unknown` errors.
|
|
637
|
+
*
|
|
638
|
+
* @example
|
|
639
|
+
* ```ts
|
|
640
|
+
* try {
|
|
641
|
+
* await client.recall({ entityId: "u1", query: "hi" });
|
|
642
|
+
* } catch (err) {
|
|
643
|
+
* if (isMnemocyteError(err) && err.code === "DB") {
|
|
644
|
+
* // handle database failure
|
|
645
|
+
* }
|
|
646
|
+
* throw err;
|
|
647
|
+
* }
|
|
648
|
+
* ```
|
|
649
|
+
*/
|
|
153
650
|
declare class MnemocyteError extends Error {
|
|
651
|
+
/** Stable, machine-readable failure code. See {@link MnemocyteErrorCode}. */
|
|
154
652
|
readonly code: MnemocyteErrorCode;
|
|
653
|
+
/** Underlying cause, if any (e.g. an original driver or embedder error). */
|
|
155
654
|
readonly cause?: unknown;
|
|
655
|
+
/**
|
|
656
|
+
* @param message - Human-readable error message.
|
|
657
|
+
* @param code - Stable failure code; see {@link MnemocyteErrorCode}.
|
|
658
|
+
* @param cause - Optional underlying cause (driver error, network error, etc.).
|
|
659
|
+
*/
|
|
156
660
|
constructor(message: string, code: MnemocyteErrorCode, cause?: unknown);
|
|
157
661
|
}
|
|
662
|
+
/**
|
|
663
|
+
* Type guard for {@link MnemocyteError}.
|
|
664
|
+
*
|
|
665
|
+
* Prefer this over `instanceof` when working across module boundaries or
|
|
666
|
+
* bundlers where multiple copies of the class may exist.
|
|
667
|
+
*
|
|
668
|
+
* @param error - Value to test (typically a caught `unknown`).
|
|
669
|
+
* @returns `true` if `error` is a {@link MnemocyteError}.
|
|
670
|
+
*/
|
|
671
|
+
declare function isMnemocyteError(error: unknown): error is MnemocyteError;
|
|
158
672
|
//#endregion
|
|
159
|
-
export { type BuildContextInput, type ContextFormat, type Embedder, type EntityStats, type GlobalStats, type ImportanceLevel, type Memory, type MemoryType, type MemoryWithScore, type MnemocyteClient, type MnemocyteConfig, MnemocyteError, type MnemocyteErrorCode, type RecallInput, type RememberInput, type RetrievalConfig, type RetrievalExplanation, type RetrievalScoreWeights, type RetrievalScores, type TokenCounter, createMnemocyte };
|
|
673
|
+
export { type BuildContextInput, type ContextFormat, type Embedder, type EntityStats, type GlobalStats, type ImportanceLevel, type Memory, type MemoryType, type MemoryWithScore, type MnemocyteBackend, type MnemocyteClient, type MnemocyteConfig, MnemocyteError, type MnemocyteErrorCode, type MnemocyteObservation, type MnemocyteObservationPhase, type MnemocyteOperation, type ObservabilityConfig, type ProviderResilienceConfig, type PruneInput, type PruneResult, type RecallInput, type RememberInput, type RetrievalConfig, type RetrievalExplanation, type RetrievalScoreWeights, type RetrievalScores, type TokenCounter, createMnemocyte, isMnemocyteError };
|
|
160
674
|
//# sourceMappingURL=index.d.mts.map
|