@agentskit/memory 0.8.3 → 0.9.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.d.cts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { ChatMemory, VectorMemory, VectorFilter, Message } from '@agentskit/core';
2
+ export { PersonalizationProfile, PersonalizationStore, createInMemoryPersonalization, renderProfileContext } from './personalization.cjs';
3
+ import { PIIRule, RedactionVault, RedactionAuditSink } from '@agentskit/core/security';
2
4
 
3
5
  /**
4
6
  * ChatMemory backed by a JSON file on disk. Node-only.
@@ -86,37 +88,6 @@ interface FileVectorMemoryConfig {
86
88
  }
87
89
  declare function fileVectorMemory(config: FileVectorMemoryConfig): VectorMemory;
88
90
 
89
- /**
90
- * Personalization — a persisted profile per subject (user id,
91
- * account id, device). The agent reads it on every run to
92
- * condition responses; the runtime updates it when new facts
93
- * appear.
94
- */
95
- interface PersonalizationProfile {
96
- subjectId: string;
97
- /** Human-editable notes, facts, preferences. */
98
- traits: Record<string, unknown>;
99
- /** ISO timestamp of the latest update. */
100
- updatedAt: string;
101
- }
102
- interface PersonalizationStore {
103
- get: (subjectId: string) => Promise<PersonalizationProfile | null>;
104
- set: (profile: PersonalizationProfile) => Promise<void>;
105
- merge: (subjectId: string, traits: Record<string, unknown>) => Promise<PersonalizationProfile>;
106
- delete?: (subjectId: string) => Promise<void>;
107
- }
108
- /**
109
- * In-memory personalization store — tests, single-process demos.
110
- * Bring your own for production (Postgres, Redis, DynamoDB).
111
- */
112
- declare function createInMemoryPersonalization(): PersonalizationStore;
113
- /**
114
- * Render a profile into a system-prompt fragment the runtime can
115
- * prepend. Kept intentionally short — full profile dumps bloat
116
- * context and leak unnecessary detail to the model.
117
- */
118
- declare function renderProfileContext(profile: PersonalizationProfile | null): string;
119
-
120
91
  /**
121
92
  * Non-linear memory: a typed knowledge graph. Use for facts the
122
93
  * agent should remember beyond a single conversation — entities,
@@ -412,4 +383,106 @@ interface HierarchicalMemory extends ChatMemory {
412
383
  */
413
384
  declare function createHierarchicalMemory(options: HierarchicalMemoryOptions): HierarchicalMemory;
414
385
 
415
- export { type ChromaConfig, type EncryptedEnvelope, type EncryptedMemoryOptions, type FileVectorMemoryConfig, type GraphEdge, type GraphMemory, type GraphNode, type GraphQuery, type HierarchicalMemory, type HierarchicalMemoryOptions, type HierarchicalRecall, type MilvusConfig, type MongoAtlasVectorConfig, type MongoCollectionLike, type PersonalizationProfile, type PersonalizationStore, type PgVectorConfig, type PgVectorRunner, type PineconeConfig, type QdrantConfig, type RedisChatMemoryConfig, type RedisClientAdapter, type RedisConnectionConfig, type RedisVectorMemoryConfig, type SqliteChatMemoryConfig, type SupabaseVectorStoreConfig, type TursoChatMemoryConfig, type UpstashVectorConfig, type VectorStore, type VectorStoreDocument, type VectorStoreResult, type WeaviateConfig, chroma, createEncryptedMemory, createHierarchicalMemory, createInMemoryGraph, createInMemoryPersonalization, fileChatMemory, fileVectorMemory, matchesFilter, milvusVectorStore, mongoAtlasVectorStore, pgvector, pinecone, qdrant, redisChatMemory, redisVectorMemory, renderProfileContext, sqliteChatMemory, supabaseVectorStore, tursoChatMemory, upstashVector, weaviateVectorStore };
386
+ /**
387
+ * GDPR / LGPD / CCPA data-subject deletion. ADR-0003 deferred
388
+ * retention; this module is the "forget the user" half.
389
+ *
390
+ * Design: rather than mutate every memory contract (and break the
391
+ * public API freeze, RFC-0007), we attach `forgetSubject` as a
392
+ * **capability** on a memory instance. Backends that can implement it
393
+ * declare a `subjectFilter` (how to recognise records belonging to a
394
+ * subject) and `deleteFn` (how to remove them). `forgetSubject(memory,
395
+ * subjectId)` walks every backend the runtime is configured with and
396
+ * runs the deletion, returning a per-backend report you can sign into
397
+ * the audit log (#162).
398
+ *
399
+ * Closes issue #798.
400
+ */
401
+ interface ForgettableMemory {
402
+ /**
403
+ * Backend identifier (`'pgvector'`, `'pinecone'`, `'sqlite'`, etc.).
404
+ * Used for the audit-log entry and for the per-backend report.
405
+ */
406
+ __agentskitBackend: string;
407
+ /** Delete every record where `metadata.subjectId === subjectId`. */
408
+ forgetSubject: (subjectId: string) => Promise<ForgetReport>;
409
+ }
410
+ interface ForgetReport {
411
+ backend: string;
412
+ deletedCount: number;
413
+ /** ISO timestamp of the deletion. */
414
+ at: string;
415
+ /** Records the deletion couldn't reach (offline replica, missing index). */
416
+ failures?: Array<{
417
+ id: string;
418
+ reason: string;
419
+ }>;
420
+ }
421
+ interface ForgetSubjectResult {
422
+ subjectId: string;
423
+ reports: ForgetReport[];
424
+ totalDeleted: number;
425
+ /** Hash you can sign into the audit log to prove the deletion ran. */
426
+ evidenceHash: string;
427
+ }
428
+ /**
429
+ * Walk every memory passed in and run `forgetSubject(subjectId)` on
430
+ * any that implement it. Memories that don't implement it are
431
+ * silently skipped — they hold no subject-scoped data, or you must
432
+ * delete out-of-band (e.g. log retention).
433
+ */
434
+ declare function forgetSubject(memories: Array<ChatMemory | VectorMemory | unknown>, subjectId: string): Promise<ForgetSubjectResult>;
435
+ /**
436
+ * Helper for backends that key records by `metadata.subjectId`. Wraps
437
+ * any `delete(ids)`-style API into a `ForgettableMemory`.
438
+ */
439
+ declare function makeForgettable<M extends object>(memory: M, options: {
440
+ backend: string;
441
+ listIds: (subjectId: string) => Promise<string[]>;
442
+ deleteIds: (ids: string[]) => Promise<void>;
443
+ }): M & ForgettableMemory;
444
+
445
+ /**
446
+ * Wrap any `ChatMemory` so PII is redacted (or tokenized) on every
447
+ * `save()`. Works with the in-memory, file, sqlite, turso, and redis
448
+ * chat memories. `load()` and `clear()` are passthrough — reveal
449
+ * happens at read time via `@agentskit/core/security` `reveal()`,
450
+ * not inside the memory.
451
+ *
452
+ * `mode: 'redact'` (default) replaces matches with the rules' bracket
453
+ * markers — irreversible. `mode: 'tokenize'` replaces matches with
454
+ * opaque `<<piitoken:…>>` markers and stores originals in the vault
455
+ * so role-gated `reveal()` can recover them.
456
+ *
457
+ * Closes the memory-write half of issue #791.
458
+ */
459
+ type RedactionMode = 'redact' | 'tokenize';
460
+ interface ChatMemoryRedactionOptions {
461
+ /**
462
+ * Rules to apply. Pass `DEFAULT_PII_RULES` for the baseline set,
463
+ * `compilePIITaxonomy(json)` for a custom JSON taxonomy, or any
464
+ * hand-rolled `PIIRule[]`. Same shape as `createPIIRedactor`.
465
+ */
466
+ rules: PIIRule[];
467
+ mode?: RedactionMode;
468
+ /** Required when `mode === 'tokenize'`. */
469
+ vault?: RedactionVault;
470
+ /** Roles allowed to reveal — required when `mode === 'tokenize'`. */
471
+ allowedRoles?: string[];
472
+ /** Optional audit sink threaded into the vault `tokenize()` calls. */
473
+ audit?: RedactionAuditSink;
474
+ }
475
+ interface VectorMemoryRedactionOptions extends ChatMemoryRedactionOptions {
476
+ }
477
+ declare function wrapChatMemoryWithRedaction(inner: ChatMemory, options: ChatMemoryRedactionOptions): ChatMemory;
478
+ /**
479
+ * Wrap any `VectorMemory` so each document's `content` is redacted (or
480
+ * tokenized) before `store()`. `search()` and `delete()` pass through.
481
+ *
482
+ * Note: embeddings pass through verbatim. Customers who embed
483
+ * plaintext PII separately (e.g. via a hosted embedding provider)
484
+ * must redact the input to their embedder, not just to this wrapper.
485
+ */
486
+ declare function wrapVectorMemoryWithRedaction(inner: VectorMemory, options: VectorMemoryRedactionOptions): VectorMemory;
487
+
488
+ export { type ChatMemoryRedactionOptions, type ChromaConfig, type EncryptedEnvelope, type EncryptedMemoryOptions, type FileVectorMemoryConfig, type ForgetReport, type ForgetSubjectResult, type ForgettableMemory, type GraphEdge, type GraphMemory, type GraphNode, type GraphQuery, type HierarchicalMemory, type HierarchicalMemoryOptions, type HierarchicalRecall, type MilvusConfig, type MongoAtlasVectorConfig, type MongoCollectionLike, type PgVectorConfig, type PgVectorRunner, type PineconeConfig, type QdrantConfig, type RedactionMode, type RedisChatMemoryConfig, type RedisClientAdapter, type RedisConnectionConfig, type RedisVectorMemoryConfig, type SqliteChatMemoryConfig, type SupabaseVectorStoreConfig, type TursoChatMemoryConfig, type UpstashVectorConfig, type VectorMemoryRedactionOptions, type VectorStore, type VectorStoreDocument, type VectorStoreResult, type WeaviateConfig, chroma, createEncryptedMemory, createHierarchicalMemory, createInMemoryGraph, fileChatMemory, fileVectorMemory, forgetSubject, makeForgettable, matchesFilter, milvusVectorStore, mongoAtlasVectorStore, pgvector, pinecone, qdrant, redisChatMemory, redisVectorMemory, sqliteChatMemory, supabaseVectorStore, tursoChatMemory, upstashVector, weaviateVectorStore, wrapChatMemoryWithRedaction, wrapVectorMemoryWithRedaction };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { ChatMemory, VectorMemory, VectorFilter, Message } from '@agentskit/core';
2
+ export { PersonalizationProfile, PersonalizationStore, createInMemoryPersonalization, renderProfileContext } from './personalization.js';
3
+ import { PIIRule, RedactionVault, RedactionAuditSink } from '@agentskit/core/security';
2
4
 
3
5
  /**
4
6
  * ChatMemory backed by a JSON file on disk. Node-only.
@@ -86,37 +88,6 @@ interface FileVectorMemoryConfig {
86
88
  }
87
89
  declare function fileVectorMemory(config: FileVectorMemoryConfig): VectorMemory;
88
90
 
89
- /**
90
- * Personalization — a persisted profile per subject (user id,
91
- * account id, device). The agent reads it on every run to
92
- * condition responses; the runtime updates it when new facts
93
- * appear.
94
- */
95
- interface PersonalizationProfile {
96
- subjectId: string;
97
- /** Human-editable notes, facts, preferences. */
98
- traits: Record<string, unknown>;
99
- /** ISO timestamp of the latest update. */
100
- updatedAt: string;
101
- }
102
- interface PersonalizationStore {
103
- get: (subjectId: string) => Promise<PersonalizationProfile | null>;
104
- set: (profile: PersonalizationProfile) => Promise<void>;
105
- merge: (subjectId: string, traits: Record<string, unknown>) => Promise<PersonalizationProfile>;
106
- delete?: (subjectId: string) => Promise<void>;
107
- }
108
- /**
109
- * In-memory personalization store — tests, single-process demos.
110
- * Bring your own for production (Postgres, Redis, DynamoDB).
111
- */
112
- declare function createInMemoryPersonalization(): PersonalizationStore;
113
- /**
114
- * Render a profile into a system-prompt fragment the runtime can
115
- * prepend. Kept intentionally short — full profile dumps bloat
116
- * context and leak unnecessary detail to the model.
117
- */
118
- declare function renderProfileContext(profile: PersonalizationProfile | null): string;
119
-
120
91
  /**
121
92
  * Non-linear memory: a typed knowledge graph. Use for facts the
122
93
  * agent should remember beyond a single conversation — entities,
@@ -412,4 +383,106 @@ interface HierarchicalMemory extends ChatMemory {
412
383
  */
413
384
  declare function createHierarchicalMemory(options: HierarchicalMemoryOptions): HierarchicalMemory;
414
385
 
415
- export { type ChromaConfig, type EncryptedEnvelope, type EncryptedMemoryOptions, type FileVectorMemoryConfig, type GraphEdge, type GraphMemory, type GraphNode, type GraphQuery, type HierarchicalMemory, type HierarchicalMemoryOptions, type HierarchicalRecall, type MilvusConfig, type MongoAtlasVectorConfig, type MongoCollectionLike, type PersonalizationProfile, type PersonalizationStore, type PgVectorConfig, type PgVectorRunner, type PineconeConfig, type QdrantConfig, type RedisChatMemoryConfig, type RedisClientAdapter, type RedisConnectionConfig, type RedisVectorMemoryConfig, type SqliteChatMemoryConfig, type SupabaseVectorStoreConfig, type TursoChatMemoryConfig, type UpstashVectorConfig, type VectorStore, type VectorStoreDocument, type VectorStoreResult, type WeaviateConfig, chroma, createEncryptedMemory, createHierarchicalMemory, createInMemoryGraph, createInMemoryPersonalization, fileChatMemory, fileVectorMemory, matchesFilter, milvusVectorStore, mongoAtlasVectorStore, pgvector, pinecone, qdrant, redisChatMemory, redisVectorMemory, renderProfileContext, sqliteChatMemory, supabaseVectorStore, tursoChatMemory, upstashVector, weaviateVectorStore };
386
+ /**
387
+ * GDPR / LGPD / CCPA data-subject deletion. ADR-0003 deferred
388
+ * retention; this module is the "forget the user" half.
389
+ *
390
+ * Design: rather than mutate every memory contract (and break the
391
+ * public API freeze, RFC-0007), we attach `forgetSubject` as a
392
+ * **capability** on a memory instance. Backends that can implement it
393
+ * declare a `subjectFilter` (how to recognise records belonging to a
394
+ * subject) and `deleteFn` (how to remove them). `forgetSubject(memory,
395
+ * subjectId)` walks every backend the runtime is configured with and
396
+ * runs the deletion, returning a per-backend report you can sign into
397
+ * the audit log (#162).
398
+ *
399
+ * Closes issue #798.
400
+ */
401
+ interface ForgettableMemory {
402
+ /**
403
+ * Backend identifier (`'pgvector'`, `'pinecone'`, `'sqlite'`, etc.).
404
+ * Used for the audit-log entry and for the per-backend report.
405
+ */
406
+ __agentskitBackend: string;
407
+ /** Delete every record where `metadata.subjectId === subjectId`. */
408
+ forgetSubject: (subjectId: string) => Promise<ForgetReport>;
409
+ }
410
+ interface ForgetReport {
411
+ backend: string;
412
+ deletedCount: number;
413
+ /** ISO timestamp of the deletion. */
414
+ at: string;
415
+ /** Records the deletion couldn't reach (offline replica, missing index). */
416
+ failures?: Array<{
417
+ id: string;
418
+ reason: string;
419
+ }>;
420
+ }
421
+ interface ForgetSubjectResult {
422
+ subjectId: string;
423
+ reports: ForgetReport[];
424
+ totalDeleted: number;
425
+ /** Hash you can sign into the audit log to prove the deletion ran. */
426
+ evidenceHash: string;
427
+ }
428
+ /**
429
+ * Walk every memory passed in and run `forgetSubject(subjectId)` on
430
+ * any that implement it. Memories that don't implement it are
431
+ * silently skipped — they hold no subject-scoped data, or you must
432
+ * delete out-of-band (e.g. log retention).
433
+ */
434
+ declare function forgetSubject(memories: Array<ChatMemory | VectorMemory | unknown>, subjectId: string): Promise<ForgetSubjectResult>;
435
+ /**
436
+ * Helper for backends that key records by `metadata.subjectId`. Wraps
437
+ * any `delete(ids)`-style API into a `ForgettableMemory`.
438
+ */
439
+ declare function makeForgettable<M extends object>(memory: M, options: {
440
+ backend: string;
441
+ listIds: (subjectId: string) => Promise<string[]>;
442
+ deleteIds: (ids: string[]) => Promise<void>;
443
+ }): M & ForgettableMemory;
444
+
445
+ /**
446
+ * Wrap any `ChatMemory` so PII is redacted (or tokenized) on every
447
+ * `save()`. Works with the in-memory, file, sqlite, turso, and redis
448
+ * chat memories. `load()` and `clear()` are passthrough — reveal
449
+ * happens at read time via `@agentskit/core/security` `reveal()`,
450
+ * not inside the memory.
451
+ *
452
+ * `mode: 'redact'` (default) replaces matches with the rules' bracket
453
+ * markers — irreversible. `mode: 'tokenize'` replaces matches with
454
+ * opaque `<<piitoken:…>>` markers and stores originals in the vault
455
+ * so role-gated `reveal()` can recover them.
456
+ *
457
+ * Closes the memory-write half of issue #791.
458
+ */
459
+ type RedactionMode = 'redact' | 'tokenize';
460
+ interface ChatMemoryRedactionOptions {
461
+ /**
462
+ * Rules to apply. Pass `DEFAULT_PII_RULES` for the baseline set,
463
+ * `compilePIITaxonomy(json)` for a custom JSON taxonomy, or any
464
+ * hand-rolled `PIIRule[]`. Same shape as `createPIIRedactor`.
465
+ */
466
+ rules: PIIRule[];
467
+ mode?: RedactionMode;
468
+ /** Required when `mode === 'tokenize'`. */
469
+ vault?: RedactionVault;
470
+ /** Roles allowed to reveal — required when `mode === 'tokenize'`. */
471
+ allowedRoles?: string[];
472
+ /** Optional audit sink threaded into the vault `tokenize()` calls. */
473
+ audit?: RedactionAuditSink;
474
+ }
475
+ interface VectorMemoryRedactionOptions extends ChatMemoryRedactionOptions {
476
+ }
477
+ declare function wrapChatMemoryWithRedaction(inner: ChatMemory, options: ChatMemoryRedactionOptions): ChatMemory;
478
+ /**
479
+ * Wrap any `VectorMemory` so each document's `content` is redacted (or
480
+ * tokenized) before `store()`. `search()` and `delete()` pass through.
481
+ *
482
+ * Note: embeddings pass through verbatim. Customers who embed
483
+ * plaintext PII separately (e.g. via a hosted embedding provider)
484
+ * must redact the input to their embedder, not just to this wrapper.
485
+ */
486
+ declare function wrapVectorMemoryWithRedaction(inner: VectorMemory, options: VectorMemoryRedactionOptions): VectorMemory;
487
+
488
+ export { type ChatMemoryRedactionOptions, type ChromaConfig, type EncryptedEnvelope, type EncryptedMemoryOptions, type FileVectorMemoryConfig, type ForgetReport, type ForgetSubjectResult, type ForgettableMemory, type GraphEdge, type GraphMemory, type GraphNode, type GraphQuery, type HierarchicalMemory, type HierarchicalMemoryOptions, type HierarchicalRecall, type MilvusConfig, type MongoAtlasVectorConfig, type MongoCollectionLike, type PgVectorConfig, type PgVectorRunner, type PineconeConfig, type QdrantConfig, type RedactionMode, type RedisChatMemoryConfig, type RedisClientAdapter, type RedisConnectionConfig, type RedisVectorMemoryConfig, type SqliteChatMemoryConfig, type SupabaseVectorStoreConfig, type TursoChatMemoryConfig, type UpstashVectorConfig, type VectorMemoryRedactionOptions, type VectorStore, type VectorStoreDocument, type VectorStoreResult, type WeaviateConfig, chroma, createEncryptedMemory, createHierarchicalMemory, createInMemoryGraph, fileChatMemory, fileVectorMemory, forgetSubject, makeForgettable, matchesFilter, milvusVectorStore, mongoAtlasVectorStore, pgvector, pinecone, qdrant, redisChatMemory, redisVectorMemory, sqliteChatMemory, supabaseVectorStore, tursoChatMemory, upstashVector, weaviateVectorStore, wrapChatMemoryWithRedaction, wrapVectorMemoryWithRedaction };
package/dist/index.js CHANGED
@@ -1,11 +1,8 @@
1
+ import { __require } from './chunk-G5S2A3MJ.js';
2
+ export { createInMemoryPersonalization, renderProfileContext } from './chunk-G5S2A3MJ.js';
1
3
  import { serializeMessages, deserializeMessages, MemoryError, ErrorCodes, ConfigError } from '@agentskit/core';
4
+ import { tokenize, createPIIRedactor } from '@agentskit/core/security';
2
5
 
3
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
- }) : x)(function(x) {
6
- if (typeof require !== "undefined") return require.apply(this, arguments);
7
- throw Error('Dynamic require of "' + x + '" is not supported');
8
- });
9
6
  function fileChatMemory(path) {
10
7
  return {
11
8
  async load() {
@@ -19,7 +16,11 @@ function fileChatMemory(path) {
19
16
  },
20
17
  async save(messages) {
21
18
  const fs = await import('fs/promises');
22
- await fs.writeFile(path, JSON.stringify(serializeMessages(messages), null, 2), "utf8");
19
+ await fs.writeFile(
20
+ path,
21
+ JSON.stringify(serializeMessages(messages), null, 2),
22
+ { encoding: "utf8", mode: 384 }
23
+ );
23
24
  },
24
25
  async clear() {
25
26
  try {
@@ -195,7 +196,7 @@ async function createRedisClientAdapter(url) {
195
196
  return await client.keys(pattern);
196
197
  },
197
198
  async disconnect() {
198
- await client.disconnect();
199
+ await client.close();
199
200
  },
200
201
  async call(command, ...args) {
201
202
  return await client.sendCommand([command, ...args.map(String)]);
@@ -423,16 +424,23 @@ function createVectraStore(dirPath) {
423
424
  return {
424
425
  async upsert(docs) {
425
426
  const idx = await getIndex();
426
- for (const doc of docs) {
427
- await idx.insertItem({
428
- vector: doc.vector,
429
- metadata: { _id: doc.id, ...doc.metadata }
430
- });
427
+ await idx.beginUpdate();
428
+ try {
429
+ for (const doc of docs) {
430
+ await idx.insertItem({
431
+ vector: doc.vector,
432
+ metadata: { _id: doc.id, ...doc.metadata }
433
+ });
434
+ }
435
+ await idx.endUpdate();
436
+ } catch (err) {
437
+ idx.cancelUpdate();
438
+ throw err;
431
439
  }
432
440
  },
433
441
  async query(vector, topK) {
434
442
  const idx = await getIndex();
435
- const results = await idx.queryItems(vector, topK);
443
+ const results = await idx.queryItems(vector, "", topK);
436
444
  return results.map((r) => ({
437
445
  id: String(r.item.metadata._id ?? ""),
438
446
  score: r.score,
@@ -483,44 +491,6 @@ function fileVectorMemory(config) {
483
491
  };
484
492
  }
485
493
 
486
- // src/personalization.ts
487
- function createInMemoryPersonalization() {
488
- const profiles = /* @__PURE__ */ new Map();
489
- return {
490
- async get(subjectId) {
491
- const hit = profiles.get(subjectId);
492
- return hit ? { ...hit, traits: { ...hit.traits } } : null;
493
- },
494
- async set(profile) {
495
- profiles.set(profile.subjectId, {
496
- ...profile,
497
- traits: { ...profile.traits },
498
- updatedAt: profile.updatedAt || (/* @__PURE__ */ new Date()).toISOString()
499
- });
500
- },
501
- async merge(subjectId, traits) {
502
- const existing = profiles.get(subjectId);
503
- const next = {
504
- subjectId,
505
- traits: { ...existing?.traits ?? {}, ...traits },
506
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
507
- };
508
- profiles.set(subjectId, next);
509
- return { ...next, traits: { ...next.traits } };
510
- },
511
- async delete(subjectId) {
512
- profiles.delete(subjectId);
513
- }
514
- };
515
- }
516
- function renderProfileContext(profile) {
517
- if (!profile || Object.keys(profile.traits).length === 0) return "";
518
- 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)}`);
519
- if (lines.length === 0) return "";
520
- return `## User profile
521
- ${lines.join("\n")}`;
522
- }
523
-
524
494
  // src/graph.ts
525
495
  function createInMemoryGraph() {
526
496
  const nodes = /* @__PURE__ */ new Map();
@@ -1257,6 +1227,102 @@ function createHierarchicalMemory(options) {
1257
1227
  };
1258
1228
  }
1259
1229
 
1260
- export { chroma, createEncryptedMemory, createHierarchicalMemory, createInMemoryGraph, createInMemoryPersonalization, fileChatMemory, fileVectorMemory, matchesFilter, milvusVectorStore, mongoAtlasVectorStore, pgvector, pinecone, qdrant, redisChatMemory, redisVectorMemory, renderProfileContext, sqliteChatMemory, supabaseVectorStore, tursoChatMemory, upstashVector, weaviateVectorStore };
1230
+ // src/forget.ts
1231
+ function isForgettable(value) {
1232
+ return !!value && typeof value === "object" && "forgetSubject" in value && typeof value.forgetSubject === "function";
1233
+ }
1234
+ async function hash(input) {
1235
+ const encoded = new TextEncoder().encode(input);
1236
+ const digest = await crypto.subtle.digest("SHA-256", encoded);
1237
+ return Array.from(new Uint8Array(digest)).map((b) => b.toString(16).padStart(2, "0")).join("");
1238
+ }
1239
+ async function forgetSubject(memories, subjectId) {
1240
+ const reports = [];
1241
+ for (const memory of memories) {
1242
+ if (!isForgettable(memory)) continue;
1243
+ reports.push(await memory.forgetSubject(subjectId));
1244
+ }
1245
+ const totalDeleted = reports.reduce((sum, r) => sum + r.deletedCount, 0);
1246
+ const evidenceHash = await hash(
1247
+ JSON.stringify({ subjectId, reports: reports.map((r) => ({ b: r.backend, n: r.deletedCount, at: r.at })) })
1248
+ );
1249
+ return { subjectId, reports, totalDeleted, evidenceHash };
1250
+ }
1251
+ function makeForgettable(memory, options) {
1252
+ return Object.assign(memory, {
1253
+ __agentskitBackend: options.backend,
1254
+ forgetSubject: async (subjectId) => {
1255
+ const ids = await options.listIds(subjectId);
1256
+ const failures = [];
1257
+ try {
1258
+ await options.deleteIds(ids);
1259
+ } catch (err) {
1260
+ for (const id of ids) failures.push({ id, reason: err.message });
1261
+ }
1262
+ return {
1263
+ backend: options.backend,
1264
+ deletedCount: ids.length - failures.length,
1265
+ at: (/* @__PURE__ */ new Date()).toISOString(),
1266
+ failures: failures.length ? failures : void 0
1267
+ };
1268
+ }
1269
+ });
1270
+ }
1271
+ async function transform(input, opts) {
1272
+ if (opts.mode === "tokenize") {
1273
+ if (!opts.vault) {
1274
+ throw new ConfigError({
1275
+ code: ErrorCodes.AK_CONFIG_INVALID,
1276
+ message: 'wrapMemoryWithRedaction: vault is required when mode is "tokenize"'
1277
+ });
1278
+ }
1279
+ if (!opts.allowedRoles) {
1280
+ throw new ConfigError({
1281
+ code: ErrorCodes.AK_CONFIG_INVALID,
1282
+ message: 'wrapMemoryWithRedaction: allowedRoles is required when mode is "tokenize"'
1283
+ });
1284
+ }
1285
+ const result = await tokenize(input, {
1286
+ rules: opts.rules,
1287
+ vault: opts.vault,
1288
+ allowedRoles: opts.allowedRoles,
1289
+ audit: opts.audit
1290
+ });
1291
+ return result.value;
1292
+ }
1293
+ return createPIIRedactor({ rules: opts.rules }).redact(input).value;
1294
+ }
1295
+ function wrapChatMemoryWithRedaction(inner, options) {
1296
+ return {
1297
+ load: () => inner.load(),
1298
+ save: async (messages) => {
1299
+ const redacted = await Promise.all(
1300
+ messages.map(async (m) => ({
1301
+ ...m,
1302
+ content: await transform(m.content ?? "", options)
1303
+ }))
1304
+ );
1305
+ await inner.save(redacted);
1306
+ },
1307
+ clear: inner.clear ? () => inner.clear() : void 0
1308
+ };
1309
+ }
1310
+ function wrapVectorMemoryWithRedaction(inner, options) {
1311
+ return {
1312
+ store: async (docs) => {
1313
+ const redacted = await Promise.all(
1314
+ docs.map(async (d) => ({
1315
+ ...d,
1316
+ content: await transform(d.content, options)
1317
+ }))
1318
+ );
1319
+ await inner.store(redacted);
1320
+ },
1321
+ search: (embedding, opts) => inner.search(embedding, opts),
1322
+ delete: inner.delete ? (ids) => inner.delete(ids) : void 0
1323
+ };
1324
+ }
1325
+
1326
+ export { chroma, createEncryptedMemory, createHierarchicalMemory, createInMemoryGraph, fileChatMemory, fileVectorMemory, forgetSubject, makeForgettable, matchesFilter, milvusVectorStore, mongoAtlasVectorStore, pgvector, pinecone, qdrant, redisChatMemory, redisVectorMemory, sqliteChatMemory, supabaseVectorStore, tursoChatMemory, upstashVector, weaviateVectorStore, wrapChatMemoryWithRedaction, wrapVectorMemoryWithRedaction };
1261
1327
  //# sourceMappingURL=index.js.map
1262
1328
  //# sourceMappingURL=index.js.map