@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.
@@ -0,0 +1,651 @@
1
+ import { IStorageAdapter, LedgerEntry, SandboxHooks, WorkflowError } from "@alineo-labs/core";
2
+
3
+ //#region src/types.d.ts
4
+ /**
5
+ * The durable identity memory is scoped by — deliberately NOT a `sandboxId` or session id.
6
+ * A `sandboxId` identifies one sandbox *session* (what the ledger already keys episodic
7
+ * events by); a `resourceId` is expected to outlive any number of those sessions, because
8
+ * the entire point of working/semantic memory is surviving past the session it was learned
9
+ * in. Conflating the two would silently break that guarantee.
10
+ *
11
+ * `teamId` is optional widening for shared/team memory — every provider receives it, but
12
+ * what a given provider does with it (row-level security, app-layer filtering, ignoring it)
13
+ * is that provider's problem, not this package's.
14
+ */
15
+ interface ResourceRef {
16
+ resourceId: string;
17
+ teamId?: string;
18
+ }
19
+ /**
20
+ * Composite key every in-memory reference provider in this package scopes its storage by.
21
+ *
22
+ * Each part is escaped (`\` → `\\`, `:` → `\:`) before joining — without this, an untenanted
23
+ * caller passing `resourceId: "acme:corp"` would produce the exact same string as a tenanted
24
+ * caller passing `{teamId: "acme", resourceId: "corp"}`, silently colliding two different
25
+ * callers' storage onto one key. On a backend keyed solely by this string (in-memory,
26
+ * `@alineo-labs/sqlite-memory`), combined with `access-control.ts`'s `assertAccess()` skipping
27
+ * its check entirely for a `ref` with no `teamId`, an unescaped join made that a real
28
+ * cross-tenant read/write, not just a naming curiosity.
29
+ */
30
+ declare function scopeKey(ref: ResourceRef): string;
31
+ //#endregion
32
+ //#region src/errors.d.ts
33
+ /** Memory capabilities a `Memory` instance may or may not have been configured with. */
34
+ type MemoryCapability = "semantic";
35
+ /**
36
+ * Thrown when a `Memory` method is called for a capability (e.g. semantic recall) that this
37
+ * instance was never given a provider for. Deliberately loud — matching `errors.ts`'s existing
38
+ * convention of distinguishable error classes (`CommandError`, `SandboxError`) callers can
39
+ * catch specifically — rather than a silent no-op or an empty result set that looks
40
+ * indistinguishable from "no facts matched."
41
+ */
42
+ declare class MemoryCapabilityError extends WorkflowError {
43
+ readonly capability: MemoryCapability;
44
+ constructor(capability: MemoryCapability);
45
+ }
46
+ //#endregion
47
+ //#region src/working.d.ts
48
+ /**
49
+ * Structured, per-resource key/value facts — the smallest, cheapest-to-build memory
50
+ * capability (Phase 0 of the exploration research). Every deployment needs at least this;
51
+ * it's the only required provider on `MemoryOptions`.
52
+ */
53
+ interface IWorkingMemoryProvider {
54
+ get(ref: ResourceRef, key: string): Promise<unknown | undefined>;
55
+ set(ref: ResourceRef, key: string, value: unknown): Promise<void>;
56
+ list(ref: ResourceRef): Promise<Record<string, unknown>>;
57
+ delete(ref: ResourceRef, key: string): Promise<void>;
58
+ }
59
+ /**
60
+ * Reference implementation — a process-local `Map`. Not durable across restarts, not shared
61
+ * across processes or hosts. Exists to prove `IWorkingMemoryProvider` composes with `Memory`,
62
+ * to give unit tests something to run against without a real database, and to give a first
63
+ * consumer something to hold before a real backend package (Postgres, SQLite, ...) exists.
64
+ * Not a production recommendation — the same relationship `InMemoryStore` has to LangGraph's
65
+ * real backends.
66
+ */
67
+ declare class InMemoryWorkingMemoryProvider implements IWorkingMemoryProvider {
68
+ private readonly buckets;
69
+ private bucketFor;
70
+ get(ref: ResourceRef, key: string): Promise<unknown | undefined>;
71
+ set(ref: ResourceRef, key: string, value: unknown): Promise<void>;
72
+ list(ref: ResourceRef): Promise<Record<string, unknown>>;
73
+ delete(ref: ResourceRef, key: string): Promise<void>;
74
+ }
75
+ //#endregion
76
+ //#region src/semantic.d.ts
77
+ /**
78
+ * Independently pluggable embedding source — constructor input to a real
79
+ * `ISemanticMemoryProvider` implementation, the same way `nvidiaProvider` is passed into
80
+ * `languageModel()` in `@alineo-labs/model-providers` today. This package only needs to know
81
+ * the shape; it never depends on a concrete provider.
82
+ */
83
+ interface EmbeddingProvider {
84
+ id: string;
85
+ /**
86
+ * `opts.type` distinguishes embedding a fact being *stored* (`"passage"`) from embedding a
87
+ * search string at *recall* time (`"query"`) — asymmetric embedding models (most real ones,
88
+ * including NVIDIA NIM's) rank meaningfully better when this matches how the text is
89
+ * actually used, and conflating the two silently degrades relevance rather than erroring.
90
+ * Optional and provider-defined: a symmetric or single-purpose provider is free to ignore it.
91
+ */
92
+ embed(texts: string[], opts?: {
93
+ type?: "query" | "passage";
94
+ }): Promise<number[][]>;
95
+ }
96
+ /** One recalled or remembered fact. */
97
+ interface MemoryFact {
98
+ content: string;
99
+ /**
100
+ * Ties a fact back to the ledger entry it was derived from — the "verified memory" idea
101
+ * from the exploration research (a fact is trustworthy exactly when it's traceable to a
102
+ * real ledger entry, not a hallucinated summary). Backend-agnostic: it's just an opaque
103
+ * pointer the caller supplies, alineo-specific but not provider-specific.
104
+ */
105
+ sourceRef?: {
106
+ sandboxId: string;
107
+ entryIndex: number;
108
+ };
109
+ /**
110
+ * Whether this fact is traceable to a real ledger entry. Always **computed**, never
111
+ * caller-set: every conforming provider derives it as `sourceRef != null` at `remember()`
112
+ * time and ignores any value passed in on the input `MemoryFact` — a caller can't just
113
+ * claim `verified: true` for a free-form fact. Meaningless (and absent) on `remember()`
114
+ * input; always present on facts returned by `recall()`/`listAll()`.
115
+ */
116
+ verified?: boolean;
117
+ }
118
+ /**
119
+ * Semantic recall is independently pluggable and may not exist at all — mirroring Mastra's
120
+ * `MastraVector | false` split rather than LangGraph's opt-in-config, because working and
121
+ * semantic memory are already two separate provider slots on `MemoryOptions`, so there's no
122
+ * single object to attach an index config to.
123
+ */
124
+ interface ISemanticMemoryProvider {
125
+ remember(ref: ResourceRef, fact: MemoryFact): Promise<void>;
126
+ recall(ref: ResourceRef, query: string, opts?: {
127
+ topK?: number;
128
+ }): Promise<MemoryFact[]>;
129
+ }
130
+ /** A fact as returned by `IPrunableSemanticMemoryProvider.listAll` — every provider that
131
+ * supports pruning must give each fact a stable `id` (so `forget()` can name it after a
132
+ * separate round trip — a plain object-identity check would break on a real, persisted
133
+ * backend where `listAll()` reconstructs fresh objects from rows) and say when it was
134
+ * remembered. */
135
+ type RememberedFact = MemoryFact & {
136
+ id: string;
137
+ rememberedAt: number;
138
+ };
139
+ /**
140
+ * Optional capability: a semantic memory provider that can enumerate and remove its own
141
+ * facts. Kept separate from `ISemanticMemoryProvider` rather than added to it — most callers
142
+ * only ever `remember()`/`recall()`, and not every provider needs to support pruning to be
143
+ * useful (an append-only audit-style store, for instance). `compactSemanticMemory()` requires
144
+ * this capability; `Memory` checks for it structurally rather than requiring every provider
145
+ * to implement it.
146
+ */
147
+ interface IPrunableSemanticMemoryProvider extends ISemanticMemoryProvider {
148
+ /** Every fact currently stored for this resource, newest or oldest first is unspecified. */
149
+ listAll(ref: ResourceRef): Promise<RememberedFact[]>;
150
+ /** Remove the facts with these `id`s. Returns the number actually removed. */
151
+ forget(ref: ResourceRef, ids: string[]): Promise<number>;
152
+ }
153
+ /** True if `provider` implements the optional pruning capability. */
154
+ declare function isPrunable(provider: ISemanticMemoryProvider): provider is IPrunableSemanticMemoryProvider;
155
+ /**
156
+ * Optional capability: a semantic memory provider that can remember many facts in one call,
157
+ * batching the embedding call (one `embed()` invocation covering every fact's content) instead
158
+ * of one `embed()` per fact. `Memory.fork()` uses this when copying a resource's semantic
159
+ * memory wholesale — without it, forking a resource with hundreds of facts means hundreds of
160
+ * sequential embedding-API round trips just to reproduce vectors for content that's already
161
+ * known. Falls back to plain `remember()` calls (still parallelized, but not batched) for a
162
+ * provider that doesn't implement this.
163
+ */
164
+ interface IBulkSemanticMemoryProvider extends ISemanticMemoryProvider {
165
+ rememberMany(ref: ResourceRef, facts: MemoryFact[]): Promise<void>;
166
+ }
167
+ /** True if `provider` implements the optional bulk-remember capability. */
168
+ declare function isBulkRememberable(provider: ISemanticMemoryProvider): provider is IBulkSemanticMemoryProvider;
169
+ /**
170
+ * Row shape common to `@alineo-labs/sqlite-memory` and `@alineo-labs/postgres-memory`'s
171
+ * semantic-memory tables — both store the same columns, differing only in what each driver
172
+ * hands back for `remembered_at` (a `number` from `bun:sqlite`, a numeric-string from
173
+ * `postgres`'s `BIGINT`; callers `Number()`-coerce before calling this).
174
+ */
175
+ interface SemanticFactRow {
176
+ id: string;
177
+ content: string;
178
+ source_sandbox_id: string | null;
179
+ source_entry_index: number | null;
180
+ remembered_at: number;
181
+ }
182
+ /** Shared row→fact mapping for any backend storing facts in the shape above — exported so
183
+ * `@alineo-labs/sqlite-memory` and `@alineo-labs/postgres-memory` don't each hand-roll the
184
+ * same conversion (including the `verified` derivation) with their own copy of this logic. */
185
+ declare function factFromRow(row: SemanticFactRow): RememberedFact;
186
+ /** Shared ranking primitive for any backend doing its own naive (non-indexed) vector scan —
187
+ * exported so real backends (`@alineo-labs/sqlite-memory`, `@alineo-labs/postgres-memory`)
188
+ * don't each reimplement it. A backend with a real vector index (pgvector, sqlite-vec) should
189
+ * rank in SQL instead and never needs this. */
190
+ declare function cosineSimilarity(a: number[], b: number[]): number;
191
+ /**
192
+ * Reference implementation — an array per resource, ranked by naive cosine similarity over
193
+ * whatever `EmbeddingProvider` is passed in. Same purpose as `InMemoryWorkingMemoryProvider`:
194
+ * proves the interface composes end to end, gives tests something real to run against, not a
195
+ * production recommendation (no persistence, no approximate-nearest-neighbor indexing —
196
+ * O(n) scan per `recall()`).
197
+ */
198
+ declare class InMemorySemanticMemoryProvider implements IPrunableSemanticMemoryProvider, IBulkSemanticMemoryProvider {
199
+ private readonly embeddings;
200
+ private readonly entries;
201
+ constructor(embeddings: EmbeddingProvider);
202
+ /** Batches the embedding call for all `facts` into one `embed()` invocation — see
203
+ * `IBulkSemanticMemoryProvider`. */
204
+ rememberMany(ref: ResourceRef, facts: MemoryFact[]): Promise<void>;
205
+ remember(ref: ResourceRef, fact: MemoryFact): Promise<void>;
206
+ recall(ref: ResourceRef, query: string, opts?: {
207
+ topK?: number;
208
+ }): Promise<MemoryFact[]>;
209
+ listAll(ref: ResourceRef): Promise<RememberedFact[]>;
210
+ forget(ref: ResourceRef, ids: string[]): Promise<number>;
211
+ }
212
+ //#endregion
213
+ //#region src/episodic.d.ts
214
+ /** One sandbox session's identity, as needed to read its ledger entries back out. */
215
+ interface SandboxSessionRef {
216
+ name: string;
217
+ sandboxId: string;
218
+ }
219
+ interface EpisodicRecallOptions {
220
+ /**
221
+ * Resolve which sandbox sessions belong to a resource. Episodic memory needs no new
222
+ * storage — it's a read-shaped view over what the ledger already owns — because
223
+ * `SandboxDetails.resourceId` is threaded through the ledger's `sandbox_created` payload
224
+ * the same way `runId` already was, not a new schema column. The default resolver matches
225
+ * on that field; sessions written before it existed (or by a caller that never set
226
+ * `SandboxOptions.resourceId`) fall back to matching the ledger's `name` against
227
+ * `resourceId` — i.e. sandboxes named after the resource they belong to. Supply a custom
228
+ * resolver if neither convention fits your app.
229
+ */
230
+ resolveSessions?: (adapter: IStorageAdapter, ref: ResourceRef) => Promise<SandboxSessionRef[]>;
231
+ /** Return only the most recent N entries across all resolved sessions, oldest first. */
232
+ limit?: number;
233
+ /**
234
+ * `"flat"` (default) returns only the entries of sessions directly resolved for this
235
+ * resource. `"lineage"` also walks each resolved session's `parentSandboxId` chain
236
+ * (written by `sb.fork()`) upward and includes every ancestor session's entries too — so
237
+ * memory recalled for a forked sandbox includes what happened before the fork. Still one
238
+ * merged, flat, time-ordered stream in the result — alineo's ledger has no branch/lane
239
+ * concept the way e.g. Pi's own session storage does, so "lineage" is the closest
240
+ * approximation to branch-awareness available without inventing one.
241
+ */
242
+ branch?: "flat" | "lineage";
243
+ }
244
+ /**
245
+ * Episodic memory, deliberately not a provider at all: it's a read API over the ledger
246
+ * alineo already has (`@alineo-labs/core`'s `IStorageAdapter`), reshaped by `resourceId` and
247
+ * `teamId`. No new storage, no ledger schema change — both ride along in the existing
248
+ * `sandbox_created` payload the same way `runId` does. See `resolveSessionsByResourceId`'s own
249
+ * doc comment for exactly how `teamId` is enforced (and its one documented trade-off).
250
+ */
251
+ declare function episodicRecall(adapter: IStorageAdapter, ref: ResourceRef, opts?: EpisodicRecallOptions): Promise<LedgerEntry[]>;
252
+ //#endregion
253
+ //#region src/episodic-tree.d.ts
254
+ /** One session's place in the fork tree — its own entries plus every session forked from it. */
255
+ interface EpisodicBranch {
256
+ sandboxId: string;
257
+ name: string;
258
+ /** Absent for a root branch (a session with no known parent, or whose parent wasn't
259
+ * resolved into this tree). */
260
+ parentSandboxId?: string;
261
+ /** This session's own ledger entries, time-ordered. Does not include descendants' entries —
262
+ * that's what `children` is for. */
263
+ entries: LedgerEntry[];
264
+ /** Sessions forked from this one, in the same shape, recursively. */
265
+ children: EpisodicBranch[];
266
+ }
267
+ interface EpisodicTreeOptions {
268
+ /** Same resolver contract as `EpisodicRecallOptions.resolveSessions`. */
269
+ resolveSessions?: (adapter: IStorageAdapter, ref: ResourceRef) => Promise<SandboxSessionRef[]>;
270
+ }
271
+ /**
272
+ * The branch-aware counterpart to `episodicRecall()`: instead of flattening every resolved
273
+ * session (plus ancestry) into one merged chronological stream, this returns the actual fork
274
+ * tree — each session as its own node, `sb.fork()`-descended sessions nested under their
275
+ * parent. Lets an agent reason about "what happened on this branch" vs. "what happened on a
276
+ * sibling branch forked from the same point," which a flat stream inherently can't represent.
277
+ *
278
+ * Every resolved session's ancestor chain is included automatically (the same way
279
+ * `episodicRecall({branch: "lineage"})` opts into it) — a tree with gaps in its own lineage
280
+ * wouldn't have coherent root nodes.
281
+ *
282
+ * Returns the root branches (sessions with no parent among the resolved set); walk `.children`
283
+ * to reach descendants. Root order and each branch's `children` are sorted by the branch's own
284
+ * first entry timestamp, for a deterministic result.
285
+ */
286
+ declare function episodicTree(adapter: IStorageAdapter, ref: ResourceRef, opts?: EpisodicTreeOptions): Promise<EpisodicBranch[]>;
287
+ //#endregion
288
+ //#region src/compaction.d.ts
289
+ interface CompactionOptions {
290
+ /** Drop the oldest facts beyond this count, keeping the most recently remembered ones. */
291
+ maxFacts?: number;
292
+ /** Drop any fact remembered more than this many milliseconds ago. */
293
+ maxAgeMs?: number;
294
+ /** Override "now" for age comparisons — mainly for tests. Defaults to `Date.now()`. */
295
+ now?: number;
296
+ /**
297
+ * When set, facts selected for removal are summarized rather than just discarded: this
298
+ * function receives the to-be-removed facts (oldest first) and returns the contents of
299
+ * fewer, denser replacement facts, which are `remember()`'d *before* the originals are
300
+ * removed — pruning that consolidates information instead of throwing it away. Typically a
301
+ * thin wrapper around an LLM call ("summarize these N facts into fewer bullet points"); the
302
+ * function itself is caller-supplied so this package never depends on a concrete model.
303
+ * Replacement facts carry no `sourceRef` — they're synthesized, not tied to one ledger entry.
304
+ * Omit to fall back to plain deletion.
305
+ */
306
+ summarize?: (facts: RememberedFact[]) => Promise<string[]>;
307
+ }
308
+ interface CompactionResult {
309
+ removed: number;
310
+ remaining: number;
311
+ /** Number of consolidated replacement facts written by `summarize`, if it was set and had
312
+ * something to summarize. `0` when `summarize` was omitted or nothing was removed. */
313
+ summarized: number;
314
+ }
315
+ /**
316
+ * Prune a resource's semantic memory so facts don't accumulate forever. Without this, a
317
+ * `remember()`'d fact stays verbatim until manually deleted — fine for a demo, not for an
318
+ * agent that runs for months. Requires a provider that supports the optional
319
+ * `IPrunableSemanticMemoryProvider` capability (`listAll`/`forget`); throws otherwise, same
320
+ * "loud on missing capability" convention as `Memory.remember()`/`recall()`.
321
+ *
322
+ * Both `maxAgeMs` and `maxFacts` may be set together — age-based removal runs first, then the
323
+ * count cap is applied to whatever's left. Neither set is a no-op (returns `{removed: 0, ...}`
324
+ * without calling `forget()`).
325
+ */
326
+ declare function compactSemanticMemory(provider: ISemanticMemoryProvider, ref: ResourceRef, opts?: CompactionOptions): Promise<CompactionResult>;
327
+ //#endregion
328
+ //#region src/memory.d.ts
329
+ /** Auto-compaction settings — see `Memory.remember()`. Shares its thresholds with
330
+ * `CompactionOptions`, minus `now` (always real time here). */
331
+ interface AutoCompactOptions {
332
+ maxFacts?: number;
333
+ maxAgeMs?: number;
334
+ summarize?: CompactionOptions["summarize"];
335
+ /** Only actually run the compaction check every Nth `remember()` call for a given resource,
336
+ * to bound overhead when `remember()` is called frequently. Defaults to `1` (every call).
337
+ * A value below `1` (including `0`) is treated as `1` — a lower value can't mean "check less
338
+ * often," so it's clamped rather than silently disabling the check entirely via `count %
339
+ * 0` evaluating to `NaN`. */
340
+ checkEvery?: number;
341
+ }
342
+ interface ForkMemoryResult {
343
+ /** The new child resource's scope — `{resourceId: childResourceId, teamId: parentRef.teamId}`. */
344
+ ref: ResourceRef;
345
+ workingKeysCopied: number;
346
+ /** `0` if there's no semantic provider configured, or it doesn't support the pruning
347
+ * capability (`listAll` is what makes copying possible) — semantic memory silently isn't
348
+ * copied in that case; working memory still is. */
349
+ semanticFactsCopied: number;
350
+ }
351
+ interface MemoryOptions {
352
+ /** Required — every deployment needs at least structured working memory. */
353
+ workingMemory: IWorkingMemoryProvider;
354
+ /** Optional — absence is a typed, explicit state (see `MemoryCapabilityError`), not a silent no-op. */
355
+ semantic?: ISemanticMemoryProvider;
356
+ /**
357
+ * When set, `remember()` automatically runs `compactSemanticMemory()` after writing, once
358
+ * every `checkEvery` calls for a given resource — the "the package owns compaction, not the
359
+ * caller" behavior from the original design goal. Silently skipped (not an error) if the
360
+ * configured `semantic` provider doesn't support the pruning capability. Requires
361
+ * `semantic` to be set; ignored otherwise.
362
+ */
363
+ autoCompact?: AutoCompactOptions;
364
+ }
365
+ /**
366
+ * The provider-agnostic memory facade: one object an agent holds, backed by whichever
367
+ * providers were configured. Plain public constructor (like `SandboxHandle`), not the
368
+ * load/attach/spawn factory pattern `Agent` uses — `Memory` has no async setup step (no
369
+ * snapshot restore, no bridge process) that would need a factory to hide.
370
+ */
371
+ declare class Memory {
372
+ readonly workingMemory: {
373
+ get(ref: ResourceRef, key: string): Promise<unknown | undefined>;
374
+ set(ref: ResourceRef, key: string, value: unknown): Promise<void>;
375
+ list(ref: ResourceRef): Promise<Record<string, unknown>>;
376
+ delete(ref: ResourceRef, key: string): Promise<void>;
377
+ };
378
+ private readonly semanticProvider;
379
+ private readonly autoCompact;
380
+ /** Per-resource remember() count since the last auto-compact check, keyed by `scopeKey`. */
381
+ private readonly rememberCounts;
382
+ constructor(opts: MemoryOptions);
383
+ /** Whether this instance was configured with a semantic memory provider. */
384
+ get hasSemanticMemory(): boolean;
385
+ /**
386
+ * @throws {MemoryCapabilityError} if no semantic memory provider was configured.
387
+ * @throws whatever `compactSemanticMemory()` throws if auto-compaction is configured and its
388
+ * check fires on this call — a failed compaction fails the `remember()` call it rode along
389
+ * with, rather than being silently swallowed. Configure `autoCompact.checkEvery` higher, or
390
+ * call `compactSemanticMemory()` yourself on a separate schedule, to decouple the two.
391
+ */
392
+ remember(ref: ResourceRef, fact: MemoryFact): Promise<void>;
393
+ /** @throws {MemoryCapabilityError} if no semantic memory provider was configured. */
394
+ recall(ref: ResourceRef, query: string, opts?: {
395
+ topK?: number;
396
+ }): Promise<MemoryFact[]>;
397
+ /**
398
+ * Prune old/excess facts from semantic memory — see `compactSemanticMemory()`. Distinct from
399
+ * the automatic compaction `autoCompact` triggers: this always runs immediately, regardless
400
+ * of `checkEvery`.
401
+ * @throws {MemoryCapabilityError} if no semantic memory provider was configured.
402
+ * @throws if the configured provider doesn't support the pruning capability
403
+ * (`IPrunableSemanticMemoryProvider`).
404
+ */
405
+ compactSemanticMemory(ref: ResourceRef, opts?: CompactionOptions): Promise<CompactionResult>;
406
+ /**
407
+ * Copy a resource's current memory into a brand-new resource scope the child can mutate
408
+ * independently — the memory-layer counterpart to `sb.fork()`'s copy-on-write sandbox
409
+ * snapshot. Unlike `episodicRecall({branch: "lineage"})`, which reads the *parent's* history
410
+ * through the child's own lens without duplicating anything, this actually writes a real,
411
+ * independent copy: mutating the child's memory afterward never touches the parent's.
412
+ *
413
+ * Working memory is always copied in full. Semantic memory is copied only if the configured
414
+ * provider supports the pruning capability (`listAll` is what makes enumerating "everything
415
+ * to copy" possible) — see `ForkMemoryResult.semanticFactsCopied`. Copied semantic facts
416
+ * keep their original `content`/`sourceRef` (so `verified` is recomputed identically by
417
+ * whatever provider stores them) but get a fresh `id`/`rememberedAt` from the provider, same
418
+ * as any other `remember()` call.
419
+ *
420
+ * Both copy steps run their per-item writes concurrently (`Promise.all`), not sequentially.
421
+ * Semantic facts are additionally batched into one `embed()` call, not one per fact, when the
422
+ * provider supports the optional `IBulkSemanticMemoryProvider` capability (all three shipped
423
+ * providers do) — re-deriving vectors for content the provider already embedded once is
424
+ * otherwise a full round trip to the embedding API per fact.
425
+ *
426
+ * Does not read or write anything about the *sandbox* itself — call this alongside
427
+ * `sb.fork()`/`Alineo.spawn()`, not instead of it. `Alineo.spawn()` already calls this
428
+ * automatically when the parent agent has `.memory` configured.
429
+ */
430
+ fork(parentRef: ResourceRef, childResourceId: string): Promise<ForkMemoryResult>;
431
+ }
432
+ //#endregion
433
+ //#region src/lifecycle-hooks.d.ts
434
+ interface MemoryLifecycleHooksOptions {
435
+ /** Working-memory key the last checkpoint's metadata is stored under. */
436
+ checkpointKey?: string;
437
+ /** Working-memory key the most recently active sandboxId is stored under. */
438
+ sessionKey?: string;
439
+ /** Called when a working-memory write triggered by a hook fails. Hooks (per
440
+ * `@alineo-labs/core`'s own `composeHooks` convention) must never throw or reject
441
+ * unhandled — one broken write here must not break the sandbox operation that
442
+ * triggered it. Defaults to a no-op; the write is simply dropped. */
443
+ onError?: (error: unknown) => void;
444
+ }
445
+ /** Metadata recorded under `checkpointKey` by `onCheckpoint`. */
446
+ interface LastCheckpointRecord {
447
+ sandboxId: string;
448
+ snapshotId: string;
449
+ name?: string;
450
+ at: number;
451
+ }
452
+ /**
453
+ * Binds a `Memory` instance into a sandbox's lifecycle via the existing `SandboxHooks`
454
+ * extension point (`SandboxOptions.hooks`, composable with `composeHooks()`) rather than any
455
+ * change to `@alineo-labs/core`'s sandbox lifecycle code itself — the safest place to hang
456
+ * this: `SandboxHooks` already exists specifically so cross-cutting concerns like this one
457
+ * (otel tracing, billing, and now memory) can observe lifecycle events without core needing
458
+ * to know they exist.
459
+ *
460
+ * Records, in working memory scoped to `ref`:
461
+ * - the most recently active `sandboxId` for this resource (`onSandboxCreated`)
462
+ * - the most recent checkpoint's `{sandboxId, snapshotId, name, at}` (`onCheckpoint`)
463
+ *
464
+ * This does not restore or replay any state on resume — restoring a sandbox's filesystem
465
+ * from a snapshot is `@alineo-labs/core`'s job, not this package's. What it gives an agent is
466
+ * a durable answer to "what was the last checkpoint for this resource, across however many
467
+ * sandbox sessions it's had" without re-deriving it from the ledger every time.
468
+ *
469
+ * @example
470
+ * ```ts
471
+ * import { composeHooks } from "@alineo-labs/core";
472
+ * import { createMemoryLifecycleHooks } from "@alineo-labs/memory";
473
+ *
474
+ * const sb = await client.sandbox({
475
+ * image: "node:22",
476
+ * resources: { cpu: "500m", memory: "512Mi" },
477
+ * resourceId: ref.resourceId,
478
+ * hooks: composeHooks([createMemoryLifecycleHooks(memory, ref), otelHooks(tracer)]),
479
+ * });
480
+ * ```
481
+ */
482
+ declare function createMemoryLifecycleHooks(memory: Memory, ref: ResourceRef, opts?: MemoryLifecycleHooksOptions): SandboxHooks;
483
+ //#endregion
484
+ //#region src/schema-working-memory.d.ts
485
+ /**
486
+ * Minimal shape every popular schema library already satisfies (`ZodSchema.parse`,
487
+ * `valibot`'s `parse()` wrapper, a hand-rolled validator) — duck-typed the same way
488
+ * `EmbeddingProvider` is, so this package never depends on a concrete schema library. Throws
489
+ * on invalid input; the exact error type is whatever the underlying library throws.
490
+ */
491
+ interface SchemaValidator<T> {
492
+ parse(data: unknown): T;
493
+ }
494
+ /**
495
+ * A typed, validated profile stored as one working-memory record — the structured
496
+ * counterpart to `IWorkingMemoryProvider`'s raw untyped key/value pairs. Useful for the
497
+ * common "agent maintains a structured user profile" shape (name, preferences, goals) where
498
+ * raw key/value gives no guarantee about what's actually stored.
499
+ *
500
+ * Validation only fires on `update()`, not on `get()` — a profile written by an older schema
501
+ * version should still be readable (as `Partial<T>`, since it may be missing fields a newer
502
+ * schema requires) rather than throwing on every read after a schema change.
503
+ *
504
+ * @example
505
+ * ```ts
506
+ * import { z } from "zod";
507
+ * import { SchemaWorkingMemory } from "@alineo-labs/memory";
508
+ *
509
+ * const ProfileSchema = z.object({
510
+ * name: z.string().optional(),
511
+ * preferredLanguage: z.string().optional(),
512
+ * });
513
+ *
514
+ * const profile = new SchemaWorkingMemory(workingMemoryProvider, ProfileSchema);
515
+ * await profile.update(ref, { preferredLanguage: "TypeScript" });
516
+ * await profile.get(ref); // { preferredLanguage: "TypeScript" }
517
+ * ```
518
+ *
519
+ * Pass a schema that already tolerates partial input (e.g. Zod's own `.partial()`) if
520
+ * `update()` should succeed before every field has been filled in — this class imposes no
521
+ * partial/full policy of its own, it only merges and validates with whatever `schema` given.
522
+ */
523
+ declare class SchemaWorkingMemory<T extends Record<string, unknown>> {
524
+ private readonly provider;
525
+ private readonly schema;
526
+ /** Working-memory key the whole profile is stored under. */
527
+ private readonly key;
528
+ constructor(provider: IWorkingMemoryProvider, schema: SchemaValidator<T>, /** Working-memory key the whole profile is stored under. */
529
+
530
+ key?: string);
531
+ /** The stored profile, or `{}` if nothing has been set yet. Not re-validated on read. */
532
+ get(ref: ResourceRef): Promise<Partial<T>>;
533
+ /**
534
+ * Shallow-merge `patch` into the current profile, validate the result against `schema`, and
535
+ * persist it. Returns the validated (and possibly schema-transformed, e.g. defaults filled
536
+ * in) profile.
537
+ * @throws whatever `schema.parse()` throws if the merged object is invalid.
538
+ */
539
+ update(ref: ResourceRef, patch: Partial<T>): Promise<T>;
540
+ /** Remove the whole profile. */
541
+ clear(ref: ResourceRef): Promise<void>;
542
+ }
543
+ //#endregion
544
+ //#region src/tools.d.ts
545
+ /**
546
+ * A tool definition in the shape most agent-tool-calling conventions already expect: a name,
547
+ * a description the model reads to decide when to call it, a JSON Schema for its arguments,
548
+ * and an executor. Deliberately generic rather than typed against Pi's own RPC tool-call
549
+ * protocol — `alineo`'s Pi bridge (`packages/agent/src/adapters/pi-bridge.js`) doesn't yet
550
+ * expose a way to register caller-defined tools into a running Pi session, so wiring these
551
+ * into an actual live agent is left to the caller (or a follow-up change to the bridge).
552
+ * What this gives you today is the tool *definitions* ready to adapt into whatever surface —
553
+ * Pi once it supports it, a different agent framework, or a manual dispatch loop.
554
+ */
555
+ interface MemoryTool {
556
+ name: string;
557
+ description: string;
558
+ /** JSON Schema for the tool's arguments object. */
559
+ parameters: Record<string, unknown>;
560
+ execute(args: Record<string, unknown>): Promise<unknown>;
561
+ }
562
+ /**
563
+ * Build the standard set of memory tools for one resource: working-memory get/set, and (only
564
+ * when `memory.hasSemanticMemory`) remember/recall. This is what lets a *model*, not just the
565
+ * surrounding application code, decide to persist or retrieve a fact mid-conversation — the
566
+ * gap left by `Memory` being a plain TS API a developer must call explicitly.
567
+ */
568
+ declare function createMemoryTools(memory: Memory, ref: ResourceRef): MemoryTool[];
569
+ //#endregion
570
+ //#region src/pipeline.d.ts
571
+ interface ContextSnippetOptions {
572
+ /** Run semantic recall against this query and fold the results in. Omit to skip semantic
573
+ * recall entirely (e.g. no semantic provider configured, or nothing relevant to search for
574
+ * yet — a fresh session with no user message). */
575
+ query?: string;
576
+ /** Max facts to pull from semantic recall. Passed through to `Memory.recall()`. */
577
+ topK?: number;
578
+ /** Cap how many working-memory keys are included, in case a resource has accumulated many. */
579
+ maxWorkingMemoryKeys?: number;
580
+ }
581
+ /**
582
+ * Assemble a plain-text context block from a resource's working + semantic memory — the
583
+ * "inject relevant memory into the prompt on session start" half of owning the memory
584
+ * pipeline, previously entirely missing (the package shipped only the primitives an app had
585
+ * to remember to call). Returns `""` if there's nothing to say (fresh resource, no query).
586
+ *
587
+ * This builds the string; it does not inject it anywhere on its own — `alineo`'s Pi bridge has
588
+ * no hook today for prepending to a session's system prompt, so wiring the result of this into
589
+ * an actual agent conversation is left to the caller (e.g. prepend it to the first `prompt()`
590
+ * call, or fold it into `AgentSpec.env`/setup for now).
591
+ *
592
+ * @example
593
+ * ```ts
594
+ * const context = await buildContextSnippet(memory, agent.resourceRef, { query: userMessage });
595
+ * for await (const chunk of agent.prompt(context ? `${context}\n\n${userMessage}` : userMessage)) { ... }
596
+ * ```
597
+ */
598
+ declare function buildContextSnippet(memory: Memory, ref: ResourceRef, opts?: ContextSnippetOptions): Promise<string>;
599
+ //#endregion
600
+ //#region src/access-control.d.ts
601
+ declare class MemoryAccessDeniedError extends Error {
602
+ readonly teamId: string;
603
+ constructor(teamId: string);
604
+ }
605
+ /**
606
+ * Authorization check for team-scoped memory access. Deliberately minimal — one method,
607
+ * caller decides how "can access" is determined (a JWT claim, a database lookup, a static
608
+ * allowlist). This package never assumes a concrete auth mechanism.
609
+ */
610
+ interface TeamAccessChecker {
611
+ /** Return `true` if the current caller may access data scoped to this `teamId`. */
612
+ canAccess(teamId: string): boolean | Promise<boolean>;
613
+ }
614
+ /**
615
+ * Wrap an `IWorkingMemoryProvider` with app-layer team-scoping enforcement, checked before
616
+ * every call. `@alineo-labs/postgres-memory` enforces `teamId` isolation at the database
617
+ * layer via row-level security; every other provider (in-memory, `@alineo-labs/sqlite-memory`)
618
+ * only isolates `teamId` structurally — `ResourceRef.teamId` folds into the storage key, so
619
+ * data for one team simply doesn't collide with another's, but nothing stops a caller passing
620
+ * the "wrong" `teamId` on purpose from reading it. This closes that gap for any backend,
621
+ * making the enforcement guarantee backend-independent rather than something only a Postgres
622
+ * deployment gets — and a Postgres deployment can still layer this on top of its own RLS for
623
+ * defense-in-depth, it isn't an either/or.
624
+ *
625
+ * A `ResourceRef` with no `teamId` always passes through untouched — there's nothing to check
626
+ * for an untenanted resource.
627
+ */
628
+ declare function withTeamAccessControl(provider: IWorkingMemoryProvider, checker: TeamAccessChecker): IWorkingMemoryProvider;
629
+ /**
630
+ * Which of `ISemanticMemoryProvider`'s optional capability interfaces `withTeamAccessControlSemantic`
631
+ * returns, computed from what the *input* provider actually implements — never the input's
632
+ * own concrete class. That distinction is load-bearing: the previous version of this function
633
+ * returned `T` (the caller's exact concrete provider type) via `as unknown as T`, which let
634
+ * `T` be inferred as a class with extra methods (e.g. a `.close()` a real provider exposes but
635
+ * neither `ISemanticMemoryProvider` nor this wrapper's returned object ever implements) —
636
+ * calling one of those through the "typed" result would throw at runtime with no compiler
637
+ * warning. Every branch below is a real interface the returned object literal actually
638
+ * satisfies structurally, so no unsafe cast is needed at the call site — only internally, where
639
+ * TypeScript can't otherwise prove a dynamically-assembled object matches a conditional type.
640
+ */
641
+ type TeamGuardedSemanticProvider<T extends ISemanticMemoryProvider> = T extends IPrunableSemanticMemoryProvider & IBulkSemanticMemoryProvider ? IPrunableSemanticMemoryProvider & IBulkSemanticMemoryProvider : T extends IPrunableSemanticMemoryProvider ? IPrunableSemanticMemoryProvider : T extends IBulkSemanticMemoryProvider ? IBulkSemanticMemoryProvider : ISemanticMemoryProvider;
642
+ /**
643
+ * Same enforcement for `ISemanticMemoryProvider`. Preserves whichever optional capabilities
644
+ * the wrapped provider has (`IPrunableSemanticMemoryProvider`, `IBulkSemanticMemoryProvider`) —
645
+ * `isPrunable()`/`isBulkRememberable()` still report correctly against the wrapped result, so
646
+ * `compactSemanticMemory()` and `Memory.fork()`'s batched-embed path keep working through the
647
+ * wrapper. See `TeamGuardedSemanticProvider` for why the return type is never just `T`.
648
+ */
649
+ declare function withTeamAccessControlSemantic<T extends ISemanticMemoryProvider>(provider: T, checker: TeamAccessChecker): TeamGuardedSemanticProvider<T>;
650
+ //#endregion
651
+ export { type AutoCompactOptions, type CompactionOptions, type CompactionResult, type ContextSnippetOptions, type EmbeddingProvider, type EpisodicBranch, type EpisodicRecallOptions, type EpisodicTreeOptions, type ForkMemoryResult, type IBulkSemanticMemoryProvider, type IPrunableSemanticMemoryProvider, type ISemanticMemoryProvider, type IWorkingMemoryProvider, InMemorySemanticMemoryProvider, InMemoryWorkingMemoryProvider, type LastCheckpointRecord, Memory, MemoryAccessDeniedError, type MemoryCapability, MemoryCapabilityError, type MemoryFact, type MemoryLifecycleHooksOptions, type MemoryOptions, type MemoryTool, type RememberedFact, type ResourceRef, type SandboxSessionRef, type SchemaValidator, SchemaWorkingMemory, type SemanticFactRow, type TeamAccessChecker, buildContextSnippet, compactSemanticMemory, cosineSimilarity, createMemoryLifecycleHooks, createMemoryTools, episodicRecall, episodicTree, factFromRow, isBulkRememberable, isPrunable, scopeKey, withTeamAccessControl, withTeamAccessControlSemantic };