@agentskit/memory 0.5.5 → 0.7.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.js CHANGED
@@ -87,6 +87,78 @@ function sqliteChatMemory(config) {
87
87
  }
88
88
  };
89
89
  }
90
+ var cachedSdk = null;
91
+ async function loadSdk() {
92
+ if (!cachedSdk) {
93
+ cachedSdk = (async () => {
94
+ try {
95
+ const moduleId = "@libsql/client";
96
+ return await import(
97
+ /* @vite-ignore */
98
+ moduleId
99
+ );
100
+ } catch {
101
+ throw new Error("Install @libsql/client to use tursoChatMemory: npm install @libsql/client");
102
+ }
103
+ })();
104
+ }
105
+ return cachedSdk;
106
+ }
107
+ function encodeMessages2(messages) {
108
+ return JSON.stringify(serializeMessages(messages));
109
+ }
110
+ function decodeMessages2(json) {
111
+ if (!json) return [];
112
+ try {
113
+ return deserializeMessages(JSON.parse(json));
114
+ } catch {
115
+ return [];
116
+ }
117
+ }
118
+ function tursoChatMemory(config) {
119
+ const conversationId = config.conversationId ?? "default";
120
+ let clientPromise = null;
121
+ const getClient = async () => {
122
+ if (!clientPromise) {
123
+ clientPromise = (async () => {
124
+ const sdk = await loadSdk();
125
+ const client = sdk.createClient({ url: config.url, authToken: config.authToken });
126
+ await client.execute({
127
+ sql: "CREATE TABLE IF NOT EXISTS conversations (id TEXT PRIMARY KEY, messages TEXT NOT NULL)"
128
+ });
129
+ return client;
130
+ })();
131
+ }
132
+ return clientPromise;
133
+ };
134
+ return {
135
+ async load() {
136
+ const client = await getClient();
137
+ const result = await client.execute({
138
+ sql: "SELECT messages FROM conversations WHERE id = ?",
139
+ args: [conversationId]
140
+ });
141
+ const row = result.rows[0];
142
+ return decodeMessages2(row?.messages);
143
+ },
144
+ async save(messages) {
145
+ const client = await getClient();
146
+ const json = encodeMessages2(messages);
147
+ await client.execute({
148
+ sql: `INSERT INTO conversations (id, messages) VALUES (?, ?)
149
+ ON CONFLICT(id) DO UPDATE SET messages = excluded.messages`,
150
+ args: [conversationId, json]
151
+ });
152
+ },
153
+ async clear() {
154
+ const client = await getClient();
155
+ await client.execute({
156
+ sql: "DELETE FROM conversations WHERE id = ?",
157
+ args: [conversationId]
158
+ });
159
+ }
160
+ };
161
+ }
90
162
 
91
163
  // src/redis-client.ts
92
164
  async function createRedisClientAdapter(url) {
@@ -122,10 +194,10 @@ async function createRedisClientAdapter(url) {
122
194
  }
123
195
 
124
196
  // src/redis-chat.ts
125
- function encodeMessages2(messages) {
197
+ function encodeMessages3(messages) {
126
198
  return JSON.stringify(serializeMessages(messages));
127
199
  }
128
- function decodeMessages2(json) {
200
+ function decodeMessages3(json) {
129
201
  if (!json) return [];
130
202
  try {
131
203
  return deserializeMessages(JSON.parse(json));
@@ -147,11 +219,11 @@ function redisChatMemory(config) {
147
219
  async load() {
148
220
  const client = await getClient();
149
221
  const json = await client.get(key);
150
- return decodeMessages2(json);
222
+ return decodeMessages3(json);
151
223
  },
152
224
  async save(messages) {
153
225
  const client = await getClient();
154
- await client.set(key, encodeMessages2(messages));
226
+ await client.set(key, encodeMessages3(messages));
155
227
  },
156
228
  async clear() {
157
229
  const client = await getClient();
@@ -281,6 +353,40 @@ function redisVectorMemory(config) {
281
353
  };
282
354
  }
283
355
 
356
+ // src/vector/filter.ts
357
+ function isPrimitive(value) {
358
+ const t = typeof value;
359
+ return value === null || t === "string" || t === "number" || t === "boolean";
360
+ }
361
+ function evalOperator(actual, op) {
362
+ if ("$eq" in op) return actual === op.$eq;
363
+ if ("$ne" in op) return actual !== op.$ne;
364
+ if ("$in" in op) return op.$in.includes(actual);
365
+ if ("$nin" in op) return !op.$nin.includes(actual);
366
+ if ("$gt" in op) return actual > op.$gt;
367
+ if ("$gte" in op) return actual >= op.$gte;
368
+ if ("$lt" in op) return actual < op.$lt;
369
+ if ("$lte" in op) return actual <= op.$lte;
370
+ if ("$exists" in op) return actual !== void 0 === op.$exists;
371
+ return false;
372
+ }
373
+ function evalPredicate(actual, predicate) {
374
+ if (isPrimitive(predicate)) return actual === predicate;
375
+ return evalOperator(actual, predicate);
376
+ }
377
+ function matchesFilter(metadata, filter) {
378
+ if (!filter) return true;
379
+ const meta = metadata ?? {};
380
+ const compound = filter;
381
+ if (compound.$and) return compound.$and.every((f) => matchesFilter(meta, f));
382
+ if (compound.$or) return compound.$or.some((f) => matchesFilter(meta, f));
383
+ for (const [field, predicate] of Object.entries(filter)) {
384
+ if (field.startsWith("$")) continue;
385
+ if (!evalPredicate(meta[field], predicate)) return false;
386
+ }
387
+ return true;
388
+ }
389
+
284
390
  // src/file-vector.ts
285
391
  function requireVectra() {
286
392
  try {
@@ -349,8 +455,9 @@ function fileVectorMemory(config) {
349
455
  async search(embedding, options) {
350
456
  const topK = options?.topK ?? 5;
351
457
  const threshold = options?.threshold ?? 0;
352
- const results = await store.query(embedding, topK);
353
- return results.filter((r) => r.score >= threshold).map((r) => ({
458
+ const fetchK = options?.filter ? Math.max(topK * 4, 50) : topK;
459
+ const results = await store.query(embedding, fetchK);
460
+ return results.filter((r) => r.score >= threshold).filter((r) => matchesFilter(r.metadata, options?.filter)).slice(0, topK).map((r) => ({
354
461
  id: r.id,
355
462
  content: String(r.metadata.content ?? contentCache.get(r.id) ?? ""),
356
463
  score: r.score,
@@ -364,6 +471,581 @@ function fileVectorMemory(config) {
364
471
  };
365
472
  }
366
473
 
367
- export { fileChatMemory, fileVectorMemory, redisChatMemory, redisVectorMemory, sqliteChatMemory };
474
+ // src/personalization.ts
475
+ function createInMemoryPersonalization() {
476
+ const profiles = /* @__PURE__ */ new Map();
477
+ return {
478
+ async get(subjectId) {
479
+ const hit = profiles.get(subjectId);
480
+ return hit ? { ...hit, traits: { ...hit.traits } } : null;
481
+ },
482
+ async set(profile) {
483
+ profiles.set(profile.subjectId, {
484
+ ...profile,
485
+ traits: { ...profile.traits },
486
+ updatedAt: profile.updatedAt || (/* @__PURE__ */ new Date()).toISOString()
487
+ });
488
+ },
489
+ async merge(subjectId, traits) {
490
+ const existing = profiles.get(subjectId);
491
+ const next = {
492
+ subjectId,
493
+ traits: { ...existing?.traits ?? {}, ...traits },
494
+ updatedAt: (/* @__PURE__ */ new Date()).toISOString()
495
+ };
496
+ profiles.set(subjectId, next);
497
+ return { ...next, traits: { ...next.traits } };
498
+ },
499
+ async delete(subjectId) {
500
+ profiles.delete(subjectId);
501
+ }
502
+ };
503
+ }
504
+ function renderProfileContext(profile) {
505
+ if (!profile || Object.keys(profile.traits).length === 0) return "";
506
+ const lines = Object.entries(profile.traits).filter(([, value]) => value !== void 0 && value !== null && value !== "").map(([key, value]) => `- ${key}: ${typeof value === "string" ? value : JSON.stringify(value)}`);
507
+ if (lines.length === 0) return "";
508
+ return `## User profile
509
+ ${lines.join("\n")}`;
510
+ }
511
+
512
+ // src/graph.ts
513
+ function createInMemoryGraph() {
514
+ const nodes = /* @__PURE__ */ new Map();
515
+ const edges = /* @__PURE__ */ new Map();
516
+ const matchesNode = (node, query) => {
517
+ if (!query) return true;
518
+ if (query.kind && node.kind !== query.kind) return false;
519
+ return true;
520
+ };
521
+ const matchesEdge = (edge, query) => {
522
+ if (!query) return true;
523
+ if (query.label && edge.label !== query.label) return false;
524
+ if (query.from && edge.from !== query.from) return false;
525
+ if (query.to && edge.to !== query.to) return false;
526
+ return true;
527
+ };
528
+ return {
529
+ async upsertNode(node) {
530
+ const now = (/* @__PURE__ */ new Date()).toISOString();
531
+ const existing = nodes.get(node.id);
532
+ const merged = {
533
+ ...existing ?? {},
534
+ ...node,
535
+ createdAt: existing?.createdAt ?? now,
536
+ updatedAt: now
537
+ };
538
+ nodes.set(node.id, merged);
539
+ return merged;
540
+ },
541
+ async upsertEdge(edge) {
542
+ edges.set(edge.id, edge);
543
+ return edge;
544
+ },
545
+ async getNode(id) {
546
+ const hit = nodes.get(id);
547
+ return hit ? { ...hit } : null;
548
+ },
549
+ async findNodes(query) {
550
+ return Array.from(nodes.values()).filter((n) => matchesNode(n, query)).map((n) => ({ ...n }));
551
+ },
552
+ async findEdges(query) {
553
+ return Array.from(edges.values()).filter((e) => matchesEdge(e, query)).map((e) => ({ ...e }));
554
+ },
555
+ async neighbors(id, options = {}) {
556
+ const depth = Math.max(1, options.depth ?? 1);
557
+ const visited = /* @__PURE__ */ new Set([id]);
558
+ let frontier = /* @__PURE__ */ new Set([id]);
559
+ for (let i = 0; i < depth; i++) {
560
+ const next = /* @__PURE__ */ new Set();
561
+ for (const edge of edges.values()) {
562
+ if (options.label && edge.label !== options.label) continue;
563
+ if (frontier.has(edge.from) && !visited.has(edge.to)) next.add(edge.to);
564
+ if (frontier.has(edge.to) && !visited.has(edge.from)) next.add(edge.from);
565
+ }
566
+ for (const n of next) visited.add(n);
567
+ frontier = next;
568
+ if (next.size === 0) break;
569
+ }
570
+ visited.delete(id);
571
+ return Array.from(visited, (nid) => nodes.get(nid)).filter((n) => Boolean(n)).map((n) => ({ ...n }));
572
+ },
573
+ async deleteNode(id) {
574
+ nodes.delete(id);
575
+ for (const [eid, edge] of edges) {
576
+ if (edge.from === id || edge.to === id) edges.delete(eid);
577
+ }
578
+ },
579
+ async deleteEdge(id) {
580
+ edges.delete(id);
581
+ },
582
+ async clear() {
583
+ nodes.clear();
584
+ edges.clear();
585
+ }
586
+ };
587
+ }
588
+
589
+ // src/vector/pgvector.ts
590
+ function formatVector(embedding) {
591
+ return `[${embedding.join(",")}]`;
592
+ }
593
+ function pgvector(config) {
594
+ const table = config.table ?? "agentskit_vectors";
595
+ const defaultTopK = Math.max(1, config.topK ?? 10);
596
+ return {
597
+ async store(docs) {
598
+ if (docs.length === 0) return;
599
+ const values = [];
600
+ const placeholders = docs.map((doc, i) => {
601
+ const base = i * 4;
602
+ values.push(doc.id, doc.content, formatVector(doc.embedding), JSON.stringify(doc.metadata ?? {}));
603
+ return `($${base + 1}, $${base + 2}, $${base + 3}::vector, $${base + 4}::jsonb)`;
604
+ }).join(", ");
605
+ await config.runner.query(
606
+ `INSERT INTO ${table} (id, content, embedding, metadata) VALUES ${placeholders}
607
+ ON CONFLICT (id) DO UPDATE SET content = EXCLUDED.content, embedding = EXCLUDED.embedding, metadata = EXCLUDED.metadata`,
608
+ values
609
+ );
610
+ },
611
+ async search(embedding, options = {}) {
612
+ const topK = options.topK ?? defaultTopK;
613
+ const threshold = options.threshold ?? 0;
614
+ const { rows } = await config.runner.query(
615
+ `SELECT id, content, metadata, (embedding <=> $1::vector) AS distance
616
+ FROM ${table}
617
+ ORDER BY embedding <=> $1::vector
618
+ LIMIT $2`,
619
+ [formatVector(embedding), topK]
620
+ );
621
+ return rows.map((r) => ({
622
+ id: r.id,
623
+ content: r.content,
624
+ metadata: r.metadata ?? void 0,
625
+ score: 1 - r.distance
626
+ })).filter((r) => (r.score ?? 0) >= threshold);
627
+ },
628
+ async delete(ids) {
629
+ if (ids.length === 0) return;
630
+ const placeholders = ids.map((_, i) => `$${i + 1}`).join(",");
631
+ await config.runner.query(`DELETE FROM ${table} WHERE id IN (${placeholders})`, ids);
632
+ }
633
+ };
634
+ }
635
+
636
+ // src/vector/pinecone.ts
637
+ async function call(config, path, body) {
638
+ const fetchImpl = config.fetch ?? globalThis.fetch;
639
+ const response = await fetchImpl(`${config.indexUrl}${path}`, {
640
+ method: "POST",
641
+ headers: {
642
+ "content-type": "application/json",
643
+ "api-key": config.apiKey
644
+ },
645
+ body: JSON.stringify(body)
646
+ });
647
+ const text = await response.text();
648
+ if (!response.ok) throw new Error(`pinecone ${response.status}: ${text.slice(0, 200)}`);
649
+ return text.length > 0 ? JSON.parse(text) : {};
650
+ }
651
+ function pinecone(config) {
652
+ const defaultTopK = Math.max(1, config.topK ?? 10);
653
+ const namespace = config.namespace ?? "";
654
+ return {
655
+ async store(docs) {
656
+ if (docs.length === 0) return;
657
+ await call(config, "/vectors/upsert", {
658
+ namespace,
659
+ vectors: docs.map((d) => ({
660
+ id: d.id,
661
+ values: d.embedding,
662
+ metadata: { content: d.content, ...d.metadata ?? {} }
663
+ }))
664
+ });
665
+ },
666
+ async search(embedding, options = {}) {
667
+ const topK = options.topK ?? defaultTopK;
668
+ const threshold = options.threshold ?? 0;
669
+ const result = await call(config, "/query", {
670
+ namespace,
671
+ topK,
672
+ vector: embedding,
673
+ includeMetadata: true
674
+ });
675
+ return (result.matches ?? []).filter((m) => m.score >= threshold).map((m) => ({
676
+ id: m.id,
677
+ content: String((m.metadata ?? {}).content ?? ""),
678
+ metadata: m.metadata,
679
+ score: m.score
680
+ }));
681
+ },
682
+ async delete(ids) {
683
+ if (ids.length === 0) return;
684
+ await call(config, "/vectors/delete", { namespace, ids });
685
+ }
686
+ };
687
+ }
688
+
689
+ // src/vector/qdrant.ts
690
+ async function call2(config, method, path, body) {
691
+ const fetchImpl = config.fetch ?? globalThis.fetch;
692
+ const response = await fetchImpl(`${config.url}${path}`, {
693
+ method,
694
+ headers: {
695
+ "content-type": "application/json",
696
+ ...config.apiKey ? { "api-key": config.apiKey } : {}
697
+ },
698
+ body: body === void 0 ? void 0 : JSON.stringify(body)
699
+ });
700
+ const text = await response.text();
701
+ if (!response.ok) throw new Error(`qdrant ${response.status}: ${text.slice(0, 200)}`);
702
+ return text.length > 0 ? JSON.parse(text) : {};
703
+ }
704
+ function qdrant(config) {
705
+ const defaultTopK = Math.max(1, config.topK ?? 10);
706
+ return {
707
+ async store(docs) {
708
+ if (docs.length === 0) return;
709
+ await call2(config, "PUT", `/collections/${config.collection}/points`, {
710
+ points: docs.map((d) => ({
711
+ id: d.id,
712
+ vector: d.embedding,
713
+ payload: { content: d.content, ...d.metadata ?? {} }
714
+ }))
715
+ });
716
+ },
717
+ async search(embedding, options = {}) {
718
+ const topK = options.topK ?? defaultTopK;
719
+ const threshold = options.threshold ?? 0;
720
+ const result = await call2(config, "POST", `/collections/${config.collection}/points/search`, {
721
+ vector: embedding,
722
+ limit: topK,
723
+ with_payload: true
724
+ });
725
+ return (result.result ?? []).filter((m) => m.score >= threshold).map((m) => ({
726
+ id: String(m.id),
727
+ content: String((m.payload ?? {}).content ?? ""),
728
+ metadata: m.payload,
729
+ score: m.score
730
+ }));
731
+ },
732
+ async delete(ids) {
733
+ if (ids.length === 0) return;
734
+ await call2(config, "POST", `/collections/${config.collection}/points/delete`, {
735
+ points: ids
736
+ });
737
+ }
738
+ };
739
+ }
740
+
741
+ // src/vector/chroma.ts
742
+ async function call3(config, method, path, body) {
743
+ const fetchImpl = config.fetch ?? globalThis.fetch;
744
+ const response = await fetchImpl(`${config.url}${path}`, {
745
+ method,
746
+ headers: { "content-type": "application/json" },
747
+ body: body === void 0 ? void 0 : JSON.stringify(body)
748
+ });
749
+ const text = await response.text();
750
+ if (!response.ok) throw new Error(`chroma ${response.status}: ${text.slice(0, 200)}`);
751
+ return text.length > 0 ? JSON.parse(text) : {};
752
+ }
753
+ function chroma(config) {
754
+ const defaultTopK = Math.max(1, config.topK ?? 10);
755
+ return {
756
+ async store(docs) {
757
+ if (docs.length === 0) return;
758
+ await call3(config, "POST", `/api/v1/collections/${config.collection}/upsert`, {
759
+ ids: docs.map((d) => d.id),
760
+ embeddings: docs.map((d) => d.embedding),
761
+ documents: docs.map((d) => d.content),
762
+ metadatas: docs.map((d) => d.metadata ?? {})
763
+ });
764
+ },
765
+ async search(embedding, options = {}) {
766
+ const topK = options.topK ?? defaultTopK;
767
+ const threshold = options.threshold ?? 0;
768
+ const result = await call3(config, "POST", `/api/v1/collections/${config.collection}/query`, {
769
+ query_embeddings: [embedding],
770
+ n_results: topK
771
+ });
772
+ const ids = result.ids?.[0] ?? [];
773
+ const documents = result.documents?.[0] ?? [];
774
+ const metadatas = result.metadatas?.[0] ?? [];
775
+ const distances = result.distances?.[0] ?? [];
776
+ return ids.map((id, i) => ({
777
+ id,
778
+ content: documents[i] ?? "",
779
+ metadata: metadatas[i],
780
+ score: distances[i] !== void 0 ? 1 - distances[i] : 0
781
+ })).filter((r) => (r.score ?? 0) >= threshold);
782
+ },
783
+ async delete(ids) {
784
+ if (ids.length === 0) return;
785
+ await call3(config, "POST", `/api/v1/collections/${config.collection}/delete`, { ids });
786
+ }
787
+ };
788
+ }
789
+
790
+ // src/vector/upstash.ts
791
+ async function call4(config, path, body) {
792
+ const fetchImpl = config.fetch ?? globalThis.fetch;
793
+ const response = await fetchImpl(`${config.url}${path}`, {
794
+ method: "POST",
795
+ headers: {
796
+ "content-type": "application/json",
797
+ authorization: `Bearer ${config.token}`
798
+ },
799
+ body: JSON.stringify(body)
800
+ });
801
+ const text = await response.text();
802
+ if (!response.ok) throw new Error(`upstash-vector ${response.status}: ${text.slice(0, 200)}`);
803
+ return text.length > 0 ? JSON.parse(text) : {};
804
+ }
805
+ function upstashVector(config) {
806
+ const defaultTopK = Math.max(1, config.topK ?? 10);
807
+ return {
808
+ async store(docs) {
809
+ if (docs.length === 0) return;
810
+ await call4(
811
+ config,
812
+ "/upsert",
813
+ docs.map((d) => ({
814
+ id: d.id,
815
+ vector: d.embedding,
816
+ metadata: { content: d.content, ...d.metadata ?? {} }
817
+ }))
818
+ );
819
+ },
820
+ async search(embedding, options = {}) {
821
+ const topK = options.topK ?? defaultTopK;
822
+ const threshold = options.threshold ?? 0;
823
+ const result = await call4(config, "/query", { vector: embedding, topK, includeMetadata: true });
824
+ return (result.result ?? []).filter((m) => m.score >= threshold).map((m) => ({
825
+ id: m.id,
826
+ content: String((m.metadata ?? {}).content ?? ""),
827
+ metadata: m.metadata,
828
+ score: m.score
829
+ }));
830
+ },
831
+ async delete(ids) {
832
+ if (ids.length === 0) return;
833
+ await call4(config, "/delete", { ids });
834
+ }
835
+ };
836
+ }
837
+
838
+ // src/vector/supabase.ts
839
+ var cachedSdk2 = null;
840
+ async function loadSdk2() {
841
+ if (!cachedSdk2) {
842
+ cachedSdk2 = (async () => {
843
+ try {
844
+ const moduleId = "@supabase/supabase-js";
845
+ return await import(
846
+ /* @vite-ignore */
847
+ moduleId
848
+ );
849
+ } catch {
850
+ throw new Error(
851
+ "Install @supabase/supabase-js to use supabaseVectorStore: npm install @supabase/supabase-js"
852
+ );
853
+ }
854
+ })();
855
+ }
856
+ return cachedSdk2;
857
+ }
858
+ function buildRunner(client) {
859
+ return {
860
+ async query(sql, params) {
861
+ const result = await client.rpc("agentskit_execute_sql", { sql, params });
862
+ if (result.error) throw new Error(`supabase: ${result.error.message}`);
863
+ return { rows: result.data ?? [] };
864
+ }
865
+ };
866
+ }
867
+ function supabaseVectorStore(config) {
868
+ let runnerPromise = null;
869
+ const getRunner = () => {
870
+ if (!runnerPromise) {
871
+ runnerPromise = (async () => {
872
+ const sdk = await loadSdk2();
873
+ const client = sdk.createClient(config.url, config.serviceRoleKey);
874
+ return buildRunner(client);
875
+ })();
876
+ }
877
+ return runnerPromise;
878
+ };
879
+ let backend = null;
880
+ const getBackend = async () => {
881
+ if (!backend) {
882
+ const runner = await getRunner();
883
+ backend = pgvector({
884
+ runner,
885
+ table: config.table,
886
+ topK: config.topK
887
+ });
888
+ }
889
+ return backend;
890
+ };
891
+ return {
892
+ async store(docs) {
893
+ const b = await getBackend();
894
+ return b.store(docs);
895
+ },
896
+ async search(embedding, options) {
897
+ const b = await getBackend();
898
+ return b.search(embedding, options);
899
+ },
900
+ async delete(ids) {
901
+ const b = await getBackend();
902
+ return b.delete?.(ids);
903
+ }
904
+ };
905
+ }
906
+
907
+ // src/encrypted.ts
908
+ function toBase64(bytes) {
909
+ if (typeof Buffer !== "undefined") return Buffer.from(bytes).toString("base64");
910
+ let binary = "";
911
+ for (const b of bytes) binary += String.fromCharCode(b);
912
+ return btoa(binary);
913
+ }
914
+ function fromBase64(value) {
915
+ if (typeof Buffer !== "undefined") return new Uint8Array(Buffer.from(value, "base64"));
916
+ const binary = atob(value);
917
+ const bytes = new Uint8Array(binary.length);
918
+ for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
919
+ return bytes;
920
+ }
921
+ async function resolveKey(subtle, material) {
922
+ if ("type" in material && material.type === "secret") return material;
923
+ const raw = material;
924
+ if (raw.byteLength !== 32) {
925
+ throw new Error(`createEncryptedMemory: key must be 32 bytes (got ${raw.byteLength})`);
926
+ }
927
+ return subtle.importKey("raw", raw, { name: "AES-GCM" }, false, ["encrypt", "decrypt"]);
928
+ }
929
+ async function createEncryptedMemory(options) {
930
+ const subtle = options.subtle ?? globalThis.crypto?.subtle;
931
+ const random = options.getRandomValues ?? ((v) => globalThis.crypto.getRandomValues(v));
932
+ if (!subtle) throw new Error("createEncryptedMemory: SubtleCrypto not available");
933
+ const key = await resolveKey(subtle, options.key);
934
+ const aad = options.aad;
935
+ const encrypt = async (plain) => {
936
+ const iv = random(new Uint8Array(12));
937
+ const data = new TextEncoder().encode(plain);
938
+ const params = aad ? { name: "AES-GCM", iv, additionalData: aad } : { name: "AES-GCM", iv };
939
+ const cipher = await subtle.encrypt(params, key, data);
940
+ return {
941
+ ciphertext: toBase64(new Uint8Array(cipher)),
942
+ iv: toBase64(iv),
943
+ length: plain.length
944
+ };
945
+ };
946
+ const decrypt = async (envelope) => {
947
+ const iv = fromBase64(envelope.iv);
948
+ const params = aad ? { name: "AES-GCM", iv, additionalData: aad } : { name: "AES-GCM", iv };
949
+ const plain = await subtle.decrypt(params, key, fromBase64(envelope.ciphertext));
950
+ return new TextDecoder().decode(plain);
951
+ };
952
+ const encryptMessage = async (m) => {
953
+ if (m.metadata?.agentskitEncrypted) return m;
954
+ const envelope = await encrypt(m.content ?? "");
955
+ return {
956
+ ...m,
957
+ content: "",
958
+ metadata: {
959
+ ...m.metadata ?? {},
960
+ agentskitEncrypted: true,
961
+ ciphertext: envelope.ciphertext,
962
+ iv: envelope.iv,
963
+ length: envelope.length
964
+ }
965
+ };
966
+ };
967
+ const decryptMessage = async (m) => {
968
+ if (!m.metadata?.agentskitEncrypted) return m;
969
+ const envelope = {
970
+ ciphertext: String(m.metadata.ciphertext),
971
+ iv: String(m.metadata.iv),
972
+ length: Number(m.metadata.length ?? 0)
973
+ };
974
+ const content = await decrypt(envelope);
975
+ const { agentskitEncrypted: _, ciphertext: __, iv: ___, length: ____, ...rest } = m.metadata;
976
+ return { ...m, content, metadata: Object.keys(rest).length > 0 ? rest : void 0 };
977
+ };
978
+ return {
979
+ async load() {
980
+ const stored = await options.backing.load();
981
+ return Promise.all(stored.map(decryptMessage));
982
+ },
983
+ async save(messages) {
984
+ const encrypted = await Promise.all(messages.map(encryptMessage));
985
+ await options.backing.save(encrypted);
986
+ },
987
+ async clear() {
988
+ await options.backing.clear?.();
989
+ }
990
+ };
991
+ }
992
+
993
+ // src/hierarchical.ts
994
+ function mergeChronological(a, b) {
995
+ const out = [...a, ...b];
996
+ out.sort((x, y) => x.createdAt.getTime() - y.createdAt.getTime());
997
+ return out;
998
+ }
999
+ function createHierarchicalMemory(options) {
1000
+ const workingLimit = Math.max(1, options.workingLimit ?? 50);
1001
+ const recallTopK = Math.max(0, options.recallTopK ?? 5);
1002
+ const loadAll = async (source) => [...await source.load()];
1003
+ return {
1004
+ async load() {
1005
+ const hot = await loadAll(options.working);
1006
+ if (!options.recall || recallTopK === 0) return hot;
1007
+ let recalled = [];
1008
+ try {
1009
+ recalled = [...await options.recall.query({ working: hot, topK: recallTopK })];
1010
+ } catch {
1011
+ recalled = [];
1012
+ }
1013
+ const hotIds = new Set(hot.map((m) => m.id));
1014
+ return mergeChronological(
1015
+ recalled.filter((m) => !hotIds.has(m.id)),
1016
+ hot
1017
+ );
1018
+ },
1019
+ async save(messages) {
1020
+ const knownArchival = await loadAll(options.archival);
1021
+ const archivalIds = new Set(knownArchival.map((m) => m.id));
1022
+ const fresh = messages.filter((m) => !archivalIds.has(m.id));
1023
+ if (fresh.length > 0) {
1024
+ await options.archival.save(mergeChronological(knownArchival, fresh));
1025
+ }
1026
+ const tail = messages.slice(Math.max(0, messages.length - workingLimit));
1027
+ const overflow = messages.slice(0, Math.max(0, messages.length - workingLimit));
1028
+ await options.working.save(tail);
1029
+ if (options.recall) {
1030
+ const knownOverflow = overflow.filter((m) => fresh.some((f) => f.id === m.id));
1031
+ for (const m of knownOverflow) await options.recall.index(m);
1032
+ const appended = fresh.filter((m) => !tail.some((t) => t.id === m.id));
1033
+ for (const m of appended) await options.recall.index(m);
1034
+ }
1035
+ },
1036
+ async clear() {
1037
+ await options.working.clear?.();
1038
+ await options.archival.clear?.();
1039
+ },
1040
+ async archival() {
1041
+ return loadAll(options.archival);
1042
+ },
1043
+ async working() {
1044
+ return loadAll(options.working);
1045
+ }
1046
+ };
1047
+ }
1048
+
1049
+ export { chroma, createEncryptedMemory, createHierarchicalMemory, createInMemoryGraph, createInMemoryPersonalization, fileChatMemory, fileVectorMemory, matchesFilter, pgvector, pinecone, qdrant, redisChatMemory, redisVectorMemory, renderProfileContext, sqliteChatMemory, supabaseVectorStore, tursoChatMemory, upstashVector };
368
1050
  //# sourceMappingURL=index.js.map
369
1051
  //# sourceMappingURL=index.js.map