import { ChatMemory, VectorMemory, VectorFilter, Message } from '@agentskit/core'; export { WebStorageLike, WebStorageMemoryMigration, WebStorageMemoryOptions, createWebStorageMemory } from './web-storage.cjs'; export { PersonalizationProfile, PersonalizationStore, createInMemoryPersonalization, renderProfileContext } from './personalization.cjs'; import { PIIRule, RedactionVault, RedactionAuditSink } from '@agentskit/core/security'; /** * ChatMemory backed by a JSON file on disk. Node-only. * * Implements the Memory contract (ADR 0003): * - load() returns a snapshot (CM1) * - save() is replace-all, not append (CM2) * - empty state returns [] (CM5) * - clear() is optional but provided here */ declare function fileChatMemory(path: string): ChatMemory; interface SqliteChatMemoryConfig { path: string; conversationId?: string; } declare function sqliteChatMemory(config: SqliteChatMemoryConfig): ChatMemory; interface TursoChatMemoryConfig { /** libSQL URL — file:..., libsql://..., or http://... */ url: string; /** Auth token — required for hosted (libsql://) URLs. */ authToken?: string; conversationId?: string; } /** * libSQL / Turso-backed chat memory. Mirrors the `sqliteChatMemory` shape so * code paths can swap between local SQLite and replicated libSQL by changing * one import. * * `@libsql/client` is an optional peer dependency loaded lazily. */ declare function tursoChatMemory(config: TursoChatMemoryConfig): ChatMemory; /** * Internal Redis client adapter interface. * Abstracts the underlying Redis library so it can be swapped * (e.g., from `redis` to `ioredis`) without changing consumers. */ interface RedisClientAdapter { get(key: string): Promise; set(key: string, value: string): Promise; del(key: string | string[]): Promise; keys(pattern: string): Promise; disconnect(): Promise; call(command: string, ...args: (string | number | Buffer)[]): Promise; } interface RedisConnectionConfig { url: string; client?: RedisClientAdapter; } interface RedisChatMemoryConfig extends RedisConnectionConfig { keyPrefix?: string; conversationId?: string; } declare function redisChatMemory(config: RedisChatMemoryConfig): ChatMemory; interface RedisVectorMemoryConfig extends RedisConnectionConfig { indexName?: string; keyPrefix?: string; dimensions?: number; } declare function redisVectorMemory(config: RedisVectorMemoryConfig): VectorMemory; interface VectorStoreDocument { id: string; vector: number[]; metadata: Record; } interface VectorStoreResult { id: string; score: number; metadata: Record; } interface VectorStore { upsert(docs: VectorStoreDocument[]): Promise; query(vector: number[], topK: number): Promise; delete(ids: string[]): Promise; } interface FileVectorMemoryConfig { path: string; store?: VectorStore; } declare function fileVectorMemory(config: FileVectorMemoryConfig): VectorMemory; /** * Non-linear memory: a typed knowledge graph. Use for facts the * agent should remember beyond a single conversation — entities, * relationships, derived beliefs. Designed to be backed by anything * from an in-memory Map (tests, demos) to Neo4j / Memgraph / Neptune. */ interface GraphNode> { id: string; /** Type / label — 'person', 'company', 'topic'. */ kind: string; properties?: TProps; /** ISO timestamp when the node was first inserted. */ createdAt?: string; /** ISO timestamp of the latest update. */ updatedAt?: string; } interface GraphEdge> { id: string; /** Verb / relation type — 'knows', 'works-at', 'cites'. */ label: string; from: string; to: string; /** Optional weight — confidence, recency, or frequency. */ weight?: number; properties?: TProps; } interface GraphQuery { kind?: string; label?: string; from?: string; to?: string; } interface GraphMemory { upsertNode: (node: GraphNode) => Promise>; upsertEdge: (edge: GraphEdge) => Promise>; getNode: (id: string) => Promise | null>; findNodes: (query?: GraphQuery) => Promise[]>; findEdges: (query?: GraphQuery) => Promise[]>; /** Breadth-first neighbors of `id` up to `depth`. Default 1. */ neighbors: (id: string, options?: { depth?: number; label?: string; }) => Promise[]>; deleteNode: (id: string) => Promise; deleteEdge: (id: string) => Promise; clear?: () => Promise; } /** * In-memory graph — fine for tests, single-process demos, and as * reference for what a backing store needs to implement. */ declare function createInMemoryGraph(): GraphMemory; /** * pgvector-backed VectorMemory. We accept a minimal async SQL runner * so the caller picks the driver (`pg`, `postgres`, `@neondatabase/serverless`, * `@supabase/postgres-js`, ...). Expects a table with columns * `id text primary key`, `content text`, `embedding vector(N)`, * `metadata jsonb`. */ interface PgVectorRunner { query: >(sql: string, params: unknown[]) => Promise<{ rows: T[]; }>; } interface PgVectorConfig { runner: PgVectorRunner; /** Table name. Default 'agentskit_vectors'. */ table?: string; /** Default topK for search. Default 10. */ topK?: number; } declare function pgvector(config: PgVectorConfig): VectorMemory; interface PineconeConfig { /** Full index URL, e.g. `https://-.svc..pinecone.io`. */ indexUrl: string; apiKey: string; /** Namespace. Default ''. */ namespace?: string; /** Default topK for search. Default 10. */ topK?: number; fetch?: typeof globalThis.fetch; } declare function pinecone(config: PineconeConfig): VectorMemory; interface QdrantConfig { /** Base URL, e.g. `https://xxx.cluster-qdrant.io`. */ url: string; apiKey?: string; collection: string; topK?: number; fetch?: typeof globalThis.fetch; } declare function qdrant(config: QdrantConfig): VectorMemory; interface ChromaConfig { /** Base URL of a running Chroma HTTP server. */ url: string; collection: string; /** Chroma tenant. Defaults to `default_tenant`. */ tenant?: string; /** Chroma database. Defaults to `default_database`. */ database?: string; /** Chroma token sent through the `x-chroma-token` header. */ apiKey?: string; /** Additional headers for hosted or proxied Chroma deployments. */ headers?: Record; topK?: number; fetch?: typeof globalThis.fetch; } declare function chroma(config: ChromaConfig): VectorMemory; interface UpstashVectorConfig { url: string; token: string; topK?: number; fetch?: typeof globalThis.fetch; } /** * Upstash Vector — HTTP-only serverless vector DB. The REST surface * is tiny enough to implement directly without pulling the SDK. */ declare function upstashVector(config: UpstashVectorConfig): VectorMemory; interface SupabaseVectorStoreConfig { /** Supabase project URL, e.g. `https://xyz.supabase.co`. */ url: string; /** Service-role key (server-side only). */ serviceRoleKey: string; /** Table name. Default `agentskit_vectors`. */ table?: string; /** Purpose-specific similarity-search RPC. Default `match_agentskit_vectors`. */ matchFunction?: string; /** Default topK for search. Default 10. */ topK?: number; } /** * Supabase-hosted pgvector using direct PostgREST mutations and one * purpose-specific similarity-search RPC. The service-role key stays * server-side and `@supabase/supabase-js` is loaded lazily. */ declare function supabaseVectorStore(config: SupabaseVectorStoreConfig): VectorMemory; interface WeaviateConfig { /** Cluster URL, e.g. `https://my-cluster.weaviate.network`. */ url: string; /** Optional API key (Weaviate Cloud Services). */ apiKey?: string; /** Class name in the Weaviate schema. */ className: string; topK?: number; fetch?: typeof globalThis.fetch; } declare function weaviateVectorStore(config: WeaviateConfig): VectorMemory; interface MilvusConfig { /** Milvus REST endpoint, e.g. `https://in03-xxx.api.gcp-us-west1.zillizcloud.com`. */ url: string; /** API key / Zilliz Cloud token (Bearer). */ token?: string; collection: string; /** Vector field name in the schema. Default `vector`. */ vectorField?: string; topK?: number; fetch?: typeof globalThis.fetch; } declare function milvusVectorStore(config: MilvusConfig): VectorMemory; /** * MongoDB Atlas Vector Search adapter. Caller injects a typed collection * shape (drop-in for the official `mongodb` driver's `Collection` type) so * we don't bundle a driver. Atlas' \`$vectorSearch\` aggregation runs * server-side; we just translate \`store\` / \`search\` / \`delete\` to * insertMany + aggregate + deleteMany. */ interface MongoCollectionLike { insertMany(docs: Array>, options?: unknown): Promise; deleteMany(filter: Record): Promise; aggregate>(pipeline: Array>): { toArray(): Promise; }; } interface MongoAtlasVectorConfig { collection: MongoCollectionLike; /** Atlas Search index name on the embedding field. */ indexName: string; /** Field that holds the embedding vector. Default `embedding`. */ vectorField?: string; /** numCandidates for $vectorSearch. Default `topK * 10`. */ numCandidates?: number; topK?: number; } declare function mongoAtlasVectorStore(config: MongoAtlasVectorConfig): VectorMemory; /** * Evaluate a `VectorFilter` against a metadata record. Used by in-memory / * file-backed vector stores. Backends with native filter languages (pgvector, * Pinecone, Qdrant, etc.) translate the filter to their own form instead. */ declare function matchesFilter(metadata: Record | undefined, filter: VectorFilter | undefined): boolean; /** * Client-side encrypted ChatMemory wrapper. Keys never leave the * caller — the backing store only ever sees an opaque * `{ iv, ct }` payload stashed in `metadata.ciphertext` and * `metadata.iv`; `content` becomes an empty string so rogue * middleware can't peek at it either. * * Uses Web Crypto (AES-GCM, 256-bit). Available on Node 20+ and all * modern browsers. BYO key material — typically generated per-user * during onboarding and stored only on their device. */ interface EncryptedMemoryOptions { backing: ChatMemory; /** 32-byte raw key (e.g. `crypto.getRandomValues(new Uint8Array(32))`). */ key: Uint8Array | CryptoKey; /** Override for tests. Defaults to `globalThis.crypto.subtle`. */ subtle?: SubtleCrypto; /** Random source. Defaults to `globalThis.crypto.getRandomValues`. */ getRandomValues?: (array: T) => T; /** Optional AAD — content that binds ciphertext to context (user id, room). */ aad?: Uint8Array; } interface EncryptedEnvelope { ciphertext: string; iv: string; /** Plaintext-length marker so the agent sees a non-empty content hint. */ length: number; } declare function createEncryptedMemory(options: EncryptedMemoryOptions): Promise; interface HierarchicalRecall { /** * Index a message for later retrieval. Called once per message as * it moves from working → recall (usually: embed + store in a * vector DB). */ index: (message: Message) => void | Promise; /** * Given the hot working window, return up to `topK` messages from * the recall tier that are relevant to the current turn. The hub * splices results chronologically alongside the working window. */ query: (input: { working: Message[]; topK: number; }) => Message[] | Promise; } interface HierarchicalMemoryOptions { /** Hot window — the messages always loaded in full. */ working: ChatMemory; /** Cold storage — every message ever seen is written here. */ archival: ChatMemory; /** * Mid-term recall layer (usually a vector store). Optional; * without it the hub behaves like virtualized memory with a hard * backing store. */ recall?: HierarchicalRecall; /** * Maximum messages to keep in `working`. Older messages spill * into recall + archival. Default 50. */ workingLimit?: number; /** * Max recalled messages to splice on each `load()`. Default 5. */ recallTopK?: number; } interface HierarchicalMemory extends ChatMemory { /** Full archival history. Always the source of truth. */ archival: () => Promise; /** Current working-window snapshot. */ working: () => Promise; } /** * MemGPT-style tiered memory. Three tiers: * - working: always-loaded hot window (bounded by `workingLimit`). * - recall: mid-term searchable layer (usually a vector store). * - archival: cold store that always holds the full conversation. * * On every `save`, new messages are appended to archival, messages * that overflow the working window are indexed into recall, and the * working tier is trimmed to `workingLimit`. * * On every `load`, the hub returns working + up to `recallTopK` * messages surfaced by the recall tier, spliced chronologically. */ declare function createHierarchicalMemory(options: HierarchicalMemoryOptions): HierarchicalMemory; /** * GDPR / LGPD / CCPA data-subject deletion. ADR-0003 deferred * retention; this module is the "forget the user" half. * * Design: rather than mutate every memory contract (and break the * public API freeze, RFC-0007), we attach `forgetSubject` as a * **capability** on a memory instance. Backends that can implement it * declare a `subjectFilter` (how to recognise records belonging to a * subject) and `deleteFn` (how to remove them). `forgetSubject(memory, * subjectId)` walks every backend the runtime is configured with and * runs the deletion, returning a per-backend report you can sign into * the audit log (#162). * * Closes issue #798. */ interface ForgettableMemory { /** * Backend identifier (`'pgvector'`, `'pinecone'`, `'sqlite'`, etc.). * Used for the audit-log entry and for the per-backend report. */ __agentskitBackend: string; /** Delete every record where `metadata.subjectId === subjectId`. */ forgetSubject: (subjectId: string) => Promise; } interface ForgetReport { backend: string; deletedCount: number; /** ISO timestamp of the deletion. */ at: string; /** Records the deletion couldn't reach (offline replica, missing index). */ failures?: Array<{ id: string; reason: string; }>; } interface ForgetSubjectResult { subjectId: string; reports: ForgetReport[]; totalDeleted: number; /** Hash you can sign into the audit log to prove the deletion ran. */ evidenceHash: string; } /** * Walk every memory passed in and run `forgetSubject(subjectId)` on * any that implement it. Memories that don't implement it are * silently skipped — they hold no subject-scoped data, or you must * delete out-of-band (e.g. log retention). */ declare function forgetSubject(memories: Array, subjectId: string): Promise; /** * Helper for backends that key records by `metadata.subjectId`. Wraps * any `delete(ids)`-style API into a `ForgettableMemory`. */ declare function makeForgettable(memory: M, options: { backend: string; listIds: (subjectId: string) => Promise; deleteIds: (ids: string[]) => Promise; }): M & ForgettableMemory; /** * Wrap any `ChatMemory` so PII is redacted (or tokenized) on every * `save()`. Works with the in-memory, file, sqlite, turso, and redis * chat memories. `load()` and `clear()` are passthrough — reveal * happens at read time via `@agentskit/core/security` `reveal()`, * not inside the memory. * * `mode: 'redact'` (default) replaces matches with the rules' bracket * markers — irreversible. `mode: 'tokenize'` replaces matches with * opaque `<>` markers and stores originals in the vault * so role-gated `reveal()` can recover them. * * Closes the memory-write half of issue #791. */ type RedactionMode = 'redact' | 'tokenize'; interface ChatMemoryRedactionOptions { /** * Rules to apply. Pass `DEFAULT_PII_RULES` for the baseline set, * `compilePIITaxonomy(json)` for a custom JSON taxonomy, or any * hand-rolled `PIIRule[]`. Same shape as `createPIIRedactor`. */ rules: PIIRule[]; mode?: RedactionMode; /** Required when `mode === 'tokenize'`. */ vault?: RedactionVault; /** Roles allowed to reveal — required when `mode === 'tokenize'`. */ allowedRoles?: string[]; /** Optional audit sink threaded into the vault `tokenize()` calls. */ audit?: RedactionAuditSink; } interface VectorMemoryRedactionOptions extends ChatMemoryRedactionOptions { } declare function wrapChatMemoryWithRedaction(inner: ChatMemory, options: ChatMemoryRedactionOptions): ChatMemory; /** * Wrap any `VectorMemory` so each document's `content` is redacted (or * tokenized) before `store()`. `search()` and `delete()` pass through. * * Note: embeddings pass through verbatim. Customers who embed * plaintext PII separately (e.g. via a hosted embedding provider) * must redact the input to their embedder, not just to this wrapper. */ declare function wrapVectorMemoryWithRedaction(inner: VectorMemory, options: VectorMemoryRedactionOptions): VectorMemory; /** Minimal KV store contract. */ interface AgentskitMemoryStore { readonly id: string | undefined; get(key: string): Promise; set(key: string, value: unknown): Promise; } interface KvEntry { readonly value: unknown; readonly insertedAt: number; } interface CommonKvConfig { readonly maxMessages?: number; readonly ttlSeconds?: number; } interface InMemoryKvConfig extends CommonKvConfig { readonly backend: 'in-memory'; } interface FileKvConfig extends CommonKvConfig { readonly backend: 'file'; readonly path: string; } interface SqliteKvConfig extends CommonKvConfig { readonly backend: 'sqlite'; readonly path: string; } interface RedisKvConfig extends CommonKvConfig { readonly backend: 'redis'; readonly url: string; readonly prefix: string; } interface VectorKvConfig extends CommonKvConfig { readonly backend: 'vector'; readonly provider: string; readonly collection: string; } interface LocalStorageKvConfig extends CommonKvConfig { readonly backend: 'localstorage'; readonly key: string; } type KvMemoryConfig = InMemoryKvConfig | FileKvConfig | SqliteKvConfig | RedisKvConfig | VectorKvConfig | LocalStorageKvConfig; interface RedisLike { get(key: string): Promise; set(key: string, value: string, options?: { readonly EX?: number; }): Promise; del(key: string): Promise; keys(pattern: string): Promise; } interface SqliteStmt { run(...params: unknown[]): void; get(...params: unknown[]): unknown; all(...params: unknown[]): unknown[]; } interface SqliteLike { exec(sql: string): void; prepare(sql: string): SqliteStmt; } type SqliteOpener = (path: string) => SqliteLike; interface MemoryVectorStoreLike { upsert(rows: readonly { readonly chunkId: string; readonly vec: readonly number[]; readonly metadata: Record; }[]): Promise; query(vec: readonly number[], k: number, filter?: Record): Promise; }[]>; } interface MemoryEmbedderLike { embed(texts: readonly string[]): Promise; } interface LocalStorageLike { getItem(key: string): string | null; setItem(key: string, value: string): void; } declare const createInMemoryStore: (config: InMemoryKvConfig) => AgentskitMemoryStore; declare const createFileStore: (config: FileKvConfig) => AgentskitMemoryStore; interface CreateLocalStorageStoreOpts { readonly config: LocalStorageKvConfig; readonly storage?: LocalStorageLike; readonly filePath?: string; } declare const createLocalStorageStore: ({ config, storage, filePath, }: CreateLocalStorageStoreOpts) => AgentskitMemoryStore; interface CreateSqliteStoreOpts { readonly config: SqliteKvConfig; readonly open: SqliteOpener; } declare const createSqliteStore: ({ config, open }: CreateSqliteStoreOpts) => AgentskitMemoryStore; /** * Lazy-import `better-sqlite3` and return an opener, or `undefined` when the * optional peer dep is absent (caller surfaces AK_MEMORY_PEER_MISSING). */ declare const tryDefaultSqliteOpener: () => Promise; interface CreateRedisStoreOpts { readonly config: RedisKvConfig; readonly client: RedisLike; } declare const createRedisStore: ({ config, client }: CreateRedisStoreOpts) => AgentskitMemoryStore; /** Bridge an `ioredis`-style client to the {@link RedisLike} options-object shape. */ declare const adaptIoredis: (io: { get(key: string): Promise; set(key: string, value: string, mode?: string, ttl?: number): Promise; del(key: string): Promise; keys(pattern: string): Promise; }) => RedisLike; /** Lazy-import `redis` (node-redis v4), connect, and return a client; `undefined` if absent. */ declare const tryDefaultRedisClient: (url: string) => Promise; interface CreateVectorStoreOpts { readonly config: VectorKvConfig; readonly vectorStore: MemoryVectorStoreLike; readonly embedder: MemoryEmbedderLike; } declare const createVectorStore: ({ config, vectorStore, embedder, }: CreateVectorStoreOpts) => AgentskitMemoryStore & { recall(query: string, k?: number): Promise; }; declare class MemoryBackendNotImplementedError extends Error { readonly code = "MEMORY_BACKEND_NOT_IMPLEMENTED"; readonly backend: KvMemoryConfig['backend']; constructor(backend: KvMemoryConfig['backend']); } type MemoryBackendStatus = 'supported' | 'planned'; declare const MEMORY_BACKEND_SUPPORT: Readonly>; declare const isMemoryBackendSupported: (backend: KvMemoryConfig["backend"]) => boolean; interface CreateKvMemoryFromConfigOpts { readonly config: KvMemoryConfig; readonly sqlite?: SqliteOpener; readonly localStorageFilePath?: string; readonly redis?: RedisLike; readonly vectorStore?: MemoryVectorStoreLike; readonly embedder?: MemoryEmbedderLike; } declare const createKvMemoryFromConfig: ({ config, sqlite, localStorageFilePath, redis, vectorStore, embedder, }: CreateKvMemoryFromConfigOpts) => AgentskitMemoryStore; declare const createKvMemoryFromConfigAuto: (config: KvMemoryConfig) => Promise; export { type AgentskitMemoryStore, type ChatMemoryRedactionOptions, type ChromaConfig, type CreateKvMemoryFromConfigOpts, type CreateLocalStorageStoreOpts, type CreateRedisStoreOpts, type CreateSqliteStoreOpts, type CreateVectorStoreOpts, type EncryptedEnvelope, type EncryptedMemoryOptions, type FileKvConfig, type FileVectorMemoryConfig, type ForgetReport, type ForgetSubjectResult, type ForgettableMemory, type GraphEdge, type GraphMemory, type GraphNode, type GraphQuery, type HierarchicalMemory, type HierarchicalMemoryOptions, type HierarchicalRecall, type InMemoryKvConfig, type KvEntry, type KvMemoryConfig, type LocalStorageKvConfig, type LocalStorageLike, MEMORY_BACKEND_SUPPORT, MemoryBackendNotImplementedError, type MemoryBackendStatus, type MemoryEmbedderLike, type MemoryVectorStoreLike, type MilvusConfig, type MongoAtlasVectorConfig, type MongoCollectionLike, type PgVectorConfig, type PgVectorRunner, type PineconeConfig, type QdrantConfig, type RedactionMode, type RedisChatMemoryConfig, type RedisClientAdapter, type RedisConnectionConfig, type RedisKvConfig, type RedisLike, type RedisVectorMemoryConfig, type SqliteChatMemoryConfig, type SqliteKvConfig, type SqliteLike, type SqliteOpener, type SqliteStmt, type SupabaseVectorStoreConfig, type TursoChatMemoryConfig, type UpstashVectorConfig, type VectorKvConfig, type VectorMemoryRedactionOptions, type VectorStore, type VectorStoreDocument, type VectorStoreResult, type WeaviateConfig, adaptIoredis, chroma, createEncryptedMemory, createFileStore, createHierarchicalMemory, createInMemoryGraph, createInMemoryStore, createKvMemoryFromConfig, createKvMemoryFromConfigAuto, createLocalStorageStore, createRedisStore, createSqliteStore, createVectorStore, fileChatMemory, fileVectorMemory, forgetSubject, isMemoryBackendSupported, makeForgettable, matchesFilter, milvusVectorStore, mongoAtlasVectorStore, pgvector, pinecone, qdrant, redisChatMemory, redisVectorMemory, sqliteChatMemory, supabaseVectorStore, tryDefaultRedisClient, tryDefaultSqliteOpener, tursoChatMemory, upstashVector, weaviateVectorStore, wrapChatMemoryWithRedaction, wrapVectorMemoryWithRedaction };