@alineo-labs/memory 0.2.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/dist/index.mjs ADDED
@@ -0,0 +1,771 @@
1
+ import { WorkflowError } from "@alineo-labs/core";
2
+ //#region src/types.ts
3
+ /**
4
+ * Composite key every in-memory reference provider in this package scopes its storage by.
5
+ *
6
+ * Each part is escaped (`\` → `\\`, `:` → `\:`) before joining — without this, an untenanted
7
+ * caller passing `resourceId: "acme:corp"` would produce the exact same string as a tenanted
8
+ * caller passing `{teamId: "acme", resourceId: "corp"}`, silently colliding two different
9
+ * callers' storage onto one key. On a backend keyed solely by this string (in-memory,
10
+ * `@alineo-labs/sqlite-memory`), combined with `access-control.ts`'s `assertAccess()` skipping
11
+ * its check entirely for a `ref` with no `teamId`, an unescaped join made that a real
12
+ * cross-tenant read/write, not just a naming curiosity.
13
+ */
14
+ function scopeKey(ref) {
15
+ const escape = (part) => part.replace(/\\/g, "\\\\").replace(/:/g, "\\:");
16
+ return ref.teamId ? `${escape(ref.teamId)}:${escape(ref.resourceId)}` : escape(ref.resourceId);
17
+ }
18
+ //#endregion
19
+ //#region src/errors.ts
20
+ /**
21
+ * Thrown when a `Memory` method is called for a capability (e.g. semantic recall) that this
22
+ * instance was never given a provider for. Deliberately loud — matching `errors.ts`'s existing
23
+ * convention of distinguishable error classes (`CommandError`, `SandboxError`) callers can
24
+ * catch specifically — rather than a silent no-op or an empty result set that looks
25
+ * indistinguishable from "no facts matched."
26
+ */
27
+ var MemoryCapabilityError = class extends WorkflowError {
28
+ capability;
29
+ constructor(capability) {
30
+ super(`No ${capability} memory provider configured on this Memory instance.`);
31
+ this.capability = capability;
32
+ this.name = "MemoryCapabilityError";
33
+ }
34
+ };
35
+ //#endregion
36
+ //#region src/working.ts
37
+ /**
38
+ * Reference implementation — a process-local `Map`. Not durable across restarts, not shared
39
+ * across processes or hosts. Exists to prove `IWorkingMemoryProvider` composes with `Memory`,
40
+ * to give unit tests something to run against without a real database, and to give a first
41
+ * consumer something to hold before a real backend package (Postgres, SQLite, ...) exists.
42
+ * Not a production recommendation — the same relationship `InMemoryStore` has to LangGraph's
43
+ * real backends.
44
+ */
45
+ var InMemoryWorkingMemoryProvider = class {
46
+ buckets = /* @__PURE__ */ new Map();
47
+ bucketFor(ref) {
48
+ const key = scopeKey(ref);
49
+ let bucket = this.buckets.get(key);
50
+ if (!bucket) {
51
+ bucket = /* @__PURE__ */ new Map();
52
+ this.buckets.set(key, bucket);
53
+ }
54
+ return bucket;
55
+ }
56
+ async get(ref, key) {
57
+ return this.buckets.get(scopeKey(ref))?.get(key);
58
+ }
59
+ async set(ref, key, value) {
60
+ this.bucketFor(ref).set(key, value);
61
+ }
62
+ async list(ref) {
63
+ const bucket = this.buckets.get(scopeKey(ref));
64
+ return bucket ? Object.fromEntries(bucket) : {};
65
+ }
66
+ async delete(ref, key) {
67
+ this.buckets.get(scopeKey(ref))?.delete(key);
68
+ }
69
+ };
70
+ //#endregion
71
+ //#region src/semantic.ts
72
+ /** True if `provider` implements the optional pruning capability. */
73
+ function isPrunable(provider) {
74
+ return typeof provider.listAll === "function" && typeof provider.forget === "function";
75
+ }
76
+ /** True if `provider` implements the optional bulk-remember capability. */
77
+ function isBulkRememberable(provider) {
78
+ return typeof provider.rememberMany === "function";
79
+ }
80
+ /** Shared row→fact mapping for any backend storing facts in the shape above — exported so
81
+ * `@alineo-labs/sqlite-memory` and `@alineo-labs/postgres-memory` don't each hand-roll the
82
+ * same conversion (including the `verified` derivation) with their own copy of this logic. */
83
+ function factFromRow(row) {
84
+ return {
85
+ content: row.content,
86
+ sourceRef: row.source_sandbox_id != null ? {
87
+ sandboxId: row.source_sandbox_id,
88
+ entryIndex: row.source_entry_index
89
+ } : void 0,
90
+ verified: row.source_sandbox_id != null,
91
+ id: row.id,
92
+ rememberedAt: row.remembered_at
93
+ };
94
+ }
95
+ /** Shared ranking primitive for any backend doing its own naive (non-indexed) vector scan —
96
+ * exported so real backends (`@alineo-labs/sqlite-memory`, `@alineo-labs/postgres-memory`)
97
+ * don't each reimplement it. A backend with a real vector index (pgvector, sqlite-vec) should
98
+ * rank in SQL instead and never needs this. */
99
+ function cosineSimilarity(a, b) {
100
+ let dot = 0;
101
+ let normA = 0;
102
+ let normB = 0;
103
+ for (let i = 0; i < a.length; i++) {
104
+ dot += a[i] * b[i];
105
+ normA += a[i] * a[i];
106
+ normB += b[i] * b[i];
107
+ }
108
+ if (normA === 0 || normB === 0) return 0;
109
+ return dot / (Math.sqrt(normA) * Math.sqrt(normB));
110
+ }
111
+ /**
112
+ * Reference implementation — an array per resource, ranked by naive cosine similarity over
113
+ * whatever `EmbeddingProvider` is passed in. Same purpose as `InMemoryWorkingMemoryProvider`:
114
+ * proves the interface composes end to end, gives tests something real to run against, not a
115
+ * production recommendation (no persistence, no approximate-nearest-neighbor indexing —
116
+ * O(n) scan per `recall()`).
117
+ */
118
+ var InMemorySemanticMemoryProvider = class {
119
+ embeddings;
120
+ entries = /* @__PURE__ */ new Map();
121
+ constructor(embeddings) {
122
+ this.embeddings = embeddings;
123
+ }
124
+ /** Batches the embedding call for all `facts` into one `embed()` invocation — see
125
+ * `IBulkSemanticMemoryProvider`. */
126
+ async rememberMany(ref, facts) {
127
+ if (facts.length === 0) return;
128
+ const vectors = await this.embeddings.embed(facts.map((f) => f.content), { type: "passage" });
129
+ const key = scopeKey(ref);
130
+ const bucket = this.entries.get(key) ?? [];
131
+ const now = Date.now();
132
+ for (let i = 0; i < facts.length; i++) {
133
+ const vector = vectors[i];
134
+ const fact = facts[i];
135
+ if (!vector) continue;
136
+ bucket.push({
137
+ fact: {
138
+ content: fact.content,
139
+ sourceRef: fact.sourceRef,
140
+ verified: fact.sourceRef != null,
141
+ id: crypto.randomUUID(),
142
+ rememberedAt: now
143
+ },
144
+ vector
145
+ });
146
+ }
147
+ this.entries.set(key, bucket);
148
+ }
149
+ async remember(ref, fact) {
150
+ const [vector] = await this.embeddings.embed([fact.content], { type: "passage" });
151
+ if (!vector) return;
152
+ const key = scopeKey(ref);
153
+ const bucket = this.entries.get(key) ?? [];
154
+ bucket.push({
155
+ fact: {
156
+ content: fact.content,
157
+ sourceRef: fact.sourceRef,
158
+ verified: fact.sourceRef != null,
159
+ id: crypto.randomUUID(),
160
+ rememberedAt: Date.now()
161
+ },
162
+ vector
163
+ });
164
+ this.entries.set(key, bucket);
165
+ }
166
+ async recall(ref, query, opts = {}) {
167
+ const bucket = this.entries.get(scopeKey(ref));
168
+ if (!bucket || bucket.length === 0) return [];
169
+ const [queryVector] = await this.embeddings.embed([query], { type: "query" });
170
+ if (!queryVector) return [];
171
+ const topK = opts.topK ?? 5;
172
+ return bucket.map((entry) => ({
173
+ fact: entry.fact,
174
+ score: cosineSimilarity(queryVector, entry.vector)
175
+ })).sort((a, b) => b.score - a.score).slice(0, topK).map((ranked) => ranked.fact);
176
+ }
177
+ async listAll(ref) {
178
+ return (this.entries.get(scopeKey(ref)) ?? []).map((entry) => entry.fact);
179
+ }
180
+ async forget(ref, ids) {
181
+ const key = scopeKey(ref);
182
+ const bucket = this.entries.get(key);
183
+ if (!bucket) return 0;
184
+ const idSet = new Set(ids);
185
+ const kept = bucket.filter((entry) => !idSet.has(entry.fact.id));
186
+ const removed = bucket.length - kept.length;
187
+ this.entries.set(key, kept);
188
+ return removed;
189
+ }
190
+ };
191
+ //#endregion
192
+ //#region src/episodic.ts
193
+ /** The default session resolver — exported so `episodicTree()` (a separate module) can reuse
194
+ * it as its own default without duplicating the resourceId/name-fallback matching logic.
195
+ *
196
+ * Also enforces `ref.teamId`, not just `ref.resourceId` — the ledger has no team concept of
197
+ * its own, so without this, two different teams' sessions sharing a `resourceId` (plausible:
198
+ * `Alineo.resourceRef` defaults `resourceId` to the agent's own name) would have their ledger
199
+ * histories silently merged, with zero access-control check. Match is strict equality
200
+ * (`d.teamId === ref.teamId`), including the both-undefined case for an untenanted caller —
201
+ * deliberately not treating a session with no recorded `teamId` as "visible to any team," the
202
+ * way row-level security elsewhere in this package treats `team_id IS NULL`. That's a
203
+ * conservative choice, not an oversight: a session written before `SandboxOptions.teamId`
204
+ * existed (or by a caller that never set it) becomes invisible to a team-scoped caller rather
205
+ * than risking it actually belonging to a different team. */
206
+ async function resolveSessionsByResourceId(adapter, ref) {
207
+ return (await adapter.listAllSandboxDetails()).filter((d) => (d.resourceId === ref.resourceId || d.resourceId == null && d.name === ref.resourceId) && d.teamId === ref.teamId).map((d) => ({
208
+ name: d.name,
209
+ sandboxId: d.sandboxId
210
+ }));
211
+ }
212
+ /** Walk `parentSandboxId` upward from each of `sessions`, returning the transitive closure
213
+ * (originals included, no duplicates). Stops at a sandboxId with no known details (deleted,
214
+ * or from before this field existed) rather than throwing. Exported for `episodicTree()`. */
215
+ async function withAncestors(adapter, sessions) {
216
+ const allDetails = await adapter.listAllSandboxDetails();
217
+ const bySandboxId = new Map(allDetails.map((d) => [d.sandboxId, d]));
218
+ const seen = /* @__PURE__ */ new Map();
219
+ for (const session of sessions) {
220
+ let current = session;
221
+ while (current && !seen.has(current.sandboxId)) {
222
+ seen.set(current.sandboxId, current);
223
+ const parentId = bySandboxId.get(current.sandboxId)?.parentSandboxId;
224
+ const parentDetails = parentId ? bySandboxId.get(parentId) : void 0;
225
+ current = parentDetails ? {
226
+ name: parentDetails.name,
227
+ sandboxId: parentDetails.sandboxId
228
+ } : void 0;
229
+ }
230
+ }
231
+ return [...seen.values()];
232
+ }
233
+ /**
234
+ * Episodic memory, deliberately not a provider at all: it's a read API over the ledger
235
+ * alineo already has (`@alineo-labs/core`'s `IStorageAdapter`), reshaped by `resourceId` and
236
+ * `teamId`. No new storage, no ledger schema change — both ride along in the existing
237
+ * `sandbox_created` payload the same way `runId` does. See `resolveSessionsByResourceId`'s own
238
+ * doc comment for exactly how `teamId` is enforced (and its one documented trade-off).
239
+ */
240
+ async function episodicRecall(adapter, ref, opts = {}) {
241
+ let sessions = await (opts.resolveSessions ?? resolveSessionsByResourceId)(adapter, ref);
242
+ if (opts.branch === "lineage") sessions = await withAncestors(adapter, sessions);
243
+ const entries = (await Promise.all(sessions.map((session) => adapter.readAll(session.name, session.sandboxId)))).flat().sort((a, b) => a.ts - b.ts);
244
+ if (opts.limit == null) return entries;
245
+ return opts.limit <= 0 ? [] : entries.slice(-opts.limit);
246
+ }
247
+ //#endregion
248
+ //#region src/episodic-tree.ts
249
+ /**
250
+ * The branch-aware counterpart to `episodicRecall()`: instead of flattening every resolved
251
+ * session (plus ancestry) into one merged chronological stream, this returns the actual fork
252
+ * tree — each session as its own node, `sb.fork()`-descended sessions nested under their
253
+ * parent. Lets an agent reason about "what happened on this branch" vs. "what happened on a
254
+ * sibling branch forked from the same point," which a flat stream inherently can't represent.
255
+ *
256
+ * Every resolved session's ancestor chain is included automatically (the same way
257
+ * `episodicRecall({branch: "lineage"})` opts into it) — a tree with gaps in its own lineage
258
+ * wouldn't have coherent root nodes.
259
+ *
260
+ * Returns the root branches (sessions with no parent among the resolved set); walk `.children`
261
+ * to reach descendants. Root order and each branch's `children` are sorted by the branch's own
262
+ * first entry timestamp, for a deterministic result.
263
+ */
264
+ async function episodicTree(adapter, ref, opts = {}) {
265
+ const sessions = await withAncestors(adapter, await (opts.resolveSessions ?? resolveSessionsByResourceId)(adapter, ref));
266
+ const allDetails = await adapter.listAllSandboxDetails();
267
+ const parentBySandboxId = new Map(allDetails.map((d) => [d.sandboxId, d.parentSandboxId]));
268
+ const branches = /* @__PURE__ */ new Map();
269
+ for (const session of sessions) {
270
+ const entries = (await adapter.readAll(session.name, session.sandboxId)).sort((a, b) => a.ts - b.ts);
271
+ branches.set(session.sandboxId, {
272
+ sandboxId: session.sandboxId,
273
+ name: session.name,
274
+ parentSandboxId: parentBySandboxId.get(session.sandboxId) ?? void 0,
275
+ entries,
276
+ children: []
277
+ });
278
+ }
279
+ const roots = [];
280
+ for (const branch of branches.values()) {
281
+ const parent = branch.parentSandboxId ? branches.get(branch.parentSandboxId) : void 0;
282
+ if (parent) parent.children.push(branch);
283
+ else {
284
+ branch.parentSandboxId = void 0;
285
+ roots.push(branch);
286
+ }
287
+ }
288
+ const firstTs = (b) => b.entries[0]?.ts ?? 0;
289
+ const sortRecursively = (list) => {
290
+ list.sort((a, b) => firstTs(a) - firstTs(b));
291
+ for (const branch of list) sortRecursively(branch.children);
292
+ };
293
+ sortRecursively(roots);
294
+ return roots;
295
+ }
296
+ //#endregion
297
+ //#region src/compaction.ts
298
+ /**
299
+ * Prune a resource's semantic memory so facts don't accumulate forever. Without this, a
300
+ * `remember()`'d fact stays verbatim until manually deleted — fine for a demo, not for an
301
+ * agent that runs for months. Requires a provider that supports the optional
302
+ * `IPrunableSemanticMemoryProvider` capability (`listAll`/`forget`); throws otherwise, same
303
+ * "loud on missing capability" convention as `Memory.remember()`/`recall()`.
304
+ *
305
+ * Both `maxAgeMs` and `maxFacts` may be set together — age-based removal runs first, then the
306
+ * count cap is applied to whatever's left. Neither set is a no-op (returns `{removed: 0, ...}`
307
+ * without calling `forget()`).
308
+ */
309
+ async function compactSemanticMemory(provider, ref, opts = {}) {
310
+ if (!isPrunable(provider)) throw new Error("compactSemanticMemory() requires a provider implementing IPrunableSemanticMemoryProvider (listAll/forget) — this provider only implements remember/recall.");
311
+ return compactPrunable(provider, ref, opts);
312
+ }
313
+ async function compactPrunable(provider, ref, opts) {
314
+ const now = opts.now ?? Date.now();
315
+ const facts = await provider.listAll(ref);
316
+ const toRemove = /* @__PURE__ */ new Set();
317
+ if (opts.maxAgeMs != null) {
318
+ for (const fact of facts) if (now - fact.rememberedAt > opts.maxAgeMs) toRemove.add(fact.id);
319
+ }
320
+ if (opts.maxFacts != null) {
321
+ const remaining = facts.filter((f) => !toRemove.has(f.id));
322
+ if (remaining.length > opts.maxFacts) {
323
+ const oldestFirst = [...remaining].sort((a, b) => a.rememberedAt - b.rememberedAt);
324
+ const excess = oldestFirst.length - opts.maxFacts;
325
+ for (let i = 0; i < excess; i++) toRemove.add(oldestFirst[i].id);
326
+ }
327
+ }
328
+ if (toRemove.size === 0) return {
329
+ removed: 0,
330
+ remaining: facts.length,
331
+ summarized: 0
332
+ };
333
+ let summarized = 0;
334
+ if (opts.summarize) {
335
+ const removedFacts = facts.filter((f) => toRemove.has(f.id)).sort((a, b) => a.rememberedAt - b.rememberedAt);
336
+ const consolidated = await opts.summarize(removedFacts);
337
+ for (const content of consolidated) await provider.remember(ref, { content });
338
+ summarized = consolidated.length;
339
+ }
340
+ return {
341
+ removed: await provider.forget(ref, [...toRemove]),
342
+ remaining: (await provider.listAll(ref)).length,
343
+ summarized
344
+ };
345
+ }
346
+ //#endregion
347
+ //#region src/lifecycle-hooks.ts
348
+ const DEFAULT_CHECKPOINT_KEY = "__alineo_memory_lastCheckpoint";
349
+ const DEFAULT_SESSION_KEY = "__alineo_memory_lastSessionId";
350
+ /**
351
+ * Binds a `Memory` instance into a sandbox's lifecycle via the existing `SandboxHooks`
352
+ * extension point (`SandboxOptions.hooks`, composable with `composeHooks()`) rather than any
353
+ * change to `@alineo-labs/core`'s sandbox lifecycle code itself — the safest place to hang
354
+ * this: `SandboxHooks` already exists specifically so cross-cutting concerns like this one
355
+ * (otel tracing, billing, and now memory) can observe lifecycle events without core needing
356
+ * to know they exist.
357
+ *
358
+ * Records, in working memory scoped to `ref`:
359
+ * - the most recently active `sandboxId` for this resource (`onSandboxCreated`)
360
+ * - the most recent checkpoint's `{sandboxId, snapshotId, name, at}` (`onCheckpoint`)
361
+ *
362
+ * This does not restore or replay any state on resume — restoring a sandbox's filesystem
363
+ * from a snapshot is `@alineo-labs/core`'s job, not this package's. What it gives an agent is
364
+ * a durable answer to "what was the last checkpoint for this resource, across however many
365
+ * sandbox sessions it's had" without re-deriving it from the ledger every time.
366
+ *
367
+ * @example
368
+ * ```ts
369
+ * import { composeHooks } from "@alineo-labs/core";
370
+ * import { createMemoryLifecycleHooks } from "@alineo-labs/memory";
371
+ *
372
+ * const sb = await client.sandbox({
373
+ * image: "node:22",
374
+ * resources: { cpu: "500m", memory: "512Mi" },
375
+ * resourceId: ref.resourceId,
376
+ * hooks: composeHooks([createMemoryLifecycleHooks(memory, ref), otelHooks(tracer)]),
377
+ * });
378
+ * ```
379
+ */
380
+ function createMemoryLifecycleHooks(memory, ref, opts = {}) {
381
+ const checkpointKey = opts.checkpointKey ?? DEFAULT_CHECKPOINT_KEY;
382
+ const sessionKey = opts.sessionKey ?? DEFAULT_SESSION_KEY;
383
+ const onError = opts.onError ?? (() => {});
384
+ return {
385
+ onSandboxCreated(sandboxId) {
386
+ memory.workingMemory.set(ref, sessionKey, sandboxId).catch(onError);
387
+ },
388
+ onCheckpoint(sandboxId, snapshotId, name) {
389
+ const record = {
390
+ sandboxId,
391
+ snapshotId,
392
+ name,
393
+ at: Date.now()
394
+ };
395
+ memory.workingMemory.set(ref, checkpointKey, record).catch(onError);
396
+ }
397
+ };
398
+ }
399
+ //#endregion
400
+ //#region src/schema-working-memory.ts
401
+ /**
402
+ * A typed, validated profile stored as one working-memory record — the structured
403
+ * counterpart to `IWorkingMemoryProvider`'s raw untyped key/value pairs. Useful for the
404
+ * common "agent maintains a structured user profile" shape (name, preferences, goals) where
405
+ * raw key/value gives no guarantee about what's actually stored.
406
+ *
407
+ * Validation only fires on `update()`, not on `get()` — a profile written by an older schema
408
+ * version should still be readable (as `Partial<T>`, since it may be missing fields a newer
409
+ * schema requires) rather than throwing on every read after a schema change.
410
+ *
411
+ * @example
412
+ * ```ts
413
+ * import { z } from "zod";
414
+ * import { SchemaWorkingMemory } from "@alineo-labs/memory";
415
+ *
416
+ * const ProfileSchema = z.object({
417
+ * name: z.string().optional(),
418
+ * preferredLanguage: z.string().optional(),
419
+ * });
420
+ *
421
+ * const profile = new SchemaWorkingMemory(workingMemoryProvider, ProfileSchema);
422
+ * await profile.update(ref, { preferredLanguage: "TypeScript" });
423
+ * await profile.get(ref); // { preferredLanguage: "TypeScript" }
424
+ * ```
425
+ *
426
+ * Pass a schema that already tolerates partial input (e.g. Zod's own `.partial()`) if
427
+ * `update()` should succeed before every field has been filled in — this class imposes no
428
+ * partial/full policy of its own, it only merges and validates with whatever `schema` given.
429
+ */
430
+ var SchemaWorkingMemory = class {
431
+ provider;
432
+ schema;
433
+ key;
434
+ constructor(provider, schema, key = "__profile") {
435
+ this.provider = provider;
436
+ this.schema = schema;
437
+ this.key = key;
438
+ }
439
+ /** The stored profile, or `{}` if nothing has been set yet. Not re-validated on read. */
440
+ async get(ref) {
441
+ return await this.provider.get(ref, this.key) ?? {};
442
+ }
443
+ /**
444
+ * Shallow-merge `patch` into the current profile, validate the result against `schema`, and
445
+ * persist it. Returns the validated (and possibly schema-transformed, e.g. defaults filled
446
+ * in) profile.
447
+ * @throws whatever `schema.parse()` throws if the merged object is invalid.
448
+ */
449
+ async update(ref, patch) {
450
+ const merged = {
451
+ ...await this.get(ref),
452
+ ...patch
453
+ };
454
+ const validated = this.schema.parse(merged);
455
+ await this.provider.set(ref, this.key, validated);
456
+ return validated;
457
+ }
458
+ /** Remove the whole profile. */
459
+ async clear(ref) {
460
+ await this.provider.delete(ref, this.key);
461
+ }
462
+ };
463
+ //#endregion
464
+ //#region src/tools.ts
465
+ /**
466
+ * Build the standard set of memory tools for one resource: working-memory get/set, and (only
467
+ * when `memory.hasSemanticMemory`) remember/recall. This is what lets a *model*, not just the
468
+ * surrounding application code, decide to persist or retrieve a fact mid-conversation — the
469
+ * gap left by `Memory` being a plain TS API a developer must call explicitly.
470
+ */
471
+ function createMemoryTools(memory, ref) {
472
+ const tools = [{
473
+ name: "set_working_memory",
474
+ description: "Store a structured fact about this resource in working memory, under a named key. Overwrites any existing value for that key.",
475
+ parameters: {
476
+ type: "object",
477
+ properties: {
478
+ key: {
479
+ type: "string",
480
+ description: "The fact's name, e.g. 'preferredLanguage'."
481
+ },
482
+ value: { description: "The value to store. Any JSON-serializable value." }
483
+ },
484
+ required: ["key", "value"]
485
+ },
486
+ async execute(args) {
487
+ const key = String(args.key ?? "");
488
+ await memory.workingMemory.set(ref, key, args.value);
489
+ return { ok: true };
490
+ }
491
+ }, {
492
+ name: "get_working_memory",
493
+ description: "Retrieve every structured working-memory fact stored for this resource.",
494
+ parameters: {
495
+ type: "object",
496
+ properties: {}
497
+ },
498
+ async execute() {
499
+ return memory.workingMemory.list(ref);
500
+ }
501
+ }];
502
+ if (memory.hasSemanticMemory) tools.push({
503
+ name: "remember_fact",
504
+ description: "Store a fact in long-term semantic memory, for later recall by meaning rather than exact key. Use for things worth remembering across sessions.",
505
+ parameters: {
506
+ type: "object",
507
+ properties: { content: {
508
+ type: "string",
509
+ description: "The fact to remember, as plain text."
510
+ } },
511
+ required: ["content"]
512
+ },
513
+ async execute(args) {
514
+ const content = String(args.content ?? "");
515
+ await memory.remember(ref, { content });
516
+ return { ok: true };
517
+ }
518
+ }, {
519
+ name: "recall_facts",
520
+ description: "Search long-term semantic memory for facts relevant to a query.",
521
+ parameters: {
522
+ type: "object",
523
+ properties: {
524
+ query: {
525
+ type: "string",
526
+ description: "What to search for."
527
+ },
528
+ topK: {
529
+ type: "number",
530
+ description: "Max number of facts to return. Defaults to 5."
531
+ }
532
+ },
533
+ required: ["query"]
534
+ },
535
+ async execute(args) {
536
+ const query = String(args.query ?? "");
537
+ const topK = typeof args.topK === "number" ? args.topK : void 0;
538
+ return { facts: (await memory.recall(ref, query, { topK })).map((f) => f.content) };
539
+ }
540
+ });
541
+ return tools;
542
+ }
543
+ //#endregion
544
+ //#region src/pipeline.ts
545
+ /**
546
+ * Assemble a plain-text context block from a resource's working + semantic memory — the
547
+ * "inject relevant memory into the prompt on session start" half of owning the memory
548
+ * pipeline, previously entirely missing (the package shipped only the primitives an app had
549
+ * to remember to call). Returns `""` if there's nothing to say (fresh resource, no query).
550
+ *
551
+ * This builds the string; it does not inject it anywhere on its own — `alineo`'s Pi bridge has
552
+ * no hook today for prepending to a session's system prompt, so wiring the result of this into
553
+ * an actual agent conversation is left to the caller (e.g. prepend it to the first `prompt()`
554
+ * call, or fold it into `AgentSpec.env`/setup for now).
555
+ *
556
+ * @example
557
+ * ```ts
558
+ * const context = await buildContextSnippet(memory, agent.resourceRef, { query: userMessage });
559
+ * for await (const chunk of agent.prompt(context ? `${context}\n\n${userMessage}` : userMessage)) { ... }
560
+ * ```
561
+ */
562
+ async function buildContextSnippet(memory, ref, opts = {}) {
563
+ const sections = [];
564
+ const working = await memory.workingMemory.list(ref);
565
+ const keys = Object.keys(working).slice(0, opts.maxWorkingMemoryKeys ?? 20);
566
+ if (keys.length > 0) sections.push(`Known facts about this resource:\n${keys.map((k) => `- ${k}: ${JSON.stringify(working[k])}`).join("\n")}`);
567
+ if (opts.query && memory.hasSemanticMemory) {
568
+ const facts = await memory.recall(ref, opts.query, { topK: opts.topK });
569
+ if (facts.length > 0) sections.push(`Relevant memories:\n${facts.map((f) => `- ${f.content}`).join("\n")}`);
570
+ }
571
+ return sections.join("\n\n");
572
+ }
573
+ //#endregion
574
+ //#region src/access-control.ts
575
+ var MemoryAccessDeniedError = class extends Error {
576
+ teamId;
577
+ constructor(teamId) {
578
+ super(`Access denied to team scope "${teamId}"`);
579
+ this.teamId = teamId;
580
+ this.name = "MemoryAccessDeniedError";
581
+ }
582
+ };
583
+ async function assertAccess(ref, checker) {
584
+ if (ref.teamId != null && !await checker.canAccess(ref.teamId)) throw new MemoryAccessDeniedError(ref.teamId);
585
+ }
586
+ /**
587
+ * Wrap an `IWorkingMemoryProvider` with app-layer team-scoping enforcement, checked before
588
+ * every call. `@alineo-labs/postgres-memory` enforces `teamId` isolation at the database
589
+ * layer via row-level security; every other provider (in-memory, `@alineo-labs/sqlite-memory`)
590
+ * only isolates `teamId` structurally — `ResourceRef.teamId` folds into the storage key, so
591
+ * data for one team simply doesn't collide with another's, but nothing stops a caller passing
592
+ * the "wrong" `teamId` on purpose from reading it. This closes that gap for any backend,
593
+ * making the enforcement guarantee backend-independent rather than something only a Postgres
594
+ * deployment gets — and a Postgres deployment can still layer this on top of its own RLS for
595
+ * defense-in-depth, it isn't an either/or.
596
+ *
597
+ * A `ResourceRef` with no `teamId` always passes through untouched — there's nothing to check
598
+ * for an untenanted resource.
599
+ */
600
+ function withTeamAccessControl(provider, checker) {
601
+ return {
602
+ async get(ref, key) {
603
+ await assertAccess(ref, checker);
604
+ return provider.get(ref, key);
605
+ },
606
+ async set(ref, key, value) {
607
+ await assertAccess(ref, checker);
608
+ return provider.set(ref, key, value);
609
+ },
610
+ async list(ref) {
611
+ await assertAccess(ref, checker);
612
+ return provider.list(ref);
613
+ },
614
+ async delete(ref, key) {
615
+ await assertAccess(ref, checker);
616
+ return provider.delete(ref, key);
617
+ }
618
+ };
619
+ }
620
+ /**
621
+ * Same enforcement for `ISemanticMemoryProvider`. Preserves whichever optional capabilities
622
+ * the wrapped provider has (`IPrunableSemanticMemoryProvider`, `IBulkSemanticMemoryProvider`) —
623
+ * `isPrunable()`/`isBulkRememberable()` still report correctly against the wrapped result, so
624
+ * `compactSemanticMemory()` and `Memory.fork()`'s batched-embed path keep working through the
625
+ * wrapper. See `TeamGuardedSemanticProvider` for why the return type is never just `T`.
626
+ */
627
+ function withTeamAccessControlSemantic(provider, checker) {
628
+ let result = {
629
+ async remember(ref, fact) {
630
+ await assertAccess(ref, checker);
631
+ return provider.remember(ref, fact);
632
+ },
633
+ async recall(ref, query, opts) {
634
+ await assertAccess(ref, checker);
635
+ return provider.recall(ref, query, opts);
636
+ }
637
+ };
638
+ if (isPrunable(provider)) result = {
639
+ ...result,
640
+ async listAll(ref) {
641
+ await assertAccess(ref, checker);
642
+ return provider.listAll(ref);
643
+ },
644
+ async forget(ref, ids) {
645
+ await assertAccess(ref, checker);
646
+ return provider.forget(ref, ids);
647
+ }
648
+ };
649
+ if (isBulkRememberable(provider)) result = {
650
+ ...result,
651
+ async rememberMany(ref, facts) {
652
+ await assertAccess(ref, checker);
653
+ return provider.rememberMany(ref, facts);
654
+ }
655
+ };
656
+ return result;
657
+ }
658
+ //#endregion
659
+ //#region src/memory.ts
660
+ /**
661
+ * The provider-agnostic memory facade: one object an agent holds, backed by whichever
662
+ * providers were configured. Plain public constructor (like `SandboxHandle`), not the
663
+ * load/attach/spawn factory pattern `Agent` uses — `Memory` has no async setup step (no
664
+ * snapshot restore, no bridge process) that would need a factory to hide.
665
+ */
666
+ var Memory = class {
667
+ workingMemory;
668
+ semanticProvider;
669
+ autoCompact;
670
+ /** Per-resource remember() count since the last auto-compact check, keyed by `scopeKey`. */
671
+ rememberCounts = /* @__PURE__ */ new Map();
672
+ constructor(opts) {
673
+ const working = opts.workingMemory;
674
+ this.workingMemory = {
675
+ get: (ref, key) => working.get(ref, key),
676
+ set: (ref, key, value) => working.set(ref, key, value),
677
+ list: (ref) => working.list(ref),
678
+ delete: (ref, key) => working.delete(ref, key)
679
+ };
680
+ this.semanticProvider = opts.semantic;
681
+ this.autoCompact = opts.autoCompact;
682
+ }
683
+ /** Whether this instance was configured with a semantic memory provider. */
684
+ get hasSemanticMemory() {
685
+ return this.semanticProvider != null;
686
+ }
687
+ /**
688
+ * @throws {MemoryCapabilityError} if no semantic memory provider was configured.
689
+ * @throws whatever `compactSemanticMemory()` throws if auto-compaction is configured and its
690
+ * check fires on this call — a failed compaction fails the `remember()` call it rode along
691
+ * with, rather than being silently swallowed. Configure `autoCompact.checkEvery` higher, or
692
+ * call `compactSemanticMemory()` yourself on a separate schedule, to decouple the two.
693
+ */
694
+ async remember(ref, fact) {
695
+ if (!this.semanticProvider) throw new MemoryCapabilityError("semantic");
696
+ await this.semanticProvider.remember(ref, fact);
697
+ if (this.autoCompact && isPrunable(this.semanticProvider)) {
698
+ const key = scopeKey(ref);
699
+ const count = (this.rememberCounts.get(key) ?? 0) + 1;
700
+ this.rememberCounts.set(key, count);
701
+ if (count % Math.max(1, this.autoCompact.checkEvery ?? 1) === 0) await compactSemanticMemory(this.semanticProvider, ref, this.autoCompact);
702
+ }
703
+ }
704
+ /** @throws {MemoryCapabilityError} if no semantic memory provider was configured. */
705
+ async recall(ref, query, opts) {
706
+ if (!this.semanticProvider) throw new MemoryCapabilityError("semantic");
707
+ return this.semanticProvider.recall(ref, query, opts);
708
+ }
709
+ /**
710
+ * Prune old/excess facts from semantic memory — see `compactSemanticMemory()`. Distinct from
711
+ * the automatic compaction `autoCompact` triggers: this always runs immediately, regardless
712
+ * of `checkEvery`.
713
+ * @throws {MemoryCapabilityError} if no semantic memory provider was configured.
714
+ * @throws if the configured provider doesn't support the pruning capability
715
+ * (`IPrunableSemanticMemoryProvider`).
716
+ */
717
+ async compactSemanticMemory(ref, opts) {
718
+ if (!this.semanticProvider) throw new MemoryCapabilityError("semantic");
719
+ return compactSemanticMemory(this.semanticProvider, ref, opts);
720
+ }
721
+ /**
722
+ * Copy a resource's current memory into a brand-new resource scope the child can mutate
723
+ * independently — the memory-layer counterpart to `sb.fork()`'s copy-on-write sandbox
724
+ * snapshot. Unlike `episodicRecall({branch: "lineage"})`, which reads the *parent's* history
725
+ * through the child's own lens without duplicating anything, this actually writes a real,
726
+ * independent copy: mutating the child's memory afterward never touches the parent's.
727
+ *
728
+ * Working memory is always copied in full. Semantic memory is copied only if the configured
729
+ * provider supports the pruning capability (`listAll` is what makes enumerating "everything
730
+ * to copy" possible) — see `ForkMemoryResult.semanticFactsCopied`. Copied semantic facts
731
+ * keep their original `content`/`sourceRef` (so `verified` is recomputed identically by
732
+ * whatever provider stores them) but get a fresh `id`/`rememberedAt` from the provider, same
733
+ * as any other `remember()` call.
734
+ *
735
+ * Both copy steps run their per-item writes concurrently (`Promise.all`), not sequentially.
736
+ * Semantic facts are additionally batched into one `embed()` call, not one per fact, when the
737
+ * provider supports the optional `IBulkSemanticMemoryProvider` capability (all three shipped
738
+ * providers do) — re-deriving vectors for content the provider already embedded once is
739
+ * otherwise a full round trip to the embedding API per fact.
740
+ *
741
+ * Does not read or write anything about the *sandbox* itself — call this alongside
742
+ * `sb.fork()`/`Alineo.spawn()`, not instead of it. `Alineo.spawn()` already calls this
743
+ * automatically when the parent agent has `.memory` configured.
744
+ */
745
+ async fork(parentRef, childResourceId) {
746
+ const childRef = {
747
+ resourceId: childResourceId,
748
+ teamId: parentRef.teamId
749
+ };
750
+ const working = await this.workingMemory.list(parentRef);
751
+ await Promise.all(Object.entries(working).map(([key, value]) => this.workingMemory.set(childRef, key, structuredClone(value))));
752
+ let semanticFactsCopied = 0;
753
+ if (this.semanticProvider && isPrunable(this.semanticProvider)) {
754
+ const semanticProvider = this.semanticProvider;
755
+ const toCopy = (await semanticProvider.listAll(parentRef)).map((f) => ({
756
+ content: f.content,
757
+ sourceRef: f.sourceRef
758
+ }));
759
+ if (isBulkRememberable(semanticProvider)) await semanticProvider.rememberMany(childRef, toCopy);
760
+ else await Promise.all(toCopy.map((f) => semanticProvider.remember(childRef, f)));
761
+ semanticFactsCopied = (await semanticProvider.listAll(childRef)).length;
762
+ }
763
+ return {
764
+ ref: childRef,
765
+ workingKeysCopied: Object.keys(working).length,
766
+ semanticFactsCopied
767
+ };
768
+ }
769
+ };
770
+ //#endregion
771
+ export { InMemorySemanticMemoryProvider, InMemoryWorkingMemoryProvider, Memory, MemoryAccessDeniedError, MemoryCapabilityError, SchemaWorkingMemory, buildContextSnippet, compactSemanticMemory, cosineSimilarity, createMemoryLifecycleHooks, createMemoryTools, episodicRecall, episodicTree, factFromRow, isBulkRememberable, isPrunable, scopeKey, withTeamAccessControl, withTeamAccessControlSemantic };