@effect-agent/storage-memory 0.1.0-beta.9 → 0.1.0-beta.91

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/MemoryMessageDeliveryStore.d.mts +15 -0
  2. package/dist/MemoryMessageDeliveryStore.mjs +147 -0
  3. package/dist/MemoryMessageDeliveryStore.mjs.map +1 -0
  4. package/dist/MemoryScheduleStore.d.mts +10 -0
  5. package/dist/MemoryScheduleStore.mjs +169 -0
  6. package/dist/MemoryScheduleStore.mjs.map +1 -0
  7. package/dist/MemorySemanticIndex.d.mts +21 -0
  8. package/dist/MemorySemanticIndex.mjs +222 -0
  9. package/dist/MemorySemanticIndex.mjs.map +1 -0
  10. package/dist/MemorySubmissionLedger.d.mts +24 -0
  11. package/dist/MemorySubmissionLedger.mjs +1058 -0
  12. package/dist/MemorySubmissionLedger.mjs.map +1 -0
  13. package/dist/MemorySubscriptionStore.d.mts +9 -0
  14. package/dist/MemorySubscriptionStore.mjs +849 -0
  15. package/dist/MemorySubscriptionStore.mjs.map +1 -0
  16. package/dist/MemoryThreadStore.d.mts +17 -0
  17. package/dist/MemoryThreadStore.mjs +377 -0
  18. package/dist/MemoryThreadStore.mjs.map +1 -0
  19. package/dist/index.d.mts +7 -30
  20. package/dist/index.mjs +7 -1298
  21. package/dist/rolldown-runtime-D7D4PA-g.mjs +13 -0
  22. package/package.json +1 -45
  23. package/src/MemoryMessageDeliveryStore.ts +293 -0
  24. package/src/MemoryScheduleStore.ts +328 -0
  25. package/src/MemorySemanticIndex.ts +357 -0
  26. package/src/{memory-ledger.ts → MemorySubmissionLedger.ts} +478 -86
  27. package/src/MemorySubscriptionStore.ts +1549 -0
  28. package/src/MemoryThreadStore.ts +766 -0
  29. package/src/index.ts +6 -2
  30. package/dist/index.mjs.map +0 -1
  31. package/dist/testing.d.mts +0 -2
  32. package/dist/testing.mjs +0 -2
  33. package/src/memory-storage.ts +0 -614
  34. package/src/testing.ts +0 -10
@@ -0,0 +1,357 @@
1
+ import { Clock, Effect, Encoding, Layer, Ref, Schema } from "effect";
2
+ import { MemoryKey } from "effect-agent/memory-store";
3
+ import {
4
+ MemoryIndexCandidate,
5
+ MemoryIndexError,
6
+ MemoryIndexQuery,
7
+ MemoryIndexReplacement,
8
+ MemoryIndexSearch,
9
+ MemoryIndexSource,
10
+ SemanticMemoryChunk,
11
+ SemanticMemoryIndex,
12
+ SemanticMemoryProfile,
13
+ } from "effect-agent/semantic-memory-index";
14
+
15
+ const PositiveCapacity = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65_536 }));
16
+ const MaxStoredVectorComponents = 16_777_216;
17
+
18
+ /**
19
+ * Hard per-Layer bounds for disposable semantic index state. maxChunks times profile dimensions
20
+ * must not exceed 16,777,216 vector components. maxSourceBytes bounds the aggregate UTF-8 JSON
21
+ * of retained source identities and defaults to 16 MiB; it is not a general heap limit.
22
+ */
23
+ export class InMemorySemanticIndexCapacity extends Schema.Class<InMemorySemanticIndexCapacity>(
24
+ "@effect-agent/storage-memory/InMemorySemanticIndexCapacity",
25
+ )({
26
+ maxSources: PositiveCapacity,
27
+ maxChunks: PositiveCapacity,
28
+ maxSourceBytes: Schema.optionalKey(
29
+ Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 67_108_864 })),
30
+ ),
31
+ }) {}
32
+
33
+ type StoredEntry = {
34
+ readonly source: MemoryIndexSource;
35
+ readonly sourceBytes: number;
36
+ } & (
37
+ | {
38
+ readonly _tag: "Indexed";
39
+ readonly chunks: ReadonlyArray<SemanticMemoryChunk>;
40
+ readonly indexedAt: number;
41
+ }
42
+ | { readonly _tag: "Withdrawn" }
43
+ );
44
+
45
+ interface IndexData {
46
+ readonly closed: boolean;
47
+ readonly entries: ReadonlyMap<string, StoredEntry>;
48
+ readonly sourceBytes: number;
49
+ }
50
+
51
+ const sameProfile = Schema.toEquivalence(SemanticMemoryProfile);
52
+ const sameSource = Schema.toEquivalence(MemoryIndexSource.Wire);
53
+
54
+ const error = (operation: string, reason: MemoryIndexError["reason"]): MemoryIndexError =>
55
+ MemoryIndexError.make({ operation, reason });
56
+
57
+ const keyString = (key: MemoryKey): string => JSON.stringify([key.namespace.address, key.id]);
58
+
59
+ const sourceIdentityBytes = (source: MemoryIndexSource): number =>
60
+ Encoding.encodeHex(JSON.stringify(source)).length / 2;
61
+
62
+ const decodeBoundary = Effect.fn("InMemorySemanticIndex.decodeBoundary")(function* <A, I>(
63
+ schema: Schema.Codec<A, I, never>,
64
+ value: unknown,
65
+ operation: string,
66
+ ): Effect.fn.Return<A, MemoryIndexError> {
67
+ return yield* Schema.decodeUnknownEffect(schema)(value).pipe(
68
+ Effect.flatMap((decoded) => Schema.encodeEffect(schema)(decoded).pipe(Effect.as(decoded))),
69
+ Effect.mapError(() => error(operation, "invalid-input")),
70
+ );
71
+ });
72
+
73
+ const freezeSource = (source: MemoryIndexSource): MemoryIndexSource =>
74
+ Object.freeze(
75
+ MemoryIndexSource.make({
76
+ key: Object.freeze(
77
+ MemoryKey.make({
78
+ ...source.key,
79
+ namespace: Object.freeze({ address: source.key.namespace.address }),
80
+ }),
81
+ ),
82
+ source: Object.freeze({ ...source.source }),
83
+ sourceGeneration: source.sourceGeneration,
84
+ }),
85
+ );
86
+
87
+ const freezeChunk = (chunk: SemanticMemoryChunk): SemanticMemoryChunk =>
88
+ Object.freeze(SemanticMemoryChunk.make({ ...chunk, vector: Object.freeze([...chunk.vector]) }));
89
+
90
+ const sourceIsFenced = (source: MemoryIndexSource, existing: StoredEntry): boolean =>
91
+ source.sourceGeneration < existing.source.sourceGeneration ||
92
+ (source.sourceGeneration === existing.source.sourceGeneration &&
93
+ !sameSource(source, existing.source));
94
+
95
+ const squaredNorm = (vector: ReadonlyArray<number>): number | null => {
96
+ let sum = 0;
97
+
98
+ for (const value of vector) {
99
+ sum += value * value;
100
+ if (!Number.isFinite(sum)) return null;
101
+ }
102
+
103
+ return sum > 0 ? sum : null;
104
+ };
105
+
106
+ const validVector = (vector: ReadonlyArray<number>, profile: SemanticMemoryProfile): boolean =>
107
+ vector.length === profile.dimensions && squaredNorm(vector) !== null;
108
+
109
+ const validateChunks = Effect.fn("InMemorySemanticIndex.validateChunks")(function* (
110
+ chunks: ReadonlyArray<SemanticMemoryChunk>,
111
+ profile: SemanticMemoryProfile,
112
+ operation: string,
113
+ ): Effect.fn.Return<void, MemoryIndexError> {
114
+ let nextByte = 0;
115
+ const passageIds = new Set<string>();
116
+
117
+ for (let index = 0; index < chunks.length; index++) {
118
+ const chunk = chunks[index];
119
+ const byteLength = Encoding.encodeHex(chunk.text).length / 2;
120
+
121
+ if (
122
+ chunk.ordinal !== index ||
123
+ chunk.startByte !== nextByte ||
124
+ chunk.endByte <= chunk.startByte ||
125
+ chunk.endByte - chunk.startByte !== byteLength ||
126
+ byteLength > profile.maxChunkBytes ||
127
+ passageIds.has(chunk.passageId) ||
128
+ !validVector(chunk.vector, profile)
129
+ ) {
130
+ return yield* error(operation, "invalid-input");
131
+ }
132
+ passageIds.add(chunk.passageId);
133
+ nextByte = chunk.endByte;
134
+ }
135
+ });
136
+
137
+ const cosine = (left: ReadonlyArray<number>, right: ReadonlyArray<number>): number => {
138
+ const leftNorm = Math.sqrt(squaredNorm(left) ?? 1);
139
+ const rightNorm = Math.sqrt(squaredNorm(right) ?? 1);
140
+ let score = 0;
141
+
142
+ for (let index = 0; index < left.length; index++) {
143
+ score += (left[index] / leftNorm) * (right[index] / rightNorm);
144
+ }
145
+ const bounded = Math.max(-1, Math.min(1, score));
146
+
147
+ return bounded === 0 ? 0 : bounded;
148
+ };
149
+
150
+ const compareText = (left: string, right: string): number =>
151
+ left < right ? -1 : left > right ? 1 : 0;
152
+
153
+ const makeIndex = Effect.fn("InMemorySemanticIndex.make")(function* (
154
+ rawProfile: SemanticMemoryProfile,
155
+ rawCapacity: InMemorySemanticIndexCapacity,
156
+ ) {
157
+ const profile = Object.freeze(
158
+ SemanticMemoryProfile.make({
159
+ ...(yield* decodeBoundary(
160
+ SemanticMemoryProfile,
161
+ rawProfile,
162
+ "configure semantic memory index",
163
+ )),
164
+ }),
165
+ );
166
+
167
+ const capacity = yield* decodeBoundary(
168
+ InMemorySemanticIndexCapacity,
169
+ rawCapacity,
170
+ "configure semantic memory index",
171
+ );
172
+
173
+ if (capacity.maxChunks * profile.dimensions > MaxStoredVectorComponents) {
174
+ return yield* error("configure semantic memory index", "invalid-input");
175
+ }
176
+ const maxSourceBytes = capacity.maxSourceBytes ?? 16_777_216;
177
+ const data = yield* Ref.make<IndexData>({ closed: false, entries: new Map(), sourceBytes: 0 });
178
+
179
+ yield* Effect.addFinalizer(() =>
180
+ Ref.set(data, { closed: true, entries: new Map(), sourceBytes: 0 }),
181
+ );
182
+
183
+ const ensureOpen = Effect.fn("InMemorySemanticIndex.ensureOpen")(function* (operation: string) {
184
+ if ((yield* Ref.get(data)).closed) return yield* error(operation, "unavailable");
185
+ });
186
+
187
+ const replace: SemanticMemoryIndex["Service"]["replace"] = Effect.fn(
188
+ "InMemorySemanticIndex.replace",
189
+ )(function* (rawRequest) {
190
+ const operation = "replace semantic memory source";
191
+
192
+ yield* ensureOpen(operation);
193
+ const request = yield* decodeBoundary(MemoryIndexReplacement.Wire, rawRequest, operation);
194
+ const source = freezeSource(request.source);
195
+ const sourceBytes = sourceIdentityBytes(source);
196
+ const chunks = Object.freeze(request.chunks.map(freezeChunk));
197
+
198
+ if (source.source.id !== source.key.id) return yield* error(operation, "invalid-input");
199
+ if (!sameProfile(request.profile, profile)) return yield* error(operation, "incompatible");
200
+ yield* validateChunks(chunks, profile, operation);
201
+ const indexedAt = yield* Clock.currentTimeMillis;
202
+
203
+ const failure = yield* Ref.modify(
204
+ data,
205
+ (current): readonly [MemoryIndexError | undefined, IndexData] => {
206
+ if (current.closed) return [error(operation, "unavailable"), current];
207
+ const id = keyString(source.key);
208
+ const existing = current.entries.get(id);
209
+
210
+ if (
211
+ existing !== undefined &&
212
+ (existing._tag === "Withdrawn" || sourceIsFenced(source, existing))
213
+ ) {
214
+ return [error(operation, "fenced"), current];
215
+ }
216
+ if (existing === undefined && current.entries.size >= capacity.maxSources) {
217
+ return [error(operation, "budget"), current];
218
+ }
219
+ const nextSourceBytes = current.sourceBytes - (existing?.sourceBytes ?? 0) + sourceBytes;
220
+
221
+ if (nextSourceBytes > maxSourceBytes) return [error(operation, "budget"), current];
222
+ let count = chunks.length;
223
+
224
+ for (const [entryId, entry] of current.entries) {
225
+ if (entryId !== id && entry._tag === "Indexed") count += entry.chunks.length;
226
+ }
227
+ if (count > capacity.maxChunks) return [error(operation, "budget"), current];
228
+ const entries = new Map(current.entries);
229
+
230
+ entries.set(id, { _tag: "Indexed", source, sourceBytes, chunks, indexedAt });
231
+
232
+ return [undefined, { ...current, entries, sourceBytes: nextSourceBytes }];
233
+ },
234
+ );
235
+
236
+ if (failure !== undefined) return yield* failure;
237
+ });
238
+
239
+ const withdraw: SemanticMemoryIndex["Service"]["withdraw"] = Effect.fn(
240
+ "InMemorySemanticIndex.withdraw",
241
+ )(function* (rawSource) {
242
+ const operation = "withdraw semantic memory source";
243
+
244
+ yield* ensureOpen(operation);
245
+
246
+ const source = freezeSource(
247
+ yield* decodeBoundary(MemoryIndexSource.Wire, rawSource, operation),
248
+ );
249
+
250
+ const sourceBytes = sourceIdentityBytes(source);
251
+
252
+ if (source.source.id !== source.key.id) return yield* error(operation, "invalid-input");
253
+
254
+ const failure = yield* Ref.modify(
255
+ data,
256
+ (current): readonly [MemoryIndexError | undefined, IndexData] => {
257
+ if (current.closed) return [error(operation, "unavailable"), current];
258
+ const id = keyString(source.key);
259
+ const existing = current.entries.get(id);
260
+
261
+ if (existing !== undefined) {
262
+ if (existing._tag === "Withdrawn") {
263
+ return [
264
+ sameSource(source, existing.source) ? undefined : error(operation, "fenced"),
265
+ current,
266
+ ];
267
+ }
268
+ if (sourceIsFenced(source, existing)) return [error(operation, "fenced"), current];
269
+ } else if (current.entries.size >= capacity.maxSources) {
270
+ return [error(operation, "budget"), current];
271
+ }
272
+ const nextSourceBytes = current.sourceBytes - (existing?.sourceBytes ?? 0) + sourceBytes;
273
+
274
+ if (nextSourceBytes > maxSourceBytes) return [error(operation, "budget"), current];
275
+ const entries = new Map(current.entries);
276
+
277
+ entries.set(id, { _tag: "Withdrawn", source, sourceBytes });
278
+
279
+ return [undefined, { ...current, entries, sourceBytes: nextSourceBytes }];
280
+ },
281
+ );
282
+
283
+ if (failure !== undefined) return yield* failure;
284
+ });
285
+
286
+ const search = Effect.fn("InMemorySemanticIndex.search")(function* (rawQuery: MemoryIndexQuery) {
287
+ const operation = "search semantic memory index";
288
+
289
+ yield* ensureOpen(operation);
290
+ const query = yield* decodeBoundary(MemoryIndexQuery.Wire, rawQuery, operation);
291
+ const vector = Object.freeze([...query.vector]);
292
+
293
+ if (!validVector(vector, profile)) return yield* error(operation, "invalid-input");
294
+ const current = yield* Ref.get(data);
295
+
296
+ if (current.closed) return yield* error(operation, "unavailable");
297
+ let scannedChunks = 0;
298
+ let inspectedSources = 0;
299
+ const candidates: Array<MemoryIndexCandidate> = [];
300
+
301
+ for (const entry of current.entries.values()) {
302
+ inspectedSources += 1;
303
+ if (inspectedSources % 128 === 0) yield* Effect.yieldNow;
304
+ if (
305
+ entry.source.key.namespace.address !== query.namespace.address ||
306
+ entry._tag !== "Indexed"
307
+ )
308
+ continue;
309
+ scannedChunks += entry.chunks.length;
310
+ if (scannedChunks > query.maxScannedChunks) return yield* error(operation, "budget");
311
+ }
312
+ for (const entry of current.entries.values()) {
313
+ if (
314
+ entry.source.key.namespace.address !== query.namespace.address ||
315
+ entry._tag !== "Indexed"
316
+ )
317
+ continue;
318
+ yield* Effect.yieldNow;
319
+ for (const chunk of entry.chunks) {
320
+ const score = cosine(vector, chunk.vector);
321
+
322
+ if (score < query.minScore) continue;
323
+ candidates.push(
324
+ MemoryIndexCandidate.make({
325
+ ...entry.source,
326
+ passageId: chunk.passageId,
327
+ ordinal: chunk.ordinal,
328
+ startByte: chunk.startByte,
329
+ endByte: chunk.endByte,
330
+ text: chunk.text,
331
+ score,
332
+ indexedAt: entry.indexedAt,
333
+ }),
334
+ );
335
+ }
336
+ }
337
+ candidates.sort(
338
+ (left, right) =>
339
+ right.score - left.score ||
340
+ compareText(left.key.id, right.key.id) ||
341
+ compareText(left.source.revision, right.source.revision) ||
342
+ left.ordinal - right.ordinal,
343
+ );
344
+ yield* ensureOpen(operation);
345
+
346
+ return MemoryIndexSearch.make({ candidates: candidates.slice(0, query.limit), scannedChunks });
347
+ });
348
+
349
+ return SemanticMemoryIndex.fromAdapter({ profile, replace, withdraw, search });
350
+ });
351
+
352
+ /** Scoped disposable semantic index. No persistent build or recovery state is retained. */
353
+ export const inMemorySemanticIndexLayer = (
354
+ profile: SemanticMemoryProfile,
355
+ capacity: InMemorySemanticIndexCapacity,
356
+ ): Layer.Layer<SemanticMemoryIndex, MemoryIndexError> =>
357
+ Layer.effect(SemanticMemoryIndex, makeIndex(profile, capacity));