mnemocyte 0.3.0 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +266 -22
- package/dist/embedders/openai.d.mts +1 -1
- package/dist/embedders/openai.d.mts.map +1 -1
- package/dist/embedders/openai.mjs +24 -9
- package/dist/embedders/openai.mjs.map +1 -1
- package/dist/{errors-B_7ZdjEO.mjs → errors-DIPysVWl.mjs} +1 -1
- package/dist/errors-DIPysVWl.mjs.map +1 -0
- package/dist/index.d.mts +16 -12
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +155 -1699
- package/dist/index.mjs.map +1 -1
- package/dist/postgres-BHQ1pj16.mjs +913 -0
- package/dist/postgres-BHQ1pj16.mjs.map +1 -0
- package/dist/postgres-runtime-DxJxns07.mjs +9 -0
- package/dist/postgres-runtime-DxJxns07.mjs.map +1 -0
- package/dist/store-config-BFFTm1sj.mjs +1255 -0
- package/dist/store-config-BFFTm1sj.mjs.map +1 -0
- package/dist/stores/drizzle.d.mts +18 -0
- package/dist/stores/drizzle.d.mts.map +1 -0
- package/dist/stores/drizzle.mjs +20 -0
- package/dist/stores/drizzle.mjs.map +1 -0
- package/dist/{types-gOPLre4V.d.mts → types-XUWYDoXM.d.mts} +136 -34
- package/dist/types-XUWYDoXM.d.mts.map +1 -0
- package/migrations/0000_initial.sql.template +2 -1
- package/migrations/0002_add_embedding_model.sql +15 -0
- package/migrations/meta/0002_snapshot.json +315 -0
- package/migrations/meta/_journal.json +7 -0
- package/package.json +7 -3
- package/dist/errors-B_7ZdjEO.mjs.map +0 -1
- package/dist/types-gOPLre4V.d.mts.map +0 -1
|
@@ -0,0 +1,1255 @@
|
|
|
1
|
+
import { t as MnemocyteError } from "./errors-DIPysVWl.mjs";
|
|
2
|
+
//#region src/database-url.ts
|
|
3
|
+
function parsePostgresDatabaseUrl(databaseUrl) {
|
|
4
|
+
let url;
|
|
5
|
+
try {
|
|
6
|
+
url = new URL(databaseUrl);
|
|
7
|
+
} catch (error) {
|
|
8
|
+
throw new MnemocyteError("databaseUrl must be a valid Postgres connection URL.", "CONFIG", error);
|
|
9
|
+
}
|
|
10
|
+
if (url.protocol !== "postgres:" && url.protocol !== "postgresql:") throw new MnemocyteError("databaseUrl must use the postgres: or postgresql: protocol.", "CONFIG");
|
|
11
|
+
return url;
|
|
12
|
+
}
|
|
13
|
+
//#endregion
|
|
14
|
+
//#region src/context/formatter.ts
|
|
15
|
+
function escapeXml(value) {
|
|
16
|
+
return value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll("\"", """).replaceAll("'", "'");
|
|
17
|
+
}
|
|
18
|
+
function formatMetadata(memory) {
|
|
19
|
+
const parts = [
|
|
20
|
+
`type=${memory.type}`,
|
|
21
|
+
`importance=${memory.importance}`,
|
|
22
|
+
`score=${memory.score.toFixed(3)}`
|
|
23
|
+
];
|
|
24
|
+
if (memory.source) parts.push(`source=${memory.source}`);
|
|
25
|
+
if (memory.tags.length > 0) parts.push(`tags=${memory.tags.join(",")}`);
|
|
26
|
+
return parts.join("; ");
|
|
27
|
+
}
|
|
28
|
+
function markdownFence(value) {
|
|
29
|
+
const longestBacktickRun = Math.max(0, ...Array.from(value.matchAll(/`+/g), (match) => match[0].length));
|
|
30
|
+
return "`".repeat(Math.max(3, longestBacktickRun + 1));
|
|
31
|
+
}
|
|
32
|
+
function plainFence(values) {
|
|
33
|
+
const longestEqualsRun = Math.max(0, ...values.flatMap((value) => Array.from(value.matchAll(/=+/g), (match) => match[0].length)));
|
|
34
|
+
return "=".repeat(Math.max(8, longestEqualsRun + 1));
|
|
35
|
+
}
|
|
36
|
+
function formatMarkdown(memories, query, omittedCount) {
|
|
37
|
+
const lines = [
|
|
38
|
+
"# Memory Context",
|
|
39
|
+
"",
|
|
40
|
+
`Query: ${query}`,
|
|
41
|
+
"",
|
|
42
|
+
"## Relevant Memories"
|
|
43
|
+
];
|
|
44
|
+
for (const memory of memories) {
|
|
45
|
+
const fence = markdownFence(memory.content);
|
|
46
|
+
lines.push("", `- ${formatMetadata(memory)}`, ` ${fence}text`, ...memory.content.split("\n").map((line) => ` ${line}`), ` ${fence}`);
|
|
47
|
+
}
|
|
48
|
+
if (omittedCount > 0) lines.push("", `[${omittedCount} memories omitted to fit token budget]`);
|
|
49
|
+
return lines.join("\n");
|
|
50
|
+
}
|
|
51
|
+
function formatPlain(memories, query, omittedCount) {
|
|
52
|
+
const formattedMemories = memories.map((memory) => ({
|
|
53
|
+
memory,
|
|
54
|
+
metadata: formatMetadata(memory)
|
|
55
|
+
}));
|
|
56
|
+
const fence = plainFence([query, ...formattedMemories.flatMap(({ memory, metadata }) => [metadata, memory.content])]);
|
|
57
|
+
const lines = [
|
|
58
|
+
"MEMORY CONTEXT",
|
|
59
|
+
"",
|
|
60
|
+
`QUERY: ${query}`,
|
|
61
|
+
"",
|
|
62
|
+
"RELEVANT MEMORIES"
|
|
63
|
+
];
|
|
64
|
+
for (const [index, { memory, metadata }] of formattedMemories.entries()) lines.push("", `${fence} MEMORY ${index + 1} START ${fence}`, metadata, memory.content, `${fence} MEMORY ${index + 1} END ${fence}`);
|
|
65
|
+
if (omittedCount > 0) lines.push("", `[${omittedCount} memories omitted to fit token budget]`);
|
|
66
|
+
return lines.join("\n");
|
|
67
|
+
}
|
|
68
|
+
function formatXml(memories, query, omittedCount) {
|
|
69
|
+
const lines = [`<memory_context query="${escapeXml(query)}">`];
|
|
70
|
+
for (const memory of memories) lines.push(` <memory id="${escapeXml(memory.id)}" type="${escapeXml(memory.type)}" importance="${escapeXml(memory.importance)}" score="${memory.score.toFixed(3)}">`, ` <content>${escapeXml(memory.content)}</content>`, ` <metadata>${escapeXml(formatMetadata(memory))}</metadata>`, " </memory>");
|
|
71
|
+
if (omittedCount > 0) lines.push(` <omitted count="${omittedCount}" reason="token_budget" />`);
|
|
72
|
+
lines.push("</memory_context>");
|
|
73
|
+
return lines.join("\n");
|
|
74
|
+
}
|
|
75
|
+
function formatContext(memories, query, format, omittedCount = 0) {
|
|
76
|
+
switch (format) {
|
|
77
|
+
case "markdown": return formatMarkdown(memories, query, omittedCount);
|
|
78
|
+
case "plain": return formatPlain(memories, query, omittedCount);
|
|
79
|
+
case "xml": return formatXml(memories, query, omittedCount);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
//#endregion
|
|
83
|
+
//#region src/context/tokens.ts
|
|
84
|
+
const TRUNCATION_MARKER = "[truncated to fit token budget]";
|
|
85
|
+
const heuristicTokenCounter = { count(text) {
|
|
86
|
+
return Math.ceil(text.length / 4);
|
|
87
|
+
} };
|
|
88
|
+
function trimToTokenBudget(text, maxTokens, tokenCounter) {
|
|
89
|
+
if (maxTokens < 1 || tokenCounter.count(text) <= maxTokens) return text;
|
|
90
|
+
let low = 0;
|
|
91
|
+
let high = text.length;
|
|
92
|
+
let best = "";
|
|
93
|
+
while (low <= high) {
|
|
94
|
+
const mid = Math.floor((low + high) / 2);
|
|
95
|
+
const output = `${text.slice(0, mid).trimEnd()}\n${TRUNCATION_MARKER}`;
|
|
96
|
+
if (tokenCounter.count(output) <= maxTokens) {
|
|
97
|
+
best = output;
|
|
98
|
+
low = mid + 1;
|
|
99
|
+
} else high = mid - 1;
|
|
100
|
+
}
|
|
101
|
+
if (best) return best;
|
|
102
|
+
for (let length = 31; length > 0; length -= 1) {
|
|
103
|
+
const markerFragment = TRUNCATION_MARKER.slice(0, length);
|
|
104
|
+
if (tokenCounter.count(markerFragment) <= maxTokens) return markerFragment;
|
|
105
|
+
}
|
|
106
|
+
return "";
|
|
107
|
+
}
|
|
108
|
+
//#endregion
|
|
109
|
+
//#region src/context/builder.ts
|
|
110
|
+
async function buildContext(options) {
|
|
111
|
+
const format = options.input.format ?? "markdown";
|
|
112
|
+
const maxTokens = options.input.maxTokens ?? 1200;
|
|
113
|
+
const tokenCounter = options.input.tokenCounter ?? heuristicTokenCounter;
|
|
114
|
+
const memories = await options.recall(options.input);
|
|
115
|
+
let low = 0;
|
|
116
|
+
let high = memories.length;
|
|
117
|
+
let bestContext = "";
|
|
118
|
+
while (low <= high) {
|
|
119
|
+
const mid = Math.floor((low + high) / 2);
|
|
120
|
+
const omittedCount = memories.length - mid;
|
|
121
|
+
const context = formatContext(memories.slice(0, mid), options.input.query, format, omittedCount);
|
|
122
|
+
if (tokenCounter.count(context) <= maxTokens) {
|
|
123
|
+
bestContext = context;
|
|
124
|
+
low = mid + 1;
|
|
125
|
+
} else high = mid - 1;
|
|
126
|
+
}
|
|
127
|
+
if (bestContext || memories.length === 0) return bestContext;
|
|
128
|
+
return trimToTokenBudget(formatContext([], options.input.query, format, memories.length), maxTokens, tokenCounter);
|
|
129
|
+
}
|
|
130
|
+
//#endregion
|
|
131
|
+
//#region src/observability.ts
|
|
132
|
+
function withMetadata(event, metadata) {
|
|
133
|
+
return {
|
|
134
|
+
...event,
|
|
135
|
+
...metadata.entityId === void 0 ? {} : { entityId: metadata.entityId },
|
|
136
|
+
...metadata.memoryId === void 0 ? {} : { memoryId: metadata.memoryId },
|
|
137
|
+
...metadata.count === void 0 ? {} : { count: metadata.count }
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
async function emitObservation(config, event) {
|
|
141
|
+
try {
|
|
142
|
+
await config.observability?.onEvent?.(event);
|
|
143
|
+
} catch {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
async function observeFromStartedAt(config, backend, operation, metadata, startedAt, action, successMetadata) {
|
|
148
|
+
await emitObservation(config, withMetadata({
|
|
149
|
+
operation,
|
|
150
|
+
phase: "start",
|
|
151
|
+
backend,
|
|
152
|
+
timestamp: new Date(startedAt)
|
|
153
|
+
}, metadata));
|
|
154
|
+
try {
|
|
155
|
+
const result = await action();
|
|
156
|
+
await emitObservation(config, withMetadata({
|
|
157
|
+
operation,
|
|
158
|
+
phase: "success",
|
|
159
|
+
backend,
|
|
160
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
161
|
+
durationMs: Date.now() - startedAt
|
|
162
|
+
}, {
|
|
163
|
+
...metadata,
|
|
164
|
+
...successMetadata?.(result)
|
|
165
|
+
}));
|
|
166
|
+
return result;
|
|
167
|
+
} catch (error) {
|
|
168
|
+
await emitObservation(config, withMetadata({
|
|
169
|
+
operation,
|
|
170
|
+
phase: "error",
|
|
171
|
+
backend,
|
|
172
|
+
timestamp: /* @__PURE__ */ new Date(),
|
|
173
|
+
durationMs: Date.now() - startedAt,
|
|
174
|
+
error
|
|
175
|
+
}, metadata));
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
function observe(config, backend, operation, metadata, action, successMetadata) {
|
|
180
|
+
return observeFromStartedAt(config, backend, operation, metadata, Date.now(), action, successMetadata);
|
|
181
|
+
}
|
|
182
|
+
function observePrepared(config, backend, operation, metadata, prepare, action, successMetadata) {
|
|
183
|
+
const startedAt = Date.now();
|
|
184
|
+
try {
|
|
185
|
+
const prepared = prepare();
|
|
186
|
+
return observeFromStartedAt(config, backend, operation, metadata, startedAt, () => action(prepared), successMetadata);
|
|
187
|
+
} catch (error) {
|
|
188
|
+
return observeFromStartedAt(config, backend, operation, metadata, startedAt, async () => {
|
|
189
|
+
throw error;
|
|
190
|
+
});
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
//#endregion
|
|
194
|
+
//#region src/resilience.ts
|
|
195
|
+
/**
|
|
196
|
+
* Default per-provider-call timeout. Disabled by default so that callers
|
|
197
|
+
* who do not configure {@link ProviderResilienceConfig.timeoutMs} are
|
|
198
|
+
* unaffected.
|
|
199
|
+
*/
|
|
200
|
+
const DEFAULT_TIMEOUT_MS = 0;
|
|
201
|
+
/** Default number of retry attempts on transient provider failures. */
|
|
202
|
+
const DEFAULT_RETRIES = 0;
|
|
203
|
+
/** Default base backoff delay used between retry attempts. */
|
|
204
|
+
const DEFAULT_BASE_DELAY_MS = 100;
|
|
205
|
+
/** Default ceiling for retry backoff delay. */
|
|
206
|
+
const DEFAULT_MAX_DELAY_MS = 2e3;
|
|
207
|
+
/**
|
|
208
|
+
* Throw a {@link MnemocyteError} with code `"ABORTED"` if `signal` is
|
|
209
|
+
* already aborted. Safe to call with `undefined`.
|
|
210
|
+
*/
|
|
211
|
+
function throwIfAborted(signal) {
|
|
212
|
+
if (signal?.aborted) throw new MnemocyteError("Operation was aborted.", "ABORTED", signal.reason);
|
|
213
|
+
}
|
|
214
|
+
/**
|
|
215
|
+
* Heuristic default for whether an error should be retried.
|
|
216
|
+
*
|
|
217
|
+
* Conservative by design: only retries on common transient failure
|
|
218
|
+
* indicators (network errors, 5xx-ish messages, `ECONN*` etc.). Never
|
|
219
|
+
* retries on validation, configuration, or {@link MnemocyteError} of
|
|
220
|
+
* code `"VALIDATION"` / `"CONFIG"` / `"CONFLICT"` / `"ABORTED"`.
|
|
221
|
+
*/
|
|
222
|
+
function defaultShouldRetry(error) {
|
|
223
|
+
if (error instanceof MnemocyteError) {
|
|
224
|
+
if (error.code === "VALIDATION" || error.code === "CONFIG" || error.code === "CONFLICT" || error.code === "ABORTED") return false;
|
|
225
|
+
return true;
|
|
226
|
+
}
|
|
227
|
+
if (typeof error === "object" && error !== null && "status" in error && typeof error.status === "number" && [
|
|
228
|
+
429,
|
|
229
|
+
500,
|
|
230
|
+
502,
|
|
231
|
+
503,
|
|
232
|
+
504
|
|
233
|
+
].includes(error.status)) return true;
|
|
234
|
+
if (error instanceof Error) {
|
|
235
|
+
const message = error.message.toLowerCase();
|
|
236
|
+
if (message.includes("econn") || message.includes("etimedout") || message.includes("network") || message.includes("timeout") || message.includes("temporarily") || message.includes("rate limit") || message.includes("503") || message.includes("502") || message.includes("504") || message.includes("500")) return true;
|
|
237
|
+
}
|
|
238
|
+
return false;
|
|
239
|
+
}
|
|
240
|
+
/**
|
|
241
|
+
* Compute the backoff delay for the given retry attempt, using exponential
|
|
242
|
+
* growth capped at {@link ProviderResilienceConfig.maxDelayMs}.
|
|
243
|
+
*
|
|
244
|
+
* `attempt` is 1-indexed: the delay before the first retry uses
|
|
245
|
+
* `attempt = 1`, before the second retry `attempt = 2`, etc.
|
|
246
|
+
*/
|
|
247
|
+
function computeDelayMs(attempt, baseDelayMs, maxDelayMs) {
|
|
248
|
+
const exponential = baseDelayMs * 2 ** (attempt - 1);
|
|
249
|
+
return Math.max(0, Math.min(maxDelayMs, exponential));
|
|
250
|
+
}
|
|
251
|
+
/**
|
|
252
|
+
* Promise-based `setTimeout` that rejects with an `"ABORTED"`
|
|
253
|
+
* {@link MnemocyteError} if `signal` aborts while waiting.
|
|
254
|
+
*/
|
|
255
|
+
function delay(ms, signal) {
|
|
256
|
+
if (ms <= 0) {
|
|
257
|
+
throwIfAborted(signal);
|
|
258
|
+
return Promise.resolve();
|
|
259
|
+
}
|
|
260
|
+
return new Promise((resolve, reject) => {
|
|
261
|
+
const timer = setTimeout(() => {
|
|
262
|
+
signal?.removeEventListener("abort", onAbort);
|
|
263
|
+
resolve();
|
|
264
|
+
}, ms);
|
|
265
|
+
const onAbort = () => {
|
|
266
|
+
clearTimeout(timer);
|
|
267
|
+
reject(new MnemocyteError("Operation was aborted.", "ABORTED", signal?.reason));
|
|
268
|
+
};
|
|
269
|
+
if (signal) {
|
|
270
|
+
if (signal.aborted) {
|
|
271
|
+
clearTimeout(timer);
|
|
272
|
+
reject(new MnemocyteError("Operation was aborted.", "ABORTED", signal.reason));
|
|
273
|
+
return;
|
|
274
|
+
}
|
|
275
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
function timeoutError(timeoutMs) {
|
|
280
|
+
return new MnemocyteError(`Provider call timed out after ${timeoutMs}ms.`, "TIMEOUT");
|
|
281
|
+
}
|
|
282
|
+
/**
|
|
283
|
+
* Run one provider attempt with a signal linked to the caller's signal and
|
|
284
|
+
* Mnemocyte's configured timeout. Timeout aborts are actively propagated to
|
|
285
|
+
* providers that honor `AbortSignal`.
|
|
286
|
+
*/
|
|
287
|
+
function runAttempt(action, timeoutMs, signal) {
|
|
288
|
+
if (timeoutMs <= 0 && !signal) return action(void 0);
|
|
289
|
+
return new Promise((resolve, reject) => {
|
|
290
|
+
let settled = false;
|
|
291
|
+
const controller = new AbortController();
|
|
292
|
+
const timer = timeoutMs > 0 ? setTimeout(() => {
|
|
293
|
+
if (settled) return;
|
|
294
|
+
settled = true;
|
|
295
|
+
signal?.removeEventListener("abort", onAbort);
|
|
296
|
+
controller.abort(timeoutError(timeoutMs));
|
|
297
|
+
reject(timeoutError(timeoutMs));
|
|
298
|
+
}, timeoutMs) : void 0;
|
|
299
|
+
const onAbort = () => {
|
|
300
|
+
if (settled) return;
|
|
301
|
+
settled = true;
|
|
302
|
+
if (timer) clearTimeout(timer);
|
|
303
|
+
controller.abort(signal?.reason);
|
|
304
|
+
reject(new MnemocyteError("Operation was aborted.", "ABORTED", signal?.reason));
|
|
305
|
+
};
|
|
306
|
+
if (signal) {
|
|
307
|
+
if (signal.aborted) {
|
|
308
|
+
if (timer) clearTimeout(timer);
|
|
309
|
+
settled = true;
|
|
310
|
+
controller.abort(signal.reason);
|
|
311
|
+
reject(new MnemocyteError("Operation was aborted.", "ABORTED", signal.reason));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
315
|
+
}
|
|
316
|
+
action(controller.signal).then((value) => {
|
|
317
|
+
if (settled) return;
|
|
318
|
+
settled = true;
|
|
319
|
+
if (timer) clearTimeout(timer);
|
|
320
|
+
signal?.removeEventListener("abort", onAbort);
|
|
321
|
+
resolve(value);
|
|
322
|
+
}, (error) => {
|
|
323
|
+
if (settled) return;
|
|
324
|
+
settled = true;
|
|
325
|
+
if (timer) clearTimeout(timer);
|
|
326
|
+
signal?.removeEventListener("abort", onAbort);
|
|
327
|
+
reject(error);
|
|
328
|
+
});
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
/**
|
|
332
|
+
* Run `action` with timeout, retry, and abort handling derived from
|
|
333
|
+
* `options.resilience` and `options.signal`. Each retry attempt receives
|
|
334
|
+
* a fresh `AbortSignal` linked to the caller's signal — so callers may
|
|
335
|
+
* abort mid-retry and the in-flight attempt will cancel promptly if the
|
|
336
|
+
* underlying provider honours signals.
|
|
337
|
+
*
|
|
338
|
+
* Errors from {@link MnemocyteError} with code `"VALIDATION"` /
|
|
339
|
+
* `"CONFIG"` / `"CONFLICT"` / `"ABORTED"` are never retried.
|
|
340
|
+
*/
|
|
341
|
+
async function withResilience(action, options = {}) {
|
|
342
|
+
const config = options.resilience ?? {};
|
|
343
|
+
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
|
|
344
|
+
const retries = Math.max(0, config.retries ?? DEFAULT_RETRIES);
|
|
345
|
+
const baseDelayMs = Math.max(0, config.baseDelayMs ?? DEFAULT_BASE_DELAY_MS);
|
|
346
|
+
const maxDelayMs = Math.max(baseDelayMs, config.maxDelayMs ?? DEFAULT_MAX_DELAY_MS);
|
|
347
|
+
const shouldRetry = config.shouldRetry ?? defaultShouldRetry;
|
|
348
|
+
const externalSignal = options.signal;
|
|
349
|
+
throwIfAborted(externalSignal);
|
|
350
|
+
const maxAttempts = retries + 1;
|
|
351
|
+
let lastError;
|
|
352
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
353
|
+
throwIfAborted(externalSignal);
|
|
354
|
+
try {
|
|
355
|
+
return await runAttempt(action, timeoutMs, externalSignal);
|
|
356
|
+
} catch (error) {
|
|
357
|
+
lastError = error;
|
|
358
|
+
if (error instanceof MnemocyteError && error.code === "ABORTED") throw error;
|
|
359
|
+
if (attempt >= maxAttempts) throw error;
|
|
360
|
+
if (!shouldRetry(error, attempt)) throw error;
|
|
361
|
+
await delay(computeDelayMs(attempt, baseDelayMs, maxDelayMs), externalSignal);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
throw lastError;
|
|
365
|
+
}
|
|
366
|
+
//#endregion
|
|
367
|
+
//#region src/memory/json.ts
|
|
368
|
+
function invalidJsonValue(path, cause) {
|
|
369
|
+
return new MnemocyteError(`${path} must contain only JSON-compatible value data.`, "VALIDATION", cause);
|
|
370
|
+
}
|
|
371
|
+
function cloneJsonValue(value, path, ancestors) {
|
|
372
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return value;
|
|
373
|
+
if (typeof value === "number") {
|
|
374
|
+
if (!Number.isFinite(value)) throw invalidJsonValue(path);
|
|
375
|
+
return Object.is(value, -0) ? 0 : value;
|
|
376
|
+
}
|
|
377
|
+
if (typeof value !== "object") throw invalidJsonValue(path);
|
|
378
|
+
if (ancestors.has(value)) throw invalidJsonValue(path);
|
|
379
|
+
ancestors.add(value);
|
|
380
|
+
try {
|
|
381
|
+
if (Array.isArray(value)) {
|
|
382
|
+
if (Object.getOwnPropertySymbols(value).length > 0 || Object.keys(value).some((key) => !/^(0|[1-9]\d*)$/.test(key))) throw invalidJsonValue(path);
|
|
383
|
+
return Array.from({ length: value.length }, (_, index) => {
|
|
384
|
+
if (!Object.hasOwn(value, index)) throw invalidJsonValue(`${path}[${index}]`);
|
|
385
|
+
return cloneJsonValue(value[index], `${path}[${index}]`, ancestors);
|
|
386
|
+
});
|
|
387
|
+
}
|
|
388
|
+
const prototype = Object.getPrototypeOf(value);
|
|
389
|
+
if (prototype !== Object.prototype && prototype !== null) throw invalidJsonValue(path);
|
|
390
|
+
const descriptors = Object.getOwnPropertyDescriptors(value);
|
|
391
|
+
const entries = [];
|
|
392
|
+
for (const key of Reflect.ownKeys(descriptors)) {
|
|
393
|
+
if (typeof key !== "string") throw invalidJsonValue(path);
|
|
394
|
+
const descriptor = descriptors[key];
|
|
395
|
+
if (descriptor === void 0 || descriptor.enumerable !== true || !("value" in descriptor)) throw invalidJsonValue(`${path}.${key}`);
|
|
396
|
+
entries.push([key, cloneJsonValue(descriptor.value, `${path}.${key}`, ancestors)]);
|
|
397
|
+
}
|
|
398
|
+
return Object.fromEntries(entries);
|
|
399
|
+
} finally {
|
|
400
|
+
ancestors.delete(value);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
/** Validate and deep-clone a JSON-compatible object. */
|
|
404
|
+
function cloneJsonObject(value, path = "metadata") {
|
|
405
|
+
try {
|
|
406
|
+
if (value === null || typeof value !== "object" || Array.isArray(value)) throw invalidJsonValue(path);
|
|
407
|
+
return cloneJsonValue(value, path, /* @__PURE__ */ new Set());
|
|
408
|
+
} catch (error) {
|
|
409
|
+
if (error instanceof MnemocyteError) throw error;
|
|
410
|
+
throw invalidJsonValue(path, error);
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
//#endregion
|
|
414
|
+
//#region src/memory/records.ts
|
|
415
|
+
function normalizeTags(tags) {
|
|
416
|
+
if (!tags) return [];
|
|
417
|
+
return [...new Set(tags.map((tag) => tag.trim()).filter(Boolean))];
|
|
418
|
+
}
|
|
419
|
+
function createId() {
|
|
420
|
+
return `mem_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
|
421
|
+
}
|
|
422
|
+
/** Generate a unique audit-event id (`evt_*`). */
|
|
423
|
+
function createEventId() {
|
|
424
|
+
return `evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 10)}`;
|
|
425
|
+
}
|
|
426
|
+
function cloneMemory(memory) {
|
|
427
|
+
return {
|
|
428
|
+
id: memory.id,
|
|
429
|
+
entityId: memory.entityId,
|
|
430
|
+
content: memory.content,
|
|
431
|
+
type: memory.type,
|
|
432
|
+
importance: memory.importance,
|
|
433
|
+
tags: [...memory.tags],
|
|
434
|
+
source: memory.source,
|
|
435
|
+
metadata: cloneJsonObject(memory.metadata),
|
|
436
|
+
confidence: memory.confidence,
|
|
437
|
+
embeddingModel: memory.embeddingModel,
|
|
438
|
+
embeddingDimensions: memory.embeddingDimensions,
|
|
439
|
+
supersededBy: memory.supersededBy,
|
|
440
|
+
supersededAt: memory.supersededAt ? new Date(memory.supersededAt) : null,
|
|
441
|
+
expiresAt: memory.expiresAt ? new Date(memory.expiresAt) : null,
|
|
442
|
+
lastAccessedAt: memory.lastAccessedAt ? new Date(memory.lastAccessedAt) : null,
|
|
443
|
+
accessCount: memory.accessCount,
|
|
444
|
+
createdAt: new Date(memory.createdAt),
|
|
445
|
+
updatedAt: new Date(memory.updatedAt)
|
|
446
|
+
};
|
|
447
|
+
}
|
|
448
|
+
//#endregion
|
|
449
|
+
//#region src/retrieval/scorer.ts
|
|
450
|
+
const IMPORTANCE_SCORES = {
|
|
451
|
+
low: 0,
|
|
452
|
+
normal: .5,
|
|
453
|
+
high: .8,
|
|
454
|
+
critical: 1
|
|
455
|
+
};
|
|
456
|
+
const DEFAULT_RETRIEVAL_WEIGHTS = {
|
|
457
|
+
vector: .55,
|
|
458
|
+
lexical: .2,
|
|
459
|
+
recency: .1,
|
|
460
|
+
confidence: .05,
|
|
461
|
+
access: .05,
|
|
462
|
+
importance: .05
|
|
463
|
+
};
|
|
464
|
+
const DEFAULT_RECENCY_HALF_LIFE_DAYS = 90;
|
|
465
|
+
const DEFAULT_ACCESS_SATURATION = 10;
|
|
466
|
+
function cosineSimilarity(a, b) {
|
|
467
|
+
let dot = 0;
|
|
468
|
+
let aMagnitude = 0;
|
|
469
|
+
let bMagnitude = 0;
|
|
470
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
471
|
+
const av = a[i] ?? 0;
|
|
472
|
+
const bv = b[i] ?? 0;
|
|
473
|
+
dot += av * bv;
|
|
474
|
+
aMagnitude += av * av;
|
|
475
|
+
bMagnitude += bv * bv;
|
|
476
|
+
}
|
|
477
|
+
if (aMagnitude === 0 || bMagnitude === 0) return 0;
|
|
478
|
+
return dot / (Math.sqrt(aMagnitude) * Math.sqrt(bMagnitude));
|
|
479
|
+
}
|
|
480
|
+
function tokenizeQuery(query) {
|
|
481
|
+
return query.toLowerCase().split(/\s+/).filter(Boolean);
|
|
482
|
+
}
|
|
483
|
+
function lexicalScoreWithTerms(content, terms) {
|
|
484
|
+
if (terms.length === 0) return 0;
|
|
485
|
+
const lowerContent = content.toLowerCase();
|
|
486
|
+
return terms.filter((term) => lowerContent.includes(term)).length / terms.length;
|
|
487
|
+
}
|
|
488
|
+
function createLexicalScorer(query) {
|
|
489
|
+
const terms = tokenizeQuery(query);
|
|
490
|
+
return (content) => lexicalScoreWithTerms(content, terms);
|
|
491
|
+
}
|
|
492
|
+
function clampScore(value) {
|
|
493
|
+
if (!Number.isFinite(value)) return 0;
|
|
494
|
+
return Math.max(0, Math.min(1, value));
|
|
495
|
+
}
|
|
496
|
+
function toVectorScore(cosineSimilarity) {
|
|
497
|
+
return clampScore(cosineSimilarity);
|
|
498
|
+
}
|
|
499
|
+
function normalizeWeights(weights) {
|
|
500
|
+
const merged = {
|
|
501
|
+
...DEFAULT_RETRIEVAL_WEIGHTS,
|
|
502
|
+
...weights
|
|
503
|
+
};
|
|
504
|
+
const total = merged.vector + merged.lexical + merged.recency + merged.confidence + merged.access + merged.importance;
|
|
505
|
+
if (total <= 0) return { ...DEFAULT_RETRIEVAL_WEIGHTS };
|
|
506
|
+
return {
|
|
507
|
+
vector: merged.vector / total,
|
|
508
|
+
lexical: merged.lexical / total,
|
|
509
|
+
recency: merged.recency / total,
|
|
510
|
+
confidence: merged.confidence / total,
|
|
511
|
+
access: merged.access / total,
|
|
512
|
+
importance: merged.importance / total
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
function createScoringConfig(config) {
|
|
516
|
+
return {
|
|
517
|
+
weights: normalizeWeights(config?.weights),
|
|
518
|
+
recencyHalfLifeDays: config?.recencyHalfLifeDays ?? DEFAULT_RECENCY_HALF_LIFE_DAYS,
|
|
519
|
+
accessSaturation: config?.accessSaturation ?? DEFAULT_ACCESS_SATURATION
|
|
520
|
+
};
|
|
521
|
+
}
|
|
522
|
+
function recencyScore(createdAt, halfLifeDays) {
|
|
523
|
+
const ageMs = Date.now() - createdAt.getTime();
|
|
524
|
+
const ageDays = Math.max(0, ageMs / 864e5);
|
|
525
|
+
return Math.exp(-Math.LN2 * ageDays / halfLifeDays);
|
|
526
|
+
}
|
|
527
|
+
function accessScore(accessCount, saturation) {
|
|
528
|
+
if (accessCount <= 0) return 0;
|
|
529
|
+
return Math.min(1, Math.log1p(accessCount) / Math.log1p(saturation));
|
|
530
|
+
}
|
|
531
|
+
function toScoredMemoryWithConfig(memory, vector, lexical, input, config) {
|
|
532
|
+
const { weights } = config;
|
|
533
|
+
const recency = recencyScore(memory.createdAt, config.recencyHalfLifeDays);
|
|
534
|
+
const confidence = clampScore(memory.confidence);
|
|
535
|
+
const access = accessScore(memory.accessCount, config.accessSaturation);
|
|
536
|
+
const importance = IMPORTANCE_SCORES[memory.importance];
|
|
537
|
+
const score = Math.max(0, Math.min(1, clampScore(vector) * weights.vector + clampScore(lexical) * weights.lexical + recency * weights.recency + confidence * weights.confidence + access * weights.access + importance * weights.importance));
|
|
538
|
+
return {
|
|
539
|
+
...cloneMemory(memory),
|
|
540
|
+
score,
|
|
541
|
+
scores: {
|
|
542
|
+
vector: clampScore(vector),
|
|
543
|
+
lexical: clampScore(lexical),
|
|
544
|
+
recency,
|
|
545
|
+
confidence,
|
|
546
|
+
access,
|
|
547
|
+
importance
|
|
548
|
+
},
|
|
549
|
+
explanation: input.explain ? {
|
|
550
|
+
vectorScore: clampScore(vector),
|
|
551
|
+
lexicalScore: clampScore(lexical),
|
|
552
|
+
recencyScore: recency,
|
|
553
|
+
confidenceScore: confidence,
|
|
554
|
+
accessScore: access,
|
|
555
|
+
importanceScore: importance,
|
|
556
|
+
importanceBoost: importance * weights.importance,
|
|
557
|
+
weights,
|
|
558
|
+
finalScore: score
|
|
559
|
+
} : null
|
|
560
|
+
};
|
|
561
|
+
}
|
|
562
|
+
/**
|
|
563
|
+
* Ordering of {@link ImportanceLevel} from least to most important. Used
|
|
564
|
+
* by `prune({ maxImportance })` to compare a memory's importance against
|
|
565
|
+
* the caller-supplied ceiling.
|
|
566
|
+
*/
|
|
567
|
+
const IMPORTANCE_RANK = {
|
|
568
|
+
low: 0,
|
|
569
|
+
normal: 1,
|
|
570
|
+
high: 2,
|
|
571
|
+
critical: 3
|
|
572
|
+
};
|
|
573
|
+
/** Default cosine-similarity threshold for {@link FindDuplicatesInput}. */
|
|
574
|
+
const DEFAULT_DUPLICATE_THRESHOLD = .95;
|
|
575
|
+
//#endregion
|
|
576
|
+
//#region src/memory/embeddings.ts
|
|
577
|
+
function validateEmbedding(embedding, dimensions) {
|
|
578
|
+
if (embedding.length !== dimensions) throw new MnemocyteError("Embedder returned an embedding with unexpected dimensions.", "EMBEDDING");
|
|
579
|
+
if (embedding.some((component) => !Number.isFinite(component))) throw new MnemocyteError("Embedder returned an embedding with non-finite values.", "EMBEDDING");
|
|
580
|
+
if (embedding.every((component) => component === 0)) throw new MnemocyteError("Embedder returned an embedding with zero norm.", "EMBEDDING");
|
|
581
|
+
}
|
|
582
|
+
async function embedOne(embedder, text, options = {}) {
|
|
583
|
+
let embeddings;
|
|
584
|
+
try {
|
|
585
|
+
embeddings = await withResilience((signal) => signal === void 0 ? embedder.embed([text]) : embedder.embed([text], { signal }), {
|
|
586
|
+
...options.signal === void 0 ? {} : { signal: options.signal },
|
|
587
|
+
...options.resilience === void 0 ? {} : { resilience: options.resilience }
|
|
588
|
+
});
|
|
589
|
+
} catch (error) {
|
|
590
|
+
if (error instanceof MnemocyteError && (error.code === "TIMEOUT" || error.code === "ABORTED")) throw error;
|
|
591
|
+
throw new MnemocyteError("Failed to embed text.", "EMBEDDING", error);
|
|
592
|
+
}
|
|
593
|
+
const embedding = embeddings[0];
|
|
594
|
+
if (!embedding) throw new MnemocyteError("Embedder returned no embedding.", "EMBEDDING");
|
|
595
|
+
validateEmbedding(embedding, embedder.dimensions);
|
|
596
|
+
return embedding;
|
|
597
|
+
}
|
|
598
|
+
async function embedMany(embedder, texts, options = {}) {
|
|
599
|
+
if (texts.length === 0) return [];
|
|
600
|
+
let embeddings;
|
|
601
|
+
try {
|
|
602
|
+
embeddings = await withResilience((signal) => signal === void 0 ? embedder.embed(texts) : embedder.embed(texts, { signal }), {
|
|
603
|
+
...options.signal === void 0 ? {} : { signal: options.signal },
|
|
604
|
+
...options.resilience === void 0 ? {} : { resilience: options.resilience }
|
|
605
|
+
});
|
|
606
|
+
} catch (error) {
|
|
607
|
+
if (error instanceof MnemocyteError && (error.code === "TIMEOUT" || error.code === "ABORTED")) throw error;
|
|
608
|
+
throw new MnemocyteError("Failed to embed texts.", "EMBEDDING", error);
|
|
609
|
+
}
|
|
610
|
+
if (embeddings.length !== texts.length) throw new MnemocyteError(`Embedder returned ${embeddings.length} embeddings for ${texts.length} texts.`, "EMBEDDING");
|
|
611
|
+
for (const embedding of embeddings) validateEmbedding(embedding, embedder.dimensions);
|
|
612
|
+
return embeddings;
|
|
613
|
+
}
|
|
614
|
+
//#endregion
|
|
615
|
+
//#region src/memory/store.ts
|
|
616
|
+
function hasPruneSelector(filter) {
|
|
617
|
+
return filter.entityId !== void 0 || filter.expired === true || filter.superseded === true || filter.createdBefore !== void 0 || filter.notAccessedSince !== void 0 || filter.types !== void 0 && filter.types.length > 0 || filter.tags !== void 0 && filter.tags.length > 0 || filter.maxImportance !== void 0;
|
|
618
|
+
}
|
|
619
|
+
function assertPruneFilterHasSelector(filter) {
|
|
620
|
+
if (!hasPruneSelector(filter)) throw new MnemocyteError("prune requires at least one selector (entityId, expired, superseded, createdBefore, notAccessedSince, types, tags, or maxImportance).", "VALIDATION");
|
|
621
|
+
}
|
|
622
|
+
//#endregion
|
|
623
|
+
//#region src/memory/validation.ts
|
|
624
|
+
const MEMORY_TYPES = [
|
|
625
|
+
"fact",
|
|
626
|
+
"preference",
|
|
627
|
+
"instruction",
|
|
628
|
+
"backstory",
|
|
629
|
+
"episode",
|
|
630
|
+
"session"
|
|
631
|
+
];
|
|
632
|
+
const IMPORTANCE_LEVELS = [
|
|
633
|
+
"low",
|
|
634
|
+
"normal",
|
|
635
|
+
"high",
|
|
636
|
+
"critical"
|
|
637
|
+
];
|
|
638
|
+
function isMemoryType(value) {
|
|
639
|
+
return typeof value === "string" && MEMORY_TYPES.includes(value);
|
|
640
|
+
}
|
|
641
|
+
function isImportanceLevel(value) {
|
|
642
|
+
return typeof value === "string" && IMPORTANCE_LEVELS.includes(value);
|
|
643
|
+
}
|
|
644
|
+
function assertMemoryType(value, field) {
|
|
645
|
+
if (!isMemoryType(value)) throw new MnemocyteError(`${field} must be a known memory type.`, "VALIDATION");
|
|
646
|
+
}
|
|
647
|
+
function assertImportanceLevel(value, field) {
|
|
648
|
+
if (!isImportanceLevel(value)) throw new MnemocyteError(`${field} must be a known importance level.`, "VALIDATION");
|
|
649
|
+
}
|
|
650
|
+
function assertMemoryTypeArray(value, field) {
|
|
651
|
+
if (!Array.isArray(value)) throw new MnemocyteError(`${field} must be an array.`, "VALIDATION");
|
|
652
|
+
for (const item of value) if (!isMemoryType(item)) throw new MnemocyteError(`${field} must contain only known memory types.`, "VALIDATION");
|
|
653
|
+
}
|
|
654
|
+
function assertValidDate(value, field) {
|
|
655
|
+
if (!(value instanceof Date) || !Number.isFinite(value.getTime())) throw new MnemocyteError(`${field} must be a valid Date.`, "VALIDATION");
|
|
656
|
+
}
|
|
657
|
+
function assertNonEmptyString(value, field, code = "VALIDATION") {
|
|
658
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new MnemocyteError(`${field} must be a non-empty string.`, code);
|
|
659
|
+
}
|
|
660
|
+
function assertLimit(value) {
|
|
661
|
+
if (!Number.isInteger(value) || value < 1) throw new MnemocyteError("limit must be a positive integer.", "VALIDATION");
|
|
662
|
+
}
|
|
663
|
+
function assertMinScore(value) {
|
|
664
|
+
if (!Number.isFinite(value) || value < 0 || value > 1) throw new MnemocyteError("minScore must be a number between 0 and 1.", "VALIDATION");
|
|
665
|
+
}
|
|
666
|
+
function assertEmbedder(embedder) {
|
|
667
|
+
if (!embedder || typeof embedder.embed !== "function") throw new MnemocyteError("embedder with an embed function is required.", "CONFIG");
|
|
668
|
+
assertNonEmptyString(embedder.model, "embedder.model", "CONFIG");
|
|
669
|
+
if (!Number.isInteger(embedder.dimensions) || embedder.dimensions < 1) throw new MnemocyteError("embedder.dimensions must be a positive integer.", "CONFIG");
|
|
670
|
+
}
|
|
671
|
+
const RETRIEVAL_WEIGHT_KEYS = [
|
|
672
|
+
"vector",
|
|
673
|
+
"lexical",
|
|
674
|
+
"recency",
|
|
675
|
+
"confidence",
|
|
676
|
+
"access",
|
|
677
|
+
"importance"
|
|
678
|
+
];
|
|
679
|
+
function assertPositiveFiniteConfigValue(value, field) {
|
|
680
|
+
if (!Number.isFinite(value) || value <= 0) throw new MnemocyteError(`${field} must be a positive finite number.`, "CONFIG");
|
|
681
|
+
}
|
|
682
|
+
function validateRetrievalConfig(config) {
|
|
683
|
+
if (config === void 0) return;
|
|
684
|
+
let weightTotal = 0;
|
|
685
|
+
for (const key of RETRIEVAL_WEIGHT_KEYS) {
|
|
686
|
+
const weight = config.weights?.[key] ?? DEFAULT_RETRIEVAL_WEIGHTS[key];
|
|
687
|
+
if (!Number.isFinite(weight) || weight < 0) throw new MnemocyteError(`retrieval.weights.${key} must be a non-negative finite number.`, "CONFIG");
|
|
688
|
+
weightTotal += weight;
|
|
689
|
+
}
|
|
690
|
+
if (weightTotal === 0) throw new MnemocyteError("retrieval.weights must have an effective total greater than zero.", "CONFIG");
|
|
691
|
+
if (config.recencyHalfLifeDays !== void 0) assertPositiveFiniteConfigValue(config.recencyHalfLifeDays, "retrieval.recencyHalfLifeDays");
|
|
692
|
+
if (config.accessSaturation !== void 0) assertPositiveFiniteConfigValue(config.accessSaturation, "retrieval.accessSaturation");
|
|
693
|
+
if (config.candidateMultiplier !== void 0 && (!Number.isInteger(config.candidateMultiplier) || config.candidateMultiplier < 1)) throw new MnemocyteError("retrieval.candidateMultiplier must be an integer greater than or equal to 1.", "CONFIG");
|
|
694
|
+
}
|
|
695
|
+
function validateProviderResilienceConfig(config) {
|
|
696
|
+
if (config === void 0) return;
|
|
697
|
+
if (typeof config !== "object" || config === null || Array.isArray(config)) throw new MnemocyteError("provider must be an object.", "CONFIG");
|
|
698
|
+
for (const [field, value] of [
|
|
699
|
+
["provider.timeoutMs", config.timeoutMs],
|
|
700
|
+
["provider.baseDelayMs", config.baseDelayMs],
|
|
701
|
+
["provider.maxDelayMs", config.maxDelayMs]
|
|
702
|
+
]) if (value !== void 0 && (!Number.isFinite(value) || value < 0)) throw new MnemocyteError(`${field} must be a non-negative finite number.`, "CONFIG");
|
|
703
|
+
if (config.retries !== void 0 && (!Number.isInteger(config.retries) || config.retries < 0)) throw new MnemocyteError("provider.retries must be a non-negative integer.", "CONFIG");
|
|
704
|
+
if (config.shouldRetry !== void 0 && typeof config.shouldRetry !== "function") throw new MnemocyteError("provider.shouldRetry must be a function.", "CONFIG");
|
|
705
|
+
}
|
|
706
|
+
function validateBuildContextInput(input) {
|
|
707
|
+
if (input.maxTokens !== void 0 && (!Number.isInteger(input.maxTokens) || input.maxTokens < 1)) throw new MnemocyteError("maxTokens must be a positive integer when supplied.", "VALIDATION");
|
|
708
|
+
}
|
|
709
|
+
function validateRememberInput(input) {
|
|
710
|
+
assertNonEmptyString(input.entityId, "entityId");
|
|
711
|
+
assertNonEmptyString(input.content, "content");
|
|
712
|
+
if (input.type !== void 0) assertMemoryType(input.type, "type");
|
|
713
|
+
if (input.importance !== void 0) assertImportanceLevel(input.importance, "importance");
|
|
714
|
+
if (input.tags !== void 0) {
|
|
715
|
+
if (!Array.isArray(input.tags)) throw new MnemocyteError("tags must be an array.", "VALIDATION");
|
|
716
|
+
for (const tag of input.tags) if (typeof tag !== "string") throw new MnemocyteError("tags must contain only strings.", "VALIDATION");
|
|
717
|
+
}
|
|
718
|
+
if (input.source !== void 0 && typeof input.source !== "string") throw new MnemocyteError("source must be a string.", "VALIDATION");
|
|
719
|
+
if (input.confidence !== void 0 && (!Number.isFinite(input.confidence) || input.confidence < 0 || input.confidence > 1)) throw new MnemocyteError("confidence must be a number between 0 and 1.", "VALIDATION");
|
|
720
|
+
if (input.expiresAt !== void 0) assertValidDate(input.expiresAt, "expiresAt");
|
|
721
|
+
}
|
|
722
|
+
function validateRecallInput(input) {
|
|
723
|
+
assertNonEmptyString(input.entityId, "entityId");
|
|
724
|
+
assertNonEmptyString(input.query, "query");
|
|
725
|
+
if (input.limit !== void 0) assertLimit(input.limit);
|
|
726
|
+
if (input.minScore !== void 0) assertMinScore(input.minScore);
|
|
727
|
+
if (input.types !== void 0) assertMemoryTypeArray(input.types, "types");
|
|
728
|
+
}
|
|
729
|
+
function contextInputToRecallInput(input) {
|
|
730
|
+
return {
|
|
731
|
+
entityId: input.entityId,
|
|
732
|
+
query: input.query,
|
|
733
|
+
...input.limit === void 0 ? {} : { limit: input.limit },
|
|
734
|
+
...input.minScore === void 0 ? {} : { minScore: input.minScore },
|
|
735
|
+
...input.types === void 0 ? {} : { types: input.types },
|
|
736
|
+
...input.tags === void 0 ? {} : { tags: input.tags },
|
|
737
|
+
...input.includeSuperseded === void 0 ? {} : { includeSuperseded: input.includeSuperseded },
|
|
738
|
+
...input.includeExpired === void 0 ? {} : { includeExpired: input.includeExpired }
|
|
739
|
+
};
|
|
740
|
+
}
|
|
741
|
+
/**
|
|
742
|
+
* Validate and normalize a {@link PruneInput}. Throws a `"VALIDATION"`
|
|
743
|
+
* {@link MnemocyteError} for malformed fields or when normalization leaves no
|
|
744
|
+
* effective selector, preventing surprise full-table deletes.
|
|
745
|
+
*/
|
|
746
|
+
function validatePruneInput(input) {
|
|
747
|
+
if (input.entityId !== void 0) assertNonEmptyString(input.entityId, "entityId");
|
|
748
|
+
for (const [field, value] of [
|
|
749
|
+
["expired", input.expired],
|
|
750
|
+
["superseded", input.superseded],
|
|
751
|
+
["dryRun", input.dryRun]
|
|
752
|
+
]) if (value !== void 0 && typeof value !== "boolean") throw new MnemocyteError(`${field} must be a boolean.`, "VALIDATION");
|
|
753
|
+
for (const [field, value] of [["createdBefore", input.createdBefore], ["notAccessedSince", input.notAccessedSince]]) if (value !== void 0) assertValidDate(value, field);
|
|
754
|
+
let types;
|
|
755
|
+
if (input.types !== void 0) {
|
|
756
|
+
assertMemoryTypeArray(input.types, "types");
|
|
757
|
+
const normalized = new Set(input.types);
|
|
758
|
+
if (normalized.size > 0) types = [...normalized];
|
|
759
|
+
}
|
|
760
|
+
let tags;
|
|
761
|
+
if (input.tags !== void 0) {
|
|
762
|
+
if (!Array.isArray(input.tags)) throw new MnemocyteError("tags must be an array.", "VALIDATION");
|
|
763
|
+
const normalized = /* @__PURE__ */ new Set();
|
|
764
|
+
for (const value of input.tags) {
|
|
765
|
+
if (typeof value !== "string" || value.trim().length === 0) throw new MnemocyteError("tags must contain only non-empty strings.", "VALIDATION");
|
|
766
|
+
normalized.add(value.trim());
|
|
767
|
+
}
|
|
768
|
+
if (normalized.size > 0) tags = [...normalized];
|
|
769
|
+
}
|
|
770
|
+
if (input.maxImportance !== void 0) assertImportanceLevel(input.maxImportance, "maxImportance");
|
|
771
|
+
if (input.signal !== void 0 && (typeof input.signal !== "object" || input.signal === null || typeof input.signal.aborted !== "boolean" || typeof input.signal.addEventListener !== "function" || typeof input.signal.removeEventListener !== "function")) throw new MnemocyteError("signal must be an AbortSignal.", "VALIDATION");
|
|
772
|
+
const filter = {
|
|
773
|
+
...input.entityId === void 0 ? {} : { entityId: input.entityId },
|
|
774
|
+
...input.expired === true ? { expired: true } : {},
|
|
775
|
+
...input.superseded === true ? { superseded: true } : {},
|
|
776
|
+
...input.createdBefore === void 0 ? {} : { createdBefore: new Date(input.createdBefore) },
|
|
777
|
+
...input.notAccessedSince === void 0 ? {} : { notAccessedSince: new Date(input.notAccessedSince) },
|
|
778
|
+
...types === void 0 ? {} : { types },
|
|
779
|
+
...tags === void 0 ? {} : { tags },
|
|
780
|
+
...input.maxImportance === void 0 ? {} : { maxImportance: input.maxImportance },
|
|
781
|
+
dryRun: input.dryRun === true
|
|
782
|
+
};
|
|
783
|
+
assertPruneFilterHasSelector(filter);
|
|
784
|
+
return filter;
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Validate a {@link FindDuplicatesInput} and throw a `"VALIDATION"`
|
|
788
|
+
* {@link MnemocyteError} for malformed `threshold` / `limit` values.
|
|
789
|
+
*/
|
|
790
|
+
function validateFindDuplicatesInput(input) {
|
|
791
|
+
assertNonEmptyString(input.entityId, "entityId");
|
|
792
|
+
if (input.threshold !== void 0) {
|
|
793
|
+
if (!Number.isFinite(input.threshold) || input.threshold < 0 || input.threshold > 1) throw new MnemocyteError("threshold must be a number between 0 and 1.", "VALIDATION");
|
|
794
|
+
}
|
|
795
|
+
if (input.limit !== void 0) assertLimit(input.limit);
|
|
796
|
+
if (input.types !== void 0) assertMemoryTypeArray(input.types, "types");
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* Validate a {@link ConsolidateInput} and throw a `"VALIDATION"`
|
|
800
|
+
* {@link MnemocyteError} for malformed inputs (empty `supersededIds`
|
|
801
|
+
* a `survivorId` appearing in `supersededIds`, or duplicate loser IDs).
|
|
802
|
+
*/
|
|
803
|
+
function validateConsolidateInput(input) {
|
|
804
|
+
assertNonEmptyString(input.entityId, "entityId");
|
|
805
|
+
assertNonEmptyString(input.survivorId, "survivorId");
|
|
806
|
+
if (input.supersededIds.length === 0) throw new MnemocyteError("supersededIds must contain at least one memory id.", "VALIDATION");
|
|
807
|
+
if (input.supersededIds.includes(input.survivorId)) throw new MnemocyteError("survivorId must not appear in supersededIds.", "VALIDATION");
|
|
808
|
+
const seenIds = /* @__PURE__ */ new Set();
|
|
809
|
+
for (const id of input.supersededIds) {
|
|
810
|
+
assertNonEmptyString(id, "supersededIds[*]");
|
|
811
|
+
if (seenIds.has(id)) throw new MnemocyteError("supersededIds must not contain duplicate memory ids.", "VALIDATION");
|
|
812
|
+
seenIds.add(id);
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
/**
|
|
816
|
+
* Validate a {@link ListAuditLogInput} and throw a `"VALIDATION"`
|
|
817
|
+
* {@link MnemocyteError} when malformed.
|
|
818
|
+
*/
|
|
819
|
+
function validateListAuditLogInput(input) {
|
|
820
|
+
assertNonEmptyString(input.entityId, "entityId");
|
|
821
|
+
if (input.limit !== void 0) assertLimit(input.limit);
|
|
822
|
+
for (const [field, cursor] of [["beforeCursor", input.beforeCursor], ["afterCursor", input.afterCursor]]) {
|
|
823
|
+
if (cursor === void 0) continue;
|
|
824
|
+
assertAuditLogCursor(cursor, field);
|
|
825
|
+
}
|
|
826
|
+
}
|
|
827
|
+
function assertAuditLogCursor(value, field) {
|
|
828
|
+
if (typeof value !== "object" || value === null) throw new MnemocyteError(`${field} must be an audit-log cursor.`, "VALIDATION");
|
|
829
|
+
const cursor = value;
|
|
830
|
+
assertValidDate(cursor.timestamp, `${field}.timestamp`);
|
|
831
|
+
assertNonEmptyString(cursor.id, `${field}.id`);
|
|
832
|
+
}
|
|
833
|
+
//#endregion
|
|
834
|
+
//#region src/memory/client-core.ts
|
|
835
|
+
function isPositionalRememberManyInput(input) {
|
|
836
|
+
return Array.isArray(input);
|
|
837
|
+
}
|
|
838
|
+
function providerOptions(config, signal) {
|
|
839
|
+
return {
|
|
840
|
+
...signal === void 0 ? {} : { signal },
|
|
841
|
+
...config.provider === void 0 ? {} : { resilience: config.provider }
|
|
842
|
+
};
|
|
843
|
+
}
|
|
844
|
+
function storeOptions(signal) {
|
|
845
|
+
return signal === void 0 ? void 0 : { signal };
|
|
846
|
+
}
|
|
847
|
+
function snapshotRememberInput(input) {
|
|
848
|
+
return {
|
|
849
|
+
...input,
|
|
850
|
+
...input.tags === void 0 ? {} : { tags: Array.isArray(input.tags) ? [...input.tags] : input.tags },
|
|
851
|
+
metadata: cloneJsonObject(input.metadata ?? {}),
|
|
852
|
+
...input.expiresAt === void 0 ? {} : { expiresAt: input.expiresAt instanceof Date ? new Date(input.expiresAt) : input.expiresAt }
|
|
853
|
+
};
|
|
854
|
+
}
|
|
855
|
+
function createStoredMemory(config, input, embedding, now) {
|
|
856
|
+
return {
|
|
857
|
+
id: createId(),
|
|
858
|
+
entityId: input.entityId,
|
|
859
|
+
content: input.content,
|
|
860
|
+
type: input.type ?? "fact",
|
|
861
|
+
importance: input.importance ?? "normal",
|
|
862
|
+
tags: normalizeTags(input.tags),
|
|
863
|
+
source: input.source ?? null,
|
|
864
|
+
metadata: input.metadata,
|
|
865
|
+
confidence: input.confidence ?? 1,
|
|
866
|
+
embeddingModel: config.embedder.model,
|
|
867
|
+
embeddingDimensions: config.embedder.dimensions,
|
|
868
|
+
supersededBy: null,
|
|
869
|
+
supersededAt: null,
|
|
870
|
+
expiresAt: input.expiresAt ?? null,
|
|
871
|
+
lastAccessedAt: null,
|
|
872
|
+
accessCount: 0,
|
|
873
|
+
createdAt: now,
|
|
874
|
+
updatedAt: now,
|
|
875
|
+
embedding
|
|
876
|
+
};
|
|
877
|
+
}
|
|
878
|
+
function auditEvent(entityId, description, metadata, timestamp = /* @__PURE__ */ new Date()) {
|
|
879
|
+
return {
|
|
880
|
+
id: createEventId(),
|
|
881
|
+
entityId,
|
|
882
|
+
description,
|
|
883
|
+
metadata,
|
|
884
|
+
timestamp
|
|
885
|
+
};
|
|
886
|
+
}
|
|
887
|
+
function normalizeStoreRows(expected, returned, operation) {
|
|
888
|
+
const expectedIds = new Set(expected.map((memory) => memory.id));
|
|
889
|
+
const returnedById = /* @__PURE__ */ new Map();
|
|
890
|
+
for (const row of returned) {
|
|
891
|
+
if (!expectedIds.has(row.id)) throw new MnemocyteError(`${operation} returned an unknown ID.`, "DB");
|
|
892
|
+
if (returnedById.has(row.id)) throw new MnemocyteError(`${operation} returned a duplicate ID.`, "DB");
|
|
893
|
+
returnedById.set(row.id, row);
|
|
894
|
+
}
|
|
895
|
+
return expected.map((row) => {
|
|
896
|
+
const returnedRow = returnedById.get(row.id);
|
|
897
|
+
if (!returnedRow) throw new MnemocyteError(`${operation} did not return every requested ID.`, "DB");
|
|
898
|
+
return returnedRow;
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
function normalizePruneEntityDeletions(result, expectedEntityId) {
|
|
902
|
+
const seenEntityIds = /* @__PURE__ */ new Set();
|
|
903
|
+
let detailedDeletedCount = 0;
|
|
904
|
+
for (const detail of result.deletedByEntity) {
|
|
905
|
+
if (detail.entityId.length === 0 || !Number.isInteger(detail.deletedCount) || detail.deletedCount <= 0 || seenEntityIds.has(detail.entityId) || expectedEntityId !== void 0 && detail.entityId !== expectedEntityId) throw new MnemocyteError("Memory prune returned invalid per-entity deletion details.", "DB");
|
|
906
|
+
seenEntityIds.add(detail.entityId);
|
|
907
|
+
detailedDeletedCount += detail.deletedCount;
|
|
908
|
+
}
|
|
909
|
+
if (detailedDeletedCount !== result.deletedCount || result.dryRun && result.deletedByEntity.length > 0) throw new MnemocyteError("Memory prune deletion details did not match the deleted count.", "DB");
|
|
910
|
+
return [...result.deletedByEntity].sort((a, b) => a.entityId.localeCompare(b.entityId));
|
|
911
|
+
}
|
|
912
|
+
function toDuplicatePair(pair) {
|
|
913
|
+
return {
|
|
914
|
+
a: cloneMemory(pair.a),
|
|
915
|
+
b: cloneMemory(pair.b),
|
|
916
|
+
similarity: Math.max(0, Math.min(1, pair.similarity))
|
|
917
|
+
};
|
|
918
|
+
}
|
|
919
|
+
function createMemoryClient(config, store) {
|
|
920
|
+
let state = "open";
|
|
921
|
+
let activeOperations = 0;
|
|
922
|
+
let operationsDrainedPromise;
|
|
923
|
+
let resolveOperationsDrained;
|
|
924
|
+
let closePromise;
|
|
925
|
+
function assertOpen() {
|
|
926
|
+
if (state === "closed") throw new MnemocyteError("Mnemocyte client is closed.", "DB");
|
|
927
|
+
}
|
|
928
|
+
function beginOperation() {
|
|
929
|
+
if (state !== "open") throw new MnemocyteError("Mnemocyte client is closed.", "DB");
|
|
930
|
+
activeOperations += 1;
|
|
931
|
+
let completed = false;
|
|
932
|
+
return () => {
|
|
933
|
+
if (completed) return;
|
|
934
|
+
completed = true;
|
|
935
|
+
activeOperations -= 1;
|
|
936
|
+
if (activeOperations === 0 && resolveOperationsDrained) {
|
|
937
|
+
const resolve = resolveOperationsDrained;
|
|
938
|
+
resolveOperationsDrained = void 0;
|
|
939
|
+
operationsDrainedPromise = void 0;
|
|
940
|
+
resolve();
|
|
941
|
+
}
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
function runOperation(operationName, metadata, operation) {
|
|
945
|
+
let complete;
|
|
946
|
+
try {
|
|
947
|
+
complete = beginOperation();
|
|
948
|
+
} catch (error) {
|
|
949
|
+
return observe(config, store.backend, operationName, metadata, async () => {
|
|
950
|
+
throw error;
|
|
951
|
+
});
|
|
952
|
+
}
|
|
953
|
+
try {
|
|
954
|
+
return operation().then((result) => {
|
|
955
|
+
complete();
|
|
956
|
+
return result;
|
|
957
|
+
}, (error) => {
|
|
958
|
+
complete();
|
|
959
|
+
throw error;
|
|
960
|
+
});
|
|
961
|
+
} catch (error) {
|
|
962
|
+
complete();
|
|
963
|
+
return Promise.reject(error);
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
function waitForActiveOperations() {
|
|
967
|
+
if (activeOperations === 0) return Promise.resolve();
|
|
968
|
+
if (!operationsDrainedPromise) operationsDrainedPromise = new Promise((resolve) => {
|
|
969
|
+
resolveOperationsDrained = resolve;
|
|
970
|
+
});
|
|
971
|
+
return operationsDrainedPromise;
|
|
972
|
+
}
|
|
973
|
+
async function ensureSchema() {
|
|
974
|
+
await store.ensureSchema();
|
|
975
|
+
}
|
|
976
|
+
async function ensureEmbeddingCompatibility() {
|
|
977
|
+
await store.ensureEmbeddingCompatibility(config.embedder);
|
|
978
|
+
}
|
|
979
|
+
async function recordAudit(events) {
|
|
980
|
+
if (events.length === 0 || config.audit?.enabled !== true) return;
|
|
981
|
+
try {
|
|
982
|
+
await store.addAuditEvents(events);
|
|
983
|
+
} catch {}
|
|
984
|
+
}
|
|
985
|
+
function remember(input) {
|
|
986
|
+
return runOperation("remember", { entityId: input.entityId }, () => observePrepared(config, store.backend, "remember", { entityId: input.entityId }, () => snapshotRememberInput(input), async (preparedInput) => {
|
|
987
|
+
assertOpen();
|
|
988
|
+
validateRememberInput(preparedInput);
|
|
989
|
+
await ensureEmbeddingCompatibility();
|
|
990
|
+
const stored = [createStoredMemory(config, preparedInput, await embedOne(config.embedder, preparedInput.content, providerOptions(config, preparedInput.signal)), /* @__PURE__ */ new Date())];
|
|
991
|
+
const [memory] = normalizeStoreRows(stored, await store.insertMemories(stored), "Memory insert");
|
|
992
|
+
if (!memory) throw new MnemocyteError("Memory insert did not return the inserted ID.", "DB");
|
|
993
|
+
await recordAudit([auditEvent(memory.entityId, "memory.created", {
|
|
994
|
+
memoryId: memory.id,
|
|
995
|
+
type: memory.type,
|
|
996
|
+
importance: memory.importance
|
|
997
|
+
})]);
|
|
998
|
+
return memory;
|
|
999
|
+
}, (memory) => ({
|
|
1000
|
+
memoryId: memory.id,
|
|
1001
|
+
count: 1
|
|
1002
|
+
})));
|
|
1003
|
+
}
|
|
1004
|
+
function rememberMany(input) {
|
|
1005
|
+
const count = isPositionalRememberManyInput(input) ? input.length : input.inputs.length;
|
|
1006
|
+
return runOperation("rememberMany", { count }, () => observePrepared(config, store.backend, "rememberMany", { count }, () => {
|
|
1007
|
+
const positional = isPositionalRememberManyInput(input);
|
|
1008
|
+
return {
|
|
1009
|
+
preparedInputs: (positional ? input : input.inputs).map(snapshotRememberInput),
|
|
1010
|
+
signal: positional ? input[0]?.signal : input.signal
|
|
1011
|
+
};
|
|
1012
|
+
}, async ({ preparedInputs, signal }) => {
|
|
1013
|
+
assertOpen();
|
|
1014
|
+
if (preparedInputs.length === 0) return [];
|
|
1015
|
+
for (const item of preparedInputs) validateRememberInput(item);
|
|
1016
|
+
await ensureEmbeddingCompatibility();
|
|
1017
|
+
const embeddings = await embedMany(config.embedder, preparedInputs.map((item) => item.content), providerOptions(config, signal));
|
|
1018
|
+
const now = /* @__PURE__ */ new Date();
|
|
1019
|
+
const stored = preparedInputs.map((item, idx) => createStoredMemory(config, item, embeddings[idx], now));
|
|
1020
|
+
const memories = normalizeStoreRows(stored, await store.insertMemories(stored), "Memory insert");
|
|
1021
|
+
await recordAudit(memories.map((memory) => auditEvent(memory.entityId, "memory.created", {
|
|
1022
|
+
memoryId: memory.id,
|
|
1023
|
+
type: memory.type,
|
|
1024
|
+
importance: memory.importance
|
|
1025
|
+
})));
|
|
1026
|
+
return memories;
|
|
1027
|
+
}, (result) => ({ count: result.length })));
|
|
1028
|
+
}
|
|
1029
|
+
function recall(input) {
|
|
1030
|
+
return observe(config, store.backend, "recall", { entityId: input.entityId }, async () => {
|
|
1031
|
+
assertOpen();
|
|
1032
|
+
validateRecallInput(input);
|
|
1033
|
+
const limit = input.limit ?? config.defaults?.limit ?? 10;
|
|
1034
|
+
const minScore = input.minScore ?? config.defaults?.minScore ?? 0;
|
|
1035
|
+
assertLimit(limit);
|
|
1036
|
+
assertMinScore(minScore);
|
|
1037
|
+
await ensureEmbeddingCompatibility();
|
|
1038
|
+
const queryEmbedding = await embedOne(config.embedder, input.query, providerOptions(config, input.signal));
|
|
1039
|
+
const candidateMultiplier = config.retrieval?.candidateMultiplier ?? 3;
|
|
1040
|
+
const candidateLimit = Math.max(limit, limit * candidateMultiplier);
|
|
1041
|
+
const scoreLexical = createLexicalScorer(input.query);
|
|
1042
|
+
const scoringConfig = createScoringConfig(config.retrieval);
|
|
1043
|
+
const [vectorCandidates, lexicalCandidates] = await Promise.all([store.vectorSearch({
|
|
1044
|
+
...input,
|
|
1045
|
+
embedding: queryEmbedding,
|
|
1046
|
+
limit: candidateLimit,
|
|
1047
|
+
minVectorScore: 0
|
|
1048
|
+
}), store.lexicalSearch({
|
|
1049
|
+
...input,
|
|
1050
|
+
limit: candidateLimit
|
|
1051
|
+
})]);
|
|
1052
|
+
const merged = /* @__PURE__ */ new Map();
|
|
1053
|
+
for (const candidate of vectorCandidates) merged.set(candidate.memory.id, {
|
|
1054
|
+
memory: candidate.memory,
|
|
1055
|
+
vectorScore: candidate.vectorScore,
|
|
1056
|
+
lexicalScore: scoreLexical(candidate.memory.content)
|
|
1057
|
+
});
|
|
1058
|
+
const lexicalOnly = lexicalCandidates.filter((candidate) => !merged.has(candidate.memory.id));
|
|
1059
|
+
const lexicalOnlyEmbeddings = await store.getMemoryEmbeddings(lexicalOnly.map((candidate) => candidate.memory.id));
|
|
1060
|
+
for (const candidate of lexicalCandidates) {
|
|
1061
|
+
const existing = merged.get(candidate.memory.id);
|
|
1062
|
+
if (existing) {
|
|
1063
|
+
existing.lexicalScore = candidate.lexicalScore;
|
|
1064
|
+
continue;
|
|
1065
|
+
}
|
|
1066
|
+
const embedding = lexicalOnlyEmbeddings.get(candidate.memory.id);
|
|
1067
|
+
const similarity = embedding ? cosineSimilarity(embedding, queryEmbedding) : 0;
|
|
1068
|
+
merged.set(candidate.memory.id, {
|
|
1069
|
+
memory: candidate.memory,
|
|
1070
|
+
vectorScore: toVectorScore(similarity),
|
|
1071
|
+
lexicalScore: candidate.lexicalScore
|
|
1072
|
+
});
|
|
1073
|
+
}
|
|
1074
|
+
const scored = Array.from(merged.values()).map((entry) => toScoredMemoryWithConfig(entry.memory, Math.max(0, entry.vectorScore), Math.max(0, entry.lexicalScore), input, scoringConfig)).filter((memory) => memory.score >= minScore).sort((a, b) => b.score - a.score).slice(0, limit);
|
|
1075
|
+
const accessUpdates = normalizeStoreRows(scored, await store.markMemoriesAccessed(scored.map((memory) => memory.id)), "Memory access update");
|
|
1076
|
+
return scored.map((memory, index) => {
|
|
1077
|
+
const update = accessUpdates[index];
|
|
1078
|
+
if (!update) throw new MnemocyteError("Memory access update did not return every requested ID.", "DB");
|
|
1079
|
+
return {
|
|
1080
|
+
...memory,
|
|
1081
|
+
lastAccessedAt: new Date(update.lastAccessedAt),
|
|
1082
|
+
accessCount: update.accessCount,
|
|
1083
|
+
updatedAt: new Date(update.updatedAt)
|
|
1084
|
+
};
|
|
1085
|
+
});
|
|
1086
|
+
}, (result) => ({ count: result.length }));
|
|
1087
|
+
}
|
|
1088
|
+
return {
|
|
1089
|
+
remember,
|
|
1090
|
+
rememberMany,
|
|
1091
|
+
recall(input) {
|
|
1092
|
+
return runOperation("recall", { entityId: input.entityId }, () => recall(input));
|
|
1093
|
+
},
|
|
1094
|
+
buildContext(input) {
|
|
1095
|
+
return runOperation("buildContext", { entityId: input.entityId }, () => observe(config, store.backend, "buildContext", { entityId: input.entityId }, async () => {
|
|
1096
|
+
assertOpen();
|
|
1097
|
+
validateBuildContextInput(input);
|
|
1098
|
+
return buildContext({
|
|
1099
|
+
input,
|
|
1100
|
+
recall: (contextInput) => {
|
|
1101
|
+
const recallInput = contextInputToRecallInput(contextInput);
|
|
1102
|
+
return recall(input.signal === void 0 ? recallInput : {
|
|
1103
|
+
...recallInput,
|
|
1104
|
+
signal: input.signal
|
|
1105
|
+
});
|
|
1106
|
+
}
|
|
1107
|
+
});
|
|
1108
|
+
}));
|
|
1109
|
+
},
|
|
1110
|
+
forget(input) {
|
|
1111
|
+
return runOperation("forget", {
|
|
1112
|
+
entityId: input.entityId,
|
|
1113
|
+
memoryId: input.memoryId
|
|
1114
|
+
}, () => observe(config, store.backend, "forget", {
|
|
1115
|
+
entityId: input.entityId,
|
|
1116
|
+
memoryId: input.memoryId
|
|
1117
|
+
}, async () => {
|
|
1118
|
+
assertOpen();
|
|
1119
|
+
assertNonEmptyString(input.entityId, "entityId");
|
|
1120
|
+
assertNonEmptyString(input.memoryId, "memoryId");
|
|
1121
|
+
await ensureSchema();
|
|
1122
|
+
if (!await store.deleteMemory(input.entityId, input.memoryId)) throw new MnemocyteError("Memory was not found.", "NOT_FOUND");
|
|
1123
|
+
await recordAudit([auditEvent(input.entityId, "memory.deleted", { memoryId: input.memoryId })]);
|
|
1124
|
+
}));
|
|
1125
|
+
},
|
|
1126
|
+
forgetAll(input) {
|
|
1127
|
+
return runOperation("forgetAll", { entityId: input.entityId }, () => observe(config, store.backend, "forgetAll", { entityId: input.entityId }, async () => {
|
|
1128
|
+
assertOpen();
|
|
1129
|
+
assertNonEmptyString(input.entityId, "entityId");
|
|
1130
|
+
await ensureSchema();
|
|
1131
|
+
const deletedCount = await store.deleteMemoriesForEntity(input.entityId);
|
|
1132
|
+
await recordAudit([auditEvent(input.entityId, "entity.cleared", { count: deletedCount })]);
|
|
1133
|
+
return deletedCount;
|
|
1134
|
+
}, (count) => ({ count })).then(() => void 0));
|
|
1135
|
+
},
|
|
1136
|
+
prune(input) {
|
|
1137
|
+
return runOperation("prune", input.entityId === void 0 ? {} : { entityId: input.entityId }, () => observe(config, store.backend, "prune", input.entityId === void 0 ? {} : { entityId: input.entityId }, async () => {
|
|
1138
|
+
assertOpen();
|
|
1139
|
+
throwIfAborted(input.signal);
|
|
1140
|
+
const filter = validatePruneInput(input);
|
|
1141
|
+
await ensureSchema();
|
|
1142
|
+
const result = await store.prune(filter, storeOptions(input.signal));
|
|
1143
|
+
const deletedByEntity = normalizePruneEntityDeletions(result, input.entityId);
|
|
1144
|
+
if (result.deletedCount > 0 && result.dryRun === false) await recordAudit(deletedByEntity.map((detail) => auditEvent(detail.entityId, "memory.pruned", { count: detail.deletedCount })));
|
|
1145
|
+
return {
|
|
1146
|
+
matchedCount: result.matchedCount,
|
|
1147
|
+
deletedCount: result.deletedCount,
|
|
1148
|
+
dryRun: result.dryRun
|
|
1149
|
+
};
|
|
1150
|
+
}, (result) => ({ count: result.deletedCount })));
|
|
1151
|
+
},
|
|
1152
|
+
findDuplicates(input) {
|
|
1153
|
+
return runOperation("findDuplicates", { entityId: input.entityId }, () => observe(config, store.backend, "findDuplicates", { entityId: input.entityId }, async () => {
|
|
1154
|
+
assertOpen();
|
|
1155
|
+
throwIfAborted(input.signal);
|
|
1156
|
+
validateFindDuplicatesInput(input);
|
|
1157
|
+
await ensureEmbeddingCompatibility();
|
|
1158
|
+
return (await store.findDuplicatePairs(input, storeOptions(input.signal))).map(toDuplicatePair);
|
|
1159
|
+
}, (result) => ({ count: result.length })));
|
|
1160
|
+
},
|
|
1161
|
+
listAuditLog(input) {
|
|
1162
|
+
return runOperation("listAuditLog", { entityId: input.entityId }, () => observe(config, store.backend, "listAuditLog", { entityId: input.entityId }, async () => {
|
|
1163
|
+
assertOpen();
|
|
1164
|
+
throwIfAborted(input.signal);
|
|
1165
|
+
validateListAuditLogInput(input);
|
|
1166
|
+
await ensureSchema();
|
|
1167
|
+
return await store.listAuditLog(input, storeOptions(input.signal));
|
|
1168
|
+
}, (result) => ({ count: result.length })));
|
|
1169
|
+
},
|
|
1170
|
+
stats(input) {
|
|
1171
|
+
return runOperation("stats", input?.entityId ? { entityId: input.entityId } : {}, () => observe(config, store.backend, "stats", input?.entityId ? { entityId: input.entityId } : {}, async () => {
|
|
1172
|
+
assertOpen();
|
|
1173
|
+
await ensureSchema();
|
|
1174
|
+
return store.stats(input, /* @__PURE__ */ new Date());
|
|
1175
|
+
}));
|
|
1176
|
+
},
|
|
1177
|
+
experimental: { consolidate(input) {
|
|
1178
|
+
return runOperation("consolidate", {
|
|
1179
|
+
entityId: input.entityId,
|
|
1180
|
+
memoryId: input.survivorId
|
|
1181
|
+
}, () => observe(config, store.backend, "consolidate", {
|
|
1182
|
+
entityId: input.entityId,
|
|
1183
|
+
memoryId: input.survivorId
|
|
1184
|
+
}, async () => {
|
|
1185
|
+
assertOpen();
|
|
1186
|
+
throwIfAborted(input.signal);
|
|
1187
|
+
validateConsolidateInput(input);
|
|
1188
|
+
await ensureSchema();
|
|
1189
|
+
const survivor = await store.getMemory(input.entityId, input.survivorId, storeOptions(input.signal));
|
|
1190
|
+
throwIfAborted(input.signal);
|
|
1191
|
+
if (!survivor) throw new MnemocyteError("Survivor memory was not found.", "NOT_FOUND");
|
|
1192
|
+
if (survivor.supersededBy !== null) throw new MnemocyteError("Survivor memory is itself superseded.", "VALIDATION");
|
|
1193
|
+
const targets = await store.loadConsolidationTargets(input.entityId, input.supersededIds, storeOptions(input.signal));
|
|
1194
|
+
throwIfAborted(input.signal);
|
|
1195
|
+
const foundIds = new Set(targets.map((target) => target.id));
|
|
1196
|
+
for (const id of input.supersededIds) if (!foundIds.has(id)) throw new MnemocyteError("Superseded memory was not found.", "NOT_FOUND");
|
|
1197
|
+
if (targets.some((target) => target.supersededBy !== null && target.supersededBy !== survivor.id)) throw new MnemocyteError("Superseded memory already belongs to a different survivor.", "CONFLICT");
|
|
1198
|
+
if (targets.filter((target) => target.supersededBy === null).length === 0) return {
|
|
1199
|
+
survivorId: survivor.id,
|
|
1200
|
+
supersededCount: 0,
|
|
1201
|
+
supersededIds: []
|
|
1202
|
+
};
|
|
1203
|
+
const result = await store.consolidate({
|
|
1204
|
+
entityId: input.entityId,
|
|
1205
|
+
survivorId: survivor.id,
|
|
1206
|
+
supersededIds: input.supersededIds,
|
|
1207
|
+
mergeTags: input.mergeTags !== false,
|
|
1208
|
+
now: /* @__PURE__ */ new Date(),
|
|
1209
|
+
auditEnabled: config.audit?.enabled === true
|
|
1210
|
+
}, storeOptions(input.signal));
|
|
1211
|
+
return {
|
|
1212
|
+
survivorId: survivor.id,
|
|
1213
|
+
supersededCount: result.supersededIds.length,
|
|
1214
|
+
supersededIds: result.supersededIds
|
|
1215
|
+
};
|
|
1216
|
+
}, (result) => ({ count: result.supersededCount })));
|
|
1217
|
+
} },
|
|
1218
|
+
close() {
|
|
1219
|
+
if (closePromise) return closePromise;
|
|
1220
|
+
state = "closing";
|
|
1221
|
+
closePromise = observe(config, store.backend, "close", {}, async () => {
|
|
1222
|
+
await waitForActiveOperations();
|
|
1223
|
+
try {
|
|
1224
|
+
await store.close();
|
|
1225
|
+
state = "closed";
|
|
1226
|
+
} catch (error) {
|
|
1227
|
+
state = "open";
|
|
1228
|
+
closePromise = void 0;
|
|
1229
|
+
throw error;
|
|
1230
|
+
}
|
|
1231
|
+
});
|
|
1232
|
+
return closePromise;
|
|
1233
|
+
}
|
|
1234
|
+
};
|
|
1235
|
+
}
|
|
1236
|
+
//#endregion
|
|
1237
|
+
//#region src/memory/deletion.ts
|
|
1238
|
+
function memoryHasDependentsError(cause) {
|
|
1239
|
+
return new MnemocyteError("Memory cannot be deleted while other memories reference it as their consolidation survivor.", "CONFLICT", cause);
|
|
1240
|
+
}
|
|
1241
|
+
//#endregion
|
|
1242
|
+
//#region src/memory/store-config.ts
|
|
1243
|
+
const MEMORY_STORE_CONFIG = Symbol.for("mnemocyte.memory-store-config");
|
|
1244
|
+
function createMnemocyteStoreConfig(store) {
|
|
1245
|
+
return Object.freeze({ [MEMORY_STORE_CONFIG]: store });
|
|
1246
|
+
}
|
|
1247
|
+
function unwrapMnemocyteStoreConfig(config) {
|
|
1248
|
+
const candidate = config;
|
|
1249
|
+
if (typeof candidate !== "object" || candidate === null || !(MEMORY_STORE_CONFIG in candidate)) throw new MnemocyteError("store must be created by a supported Mnemocyte store adapter.", "CONFIG");
|
|
1250
|
+
return candidate[MEMORY_STORE_CONFIG];
|
|
1251
|
+
}
|
|
1252
|
+
//#endregion
|
|
1253
|
+
export { cloneJsonObject as _, assertEmbedder as a, validateRetrievalConfig as c, IMPORTANCE_RANK as d, cosineSimilarity as f, createEventId as g, cloneMemory as h, createMemoryClient as i, assertPruneFilterHasSelector as l, toVectorScore as m, unwrapMnemocyteStoreConfig as n, assertNonEmptyString as o, createLexicalScorer as p, memoryHasDependentsError as r, validateProviderResilienceConfig as s, createMnemocyteStoreConfig as t, DEFAULT_DUPLICATE_THRESHOLD as u, throwIfAborted as v, parsePostgresDatabaseUrl as y };
|
|
1254
|
+
|
|
1255
|
+
//# sourceMappingURL=store-config-BFFTm1sj.mjs.map
|